Concurrency & uniqueness
Prevent duplicate jobs with uniqueness, or cap simultaneous runs with concurrency limits.
Job uniqueness#
At most one job with a given key exists, from enqueue to done.
ensures_uniqueness guarantees that at most one job with a given key exists in the system at a time. The lock is held in pgbus_uniqueness_keys — never released by a timer, only when the job completes (or, for :until_executing, starts), is dead-lettered, or is found orphaned by the reaper.
class ImportOrderJob < ApplicationJob
ensures_uniqueness strategy: :until_executed,
key: ->(order_id) { "import-order-#{order_id}" },
on_conflict: :reject
def perform(order_id)
# Only ONE instance per order_id can exist — enqueue through completion.
end
endRetries keep the lock
A job that reschedules itself — retry_job(wait: 5.minutes) in perform, or retry_on SomeError, wait: 5.minutes — keeps its :until_executed lock for the whole wait. The retry enqueues through the lock the running attempt holds, and the lock moves onto the retry (or, when the retry is parked behind a limits_concurrency slot, onto the parked job). A fresh perform_later with the same key during the wait is a duplicate and gets the conflict policy.
A finishing message releases only the lock it holds: a lock that moved onto the job's retry, or that another job took after an operator released it, stays. Discarding a job, a failed job or a dead-lettered copy from the dashboard follows the same rule, judged by when the job's message was sent (a dead-lettered copy carries its original's send time); when that is unknown, only a lock bound to the message is freed and the dispatcher's reaper takes the rest. The Locks page's own Release still frees the key itself.
Retrying a dead-lettered copy (dashboard, pgbus dlq retry, Retry All) or a failed job whose message is gone sends a new message, and that message takes the lock the way an enqueue does: a lock still held by the message it came from moves onto it, and a free key is acquired. While another copy of the job holds the key the retry is refused (the alert lists the held key as a possible cause, the log names it) and the dead-lettered copy or failed job stays where it is. A :while_executing job, and an :until_executing retry_on re-enqueue, retry without a lock, as they were sent.
Strategies and conflict policies#
The strategy decides when the lock is taken; the conflict policy decides what happens to a duplicate.
| Strategy | Lock acquired | Prevents |
|---|---|---|
:until_executed | At enqueue, held until success or dead-letter | Duplicate enqueue AND execution |
:until_executing | At enqueue, released when execution starts | Duplicate enqueue while a copy is queued (a debounce) |
:while_executing | At execution start, released on completion or failure | Duplicate execution only |
Debounce with :until_executing
A job that recomputes a parent's rollup is enqueued by every child that finishes. While one copy is queued, further enqueues for the key get the conflict policy: the queued copy has not run yet and will see their state. The lock is released before perform, so an enqueue that arrives while the copy runs is accepted and queues the trailing copy. At most one copy for the key is queued at a time, and every write made before an accepted or dropped enqueue is seen by a run that starts after it.
class RollupJob < ApplicationJob
ensures_uniqueness strategy: :until_executing,
key: ->(parent_id) { "rollup-#{parent_id}" },
on_conflict: :discard
def perform(parent_id) = Parent.find(parent_id).recompute_rollup!
endTwo runs can overlap: the trailing copy can start while the first is still running. For a debounce and no overlap, add a concurrency limit of one with :block. The trailing enqueue takes the free uniqueness key and parks behind the semaphore, further enqueues are dropped by the key, and the parked copy runs when the first finishes:
class RollupJob < ApplicationJob
ensures_uniqueness strategy: :until_executing,
key: ->(parent_id) { "rollup-#{parent_id}" },
on_conflict: :discard
limits_concurrency to: 1,
key: ->(parent_id) { "rollup-#{parent_id}" },
on_conflict: :block
endA scheduled copy (set(wait:)) holds the lock for its whole wait, so enqueues during the wait are dropped; a recurring task is skipped while its previous copy is still queued. In one perform_all_later bulk, same-key jobs yield one message (on_conflict: :reject raises Pgbus::JobNotUnique at the second, as for :until_executed). A retry_on re-enqueue goes out without a lock (the attempt released its own at start), so it can sit beside one fresh copy. Both run, in no guaranteed order and possibly at once; each sees the state written before it started. Without a key:, a job enqueued with arguments raises, as for :until_executed.
A :while_executing lock is bound to the message being executed: a failed attempt releases it so the retry can run, and a row left behind by a crashed attempt is re-acquired by the same message on its next read rather than treated as a duplicate.
The enqueue-time strategies meet a duplicate when it is enqueued; :while_executing meets it when a worker reads a copy while another copy holds the key:
| Conflict policy | At enqueue (:until_executed, :until_executing) | At execution (:while_executing) |
|---|---|---|
:reject | Raise Pgbus::JobNotUnique (default) | Leave the copy queued for a backed-off redelivery: it runs once the holder is done, or dead-letters as uniqueness_conflict if skipped past max_retries |
:discard | Silently drop the duplicate | Complete the copy without running it (pgbus.job_discarded) |
:log | Log a warning and drop | As :reject, and log the skip at warn |
A :while_executing copy left queued comes back after visibility_timeout × 2^(read_ct − 1) (jittered, capped at retry_backoff_max, never below visibility_timeout), so repeated skips stretch over a long holder's run; each skip emits pgbus.job_skipped. PGMQ counts every read toward max_retries, so a copy skipped past max_retries still dead-letters, and when none of its attempts failed its DLQ headers say reason: uniqueness_conflict. A recurring :while_executing task carries its key, so a run that outlasts its interval is not overlapped by the next. For a trailing run that sees writes enqueued while the current run executes, use :until_executing.
Add the table with rails generate pgbus:add_uniqueness_keys (append --database=pgbus for a separate database).
Concurrency limits#
At most N jobs with the same key run at once.
Where uniqueness is binary (one or none), limits_concurrency is a counting semaphore — up to N jobs with the same key run simultaneously, the rest wait, drop, or raise:
class ProcessOrderJob < ApplicationJob
limits_concurrency to: 1,
key: ->(order_id) { "ProcessOrder-#{order_id}" },
duration: 15.minutes,
on_conflict: :block
def perform(order_id)
# Only one job per order_id runs at a time.
end
end| on_conflict | Behavior |
|---|---|
:block | Park the job; promoted the moment a slot frees. Never dropped, however long it waits. |
:discard | Silently drop the job. |
:raise | Raise Pgbus::ConcurrencyLimitExceeded. |
:block is the option to reach for when a job must be constrained without being lost — a per-record pipeline that may only run one at a time but must run for every enqueue. Uniqueness cannot do that: every ensures_uniqueness conflict drops or rejects the duplicate.
The guarantees behind :block:
- A parked job never ages out. The only way out of
pgbus_blocked_executionsis promotion, so a park that outlivesdurationis still promoted when its slot frees. - A promotion always takes a real slot. The finishing job releases its slot and hands it to the next parked job in one transaction; the dispatcher's sweep promotes behind a dead holder the same way. Neither can push a key past
to:. - A job parked while the holder is finishing is promoted, not stranded. The semaphore check and the park commit together under the semaphore's row lock, so a concurrent release waits and then sees the parked row.
- A duplicate delivery never releases a slot twice. Archiving the message is the exact-once claim; a worker whose message was already archived elsewhere (its heartbeat lapsed) skips the release.
- A retried job takes a slot like an enqueue. Retrying a dead-lettered copy (dashboard,
pgbus dlq retry, Retry All) or a failed job whose message is gone sends a new message, which takes a free slot first. At the limit, a:blockjob's copy is parked (the dead-lettered copy or failed job goes, the parked one runs when a slot frees); a:discardor:raisejob's retry is refused and the dead-lettered copy or failed job stays, since dropping it would lose the job the retry asked for. A failed job whose message is still queued already holds its slot: its retry only makes it visible.
Seeing it#
A blocked key is invisible until you look at it.
A key at its limit is indistinguishable from a stalled pipeline from the outside: nothing fails, nothing is in the queue, the jobs are simply parked. Four places show it.
The dashboard home carries a Parked jobs card — the count and the oldest wait, linking straight to Locks. It is usually the first sign.
The Locks page has a Concurrency section: parked jobs, the oldest wait, slots held and keys at their limit, then up to 100 key rows — busiest first — each with its value / limit, lease state, parked count and oldest wait. The cards carry the true totals, so a key missing from the table is not absent, only outside the 100 busiest. A stale lease next to a parked backlog is the shape to look for — the slot's holder died before releasing it.
Three of those four totals are exported to /pgbus/api/metrics and the AppSignal probe: pgbus_concurrency_blocked_executions, pgbus_concurrency_blocked_oldest_age_seconds and pgbus_concurrency_slots_held. Alert on the oldest wait. Keys at limit has no gauge — it is a Locks card (and an MCP field) only.
The read-only pgbus_concurrency MCP tool returns the same data, so an agent can answer "why is this order stuck?" without SQL.
Each key row on the Locks page carries two escape hatches:
- Release drops the key's semaphore row and promotes what can run. The promotion goes through the same guarded upsert an enqueue uses, so it can never push the key past its limit. Use it when a holder died and its lease outlives it. Do not use it while the lease is still fresh — a job is probably still running, and releasing lets another start beside it. The page warns you with different confirm text in that case.
- Discard parked drops every job parked behind the key. They never run. A parked batch child is resolved as failed so its batch stops waiting, and an
:until_executeduniqueness lock is released rather than orphaned. Use it only when the parked work is genuinely obsolete —:blockexists precisely so that work is not lost.
Which one do I want?#
| Use | When |
|---|---|
ensures_uniqueness | "This exact job must not run twice" — payments, order import, unique emails. |
limits_concurrency | "At most N of these at once" — rate-limited APIs, resource-constrained tasks. |