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.
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 herePostgres has four row-lock strengths. Stronger ones conflict with more:
| Clause | Use it when | Blocks |
|---|---|---|
FOR UPDATE | You will delete the row or change its key | every other row lock |
FOR NO KEY UPDATE | You will update non-key columns (a plain UPDATE takes this) | FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE |
FOR SHARE | Nobody may change the row until you finish | FOR UPDATE, FOR NO KEY UPDATE |
FOR KEY SHARE | Taken by foreign key checks on the parent row | FOR 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:
NOWAITfails at once with SQLSTATE55P03(lock_not_available) instead of waiting. Good for "someone else is editing this record" in a UI.SKIP LOCKEDsilently 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;Worker A locks the first 10 queued jobs it finds and marks them running.
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:
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:
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.
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))
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.
T1 locks row 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:
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:
- Lock in a consistent order. Sort ids before updating many rows:
UPDATE ... WHERE id = ANY($1)does not promise an order, so lock first withSELECT id FROM orders WHERE id = ANY($1) ORDER BY id FOR UPDATE. - Keep transactions short and touch as few rows as possible. Big batch jobs should work in small chunks with a commit after each.
- Retry on
40P01, with backoff. Deadlocks under load are normal in small numbers. Rising numbers mean a code path with the wrong order. - 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 slow report holds ACCESS SHARE on orders. Harmless on its own.
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 thandeadlock_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:
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.
ALTER TABLE orders ADD COLUMN note text while a 10-minute report is reading orders. What happens to ordinary app queries on orders?Match each situation to the tool that fits.
Requests on the orders API are timing out and the pool is full. Put the response in order.
- Tap the steps below in the right order.
- 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.