In PostgreSQL, what are the four row-lock strengths, and why do foreign-key checks take FOR KEY SHARE rather than FOR SHARE?
answer
- two exclusive, two shared
- key columns versus the rest
- what UPDATE and DELETE take implicitly
- the referential check's own SELECT
- several lockers, one MultiXact
basics
~20 sPostgreSQL's row locks, strongest first, are FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE and FOR KEY SHARE. A foreign-key check only needs the referenced key to survive, so FOR KEY SHARE lets non-key updates of the parent row proceed.
solid answer
~50 sFrom strongest to weakest: `FOR UPDATE` (taken by `DELETE` and by an `UPDATE` that changes a column with a unique index usable by a foreign key), `FOR NO KEY UPDATE` (taken by every other `UPDATE`), `FOR SHARE`, and `FOR KEY SHARE`. The last two are shared. `FOR KEY SHARE` conflicts only with `FOR UPDATE`, so it blocks deletes, key-changing updates and explicit `FOR UPDATE` locks, and `FOR NO KEY UPDATE` is designed not to conflict with it. When a child row is inserted, PostgreSQL's referential-integrity trigger runs a query of the form `SELECT 1 FROM <parent> x WHERE <key> = $1 FOR KEY SHARE OF x`, so it only stops the parent key from disappearing; an `UPDATE` of the parent's `status` proceeds concurrently. A `FOR SHARE` check would block that update until the child's transaction ended. Row locks are recorded in the row's tuple header, not in memory, and none of them blocks a plain `SELECT`.
code
sql · 16 lines-- session A: the send worker
BEGIN;
UPDATE email_outbox SET status = 'sent' WHERE id = 101;
-- takes FOR NO KEY UPDATE on row 101
-- session B: the delivery webhook (email_events.email_id references email_outbox.id)
BEGIN;
INSERT INTO email_events (email_id, kind) VALUES (101, 'delivered');
-- FK check takes FOR KEY SHARE on row 101: no conflict, no wait
COMMIT;
-- session A
COMMIT;
-- had session A run SELECT ... FROM email_outbox WHERE id = 101 FOR UPDATE,
-- session B's INSERT would have waited for A to finishgo deeper
Recall the four strengths in order and that none of them stops a plain SELECT from reading the row.
Explain which strength UPDATE and DELETE take implicitly and why FOR NO KEY UPDATE and FOR KEY SHARE are designed not to conflict.
Show you can trace a stalled child insert to an explicit FOR UPDATE on the parent, fix it, and connect shared row locks on hot rows to MultiXact growth.
Discuss schema choices around hot parent rows, such as foreign keys to a single shared row, against the integrity guarantees you would give up by dropping them.
## Four strengths, one conflict table Besides table locks, PostgreSQL has **row-level locks** in four strengths. Two are exclusive (`FOR UPDATE`, `FOR NO KEY UPDATE`) and two are shared (`FOR SHARE`, `FOR KEY SHARE`). They are requested explicitly with a locking clause on `SELECT` and taken implicitly by `UPDATE` and `DELETE`. An X marks a conflict between the requested lock (row) and a lock another transaction already holds (column): | Requested \ Held | `FOR KEY SHARE` | `FOR SHARE` | `FOR NO KEY UPDATE` | `FOR UPDATE` | |---|---|---|---|---| | `FOR KEY SHARE` | | | | X | | `FOR SHARE` | | | X | X | | `FOR NO KEY UPDATE` | | X | X | X | | `FOR UPDATE` | X | X | X | X | Two facts hold for all four: - Row locks block only **writers and lockers** of the same row. A plain `SELECT` never waits on them; it reads the version its snapshot sees. - They are released at transaction end, or by a rollback to a savepoint set before they were taken, just like table locks. ## Which statements take which lock implicitly - `DELETE` takes `FOR UPDATE` on each row it deletes. - `UPDATE` takes `FOR UPDATE` when it modifies a column covered by a **unique index usable by a foreign key**; partial and expression indexes do not count. - Every other `UPDATE` takes `FOR NO KEY UPDATE`. - A foreign-key check, run when a referencing row is inserted or its key updated, takes `FOR KEY SHARE` on the referenced row. So `UPDATE email_outbox SET status = 'sent' WHERE id = 7` takes `FOR NO KEY UPDATE`, while `DELETE FROM email_outbox WHERE id = 7` takes `FOR UPDATE`. ## Foreign keys: why KEY SHARE exists Suppose `email_events.email_id` references `email_outbox(id)`, and a delivery webhook races a send worker: 1. The worker runs `UPDATE email_outbox SET status = 'sent' WHERE id = 101`, taking `FOR NO KEY UPDATE` on row 101. 2. The webhook inserts an `email_events` row with `email_id = 101`. PostgreSQL's referential-integrity trigger runs a query of the form `SELECT 1 FROM <parent> x WHERE <key> = $1 FOR KEY SHARE OF x`. 3. `FOR KEY SHARE` does not conflict with `FOR NO KEY UPDATE`, so the insert proceeds at once. 4. Had the worker been deleting row 101 or changing its `id`, it would hold `FOR UPDATE`, which conflicts with the check's `FOR KEY SHARE`, and the insert would wait. That is exactly the case the check exists to stop. The check needs only the **referenced key** to keep existing until the child's transaction ends. A `FOR SHARE` lock would also block every non-key update of the parent, so the status change in step 1 would wait for the webhook's transaction, serialising unrelated work on hot parent rows. `FOR KEY SHARE` blocks only what would break the reference. ## Choosing a strength when you lock explicitly - **`FOR NO KEY UPDATE`**: you will update non-key columns. It excludes other updaters and `FOR SHARE` lockers but lets foreign-key checks through. Most read-then-update code wants this. - **`FOR UPDATE`**: you will delete the row or change a referenced key. Using it otherwise needlessly stalls inserts of child rows. - **`FOR SHARE`**: you need the row's values to stay unchanged while you work, and other readers may lock it too. - **`FOR KEY SHARE`**: you only need the row to keep existing with the same key. A common production surprise is code that writes `SELECT ... FOR UPDATE` on a parent row before updating one of its status columns, and then sees inserts of child rows stall behind it. Switching that clause to `FOR NO KEY UPDATE` removes the conflict without weakening protection against concurrent updates. ## Where row locks live: the tuple header and MultiXacts PostgreSQL does not keep row locks in shared memory, so there is **no limit** on how many rows a transaction can lock and **no lock escalation**. The lock is written into the row's tuple header, which is why `SELECT ... FOR UPDATE` causes disk writes. When **more than one transaction** locks the same row at once, for example several webhooks inserting events for one email, or a key-share lock alongside a no-key update, the header cannot hold all their IDs. PostgreSQL then stores a **MultiXact ID** in `xmax` and keeps the member list in `pg_multixact`; `pg_get_multixact_members()` decodes one. Hot parent rows referenced by many concurrent inserts therefore consume MultiXact IDs, which vacuum must eventually freeze. MultiXact wraparound is the vacuum-wraparound leaf's subject, the tuple-header layout is the visibility leaf's, and what a locking clause does under `REPEATABLE READ` when the row changed after the snapshot belongs to the isolation leaf.
- Why can a hot parent row make PostgreSQL create many MultiXact IDs?A tuple header has room for one locking transaction ID in `xmax`. When several transactions hold row locks on the same row at once, such as many concurrent child inserts each taking `FOR KEY SHARE` on one parent, PostgreSQL stores a MultiXact ID there instead and keeps the member list in `pg_multixact`. Heavy shared locking on hot parents therefore consumes MultiXact IDs, which vacuum must later freeze.
- When should explicit row locking in PostgreSQL use FOR NO KEY UPDATE instead of FOR UPDATE?Whenever the transaction will update the row without deleting it or changing a referenced key. `FOR NO KEY UPDATE` still excludes other updaters and `FOR SHARE` lockers, but it lets concurrent foreign-key checks (`FOR KEY SHARE`) through, so inserts of referencing rows are not serialised behind your transaction. Keep `FOR UPDATE` for rows you will delete or whose key you will change.
- FOR UPDATE and FOR NO KEY UPDATE are just two spellings of one lock
- Foreign-key checks lock the referenced parent row with FOR SHARE
- Any UPDATE of a parent row blocks inserts of rows that reference it
- PostgreSQL keeps row locks in shared memory and escalates them to table locks
- A FOR SHARE lock on a row blocks plain SELECTs of that row