7 min readRishi

FOR UPDATE: No Row, No Lock

FOR UPDATE: No Row, No Lock

The signup POST ran twice. Double-click, a retry after a 504, two tabs. The handler opened a transaction, selected that email FOR UPDATE, saw no row, and inserted. Both transactions saw no row. Both inserted. Postgres returned unique_violation on the second commit if users.email was unique. If it was not, you now have two accounts. SELECT … FOR UPDATE locks tuples the scan found. An empty result is not a lock on the predicate.

The SKIP LOCKED post is about rows that exist and are already held. This is the other hole: the key is not in the table yet.

What the clause actually locks

Postgres takes a row lock on each heap tuple the FOR UPDATE query returns. The lock lives until this transaction ends. A second session that needs a conflicting lock on that tuple waits, errors (NOWAIT), or omits it (SKIP LOCKED).

BEGIN;
SELECT id, email
  FROM users
 WHERE email = 'ada@example.com'
 FOR UPDATE;
-- 0 rows. This transaction holds no row lock.
INSERT INTO users (email, name)
VALUES ('ada@example.com', 'Ada');
COMMIT;

Zero rows is a successful statement. FOR UPDATE NOWAIT does not error on an empty scan — there was no locked tuple to refuse. lock_timeout does not fire.

At READ COMMITTED, the default, there is no predicate lock on email = 'ada@example.com'. The scan found no live tuple and finished. Another session can insert that email while this transaction is still open. Repeatable read does not close this: Postgres repeatable read is snapshot isolation, and snapshot isolation still does not take predicate locks for a SELECT.

Two empty scans, two inserts

T1 and T2 start together. Neither can see the other's uncommitted insert.

T1: SELECT … WHERE email = 'ada@…' FOR UPDATE   → empty
T2: SELECT … WHERE email = 'ada@…' FOR UPDATE   → empty
T1: INSERT ('ada@…')
T2: INSERT ('ada@…')                            → waits if unique, or inserts if not
T1: COMMIT
T2: COMMIT                                      → 23505, or a second row

If users.email is unique, the second INSERT tries to place an index tuple for 'ada@…', finds T1's uncommitted entry, and waits. After T1 commits, T2 rechecks and fails with unique_violation (SQLSTATE 23505). After T1 rolls back, T2 succeeds. The unique index is the lock. The SELECT … FOR UPDATE contributed nothing.

If email is not unique, both inserts commit. Two accounts. INSERT … SELECT … WHERE NOT EXISTS (…) is the same race: NOT EXISTS is a read. It does not reserve the key.

The unique index is the lock

Create the user with one statement that uses the arbiter index:

INSERT INTO users (email, name)
VALUES ('ada@example.com', 'Ada')
ON CONFLICT (email) DO NOTHING
RETURNING id;

No row returned: the email is already taken, or another transaction won the insert and committed. You did not need a prior SELECT. The inbox uses this shape because the unique key is the lock.

ON CONFLICT (email) infers a unique index or constraint on those columns. If the unique index is partial, inference has to name the predicate:

CREATE UNIQUE INDEX users_email_active
  ON users (email)
  WHERE deleted_at IS NULL;

INSERT INTO users (email, name)
VALUES ('ada@example.com', 'Ada')
ON CONFLICT (email) WHERE deleted_at IS NULL
DO NOTHING
RETURNING id;

Omit the WHERE and Postgres will not use that index as the arbiter. A different unique constraint can still throw 23505 that this ON CONFLICT does not handle. Name the constraint you mean, or accept that a second unique index is a second, unhandled conflict.

ON CONFLICT DO UPDATE locks the existing live row as FOR UPDATE would, then writes:

INSERT INTO users (email, name)
VALUES ('ada@example.com', 'Ada')
ON CONFLICT (email) DO UPDATE
   SET name = EXCLUDED.name,
       updated_at = now()
 RETURNING id;

That is an upsert of a live row, or a winner of the insert race. It is not a lock on absence that lets you do HTTP in between. Keep the transaction short. Holding it across a billing call is the SKIP LOCKED trap with a different clause.

When you must serialize work before the row exists

Sometimes the insert is not the whole unit: call billing only if this email is new, and do not let two requests both call it. FOR UPDATE of a missing row still does not help. Options that do:

Insert a placeholder first. Take the unique key, then do the slow work, then update:

INSERT INTO users (email, status)
VALUES ('ada@example.com', 'pending')
ON CONFLICT (email) DO NOTHING
RETURNING id;
-- no row: someone else holds the email. SELECT and decide.
-- row: this session owns the create. HTTP, then UPDATE status = 'active'.

A crash after the placeholder commits leaves pending. A sweeper or the next request decides. That is a lease stored as a row. Billing still needs an idempotency key; the placeholder only serializes who may start.

Transaction-scoped advisory lock on the key.

BEGIN;
SELECT pg_advisory_xact_lock(hashtextextended('ada@example.com', 0));
SELECT id FROM users WHERE email = 'ada@example.com';
-- insert if missing
COMMIT;  -- lock released

pg_advisory_xact_lock dies with the transaction. pg_advisory_lock (session) does not. Under transaction pooling the session lock stays on the backend after checkout, and the next client inherits it — or your UNLOCK runs on a different backend and does nothing. Use the _xact_ form.

hashtextextended is 64-bit. A collision serializes two unrelated emails with each other. That is extra blocking, not a lost insert, if the unique index is still there. Do not drop the unique index because you took an advisory lock.

SERIALIZABLE. Postgres SSI takes SIREAD locks on the scanned index range. T2's insert can abort T1 or T2 at commit with serialization_failure (40001). That is correct, and it is a retry loop you have to write. Wrong default for a signup path that already has a unique index.

What MySQL does instead

InnoDB REPEATABLE READ uses next-key locks. SELECT … FOR UPDATE on a missing unique value can lock the gap where that value would go, so a concurrent INSERT waits even though no tuple existed. "FOR UPDATE means I own this key" is a MySQL lesson that is false on Postgres. The hole stays open until an index tuple sits in it.

Edge cases that look like a lock and are not

NULL. A unique constraint treats NULL as distinct from NULL. Two rows with email IS NULL both commit. WHERE email = $1 with a null parameter never matches, so FOR UPDATE still locks nothing. If "no email" must be singular, use a sentinel, not uniqueness of null.

NOWAIT and empty. SELECT … FOR UPDATE NOWAIT returns empty and succeeds. The error is only for a found row that is already locked. An empty scan is not "the lock was busy."

Delete then insert. T1 deletes Ada and has not committed. T2 still sees Ada and waits on T1's row lock. After T1 commits, T2 rechecks, sees empty, and inserts. Two T2s after the delete is the original race again. FOR UPDATE only serialized with the deleter while the row existed. The unique index serializes the inserts.

NeedTool
Insert this key onceUnique index + INSERT … ON CONFLICT
Serialize work before the row existsPlaceholder row, then HTTP, then update
Short critical section on a key that may not existpg_advisory_xact_lock and a unique index
Serializable predicate on the scanSERIALIZABLE and retry 40001
This existing row, no substituteSELECT … FOR UPDATE (wait)
Claim one of many existing rowsFOR UPDATE SKIP LOCKED

The double POST did not lose a race against FOR UPDATE. It asked Postgres to lock a tuple that was not there. Postgres locked nothing. Put a unique index on the key, insert (or upsert) in one statement, and treat 23505 / DO NOTHING as "someone else already has this email." That is the lock. The select never was.

Keep reading

8 min read

SKIP LOCKED: Due Jobs, Empty Batch

SKIP LOCKED does not mean the next free job. It skips rows that currently have a conflicting lock. A forgotten transaction can make a full queue claim nothing until that session ends.

Newsletter

New posts, straight to your inbox

One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.

Comments

  • No comments yet. Be the first.