Repository navigation
Description
How to reproduce
- Create a job with a concurrency above 1 and a common concurrency_key (see code below)
- In the Rails console, enqueue many instances of the job
- In a separate terminal, run
JOB_PROCESSES=5 bin/jobs
At first, 5 jobs will run in parallel. After the first round, most of the time, fewer than 5 jobs will be processed at a time. Often, as little as one worker will process all of the jobs.
class DummJob < ApplicationJob
limits_concurrency to: 5, key: name
def perform(id)
puts "Processing job #{id}"
sleep(1)
end
end
# In the Rails console
20.times do |i|
DummJob.perform_later(i)
endThe cause
The problem is caused by a race condition and the behavior of the query used to retrieve the next blocked execution in a non-blocking way. The query below doesn't lock a single row with the specified concurrency_key, but rather locks a whole range of records with the same concurrency_key, even though only one row is returned. When two workers run this query at the same time, the second worker retrieves no records, assumes that there are no remaining blocked jobs, and moves on. This leaves the application in a state where the semaphore value is 4 (correct), but no workers are picking up the blocked jobs until they are unblocked one at a time every 10 minutes by the orchestrator. This can be dislodged by queueing more jobs since they get added to the ready_executions table, but if you have large spikes of jobs being queued (like we do), this mechanism isn't reliable.
-- This locks a range because of the index on the concurrency_key column
SELECT `solid_queue_blocked_executions`.*
FROM `solid_queue_blocked_executions`
WHERE `solid_queue_blocked_executions`.`concurrency_key` = 'DummyJob/DummyJob'
ORDER BY `solid_queue_blocked_executions`.`priority` ASC, `solid_queue_blocked_executions`.`job_id` ASC
LIMIT 1 FOR UPDATE SKIP LOCKED;
-- This locks a single row (query from docs)
SELECT job_id
FROM solid_queue_ready_executions
ORDER BY priority ASC, job_id ASC
LIMIT ?
FOR UPDATE SKIP LOCKED;Solutions
Unfortunately, I don't really have a good solution to propose, only workarounds. If we order by id instead of priority and job_id, I believe the query locks a single row at a time and fixes the problem, but I expect it will tank performance. I do, however, have some workarounds I plan on implementing.
Workarounds
By using a random number as the concurrency_key, we can limit concurrency at the cost of an inconsistent number of workers processing a job, since some numbers will be selected more often than others.
class DummJob < ApplicationJob
limits_concurrency to: 1, key: ->(_id) { SecureRandom.rand(5) }
endHowever, we can more uniformly distribute the concurrency keys using a counter. The improvement from this will depend on how many jobs are enqueued by the same process (the more by a single processor, the better).
class DummyJob < ApplicationJob
mattr_accessor :counter
limits_concurrency to: 1, key: ->(**) {
self.class.counter ||= SecureRandom.rand(5)
self.class.counter = (self.class.counter + 1) % 5
}
endI hope that's clear. Let me know what you think, and thanks for this great gem. We're aaaalllmost completely off resque and being able to query completed jobs in a SQL database for diagnosing issues has been great.
Activity
ascullion-FS commentedon Jan 6, 2026
We did some additional investigation, and it turns out that this range locking behavior is observed in MySQL, and SQL Server, but not PostgreSQL. That means the bug is not present if you're using PostgreSQL.
rosa commentedon Feb 19, 2026
Hey @ascullion-FS, great find! You're right, this is a limitation of MySQL/InnoDB with
FOR UPDATE SKIP LOCKED+ index range scans.I think, in most realistic scenarios, where jobs don't artificially take exactly the same time (i.e.
sleep(1)makes all jobs to finish exactly at the same time), workers would finish at different times, therelease_onecalls wouldn't overlap, and this wouldn't happen. If it does happen, the maintenance task (BlockedExecution.unblock) would eventually recover by finding expired blocked executions with open semaphore slots, but only afterconcurrency_durationexpires.In addition,
limits_concurrencyis designed to prevent jobs from overlapping when they shouldn't, for example, ensuring only one job per user runs at a time to avoid data conflicts. It's not intended for throttling overall throughput. For throttling (controlling how many jobs run concurrently for resource consumption reasons), the right approach is to configure the number of workers to match your desired concurrency. If you want at most 5 jobs running at once, configure 5 worker threads. No concurrency controls needed. You save all the overhead of managing semaphores and blocked jobs.Going to close this issue then, but thanks again for looking into this 🙏🏻
ascullion-FS commentedon Feb 20, 2026
We've investigated this further since opening this issue and found the source of the problem. Closing this is fine, but I'll post what we've found for anyone else who comes across this.
As it turns out, whether MySQL locks an individual row or the whole tables depends on whether it chooses to use the index or not and does so depending its own rules (table statistics, etc.). This can make reproducing the issue inconsistent and it's more likely to work correctly if the table has more data in it. Despite this, we chose not to tolerate this risk and applied the following monkey patch:
It uses
FORCE_INDEXin order force MySQL to use the index and always lock an individual row instead of the whole table. I hope someone finds this useful.rosa commentedon Feb 21, 2026
D'oh, I'm dumb! 🤣 Of course, that's the right index to use, I named it that way for a reason! I completely forgot we had that index I had created exactly for this purpose, LOL
This is the right fix. MySQL should always be picking that one. I'll include this so you can remove your monkey-patch.
In Rails, you can add hints to the query planner using this method. I'll look into how to make this work well with the other RDBMS.
Add index hint for releasing blocked executions
Add index hint for releasing blocked executions
Add index hint for releasing blocked executions
ascullion-FS commentedon Feb 23, 2026
I tried using the
optimizer_hintsmethod, but didn't have any success with it. Hopefully I just got some of the syntax wrong and you can get it to work. It'll be easier to use that for supporting different databases.