Claim a Job From the Queue
job is a queue table. Worker w1 wants work.
Claim the two highest-priority jobs that are still
queued: set their state to 'running' and
their claimed_by to 'w1'. Highest
priority first; where two jobs share a priority, the one queued
earlier wins.
Then return the whole table:
SELECT id, priority, state, claimed_by FROM job ORDER BY id;
The constraint that makes this interesting. Several workers run this at the same time. No job may ever be claimed by two of them, and a worker must not wait for another worker's job — if the obvious rows are taken, it should claim the next ones and get on with it.
Expected output
id | priority | state | claimed_by
---+----------+---------+-----------
1 | 10 | running | w9
2 | 9 | running | w1
3 | 5 | queued | NULL
4 | 1 | queued | NULL
5 | 9 | running | w1
6 | 10 | done | w9
Editorial
WITH claimed AS (
SELECT id
FROM job
WHERE state = 'queued'
ORDER BY priority DESC, queued_at ASC, id ASC
LIMIT 2
FOR UPDATE SKIP LOCKED
)
UPDATE job j
SET state = 'running', claimed_by = 'w1'
FROM claimed c
WHERE c.id = j.id;
Jobs 5 and 2 are claimed. Job 1 is priority 10 and is skipped because it is
already running; between the two priority-9 jobs, 5 was queued at
09:00 and 2 at 09:30, so 5 goes first.
Why this is one statement
The version everybody writes first is two:
-- WRONG: two workers can both get job 5
SELECT id FROM job WHERE state = 'queued'
ORDER BY priority DESC, queued_at LIMIT 2;
-- ...then, with those ids:
UPDATE job SET state = 'running', claimed_by = 'w1' WHERE id IN (5, 2);
Two workers running that within a millisecond of each other both read jobs 5 and 2 as queued, and both update them. The second update wins the row and the first worker also believes it owns the job — so the work runs twice. If the job sends an email, two emails go out.
Folding it into one statement is what closes the window:
FOR UPDATE takes a row-level write lock on each selected row as
part of the same statement that updates them, so there is no moment between
deciding and claiming.
What SKIP LOCKED changes
Three behaviours, and picking the wrong one is the usual mistake:
FOR UPDATE— the second worker blocks until the first commits, then re-reads and finds the rows no longerqueued, so it claims nothing and goes back to polling. Correct, but your workers spend their time waiting in line.FOR UPDATE NOWAIT— the second worker gets an error instead of waiting, which it must then catch and retry. Correct, noisy.FOR UPDATE SKIP LOCKED— the second worker silently ignores locked rows and takes the next two. Each worker gets a different pair, nobody waits, and throughput scales with the number of workers. This is why the idiom exists.
The trade is that SKIP LOCKED gives up on "exactly the top
LIMIT rows". A worker may skip a high-priority job because
somebody else is holding it, which is fine for a queue and would be wrong for,
say, allocating the single remaining seat on a flight — there you want the
contention, because somebody has to lose.
Why the lock is in the CTE
FOR UPDATE cannot be attached to an UPDATE, and
LIMIT cannot be either — which is the whole reason for the CTE. It
is the only way to express "lock exactly these two rows, chosen by an ordering,
then write to them" in one statement. 💡 A data-modifying CTE runs as part
of one statement with one snapshot, so the rows the CTE locked are the rows the
UPDATE writes.
Why claimed_by is not enough on its own
Nothing above stops a job from being claimed, the worker dying, and the row
sitting in running forever. Production queues add a
claimed_at timestamp and a reaper that returns jobs whose claim
has aged past a lease, and the stronger answer volunteers that before being
asked. The lock protects the claim; it does nothing about the
worker.
Deadlocks, and the one rule that prevents them
This pattern cannot deadlock on its own, because every worker locks rows in
the same order — ORDER BY inside the CTE guarantees it. Deadlocks
need two transactions taking the same locks in opposite orders: A locks row 5
then wants row 2, B locks row 2 then wants row 5, and both wait forever until
PostgreSQL kills one with a deadlock error. Lock in a consistent order
and the cycle cannot form, which is why removing the
ORDER BY from a queue claim is a real bug and not just a
correctness nicety.
What an interviewer is checking
Whether you know queue-on-a-table is a solved problem with a named solution. "SELECT FOR UPDATE SKIP LOCKED in a CTE, plus a lease for crashed workers" is the complete answer, and the expected follow-up is "when would you use a real queue instead" — the honest answer being once the throughput justifies the operational cost of running one, because a table gets you transactional enqueue for free and a broker does not.
job
6 rows
| idinteger | priorityinteger | queued_attimestamp | statetext | claimed_bytext |
|---|---|---|---|---|
| 1 | 10 | 1714550400000000 | running | w9 |
| 2 | 9 | 1714555800000000 | queued | |
| 3 | 5 | 1714551300000000 | queued | |
| 4 | 1 | 1714549500000000 | queued | |
| 5 | 9 | 1714554000000000 | queued |
Showing 5 of 6 rows.