Full answer
Test data:
sql
CREATE TABLE jobs (id int PRIMARY KEY, kind text, status text DEFAULT 'queued');
INSERT INTO jobs (id, kind) VALUES (1, 'email'), (2, 'email'), (3, 'report'), (4, 'email');sql
BEGIN; SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;Output:
text
id
----
1
(1 row)In a second session:
sql
BEGIN; SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;PostgreSQL returns:
text
id
----
2
(1 row)sql
UPDATE jobs SET status = 'done' WHERE id = 1; COMMIT;Result on PostgreSQL 17:
text
COMMITIn a second session:
sql
ROLLBACK;Result:
text
ROLLBACKsql
SELECT id, status FROM jobs ORDER BY id;Output:
text
id | status
----+--------
1 | done
2 | queued
3 | queued
4 | queued
(4 rows)Worker A takes job 1 and worker B, running the same query at the same time, skips the locked row and gets job 2. A finishes and commits. B's transaction rolls back, as a crash would, so job 2 is still queued and the next worker will take it. A partial index on (id) WHERE status = 'queued' keeps the query fast as done jobs accumulate. SKIP LOCKED gives an inconsistent view on purpose, so it is right for queues and wrong for reports.
sql
CREATE TABLE jobs (id int PRIMARY KEY, kind text, status text DEFAULT 'queued');
INSERT INTO jobs (id, kind) VALUES (1, 'email'), (2, 'email'), (3, 'report'), (4, 'email');
BEGIN; SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;
-- session B
BEGIN; SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;
UPDATE jobs SET status = 'done' WHERE id = 1; COMMIT;
-- session B
ROLLBACK;
SELECT id, status FROM jobs ORDER BY id;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- SKIP LOCKED skips rows other workers hold
- Workers never wait or duplicate work
- Process and mark done in one transaction
- Crashes release jobs automatically
- Index the queued subset
Common mistakes
- Selecting then updating without locks, causing double processing
- Long transactions holding jobs while calling slow APIs
Follow-ups
- How would you add retries and a dead-letter state?
- When would a dedicated broker be better?
Tips
- Show the second worker's choice