Skip to content
Visual explainer 3h to learn 4 steps

Locks, SELECT FOR UPDATE & deadlocks

Prevent lost updates and diagnose lock waits and deadlocks.

By Invicly Tech, , in SQL & PostgreSQL. About 12 minutes to read.

Topic 23 of 30

In short

Row locks stop two transactions from changing the same row at once. SELECT ... FOR UPDATE locks rows you plan to change, preventing lost updates. Deadlocks happen when two transactions wait on each other; Postgres aborts one.

Explained simply

MVCC lets readers and writers work side by side, but two writers changing the same row must take turns. Postgres uses locks for that. A lock is like an "in use" sign: while one transaction holds it, others that need a conflicting lock wait in line.

Most locks are taken for you. UPDATE and DELETE lock the rows they change until the transaction ends. ALTER TABLE locks the whole table. You can also ask for a row lock on purpose with SELECT ... FOR UPDATE, when you plan to read a row and then change it.

A deadlock is a traffic jam with no way out: transaction A waits for a row B holds, while B waits for a row A holds. Neither can move. Postgres notices after about a second and cancels one of them with an error, so the other can finish.

The best protection against lock trouble is boring: keep transactions short, lock rows in the same order everywhere, and never wait for something slow while holding a lock.

Press Play on a diagram to walk through it one step at a time.

SequencePreventing a lost update with FOR UPDATE
Session A
Postgres
Session B
  1. 1SELECT balance ... FOR UPDATE
    Session A to Postgres: SELECT balance ... FOR UPDATE
  2. 2100, row locked
    Postgres to Session A: 100, row locked
  3. 3SELECT balance ... FOR UPDATE
    Session B to Postgres: SELECT balance ... FOR UPDATE
  4. 4waits for A's lock
    Postgres to Session B: waits for A's lock
  5. 5UPDATE balance = 70; COMMIT
    Session A to Postgres: UPDATE balance = 70; COMMIT
  6. 6lock granted: 70
    Postgres to Session B: lock granted: 70
  7. 7UPDATE balance = 50; COMMIT
    Session B to Postgres: UPDATE balance = 50; COMMIT
SequenceHow a deadlock forms and is resolved
Txn A
Postgres
Txn B
  1. 1UPDATE account 1 (locks row 1)
    Txn A to Postgres: UPDATE account 1 (locks row 1)
  2. 2UPDATE account 2 (locks row 2)
    Txn B to Postgres: UPDATE account 2 (locks row 2)
  3. 3UPDATE account 2: waits for B
    Txn A to Postgres: UPDATE account 2: waits for B
  4. 4UPDATE account 1: waits for A
    Txn B to Postgres: UPDATE account 1: waits for A
  5. 5After 1s: ERROR 40P01 deadlock detected
    Postgres to Txn B: After 1s: ERROR 40P01 deadlock detected
  6. 6Lock on row 2 granted, A continues
    Postgres to Txn A: Lock on row 2 granted, A continues

In depth

Table-level lock modes

Every statement takes a lock on each table it touches. There are eight modes; you only need to recognise a few. ACCESS SHARE is taken by SELECT and conflicts only with ACCESS EXCLUSIVE. ROW SHARE is taken by SELECT ... FOR UPDATE or FOR SHARE. ROW EXCLUSIVE is taken by INSERT, UPDATE and DELETE; these do not conflict with each other, because row locks sort out the details. SHARE UPDATE EXCLUSIVE is taken by VACUUM, ANALYZE and CREATE INDEX CONCURRENTLY. SHARE is taken by plain CREATE INDEX and blocks writes. ACCESS EXCLUSIVE is taken by most ALTER TABLE forms, DROP, TRUNCATE and VACUUM FULL, and blocks everything, even SELECT.

Table locks are held until the transaction ends, not until the statement ends. A migration that runs ALTER TABLE and then a slow backfill in the same transaction keeps everyone out for the whole time.

LayersCommon table lock modes, weakest to strongest
  1. 1
    ACCESS SHARE

    SELECT; blocked only by ACCESS EXCLUSIVE

  2. 2
    ROW SHARE

    SELECT ... FOR UPDATE / FOR SHARE

  3. 3
    ROW EXCLUSIVE

    INSERT, UPDATE, DELETE

  4. 4
    SHARE UPDATE EXCLUSIVE

    VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY

  5. 5
    SHARE

    CREATE INDEX; blocks writes

  6. 6
    ACCESS EXCLUSIVE

    Most ALTER TABLE, DROP, TRUNCATE; blocks all

Row locks: four strengths plus NOWAIT and SKIP LOCKED

Row locks come in four strengths. FOR UPDATE is the strongest: you intend to change or delete the row. FOR NO KEY UPDATE is what a normal UPDATE takes when it does not change a key column. FOR SHARE says "do not change this row while I look at it". FOR KEY SHARE is the weakest; foreign key checks use it so that inserting a child does not block updates of the parent's non-key columns.

Two options change what happens when a row is already locked. NOWAIT fails immediately with an error instead of waiting. SKIP LOCKED silently skips locked rows, which is perfect for job queues: many workers can each grab different jobs without waiting on each other.

Row locks are stored in the row itself (in xmax), not in memory, so a transaction can lock millions of rows cheaply. That also means pg_locks does not list every locked row, only the transactions someone is waiting for.

  • FOR UPDATE > FOR NO KEY UPDATE > FOR SHARE > FOR KEY SHARE
  • NOWAIT: error at once instead of waiting
  • SKIP LOCKED: ignore rows others hold (queues)
  • FOR UPDATE OF t locks rows of one table in a join

Preventing lost updates: four options

A lost update happens when two transactions read the same value, each computes a new value in the app, and both write it back. There are four standard fixes.

Atomic update: do the math in SQL. UPDATE accounts SET balance = balance - 30 WHERE id = 1 AND balance >= 30. No read is needed, and the row count tells you whether it worked. This is the simplest and fastest when it fits.

Pessimistic locking: SELECT ... FOR UPDATE, then UPDATE in the same transaction. Others wait, so the read is always fresh. Good when the logic needs app code between read and write.

Optimistic locking: add a version column. UPDATE ... SET ..., version = version + 1 WHERE id = 1 AND version = 7. If 0 rows change, someone else won; reload and retry. Good for edits that span a user's think time, where holding a lock is impossible.

Stricter isolation: Repeatable Read or Serializable turn the lost update into an error that you retry.

CompareLost update fixes
Atomic UPDATE
  • Math in SQL
  • No extra round trip
  • Check row count
  • Only when logic fits SQL
FOR UPDATE
  • Lock, read, write, commit
  • Others wait
  • Logic can live in the app
  • Keep the transaction short
Version column
  • No lock held while user thinks
  • WHERE version = n
  • 0 rows = conflict, retry
  • Common in web forms and APIs

Deadlocks and finding who blocks whom

When a lock wait lasts longer than deadlock_timeout (default 1 second), Postgres checks for a cycle of waiters. If it finds one, it cancels one transaction with SQLSTATE 40P01, "deadlock detected", and the server log shows which processes waited for which locks and the statements involved. The app should roll back and retry.

Prevention: lock rows in a consistent order. If a transfer always locks the lower account id first (SELECT ... WHERE id IN (1, 2) ORDER BY id FOR UPDATE), two transfers can never wait on each other in a circle.

For ordinary waits, look at pg_stat_activity: wait_event_type = 'Lock' means a session is waiting, and pg_blocking_pids(pid) lists who blocks it. Follow the chain to the root blocker, which is often a session in state "idle in transaction". pg_cancel_backend(pid) cancels its current query; pg_terminate_backend(pid) ends the session. Turn on log_lock_waits to log waits longer than deadlock_timeout, and set lock_timeout so statements give up instead of waiting forever.

  • 40P01 = deadlock detected; retry
  • Lock in a fixed order, e.g. ORDER BY id FOR UPDATE
  • pg_blocking_pids(pid) shows the blockers
  • log_lock_waits = on, plus lock_timeout

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Inspect locks in pg_locks~45m
  2. 2
    Prevent lost updates with SELECT FOR UPDATE~45m
  3. 3
    Reproduce and read a deadlock~45m
  4. 4
    Keep transactions short~45m

Key points

  • Lost update: two sessions read 100, both write their own result, one change vanishes.
  • FOR UPDATE makes other writers wait until you commit or roll back.
  • Lock rows in a consistent order, such as by id, to avoid deadlocks.
  • Postgres detects deadlocks after deadlock_timeout and cancels one transaction.
  • Keep transactions short so locks are held briefly.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
-- app checks balance >= 30
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
COMMIT;

-- who is waiting on whom?
SELECT pid, pg_blocking_pids(pid) AS blocked_by, state, query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;

A job queue with FOR UPDATE SKIP LOCKED

Several workers pull jobs from one table. With plain FOR UPDATE, all workers would wait on the same first row. Step 1: each worker selects the oldest pending job with FOR UPDATE SKIP LOCKED, so rows locked by other workers are skipped. Step 2: it marks the job as running in the same statement and commits at once, so the lock is short. Step 3: it does the work outside the transaction and records the result. A partial index on pending jobs keeps the query fast.

sql
CREATE INDEX jobs_pending_idx ON jobs (run_at) WHERE status = 'pending';

UPDATE jobs SET status = 'running', started_at = now()
WHERE id = (
  SELECT id FROM jobs
  WHERE status = 'pending' AND run_at <= now()
  ORDER BY run_at
  FOR UPDATE SKIP LOCKED
  LIMIT 1
)
RETURNING id, payload;

Finding the root blocker during an incident

The app is timing out and many sessions are waiting. Step 1: list waiting sessions with their blockers using pg_blocking_pids. Step 2: the blockers are all pid 4242, which is "idle in transaction" for 25 minutes: a script opened a transaction and never committed. Step 3: terminate that session; its transaction rolls back and the queue drains. Step 4: set idle_in_transaction_session_timeout so it cannot happen again.

sql
SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type,
       now() - xact_start AS xact_age, state, left(query, 60) AS query
FROM pg_stat_activity
WHERE wait_event_type = 'Lock' OR state = 'idle in transaction'
ORDER BY xact_start;

SELECT pg_terminate_backend(4242);

ALTER DATABASE shop SET idle_in_transaction_session_timeout = '5min';

Quick reference

  • SELECT ... FOR UPDATE locks rows until COMMIT or ROLLBACK
  • FOR UPDATE SKIP LOCKED: queue workers skip rows others hold
  • FOR UPDATE NOWAIT: error at once if the row is locked
  • SET lock_timeout = '3s'; give up instead of waiting forever
  • SELECT pid, pg_blocking_pids(pid) FROM pg_stat_activity WHERE wait_event_type = 'Lock';
  • pg_cancel_backend(pid) stops a query; pg_terminate_backend(pid) ends the session
  • Deadlock = SQLSTATE 40P01; lock rows in a consistent order to avoid it
  • Optimistic lock: UPDATE ... SET version = version + 1 WHERE id = $1 AND version = $2

Common mistakes

  • Read, compute in the app, then write without a lock: classic lost update.
  • Locking rows in different orders in different code paths.
  • Calling slow external services while holding locks.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which lock does a plain SELECT take on a table?

Question 2

2Ten workers poll the same jobs table. Which clause lets each grab a different job without waiting?

Question 3

3Two transfers lock accounts in opposite orders and one fails with 40P01. What is the best lasting fix?

Question 4

4An UPDATE ... WHERE id = 1 AND version = 7 reports 0 rows updated. What does that mean with optimistic locking?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Rewrite this lost-update-prone code as one safe statement: SELECT qty FROM stock WHERE sku = 'A1'; then in the app qty = qty - 3; then UPDATE stock SET qty = (the new value) WHERE sku = 'A1'.

  2. Exercise 2medium

    Reproduce a deadlock in two psql sessions with two rows of accounts, and read the error message.

  3. Exercise 3hard

    Write a transfer of 30 from account 1 to account 2 that cannot deadlock with a concurrent transfer the other way, and that refuses to overdraw.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Does SELECT ever block in PostgreSQL?
Only when something holds an ACCESS EXCLUSIVE lock on the table, such as most ALTER TABLE commands, TRUNCATE or VACUUM FULL. Normal writes never block plain SELECTs.
What is the difference between FOR UPDATE and FOR SHARE?
FOR UPDATE is exclusive: only one transaction can hold it on a row. FOR SHARE lets several transactions hold it at once, but blocks anyone who wants to update or delete the row.
Should I use LOCK TABLE?
Rarely. It locks the whole table and hurts concurrency. Row locks with FOR UPDATE, or an advisory lock with pg_advisory_xact_lock, almost always fit better.
What is an advisory lock?
A lock on a number you choose rather than on a row or table, taken with pg_advisory_lock or pg_advisory_xact_lock. Apps use it to make sure only one worker runs a job at a time.

Go deeper

ShareXLinkedInWhatsApp