redlock-rb
redlock-rb copied to clipboard
Failed to acquire lock on
I'm receiving a Redlock::LockError Failed to acquire lock on "name-of-key" sometimes using the gem. I know this error comes from Redis but I would like to know how can I prevent it. This is the code that we have at the moment:
class Locker
extend Memoist
DEFAULT_EXPIRATION = 5.seconds
def with_lock(key, expiration: DEFAULT_EXPIRATION, retries: 1, wait: 0.1.seconds, &block)
current_retry ||= 0
lock!(key, expiration:, &block)
rescue Redlock::LockError => e
current_retry += 1
raise e if current_retry >= retries
sleep(wait)
retry
end
private
memoize def lock_manager
Redlock::Client.new([Rails.application.credentials.redis.url])
end
def lock!(key, expiration: DEFAULT_EXPIRATION, &block)
lock_manager.lock!(key, (expiration * 1000).to_i, &block)
end
end
And this is how we call the lock:
Locker.new.with_lock("key") do
action
end