Sub topic 11
NOWAIT and SKIP LOCKED for queues and fail-fast code
This chapter assumes you know the row-level lock modes from the earlier chapters, especially SELECT ... FOR UPDATE, and that you can run two psql sessions side by side. By the end you will be able to:
- make a statement fail immediately instead of waiting for a row lock;
- build a job queue where several workers claim different rows without blocking each other;
- handle the errors and edge cases both options introduce.
Waiting is the default
When a statement needs a row that another transaction has locked, PostgreSQL waits. It waits until the other transaction commits or rolls back, or until a timeout such as lock_timeout fires. This is the right behavior for most code, because the second transaction usually needs the first one's result.
Two cases make waiting a poor choice:
- Fail-fast code. A web request or API call should not hang for 30 seconds because someone else holds a row. It is better to return "busy, try again" at once.
- Work queues. If ten workers all ask for "the next pending job" and each locks the first row, nine of them wait for the tenth to finish. You wanted ten jobs in progress. You got one.
NOWAIT and SKIP LOCKED address these two cases. Both are added to the locking clause of a SELECT.
NOWAIT: raise an error instead of waiting
FOR UPDATE NOWAIT (or any other FOR clause followed by NOWAIT) tries to lock the selected rows. If any of them is already locked in a conflicting mode, the statement fails immediately.
-- Session A
BEGIN;
SELECT id FROM accounts WHERE id = 1 FOR UPDATE;
-- Session B
BEGIN;
SELECT id FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;
-- ERROR: could not obtain lock on row in relation "accounts"
-- SQLSTATE 55P03 (lock_not_available)
ROLLBACK;
-- Session A
COMMIT;Session B's transaction is now in the aborted state, so it must roll back before it can run anything else. Session A is unaffected.
The error has SQLSTATE 55P03. Your application should catch that code specifically and treat it as "resource busy", not as a general failure. Typical responses are returning HTTP 409 or 423 to the caller, or retrying after a short delay with backoff.
You can also catch the error inside the database. In PL/pgSQL the condition name is lock_not_available:
DO $$
BEGIN
PERFORM 1 FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
EXCEPTION
WHEN lock_not_available THEN
RAISE NOTICE 'account 1 is busy, try again later';
END
$$;A block with an EXCEPTION clause runs inside a subtransaction. That has a small cost, so do not wrap it around every statement in a hot loop.
NOWAIT also works on explicit table locks:
BEGIN;
LOCK TABLE accounts IN ACCESS EXCLUSIVE MODE NOWAIT;
-- fails with 55P03 if any other session holds any lock on the table
ROLLBACK;What NOWAIT does not cover
NOWAIT applies only to the row-level locks of that one statement. The statement still takes a table-level ROW SHARE lock in the normal way. That lock conflicts only with ACCESS EXCLUSIVE, so a pending ALTER TABLE can still make a SELECT ... FOR UPDATE NOWAIT wait. If you need a hard upper bound on every kind of wait, combine NOWAIT with a short lock_timeout.
SKIP LOCKED: ignore rows someone else holds
FOR UPDATE SKIP LOCKED does not wait or raise an error. It silently leaves out any row that it cannot lock immediately and returns the rest.
The diagram shows what happens when a statement reaches a row, depending on the clause.
That makes a queue possible. Two sessions can each ask for one pending job and get different ones:
CREATE TABLE jobs (
id bigserial PRIMARY KEY,
status text NOT NULL DEFAULT 'pending',
payload text NOT NULL,
claimed_at timestamptz
);
CREATE INDEX jobs_pending_idx ON jobs (id) WHERE status = 'pending';
INSERT INTO jobs (payload)
SELECT 'job ' || g FROM generate_series(1, 5) AS g;
-- Session A
BEGIN;
SELECT id FROM jobs
WHERE status = 'pending'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;
-- returns id 1
-- Session B (does not wait)
BEGIN;
SELECT id FROM jobs
WHERE status = 'pending'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;
-- returns id 2Session B skipped row 1 because session A locked it, then took the next qualifying row. The partial index on pending rows keeps the scan short even after millions of jobs have finished.
Two ways to run a queue worker
There are two common designs, and they fail differently.
Design 1: hold the lock while you work. The worker begins a transaction, selects a job with SKIP LOCKED, processes it, marks it done and commits. If the worker crashes, the connection drops, the transaction rolls back, and the lock disappears. The job is automatically available again. The cost is a transaction that stays open for the whole job. A long job holds a snapshot open, which delays vacuum, and it uses a connection for the whole time.
Design 2: claim in one statement, work outside the transaction. The worker flips the row to running in a single statement and commits at once:
WITH next_job AS (
SELECT id
FROM jobs
WHERE status = 'pending'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED
)
UPDATE jobs
SET status = 'running', claimed_at = now()
FROM next_job
WHERE jobs.id = next_job.id
RETURNING jobs.id, jobs.payload;The row lock lives only for the duration of this statement. Other workers skip the row afterward because its status is no longer pending. Transactions stay short. But a crashed worker leaves its job stuck in running, so you need a reaper that returns stale jobs to the queue:
UPDATE jobs
SET status = 'pending', claimed_at = NULL
WHERE status = 'running'
AND claimed_at < now() - interval '10 minutes';Choose a timeout longer than your slowest legitimate job, or the reaper will hand out work that is still running. A job can then run twice, so the job handler should be idempotent.
| Design | Lock held during work | Crash recovery | Main cost |
|---|---|---|---|
| Hold the lock | Yes | Automatic on rollback | Long transactions and idle connections |
| Claim then work | No | Needs a reaper | Possible duplicate runs, extra status column |
Gotchas
An empty result does not mean an empty queue. If every pending row is locked, SKIP LOCKED returns zero rows. A worker that sees no rows should sleep briefly and try again. It should not conclude that the work is finished.
The result is an inconsistent view on purpose. The PostgreSQL documentation says SKIP LOCKED gives an inconsistent view of the data and is not suitable for general-purpose work. It suits queue-like tables where each row is independent. Do not use it to compute totals or to read "all the rows".
Ordering is only approximate. Skipped rows mean a later job can run before an earlier one. In READ COMMITTED, a locking SELECT with ORDER BY and LIMIT can also return rows slightly out of order if a concurrent update changed a sort column. If strict ordering matters, a plain single-consumer design is safer.
Foreign keys can lock your rows. Inserting a child row takes a FOR KEY SHARE lock on the referenced parent row. That conflicts with FOR UPDATE, so a worker using SKIP LOCKED will skip parent rows that are only being referenced. If your worker never deletes or changes the key, use FOR NO KEY UPDATE, which does not conflict with FOR KEY SHARE.
Joins need an OF clause. When the query joins several tables, name the table whose rows you want to lock, for example FOR UPDATE OF jobs SKIP LOCKED. Without OF, every table in the query is locked.
Choosing between the options
| Option | When a row is locked | Scope | Use it for |
|---|---|---|---|
| Default | Waits indefinitely | The statement | Normal transactional code |
| `lock_timeout` | Waits, then errors | Any lock wait in the session or transaction | A safety net for migrations and general code |
| `NOWAIT` | Errors immediately | Row locks of one statement | Interactive paths that should report "busy" |
| `SKIP LOCKED` | Skips the row | Row locks of one statement | Queues where any available row will do |
NOWAIT is one specific wait policy for one statement. lock_timeout is a general limit that you set once. They work well together: NOWAIT on the row lock you expect to be contended, and lock_timeout as a backstop for everything else.
Exercise
A worker runs "SELECT id FROM jobs WHERE status = 'pending' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED" and gets no rows, although the table still contains pending jobs. What are two possible explanations, and what should the worker do?
Show answer
Either every pending row is currently locked by other workers, or another transaction holds a conflicting lock (for example a FOR KEY SHARE lock taken by a foreign key check) on the remaining rows. In both cases the queue is not necessarily empty. The worker should sleep briefly and poll again instead of exiting.
Exercise
Session A runs "BEGIN; SELECT FROM accounts WHERE id = 1 FOR UPDATE;" and stays open. Session B runs "SELECT FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;". What does session B get, which SQLSTATE does it see, and what must it do next if it was inside a transaction?
Show answer
Session B immediately gets the error "could not obtain lock on row in relation "accounts"" with SQLSTATE 55P03 (locknotavailable). Its transaction is aborted, so it must issue ROLLBACK (or roll back to a savepoint) before running further statements.