Locking & Concurrency Control
- Explain which locks Postgres and InnoDB take for reads, writes, foreign key checks and DDL
- Choose between pessimistic locking, optimistic version checks and single-statement conditional updates for a given contention level
- Build queue-style work distribution with
FOR UPDATE SKIP LOCKED - Prevent deadlocks with consistent lock ordering and diagnose them when they happen
- Design around a hot row, such as the balance of a merchant receiving thousands of payments per second
TL;DR
- MVCC means plain reads take no row locks. Writers lock rows;
SELECT … FOR UPDATElets readers lock too. Postgres has four row-lock strengths; InnoDB locks index records and gaps. - Conditional updates (
UPDATE … SET balance = balance - $2 WHERE id = $1 AND balance >= $2) are the cheapest correct way to enforce single-row invariants: one statement, one lock, no retries. - Optimistic locking (
WHERE version = $n) suits low-contention, user-paced edits; under high contention it degrades into retry storms. SKIP LOCKEDturns a table into a work queue;NOWAITfails fast instead of queueing.- Deadlocks come from acquiring the same locks in different orders. Lock in a canonical order (ascending account id), keep transactions short, retry on
40P01. - A hot row caps throughput at roughly 1 / (lock hold time). Mitigate by shortening hold time, appending entries instead of updating, splitting the row into buckets, or batching credits.
- DDL takes strong table locks and waits in the same queue as your traffic: always set
lock_timeoutfor migrations.
Why it matters
Contention is where correctness and performance collide. Payments for a large merchant all credit one balance row. Flash sales decrement one stock row. Payout jobs, outbox relays and reconciliation workers compete for the same pending rows. Get locking wrong and you see either corrupted state (double-spends, oversold stock, see Transactions & Isolation Levels) or a platform that collapses exactly at peak: lock waits pile up, connection pools exhaust, timeouts cascade into retries that make it worse.
Core concepts
Row-level locks
Postgres row-lock modes, weakest to strongest:
| Mode | Taken by | Conflicts with |
|---|---|---|
FOR KEY SHARE | Foreign key checks on the referenced (parent) row | FOR UPDATE |
FOR SHARE | Explicit SELECT … FOR SHARE | FOR NO KEY UPDATE, FOR UPDATE |
FOR NO KEY UPDATE | UPDATE that does not change key columns; explicit request | FOR SHARE, FOR NO KEY UPDATE, FOR UPDATE |
FOR UPDATE | DELETE, UPDATE of a unique/key column, explicit request | All of the above |
The split between key and non-key locks exists so that inserting an order_line (which takes FOR KEY SHARE on its orders row) does not block updating orders.status. Postgres records row locks in the tuple header, not in a memory table, so locking millions of rows does not exhaust memory and there is no lock escalation (SQL Server, by contrast, escalates to table locks). The cost is that locking a row dirties its page.
InnoDB locks index records, not rows as such:
- Record lock: on one index entry.
- Gap lock: on the gap between index entries, preventing inserts into it.
- Next-key lock: record plus the gap before it; the default for locking reads and DML under Repeatable Read, which is how InnoDB prevents phantoms.
- Insert intention lock: a gap lock taken by
INSERT, compatible with other inserts into the same gap at different positions.
Two InnoDB consequences surprise people. First, a locking statement locks every index record it scans, not only those that match: UPDATE payment SET … WHERE external_ref = ? without an index on external_ref locks the whole table's rows. Second, gap locks under Repeatable Read cause blocking and deadlocks on inserts into ranges other transactions have read with FOR UPDATE. Read Committed disables most gap locking (it remains for foreign key and duplicate-key checks), which is one reason many MySQL shops run payments at Read Committed.
Table-level locks
Every statement also takes a table lock. In Postgres the important modes are:
| Mode | Taken by | Blocks |
|---|---|---|
ACCESS SHARE | SELECT | Only ACCESS EXCLUSIVE |
ROW SHARE | SELECT … FOR UPDATE/SHARE | EXCLUSIVE, ACCESS EXCLUSIVE |
ROW EXCLUSIVE | INSERT, UPDATE, DELETE | SHARE and stronger |
SHARE UPDATE EXCLUSIVE | VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY, VALIDATE CONSTRAINT | Itself and stronger (not reads or writes) |
SHARE | CREATE INDEX (non-concurrent) | All writes |
ACCESS EXCLUSIVE | Most ALTER TABLE, DROP, TRUNCATE, VACUUM FULL | Everything, including SELECT |
The lock queue trap. Lock requests wait in order. If a migration's ALTER TABLE (wanting ACCESS EXCLUSIVE) waits behind one slow analytical SELECT, every new SELECT on that table queues behind the ALTER. A metadata change that would take 5 ms takes the table offline for as long as the slow query runs. MySQL has the same problem with metadata locks (MDL). Always set lock_timeout (for example SET lock_timeout = '3s') and retry. More in Zero-Downtime Schema Migrations.
Pessimistic locking: FOR UPDATE, NOWAIT, SKIP LOCKED
SELECT … FOR UPDATE locks the returned rows until the transaction ends. Use it when you must read, decide in application code, then write, and the decision depends on the latest value.
Variants (Postgres 9.5+, MySQL 8.0+):
NOWAIT: error immediately if any row is locked (Postgres55P03 lock_not_available, MySQL error 3572). Good for user-facing actions where waiting is worse than "try again": an agent opening a dispute case another agent is already editing.SKIP LOCKED: silently skip locked rows. This is how you build a reliable job queue on a table: each worker grabs different rows without blocking.
Allocating unique voucher codes during a campaign, with no two customers ever getting the same code:
WITH picked AS (
SELECT id
FROM voucher_code
WHERE campaign_id = $1 AND status = 'AVAILABLE'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED
)
UPDATE voucher_code v
SET status = 'ASSIGNED', customer_id = $2, assigned_at = now()
FROM picked
WHERE v.id = picked.id
RETURNING v.code;
SKIP LOCKED gives an inconsistent view by design (locked rows are invisible), so use it for "give me some available item", never for counting or reporting.
Optimistic locking with a version column
No lock is held while the user or client thinks. Each row carries a version; writes succeed only if the version is unchanged:
UPDATE cart
SET items = $3, version = version + 1, updated_at = now()
WHERE id = $1 AND version = $2;
-- rows affected = 0 => someone else changed it: reload, merge or return 409
This maps naturally to HTTP ETag / If-Match (see API Design). It is ideal for carts, profiles, back-office edits and ORM entities: conflicts are rare and resolution is "reload and reapply". It is a poor fit for hot rows: with 100 concurrent writers, 99 fail each round and retry, wasting work and adding latency.
Conditional (atomic) updates
When the invariant fits in one row, push the check into the UPDATE:
-- Wallet debit
UPDATE account
SET balance_minor = balance_minor - $2, version = version + 1
WHERE id = $1 AND balance_minor >= $2
RETURNING balance_minor;
-- Stock reservation
UPDATE inventory
SET available = available - $2, reserved = reserved + $2
WHERE sku_id = $1 AND warehouse_id = $3 AND available >= $2;
Zero rows affected means the check failed. This is correct at Read Committed in both engines (the row is locked and re-checked on its latest version), needs no retries, and holds the lock only for the statement plus commit. It should be your default for balances and stock. It does not cover invariants spanning several rows; for those, lock a common row or use Serializable.
Advisory locks
Postgres advisory locks are application-defined locks on a 64-bit key (or two 32-bit keys), unrelated to any row:
pg_advisory_xact_lock(key)/pg_try_advisory_xact_lock(key): released at transaction end. Prefer these.pg_advisory_lock(key)/pg_advisory_unlock(key): session-scoped; survive commits; leak if you forget to unlock.
Uses: ensure only one instance runs the nightly settlement for merchant 42, serialize operations per customer that do not map to one row, or guard a "create if not exists" across tables. MySQL offers GET_LOCK(name, timeout) and RELEASE_LOCK(name).
With PgBouncer in transaction pooling mode, consecutive transactions from your app may run on different server connections. Session-level advisory locks then stay held on a connection another client is using, or are "released" by a different client. Use the _xact_ variants, which are scoped to one transaction. Advisory locks also do not protect anything outside this one database; for cross-system coordination see Distributed Locks & Leases.
Deadlocks
A deadlock is a cycle in the wait-for graph. Two transfers between the same pair of accounts in opposite directions are the textbook case:
Detection:
- Postgres checks for cycles only after a transaction has waited
deadlock_timeout(default 1 s), then aborts one participant with40P01 deadlock_detected. Lock waits shorter than that are never examined, which keeps detection cheap. - InnoDB detects cycles immediately when a transaction would wait (
innodb_deadlock_detect = ON), rolls back the transaction with the fewest changes, and returns error 1213.SHOW ENGINE INNODB STATUSprints the latest deadlock.
Prevention:
- Consistent lock ordering. Lock accounts in ascending id order regardless of transfer direction. T2 then waits for A first and never holds B while waiting.
- Lock everything you need up front in one statement or at the start of the transaction, rather than escalating from
FOR SHAREtoUPDATElater. - Keep transactions short and do not wait on the network while holding locks.
- Index foreign keys and lookup columns, so statements lock only the rows they need (especially in InnoDB, where scans lock everything they touch).
- Retry deadlock victims; with good ordering, deadlocks become rare enough that retry is a safety net, not a strategy.
Hot rows
Every update to a row must wait for the previous updater to commit. If a transaction holds the row lock for h milliseconds (statement time plus commit, including the WAL flush and any synchronous replica round trip), that row can sustain at most about 1000 / h updates per second, no matter how many cores you have. Rough examples: with h ≈ 1 ms, ≈ 1,000/s; if the application does one more round trip after the update before committing, h might be ≈ 3 ms and the cap ≈ 300/s; with synchronous cross-zone replication, add the replication round trip to every commit.
A large e-commerce merchant or a utility company receiving bill payments can exceed this during a sale or a payday. Options:
- Shorten hold time first. Make the hot
UPDATEthe last statement beforeCOMMIT; send the transaction in one round trip (a single statement with CTEs, or a function); never call another service while the lock is held. - Append instead of update. Credits do not need a balance check. Insert immutable
ledger_entryrows (inserts do not conflict with each other) and compute the balance as "last snapshot plus entries since". This is what a double-entry ledger does anyway. - Bucketed sub-balances. Store
merchant_balance(merchant_id, bucket, balance_minor)with, say, 16 buckets; each credit picks a random bucket; the balance is theSUM. Debits (payouts) are the hard part: either run them in a single batch job that locks all buckets in order, or debit bucket by bucket. - Batch credits. Route payment events through a queue partitioned by merchant (see Message Queues & Event Streaming); one consumer per partition applies a hundred credits in one transaction, turning a hundred row updates into one.
- Settle asynchronously. Acquirers usually pay merchants on a schedule anyway, so the merchant's available balance can lag by seconds without business impact. Debits of customer wallets, by contrast, must be checked synchronously.
The asymmetry is the key insight to state in an interview: credits can be deferred and merged; debits need a synchronous check.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
Conditional UPDATE | One statement, no retries, minimal lock time | Single-row invariants only | Balance debits, stock decrements, state transitions (WHERE status = 'PENDING') |
SELECT … FOR UPDATE | Read-decide-write with arbitrary logic, works everywhere | Blocking, deadlock risk, longer lock hold | Multi-row checks, complex business rules |
FOR UPDATE SKIP LOCKED | Parallel workers without contention | Inconsistent view by design | Job queues, outbox relays, allocation from a pool |
NOWAIT | Fails fast, no pile-ups | Caller must handle immediate failure | User-facing edits, admin tools |
| Optimistic version column | No locks held across think time, scales for reads | Retry storms under contention | Low-contention edits, HTTP If-Match |
| Advisory lock | Locks concepts that are not rows | Easy to leak (session level); single-database only | Singleton jobs, per-entity serialization |
| Bucketed / append-only | Removes the hot-row ceiling | More complex reads and debits | Very hot aggregates (popular merchant, global counters) |
In practice
A transfer that locks in canonical order, debits conditionally, and records ledger entries:
package ledger
import (
"cmp"
"context"
"errors"
"slices"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
var (
ErrSameAccount = errors.New("cannot transfer to the same account")
ErrInsufficientFunds = errors.New("insufficient funds or unknown account")
)
type leg struct {
accountID int64
delta int64 // negative = debit
}
// Transfer moves amount (minor units) between accounts in one transaction.
func Transfer(ctx context.Context, pool *pgxpool.Pool, transferID string, from, to, amount int64) error {
if from == to {
return ErrSameAccount
}
legs := []leg{{from, -amount}, {to, amount}}
// Canonical order prevents deadlocks between A->B and B->A transfers.
slices.SortFunc(legs, func(a, b leg) int { return cmp.Compare(a.accountID, b.accountID) })
return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
for _, l := range legs {
tag, err := tx.Exec(ctx, `
UPDATE account
SET balance_minor = balance_minor + $2
WHERE id = $1 AND balance_minor + $2 >= 0`,
l.accountID, l.delta)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrInsufficientFunds
}
}
_, err := tx.Exec(ctx, `
INSERT INTO ledger_entry (transfer_id, account_id, amount_minor)
VALUES ($1, $2, $3), ($1, $4, $5)`,
transferID, from, -amount, to, amount)
return err
})
}
A UNIQUE (transfer_id, account_id) constraint on ledger_entry makes the transfer idempotent: a retried request fails with 23505 instead of moving money twice.
An outbox relay worker using SKIP LOCKED, safe to run with many replicas:
func RelayBatch(ctx context.Context, pool *pgxpool.Pool, publish func(context.Context, []byte) error) (int, error) {
n := 0
err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
rows, err := tx.Query(ctx, `
SELECT id, payload FROM outbox
WHERE published_at IS NULL
ORDER BY id
LIMIT 100
FOR UPDATE SKIP LOCKED`)
if err != nil {
return err
}
type msg struct {
id int64
payload []byte
}
var batch []msg
for rows.Next() {
var m msg
if err := rows.Scan(&m.id, &m.payload); err != nil {
return err
}
batch = append(batch, m)
}
if err := rows.Err(); err != nil {
return err
}
for _, m := range batch {
if err := publish(ctx, m.payload); err != nil {
return err // rollback: rows become available again
}
if _, err := tx.Exec(ctx, `UPDATE outbox SET published_at = now() WHERE id = $1`, m.id); err != nil {
return err
}
n++
}
return nil
})
return n, err
}
Publishing while holding row locks is acceptable here because only the relay touches these rows; consumers must still deduplicate, since a crash after publish but before commit re-sends the message (see Transactional Outbox & CDC).
Operational queries worth having in your runbook:
-- Who is blocking whom (Postgres 9.6+)
SELECT pid, pg_blocking_pids(pid) AS blocked_by, state,
now() - xact_start AS xact_age, left(query, 80) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
-- Log every lock wait longer than deadlock_timeout
ALTER SYSTEM SET log_lock_waits = on;
SELECT pg_reload_conf();
Common pitfalls
- Locking in request order instead of canonical order. Symptom: periodic
40P01deadlocks on transfers that grow with traffic. - Holding locks across network calls. Calling a fraud service or card network between
FOR UPDATEandCOMMIT. Symptom: lock waits and pool exhaustion whenever the downstream slows. - Unindexed predicates in InnoDB locking statements. Symptom: an
UPDATEby an unindexed column blocks unrelated writes across the table. - Optimistic locking on a hot row. Symptom: high CPU, many
409s or retries, throughput lower than with plain locking. - Session advisory locks behind PgBouncer transaction mode. Symptom: "lock already held" for jobs that are not running, or two instances running a singleton job.
- DDL without
lock_timeout. Symptom: a trivialALTER TABLEcauses a full outage of that table during a long query. - Using
SKIP LOCKEDresults for counting. Symptom: "available stock" shown to users is wrong while workers are busy. innodb_lock_wait_timeoutleft at 50 s. Symptom: API requests hang far beyond their own timeout, holding connections.
Interview angle
- Prompts: "How do you prevent overselling the last item?", "Two transfers A→B and B→A deadlock, why and how to fix?", "A big merchant's balance row is the bottleneck, what do you do?", "Optimistic or pessimistic locking?"
- A strong answer starts from the invariant, picks the lightest mechanism (conditional update), escalates only when needed, quantifies the hot-row ceiling, and mentions timeouts and retries.
- Show engine awareness: InnoDB gap/next-key locks and scan-locks-everything behavior; Postgres row locks in tuple headers, no escalation,
deadlock_timeout. - Follow-ups: "What if the hot row is a debit, not a credit?" (single-writer per account, queueing, or reserve-and-settle with pre-allocated limits), "How would you do this across services?" (see Distributed Locks & Leases and Inventory & Flash Sales).
- Red flags: a global mutex in Redis for every payment,
SERIALIZABLEas the answer to everything, not knowing thatSELECTwithoutFOR UPDATEtakes no row lock.
Self-check
1. Why does inserting an order_line not block an update to orders.status in Postgres?
The foreign key check takes FOR KEY SHARE on the parent orders row, and a status update that does not touch key columns takes FOR NO KEY UPDATE. Those two modes do not conflict; only operations that change the referenced key or delete the row (FOR UPDATE) conflict with FOR KEY SHARE.
2. When would you choose optimistic locking over SELECT … FOR UPDATE?
When conflicts are rare and the time between read and write is long or user-paced (editing a cart, a profile, a back-office record), so holding a database lock would be wasteful or impossible across HTTP requests. When contention is high (a hot balance or stock row), pessimistic locking or a conditional update is better because optimistic retries waste work and add latency.
3. How does SKIP LOCKED let you run ten outbox relay workers safely?
Each worker selects pending rows with FOR UPDATE SKIP LOCKED, so rows already locked by another worker are skipped rather than waited on. Every worker gets a disjoint batch, processes it, marks rows published and commits. If a worker crashes, its transaction rolls back and the rows become visible to others again, giving at-least-once delivery.
4. Two concurrent transfers, A→B and B→A, deadlock. Explain and fix.
T1 locks A then requests B; T2 locks B then requests A; each waits for the other, forming a cycle. The database aborts one after detecting the cycle. Fix by locking both accounts in a canonical order (for example ascending id) regardless of direction, so both transactions request A first and one simply waits; keep retry on 40P01 as a safety net.
5. Estimate the maximum update rate of a single hot row and name three mitigations.
Each update must wait for the previous transaction to commit, so throughput is roughly 1 / lock-hold-time: about 1,000/s if the lock is held ≈ 1 ms, much less if the transaction makes more round trips or waits for synchronous replication. Mitigations: shorten the hold (update last, one round trip), append ledger entries and aggregate later, split the row into N buckets, or batch credits through a per-merchant queue.
6. Why can an innocent-looking ALTER TABLE cause an outage, and how do you prevent it?
It needs ACCESS EXCLUSIVE, which waits behind any running transaction on the table; while it waits, new queries queue behind it, so the table is effectively offline until the long transaction finishes. Set a short lock_timeout so the DDL gives up quickly, retry in a loop, and avoid running DDL while long transactions are active.
7. Scenario: during a flash sale, 20,000 users try to buy 500 units of one SKU. How do you use the database without melting the stock row?
Use an atomic conditional decrement (available >= qty) so correctness never depends on application reads. To avoid 20,000 transactions queueing on one row, gate demand before the database: a Redis counter or token pre-allocation admits only about 500 buyers, and the rest get "sold out" fast. Alternatively, split stock into buckets or pre-generate 500 unit rows allocated with SKIP LOCKED. See Inventory & Flash Sales.
Exercise
Reproduce a deadlock and measure the hot-row ceiling.
docker run --name pg-lock -e POSTGRES_PASSWORD=pg -p 5432:5432 -d postgres:17
docker exec -it pg-lock psql -U postgres
CREATE TABLE account (id bigint PRIMARY KEY, balance_minor bigint NOT NULL CHECK (balance_minor >= 0));
INSERT INTO account VALUES (1, 1000000), (2, 1000000);
CREATE TABLE merchant_balance (merchant_id int PRIMARY KEY, balance_minor bigint NOT NULL);
INSERT INTO merchant_balance VALUES (1, 0);
CREATE TABLE merchant_balance_bucket (
merchant_id int, bucket int, balance_minor bigint NOT NULL DEFAULT 0,
PRIMARY KEY (merchant_id, bucket)
);
INSERT INTO merchant_balance_bucket SELECT 1, b, 0 FROM generate_series(0, 15) b;
- Deadlock. In two
psqlsessions: A runsBEGIN; UPDATE account SET balance_minor = balance_minor - 10 WHERE id = 1;, B runsBEGIN; UPDATE account SET balance_minor = balance_minor - 10 WHERE id = 2;, then A updates id 2 and B updates id 1. Read the error and the server log (docker logs pg-lock). - Hot row. Create the pgbench scripts and run them:
cat > hot.sql <<'EOF'
\set amt random(1, 1000)
BEGIN;
UPDATE merchant_balance SET balance_minor = balance_minor + :amt WHERE merchant_id = 1;
SELECT pg_sleep(0.002);
COMMIT;
EOF
cat > bucket.sql <<'EOF'
\set amt random(1, 1000)
\set b random(0, 15)
BEGIN;
UPDATE merchant_balance_bucket SET balance_minor = balance_minor + :amt WHERE merchant_id = 1 AND bucket = :b;
SELECT pg_sleep(0.002);
COMMIT;
EOF
docker cp hot.sql pg-lock:/tmp/hot.sql && docker cp bucket.sql pg-lock:/tmp/bucket.sql
docker exec pg-lock pgbench -U postgres -n -c 32 -j 4 -T 20 -f /tmp/hot.sql postgres
docker exec pg-lock pgbench -U postgres -n -c 32 -j 4 -T 20 -f /tmp/bucket.sql postgres
The pg_sleep(0.002) simulates an application round trip while the lock is held. Compare TPS and latency, then remove the sleep and compare again.
3. Implement the voucher allocation query with SKIP LOCKED, run it from 20 concurrent pgbench clients, and verify no code is assigned twice.
Done when you can explain the TPS numbers with the 1 / hold-time model and show zero duplicate voucher assignments.
Further reading
- PostgreSQL documentation, "Explicit Locking": postgresql.org/docs/current/explicit-locking.html.
- MySQL Reference Manual, "InnoDB Locking" and "Deadlocks in InnoDB".
- Martin Kleppmann, Designing Data-Intensive Applications, ch. 7 (two-phase locking, preventing lost updates).
- Alex Xu and Sahn Lam, System Design Interview Vol. 2, ch. 7 (hotel reservation concurrency) and ch. 12 (digital wallet).
Related
- Transactions & Isolation Levels — the anomalies these locks prevent.
- Zero-Downtime Schema Migrations — DDL locks and
lock_timeout. - Distributed Locks & Leases — locking across processes and services.
- Inventory & Flash Sales — contention on stock at peak.
- Double-Entry Ledger Design — append-only entries that sidestep hot rows.
- Concurrency & Synchronization — the same deadlock theory at OS level.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).