Learning center

How long should a retry wait after FOR UPDATE NOWAIT fails?

Wait about as long as the holder usually keeps the lock, then back off, because a fixed long park costs its full length on every conflict. If the competing transaction commits within milliseconds, a 30-second retry delay turns a short collision into a 30-second stall, and a job that conflicts a few times in a row stalls for minutes. Start the retry in milliseconds, double it up to a cap, add jitter, and keep the long delay for the case it was chosen for: many workers competing for one row.

What NOWAIT does and does not decide#

SELECT ... FOR UPDATE NOWAIT asks for a row lock and gives up at once if another transaction holds it. The PostgreSQL SELECT documentation puts it plainly: with NOWAIT, "the statement reports an error, rather than waiting, if a selected row cannot be locked immediately." The error is could not obtain lock on row in relation ... with SQLSTATE 55P03, lock_not_available.

That error tells you only that the row was busy at that instant. It says nothing about how long it will stay busy. The caller has to pick a retry delay, and a common choice is one constant reused from elsewhere in the code. The constant is often long, because it was tuned for a different contention pattern, such as hundreds of workers trying to claim the same parent row.

The useful number is the holder's lock duration. A transaction that locks a row, updates two columns and commits holds the lock for a few milliseconds. A retry 30 seconds later waits roughly ten thousand times longer than it needed to.

The lab#

The lab compares three ways to take a row lock that another session takes and releases in a loop. It needs Docker and runs in about three minutes, most of it the slow policy.

docker run -d --rm --name pl-c-nowait -e POSTGRES_PASSWORD=x postgres:18
docker exec -it pl-c-nowait psql -U postgres
CREATE TABLE reviews (id int PRIMARY KEY);
INSERT INTO reviews VALUES (1);
CREATE TABLE admissions (policy text, attempts int, waited_ms numeric);

-- Admit 40 times. On a NOWAIT conflict, sleep, then double the delay up to `cap`.
CREATE PROCEDURE admit(policy text, first float8, cap float8)
LANGUAGE plpgsql AS $$
DECLARE delay float8; tries int; t0 timestamptz;
BEGIN
  FOR i IN 1..40 LOOP
    delay := first; tries := 0; t0 := clock_timestamp();
    LOOP
      tries := tries + 1;
      BEGIN
        PERFORM 1 FROM reviews WHERE id = 1 FOR UPDATE NOWAIT;
        EXIT;
      EXCEPTION WHEN lock_not_available THEN
        PERFORM pg_sleep(delay * (0.5 + random()));   -- jitter
        delay := least(delay * 2, cap);
      END;
    END LOOP;
    INSERT INTO admissions VALUES (policy, tries,
      extract(epoch FROM clock_timestamp() - t0) * 1000);
    COMMIT;                                            -- releases the row lock
    PERFORM pg_sleep(random() * 0.1);
  END LOOP;
END $$;

-- The same 40 admissions, waiting in the lock queue for at most one second.
CREATE PROCEDURE admit_queued(policy text)
LANGUAGE plpgsql AS $$
DECLARE t0 timestamptz;
BEGIN
  FOR i IN 1..40 LOOP
    t0 := clock_timestamp();
    SET LOCAL lock_timeout = '1s';
    PERFORM 1 FROM reviews WHERE id = 1 FOR UPDATE;
    INSERT INTO admissions VALUES (policy, 1,
      extract(epoch FROM clock_timestamp() - t0) * 1000);
    COMMIT;
    PERFORM pg_sleep(random() * 0.1);
  END LOOP;
END $$;

The holder is a pgbench script that locks the row for 20 ms, commits, and idles 10 to 60 ms, so the row is busy roughly 40% of the time:

\set idle random(10, 60)
BEGIN;
SELECT id FROM reviews WHERE id = 1 FOR UPDATE;
SELECT pg_sleep(0.02);
COMMIT;
\sleep :idle ms

Save it as holder.sql, copy it in, start it, and run the three policies. The fixed delay is 2 seconds instead of 30 so the lab finishes.

docker cp holder.sql pl-c-nowait:/holder.sql
docker exec -d pl-c-nowait pgbench -U postgres -n -c 1 -T 240 -f /holder.sql postgres
docker exec pl-c-nowait psql -U postgres \
  -c "CALL admit('fixed 2 s', 2, 2)" \
  -c "CALL admit('backoff 5 ms to 100 ms', 0.005, 0.1)" \
  -c "CALL admit_queued('queue, lock_timeout 1 s')" \
  -c "SELECT policy, count(*) FILTER (WHERE waited_ms > 1) AS waited,
             sum(attempts) AS attempts, round(max(waited_ms)) AS max_ms,
             round(sum(waited_ms)) AS total_ms
      FROM admissions GROUP BY policy ORDER BY total_ms DESC"

On PostgreSQL 18.7:

         policy          |   waited   | attempts | max_ms | total_ms
-------------------------+------------+----------+--------+----------
 fixed 2 s               |         17 |      112 |  27105 |   138823
 backoff 5 ms to 100 ms  |         13 |       66 |    178 |      365
 queue, lock_timeout 1 s |          9 |       40 |     22 |      126

Each policy found the row busy on 9 to 17 of its 40 admissions (the waited column). The fixed delay paid about 2 seconds for every one of its 72 conflicts, and because the row is busy 40% of the time, some retries landed on another hold and paid again: one admission waited 27 seconds. The backoff policy spent 365 ms in total for the same 40 admissions. Waiting in the lock queue was faster still, since PostgreSQL wakes the waiter the moment the holder commits. Remove the container with docker rm -f pl-c-nowait.

Choose between a short retry and a bounded wait#

If the code uses NOWAIT only to avoid hanging forever, a plain FOR UPDATE under lock_timeout usually does the job better. The setting aborts a statement that waits longer than the limit for any lock, and in the lab it gave the lowest total wait. Its cost is that the waiting transaction stays open and holds whatever it locked earlier, and other sessions may queue behind it. A migration that waits for a lock can stall every query behind it for the same reason, at table level.

Keep NOWAIT when the caller must not hold anything while it waits: a worker that should release its connection and try other work, or a step in a durable job runner that yields between attempts. Then pick the retry delay from the holder:

  • Measure or estimate the holder's lock duration. For a short update transaction, start the retry at a few milliseconds.
  • Double the delay on each consecutive conflict and cap it. A cap of 100 ms to 1 s covers holders that occasionally run long.
  • Add jitter, so two retrying workers do not keep colliding in step.
  • Bound the number of attempts, then report contention as a normal, retryable outcome.

A long fixed delay is right in one case: when many callers compete for the same row and a short retry would only multiply refused attempts. Hundreds of workers polling one parent row every few milliseconds create load that a 30-second park avoids. The delay belongs to the contention pattern, so give each caller the delay that fits its own pattern instead of sharing one constant.

What the audit replay showed#

An audit job admitted each of its investigations by locking the parent review's row with FOR UPDATE NOWAIT. Another run of the same audit sometimes held the row, for milliseconds. The shared lock helper answered every conflict with "retry after 30 seconds", a delay chosen earlier for scan partitions, where hundreds of partitions of one scan queued on the same row. An audit runs only a few investigations at once, so it never had that problem, but it inherited the delay.

The effect showed in an end-to-end test of the audit. In forty copies of the test run together, 35 finished in under 10 seconds and 5 took 33 seconds, the 30-second park plus the work. After the admission switched to the runner's short contention delay, all 40 finished in under 10 seconds, the slowest in 9.5. The lock stayed NOWAIT, and the scan partitions kept their 30 seconds.

Where this came from#

Proofline found this in its audit job's admission step and shipped the fix in its production release of 30 November 2026. The forty test copies in What the audit replay showed are that change's before-and-after measurement. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. Start a free GitHub review ยท Eligibility and fair-use terms

Questions#

Is NOWAIT or SKIP LOCKED the right choice for a job queue?

For a queue of many rows, SKIP LOCKED lets each worker take a different free row, so nobody retries. NOWAIT fits a single row that one caller needs, such as a parent record, where skipping it is not an option.

What error does a NOWAIT conflict raise?

could not obtain lock on row in relation "...", SQLSTATE 55P03 (lock_not_available). A statement that exceeds lock_timeout raises the same SQLSTATE with the message canceling statement due to lock timeout.

Should the retry delay grow without limit?

No. Cap it near the longest lock you expect the holder to keep, and cap the number of attempts. A delay that grows to minutes hides contention that someone should look at.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading