I'm trying to lock a part of my code using Redis, with Redlock library.
I've implemented it here:
def perform(task_id, task_type) lock_manager = Redlock::Client.new([ "redis://127.0.0.1:6379" ]) lock_key = "task_runnuer_job_#{task_type}_#{task_id}" puts("locking! #{task_id}") lock_task = lock_manager.lock(lock_key , 6 * 60 * 1000)if lock_task.present? begin # Exec task... Services::ExecTasks::Run.call task.id ensure puts("unlocking! #{task_id}") lock_manager.unlock(lock_task) end else puts("Resource is locked! #{lock_key}") end end
What I get when running multiple Sidekiq jobs at the same time, is the following logs:
"locking! 520""locking! 520""unlocking! 520""unlocking! 520"
This happens when both of my 520 task, which should not be executed together, are being called with 1ms diffrence.
Yet sometimes the lock works as expected.
I've checked Redis and it works just fine.
Any ideas? Thanks!