Skip to content

Lesson 21 of 29Transactions and concurrency

Locks, Deadlocks and Safe Concurrency

Row locks, SKIP LOCKED job queues, optimistic version checks, deadlocks, the DDL lock queue and advisory locks, with the queries to find what is blocking what.

24 min read0/4 questions

A background worker sends the same receipt email twice because two workers picked up the same job. A two-second ALTER TABLE takes the whole site down for four minutes. A batch job fails every night with deadlock detected, and someone adds a retry that makes it worse. All three are locking problems, and none of them shows up on a laptop with one user. This lesson covers the locks you take on purpose, the locks the database takes for you, how deadlocks form, and how to find the session that is blocking everyone else.

Locks you get without asking

Thanks to MVCC (see Isolation levels and anomalies), plain reads take no row locks in Postgres. A SELECT never waits for an UPDATE, and an UPDATE never waits for a SELECT. What does wait is writer against writer on the same row: an UPDATE or DELETE locks each row it changes until the transaction ends, and a second writer to that row queues behind it.

That queueing is usually what you want. It is what makes UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock > 0 safe: the second request waits, then re-reads the committed row and re-checks the WHERE. It is also why long transactions hurt. Every row a transaction updated stays locked until it commits, however long that takes.

Row locks on purpose: FOR UPDATE and friends

When your logic cannot be one statement, you read a row, decide in code, then write. To stop another transaction changing the row in between, lock it as you read it:

BEGIN;
SELECT balance FROM accounts WHERE id = 42 FOR UPDATE;   -- others now wait to change row 42
-- application logic: check limits, compute fees ...
UPDATE accounts SET balance = balance - 2500 WHERE id = 42;
COMMIT;                                                   -- lock released here

Postgres has four row-lock strengths. Stronger ones conflict with more:

ClauseUse it whenBlocks
FOR UPDATEYou will delete the row or change its keyevery other row lock
FOR NO KEY UPDATEYou will update non-key columns (a plain UPDATE takes this)FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE
FOR SHARENobody may change the row until you finishFOR UPDATE, FOR NO KEY UPDATE
FOR KEY SHARETaken by foreign key checks on the parent rowFOR UPDATE only

The split exists for foreign keys. Inserting an order_items row takes FOR KEY SHARE on the referenced product, so updating that product's price (FOR NO KEY UPDATE) does not block checkouts. In practice, use FOR NO KEY UPDATE when you only update columns, and FOR UPDATE otherwise.

Two modifiers change what happens when the row is already locked:

  • NOWAIT fails at once with SQLSTATE 55P03 (lock_not_available) instead of waiting. Good for "someone else is editing this record" in a UI.
  • SKIP LOCKED silently skips locked rows. Wrong for business data (you would get an inconsistent view), and exactly right for queues.

SKIP LOCKED: a job queue in one query

Many Postgres-backed job queues (and plenty of in-house ones) claim work like this:

WITH next AS (
    SELECT id FROM jobs
    WHERE status = 'queued' AND run_at <= now()
    ORDER BY run_at
    LIMIT 10
    FOR UPDATE SKIP LOCKED
)
UPDATE jobs SET status = 'running', locked_by = $1, locked_at = now()
FROM next
WHERE jobs.id = next.id
RETURNING jobs.id, jobs.kind, jobs.payload;
Two workers claiming jobs
Worker APostgresWorker Bclaim 10 jobs ... FOR UPDATE SKIP LOCKEDsame query, a millisecond laterjobs 11 to 20COMMIT, then run the jobsUPDATE jobs SET status = 'done'

Worker A locks the first 10 queued jobs it finds and marks them running.

1/5

An index on (status, run_at), often partial with WHERE status = 'queued', keeps the claim fast as the table grows. Delete or archive finished jobs, or the table fills with dead rows.

SQLite has no FOR UPDATE, but it has one writer at a time, so a single UPDATE ... RETURNING that picks and claims a row is already safe:

Pythonclaim.py
from shopdb import connect, show db = connect()db.executescript("""CREATE TABLE jobs ( id INTEGER PRIMARY KEY, kind TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'queued', worker TEXT);INSERT INTO jobs (kind) VALUES ('send_receipt'), ('send_receipt'), ('resize_image');""") def claim(worker): with db: row = db.execute( """UPDATE jobs SET status = 'running', worker = ? WHERE id = (SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1) RETURNING id, kind""", (worker,), ).fetchone() return row for w in ["w1", "w2", "w3", "w4"]: print(w, "claimed", claim(w))show(db, "SELECT * FROM jobs")
Output
Press Run (⌘ Enter) to see what happens.

Optimistic concurrency: check, do not lock

Row locks are pessimistic: you assume a conflict and block others in advance. That cannot work across user think-time. An admin opens the edit form, goes to lunch, and you cannot hold a lock for an hour. The optimistic approach takes no lock. Each row carries a version, the client sends back the version it read, and the update only succeeds if nobody changed the row since:

Pythonoptimistic.py
from shopdb import connect, show db = connect()db.execute("ALTER TABLE products ADD COLUMN version INTEGER NOT NULL DEFAULT 1") def load(product_id): return db.execute("SELECT id, price_cents, version FROM products WHERE id = ?", (product_id,)).fetchone() def save_price(product_id, new_price, seen_version): with db: cur = db.execute( """UPDATE products SET price_cents = ?, version = version + 1 WHERE id = ? AND version = ?""", (new_price, product_id, seen_version), ) return "200 saved" if cur.rowcount == 1 else "409 conflict: someone else changed it" # Two admins open the edit form for the headphones at the same time._, _, v_ana = load(6)_, _, v_ben = load(6) print("Ana: ", save_price(6, 27900, v_ana)) # sale priceprint("Ben: ", save_price(6, 31900, v_ben)) # still holding version 1 # Ben's form reloads, he sees Ana's change, and decides again._, price, v_ben = load(6)print("Ben reloads: price", price, "version", v_ben)print("Ben: ", save_price(6, 25900, v_ben))show(db, "SELECT id, name, price_cents, version FROM products WHERE id = 6")
Output
Press Run (⌘ Enter) to see what happens.

The WHERE version = ? makes the check and the write one atomic statement. A rowcount of 0 means you lost the race: return 409 Conflict to a user, or reload and retry in a background job. HTTP has a matching pattern: send the version as an ETag, and have clients send If-Match, answering 412 Precondition Failed on a mismatch. ORMs build this in, such as SQLAlchemy's version_id_col, which raises StaleDataError.

Which one wins? Optimistic is better when conflicts are rare, when the read and write are far apart in time, or across an HTTP round trip. It costs nothing until a conflict happens. Pessimistic is better when conflicts are common (a hot counter, the last ticket for a concert), because optimistic would make most attempts fail and retry, and when retrying is expensive. Most apps use both: versions on user-edited records, FOR UPDATE or atomic updates for short server-side critical sections.

Predict the outputPython

Product 6 has version 1. Both calls use the save_price function above. What is printed?

print(save_price(6, 27900, 1))
print(save_price(6, 27900, 1))
Need a nudge? Hints walk you through it.

Deadlocks

A deadlock is a cycle of waits. Transaction 1 locks order 5 and wants order 9. Transaction 2 locked order 9 and wants order 5. Neither can ever proceed. The usual cause at work is two code paths that update the same rows in a different order, such as a batch job that updates a list of orders while a request handler updates two of them in reverse.

How a deadlock forms
Transaction 1PostgresTransaction 2UPDATE orders ... WHERE id = 5UPDATE orders ... WHERE id = 9UPDATE orders ... WHERE id = 9 (waits)UPDATE orders ... WHERE id = 5 (waits)ERROR: deadlock detected (40P01)

T1 locks row 5.

1/5

Postgres does not detect deadlocks instantly. Checking for cycles is expensive, so a waiting backend only checks after deadlock_timeout. InnoDB checks immediately by default and rolls back the transaction that is cheapest to undo. Either way, the victim's work is gone and the error must be retried, as covered in Isolation levels and anomalies. Here is the cycle check, in miniature:

Pythondeadlock.py
# A tiny lock manager: who holds each row lock, and who waits for whom.def run(schedule): holder = {} # row -> transaction holding its lock waiting = {} # transaction -> row it is waiting for for tx, op, row in schedule: if op == "commit": freed = [r for r, t in holder.items() if t == tx] for r in freed: del holder[r] print(f"{tx} commits, releasing {', '.join(freed)}") for w, r in list(waiting.items()): if r in freed: holder[r] = w del waiting[w] print(f" {w} wakes up and gets {r}") continue owner = holder.get(row) if owner is None or owner == tx: holder[row] = tx print(f"{tx} locks {row}") continue waiting[tx] = row print(f"{tx} waits for {row} (held by {owner})") # Follow the chain of waits. Getting back to tx means a cycle: a deadlock. chain, cur = [tx], owner while cur != tx and cur in waiting: chain.append(cur) cur = holder[waiting[cur]] if cur == tx: print(" DEADLOCK:", " waits for ".join(chain + [tx])) print(f" abort {tx} with 40P01; its locks are released") for r in [r for r, t in holder.items() if t == tx]: del holder[r] del waiting[tx] return print("finished, no deadlock") print("Opposite order:")run([ ("T1", "lock", "order 5"), ("T2", "lock", "order 9"), ("T1", "lock", "order 9"), ("T2", "lock", "order 5"),]) print("\nSame order (sort the ids first):")run([ ("T1", "lock", "order 5"), ("T2", "lock", "order 5"), ("T1", "lock", "order 9"), ("T1", "commit", None), ("T2", "lock", "order 9"), ("T2", "commit", None),])
Output
Press Run (⌘ Enter) to see what happens.

When both transactions take locks in the same order, the second one simply waits for the first. Waiting is fine; cycles are not. The prevention list:

  1. Lock in a consistent order. Sort ids before updating many rows: UPDATE ... WHERE id = ANY($1) does not promise an order, so lock first with SELECT id FROM orders WHERE id = ANY($1) ORDER BY id FOR UPDATE.
  2. Keep transactions short and touch as few rows as possible. Big batch jobs should work in small chunks with a commit after each.
  3. Retry on 40P01, with backoff. Deadlocks under load are normal in small numbers. Rising numbers mean a code path with the wrong order.
  4. Read the log. Postgres logs both queries in the deadlock. That message tells you which two code paths to fix.

The DDL lock queue

Schema changes take table locks. Most ALTER TABLE forms take ACCESS EXCLUSIVE, the strongest lock, which conflicts with everything, including plain SELECT (which holds ACCESS SHARE on the table). Adding a nullable column only needs that lock for a few milliseconds. The danger is waiting for it:

A fast migration that causes an outage
Analytics queryPostgresMigrationApp requestsSELECT ... FROM orders (runs 5 minutes)ALTER TABLE orders ADD COLUMN note textSELECT * FROM orders WHERE id = ...every query on orders is stuckfix: SET lock_timeout = '3s'; retry

A slow report holds ACCESS SHARE on orders. Harmless on its own.

1/5

That is why migration tooling sets lock_timeout and why you check for long-running queries before deploying schema changes. Migrations at scale without downtime builds the full playbook on this.

Advisory locks

Sometimes the thing you want to lock is not a row: "only one instance of the nightly invoice job may run", or "only one process may rebuild this cache". Advisory locks are named locks that mean nothing to Postgres except what your code agrees they mean. They are keyed by a bigint, so hash a name to get one:

BEGIN;
SELECT pg_try_advisory_xact_lock(hashtext('nightly-invoices'));  -- true or false, no waiting
-- if false: another instance is running, so exit
-- if true: do the work; the lock is released at COMMIT or ROLLBACK
COMMIT;

The _xact_ versions release automatically at the end of the transaction, which makes them hard to leak. The session-level versions (pg_advisory_lock, pg_advisory_unlock) stay held until you unlock or disconnect. Those break behind a pooler in transaction mode (PgBouncer's common setting), because your next transaction may run on a different server connection.

Finding what is blocking what

When requests pile up, these are the queries you run first:

-- Who is waiting, who is blocking them, and for how long
SELECT pid,
       pg_blocking_pids(pid)        AS blocked_by,
       state,
       wait_event_type,
       now() - xact_start           AS xact_age,
       left(query, 80)              AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0
   OR state = 'idle in transaction'
ORDER BY xact_age DESC;
 
-- Stop the blocker: cancel its current query, or end its session
SELECT pg_cancel_backend(12345);
SELECT pg_terminate_backend(12345);

pg_locks shows every lock held and requested, if you need the detail. The settings that stop one bad session from hurting everyone:

  • lock_timeout: the longest a statement waits for a lock. Set it in migrations and in latency-sensitive request paths.
  • statement_timeout: the longest any statement may run. Set a default per app role (a few seconds for a web API), and raise it per session for jobs that need longer.
  • idle_in_transaction_session_timeout: kills sessions that hold a transaction open while doing nothing.
  • log_lock_waits: logs any lock wait longer than deadlock_timeout, so you see contention before it becomes an outage.

SQLite: one writer for the whole file

SQLite locks the database, not rows. Any number of connections can read, but only one can write at a time. A transaction started with plain BEGIN (deferred) only asks for the write lock at its first write. BEGIN IMMEDIATE takes it at the start. A connection that cannot get the lock waits up to its busy timeout (Python's timeout= argument, 5 seconds by default) and then fails with database is locked:

Pythonsqlite_locks.py
import os, sqlite3, timefrom shopdb import connect PATH = "/tmp/shop.db"for f in (PATH, PATH + "-journal", PATH + "-wal", PATH + "-shm"): if os.path.exists(f): os.remove(f)connect(PATH).close() a = sqlite3.connect(PATH, autocommit=True, timeout=0)b = sqlite3.connect(PATH, autocommit=True, timeout=0.3) # busy_timeout of 300 ms def try_sql(conn, name, sql): start = time.monotonic() try: conn.execute(sql) print(f"{name}: {sql} -> ok") except sqlite3.OperationalError as err: print(f"{name}: {sql} -> {err} after {(time.monotonic() - start) * 1000:.0f} ms") print("1. Two writers: SQLite allows one write transaction at a time")try_sql(a, "A", "BEGIN IMMEDIATE")try_sql(b, "B", "BEGIN IMMEDIATE") # waits up to its busy timeout, then gives uptry_sql(b, "B", "SELECT count(*) FROM orders") # reading is still finetry_sql(a, "A", "COMMIT")try_sql(b, "B", "BEGIN IMMEDIATE") # free nowtry_sql(b, "B", "COMMIT") print("2. Deferred transactions that read first, then write")try_sql(a, "A", "BEGIN")try_sql(b, "B", "BEGIN")try_sql(a, "A", "SELECT stock FROM products WHERE id = 1")try_sql(b, "B", "SELECT stock FROM products WHERE id = 1")try_sql(a, "A", "UPDATE products SET stock = 11 WHERE id = 1")try_sql(b, "B", "UPDATE products SET stock = 11 WHERE id = 1") # A holds the write locktry_sql(a, "A", "COMMIT") # A must wait for B's read lock to gotry_sql(b, "B", "ROLLBACK") # one side has to give uptry_sql(a, "A", "COMMIT")
Output
Press Run (⌘ Enter) to see what happens.

Part 1 shows the busy timeout: B waited about 300 ms, then gave up. Part 2 is SQLite's own deadlock. Both transactions hold read locks, A has the write lock, and A cannot commit until B's read lock is gone. Notice that B failed after 0 ms despite its timeout: SQLite saw that waiting could never succeed and refused at once. This is why the standard advice for SQLite apps is BEGIN IMMEDIATE for any transaction that will write: it fails or waits at the start, before you have read anything, so this cycle cannot form. Pair it with WAL mode and a sensible busy timeout.

Quick check
A migration runs ALTER TABLE orders ADD COLUMN note text while a 10-minute report is reading orders. What happens to ordinary app queries on orders?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/6 matched

Match each situation to the tool that fits.

Choose an item, then its match on the other side.
Put it in order5 steps

Requests on the orders API are timing out and the pool is full. Put the response in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
row lock
A lock on one row, taken by UPDATE and DELETE or explicitly with SELECT ... FOR UPDATE, held until the transaction ends.
SKIP LOCKED
A row-lock option that skips rows other transactions have locked. The standard way to build a job queue on Postgres.
optimistic concurrency
No lock while reading. The write checks a version column and fails, with a 409 or a retry, if the row changed.
deadlock
A cycle of transactions each waiting for a lock another holds. The database aborts one with SQLSTATE 40P01.
ACCESS EXCLUSIVE
The strongest Postgres table lock, taken by most ALTER TABLE forms. It conflicts with every other lock, including plain reads.
lock_timeout
The longest a statement waits to acquire a lock before failing. Essential in migrations.
advisory lock
An application-defined lock on a number, such as a hashed job name, used to make sure only one process does something.