SELECT ... FOR UPDATE and SKIP LOCKED
row locks you ask for, NOWAIT, and a job queue that ten workers can drain without fighting.
- address
- everything.transactions.row_locking_clauses
- part
- part 11, transactions and isolation
- chapter
- chapter 7 of 11
- reading time
- 8 min
SELECT ... FOR UPDATE locks the rows it returns until your transaction ends, so nobody else can change or lock them first. there are four strengths, from FOR UPDATE down to FOR KEY SHARE. add NOWAIT to fail at once (55P03) instead of waiting, or SKIP LOCKED to step over rows someone else holds. that last one turns a table into a job queue many workers can drain without ever taking the same job.
the picture
you know how a plain SELECT promises nothing about the next statement? you read a row, and by the time you write it, it may have changed. FOR UPDATE is the promise: these rows are mine until I commit.
think of a table of parcels and a few couriers. FOR UPDATE is putting your hand on a parcel. the next courier who reaches for the same one can wait for you to let go (plain FOR UPDATE), give up on the spot (NOWAIT), or take the next parcel along (SKIP LOCKED).
two workers, a queue of four jobs, and the same query with each of the three endings:
W1 claims the oldest open job: 1.
look at what the waiting worker got when it woke up: job 2, not job 1. while it waited, W1 finished job 1, so done_by IS NULL was no longer true. a locking read at READ COMMITTED re-checks its WHERE on the newest version of a row it had to wait for (the re-check), job 1 dropped out, and LIMIT 1 took the next one. it waited a whole job's length for a row it was never going to get.
SELECT id FROM jobs
WHERE done_by IS NULL
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;four strengths
FOR UPDATE is the strongest. the weaker ones exist so that ordinary writes and foreign key checks don't block each other more than they have to. here's who blocks whom, captured: T1 holds a different strength on each of four rows, and T2 asks for every strength on every row with NOWAIT.
| T1 holds ↓ · T2 asks → | KEY SHARE | SHARE | NO KEY UPDATE | UPDATE |
|---|---|---|---|---|
| KEY SHARErow 1 | ok | ok | ok | |
| SHARErow 2 | ok | ok | ||
| NO KEY UPDATErow 3 | ok | |||
| UPDATErow 4 |
you rarely type the middle two, but postgres takes them for you all the time:
- an UPDATE that doesn't change a key column takes FOR NO KEY UPDATE on each row. the same capture shows it: T2's plain
UPDATE t SET note = ...on row 1 went straight through T1's FOR KEY SHARE, and on row 2 it waited for T1's FOR SHARE. - an UPDATE that changes a key column, and every DELETE, takes FOR UPDATE.
- a foreign key check takes FOR KEY SHARE on the parent row. that's the point of the split: inserting a transfer that references alice doesn't stop someone from updating alice's balance, only from deleting her or changing her id.
how a lock that lives in the row itself works (no lock table, just the row's xmax, and a MultiXact when several transactions share one) is in how row locks are stored.
a job queue
that's the pattern: a jobs table, and every worker runs the same claim query in its own transaction.
BEGIN;
SELECT id FROM jobs WHERE done_by IS NULL ORDER BY id LIMIT 2 FOR UPDATE SKIP LOCKED;
-- do the work, then:
UPDATE jobs SET done_by = 'W1' WHERE id IN (1, 2);
COMMIT;three workers, seven jobs, on a real server:
| job | locked by | done_by |
|---|---|---|
| 1 | W1 | null |
| 2 | W1 | null |
| 3 | null | null |
| 4 | null | null |
| 5 | null | null |
| 6 | null | null |
| 7 | null | null |
W1 opens a transaction and claims the two oldest jobs that nobody holds: 1 and 2. they're row-locked by W1 now.
W1 got 1 and 2, W2 got 3 and 4, W3 got 5 and 6, all with the same query, none of them waiting. W1 finished first and came back for more: 1 and 2 were done, 3 to 6 were locked, so it got 7. by the end W2's query comes back empty. that's the whole design. no "claimed" column, no polling a status, no two workers on one email.
the order of operations is what makes it work: the LockRows node sits below Limit, so rows are locked (or skipped) first and counted second. it keeps pulling rows until two of them lock.
CREATE TABLE jobs (id int PRIMARY KEY, task text NOT NULL, done_by text);
INSERT INTO jobs SELECT g, 'email #' || g, NULL FROM generate_series(1, 7) AS g;
EXPLAIN (COSTS OFF)
SELECT id FROM jobs WHERE done_by IS NULL ORDER BY id LIMIT 2 FOR UPDATE SKIP LOCKED;where FOR UPDATE can't go
it locks rows it returns, so it has to know which table row each output row came from. aggregates, GROUP BY, DISTINCT and set operations break that link:
SELECT count(*) FROM accounts WHERE balance > 1000 FOR UPDATE;in a join it locks the matching rows of every table in FROM. FOR UPDATE OF accounts narrows it to one. and SKIP LOCKED gives you a deliberately incomplete view of the table: perfect for a queue, wrong for anything that has to count or sum.
keylines
- FOR UPDATE locks the returned rows until COMMIT or ROLLBACK.
- NOWAIT fails with 55P03 instead of waiting. SKIP LOCKED leaves locked rows out.
- four strengths. UPDATE takes FOR NO KEY UPDATE, foreign keys take FOR KEY SHARE, so they don't collide.
- a waiting locking read re-checks its WHERE on the newest row, and may skip it.
- FOR UPDATE SKIP LOCKED + LIMIT is a job queue, and the open transaction is the claim.