Skip to content

limits_concurrency uses fewer workers than expected for the same concurrency_key #694

Closed

Description

@ascullion-FS

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)
end

The 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) }
end

However, 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
  }
end

I 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

  1. ascullion-FS commented on Jan 6, 2026

    @ascullion-FS
    Author

    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.

  2. rosa commented on Feb 19, 2026

    @rosa
    Member

    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, the release_one calls 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 after concurrency_duration expires.

    In addition, limits_concurrency is 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 🙏🏻

  3. ascullion-FS commented on Feb 20, 2026

    @ascullion-FS
    Author

    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:

    module SolidQueue
      module BlockedExecutionPatch
        RELEASE_INDEX_NAME = "index_solid_queue_blocked_executions_for_release"
    
        # Copy of original method from solid_queue-1.2.4/app/models/solid_queue/blocked_execution.rb:27
        # but adds FORCE INDEX to the query
        def release_one(concurrency_key)
          transaction do
            if (execution = ordered
                .where(concurrency_key: concurrency_key)
                .from("#{table_name} FORCE INDEX (#{RELEASE_INDEX_NAME})")
                .limit(1)
                .non_blocking_lock
                .first)
              execution.release
            end
          end
        end
      end
    end
    
    Rails.application.config.after_initialize do
      SolidQueue::BlockedExecution.singleton_class.prepend(SolidQueue::BlockedExecutionPatch)
    end

    It uses FORCE_INDEX in order force MySQL to use the index and always lock an individual row instead of the whole table. I hope someone finds this useful.

  4. rosa commented on Feb 21, 2026

    @rosa
    Member

    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.

  5. reopened this on Feb 21, 2026
  6. added 3 commits that reference this issue on Feb 22, 2026
    c59ef74
    7479a20
    2c4bbd3
  7. ascullion-FS commented on Feb 23, 2026

    @ascullion-FS
    Author

    I tried using the optimizer_hints method, 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions