Sub topic 11
NOWAIT and SKIP LOCKED for Queues and Fail-Fast Code
This chapter assumes you know basic SQL, transactions, primary keys, and foreign keys. You should also be able to use two concurrent psql sessions. The examples use PostgreSQL row-level locks.
Choose whether to wait
A locking clause normally waits when another transaction holds a conflicting lock. You can change that behavior:
NOWAITfails immediately if the requested row or table lock is unavailable.SKIP LOCKEDignores rows that are currently locked and continues looking for other rows.
Both options apply to locking reads such as SELECT ... FOR UPDATE. The lock still lasts until the transaction commits or rolls back.
| Option | Behavior when a row is locked | Common use |
|---|---|---|
| Default | Wait until the lock is available | Operations that must process a specific row |
| `NOWAIT` | Return an error immediately | Fail-fast commands and user-facing actions |
| `SKIP LOCKED` | Ignore the locked row | Work queues with multiple workers |
Use NOWAIT when waiting is not acceptable
Suppose an application must edit an account immediately. Waiting behind a long transaction may make the request slow or cause a request timeout. NOWAIT lets the application report that the account is busy.
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric NOT NULL
);
INSERT INTO accounts VALUES (1, 100);
-- Session A
BEGIN;
SELECT id, balance
FROM accounts
WHERE id = 1
FOR UPDATE;
-- Session B
BEGIN;
SELECT id, balance
FROM accounts
WHERE id = 1
FOR UPDATE NOWAIT;
-- ERROR: could not obtain lock on row in relation "accounts"
-- SQLSTATE: 55P03
ROLLBACK;
-- Session A
COMMIT;A failed NOWAIT statement usually aborts the current transaction. The application should catch SQLSTATE 55P03, roll back, and decide whether to retry, show a busy message, or take another action.
NOWAIT does not mean “do not wait for anything.” It applies to the lock requested by that statement. Other work in the transaction can still take time.
Use SKIP LOCKED for worker queues
A queue table contains work that workers claim and process. If every worker uses an ordinary FOR UPDATE, they form a line behind the first locked job. SKIP LOCKED allows each worker to select a different available job.
A safe claim operation changes the job state while holding the lock, then returns the claimed row:
CREATE TABLE jobs (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload text NOT NULL,
status text NOT NULL DEFAULT 'pending',
started_at timestamptz
);
INSERT INTO jobs (payload) VALUES
('send welcome email'),
('resize image'),
('rebuild search entry');
BEGIN;
WITH next_job AS (
SELECT id
FROM jobs
WHERE status = 'pending'
ORDER BY id
FOR UPDATE SKIP LOCKED
LIMIT 1
)
UPDATE jobs AS j
SET status = 'processing',
started_at = clock_timestamp()
FROM next_job
WHERE j.id = next_job.id
RETURNING j.id, j.payload;
COMMIT;Run that claim transaction concurrently in several workers. Each worker can receive a different pending job. After committing, the worker performs the job using the returned id and payload.
Understand the trade-offs
SKIP LOCKED gives an intentionally inconsistent view. It is useful for distributing work, but it is not appropriate when a query must inspect every matching row. A worker can see no row even though pending jobs exist, because other workers currently hold the locks.
Ordering is also approximate. With ORDER BY id, a locked low-numbered job may be skipped while a later job is claimed first. If processing fails after the worker commits its claim, the job needs a retry or lease mechanism. A permanent processing status can otherwise lose work.
Keep the claim transaction short. Do not hold a row lock while calling a remote service or performing slow application work.
Exercise
Two workers run a queue query with SKIP LOCKED and one worker receives no row. Does that prove the queue is empty?
Show answer
No. All matching rows may currently be locked by other workers. The worker should retry later or treat the empty result as “no work available now.”