Lock the row before changing it
Contention is high (one hot inventory row, one account) and optimistic retries keep failing.
Say it like this
Accepting an offer is a hot row with real contention, so inside the transaction I take the row lock with SELECT FOR UPDATE, change it, and commit within a few milliseconds.
Basic solution
Take the lock first: SELECT ... FOR UPDATE inside the transaction, change the row, commit. Waiters queue instead of retrying.
Two accepts, one row lock
Rider A locks the driver row first and commits. Rider B queued on the same lock, re-reads after A commits, and sees the driver is already matched. Both transactions stay inside the database and finish in milliseconds.
How it works
- The transaction begins and reads the row with SELECT ... FOR UPDATE. The database takes an exclusive lock on that row, meaning no other transaction can lock or modify it until this transaction commits or rolls back.
- Any other transaction that tries to lock the same row waits in a queue inside the database; it does not fail and it does not read a stale value, it simply pauses at that statement.
- The holder validates the state it just read (is the offer still open), applies the change with an UPDATE, and commits. Commit writes the change durably and releases the lock in one step.
- The next waiter wakes up, its SELECT ... FOR UPDATE now returns the row as the previous holder left it, and it acts on the new state (for example, it finds the offer already accepted and returns a conflict to its caller).
- For job queues the variant SELECT ... FOR UPDATE SKIP LOCKED lets each worker take a different unlocked row instead of waiting on one that another worker holds.
- For locks on things that are not rows (a name, a tenant), use an advisory lock: a lock the database holds on an arbitrary number you choose, such as a hash of the name, released when the transaction ends.
The rule that makes it safe
- Everything between taking the lock and committing must be local and fast. No HTTP calls, no queue publishes, no waiting on users while holding a row lock.
Worked example
Ride matching, two riders accept offers for the same driver
- A driver has one open offer. The offer and the driver row live in Postgres; 5,000 accepts per minute city-wide, but contention is on individual drivers.
- Rider A and rider B both tap accept within 50 ms. Both transactions run SELECT * FROM drivers WHERE id = 42 FOR UPDATE.
- A gets the lock, sees status available, sets status matched, inserts the trip, commits. About 4 ms from lock to commit.
- B was waiting on the lock for those 4 ms. It wakes, re-reads, sees status matched, and returns 409 offer no longer available. No double booking, no retry loop, and B's total latency is only 4 ms longer than A's.
- With optimistic locking instead: both read version 7, A writes version 8, B's write fails on the version check and must retry, re-read, and then fail again on business logic. Same outcome, one extra round trip, and under heavier contention (a flash sale) most attempts would retry several times.
- Throughput: lock hold time of 4 ms means one driver row can serve at most 250 accepts per second, far above the one or two it will ever see, so the lock is never the bottleneck here.
Variants and when each wins
Row lock with SELECT FOR UPDATE
- Exclusive, queued access to one row for the length of the transaction. It wins when contention is real and the critical section is a few statements, because waiters simply queue and nobody wastes work.
SKIP LOCKED for work queues
- Each worker runs SELECT ... WHERE status = 'pending' LIMIT 1 FOR UPDATE SKIP LOCKED and gets a row nobody else holds. It wins for turning a table into a safe multi-consumer queue without a separate broker.
NOWAIT
- The lock attempt fails immediately with an error instead of queueing. It wins when a request that had to wait would just time out anyway, so failing fast frees the connection.
Advisory locks
- pg_advisory_xact_lock(key) locks an arbitrary number rather than a row. It wins for guarding a resource that has no row yet, such as an alias that is about to be inserted.
Optimistic version check (the alternative)
- No lock is taken; the write says WHERE version = expected and the caller retries if zero rows changed. It wins at low contention and when the read and the write are separated by user think time, because a lock cannot be held that long.
Recommendation: pessimistic for short, hot, server-side critical sections; optimistic when the read and write span a user interaction or contention is rare.
Failure modes
Lock held across a network call
- You notice lock wait timeouts and a pile of blocked transactions during a payments slowdown. It happens because the transaction called the payments service or published an event while still holding the row lock, so every waiter inherited that network latency. Do external calls before the transaction starts or after it commits, never inside.
Deadlock
- You notice the database killing one transaction with a deadlock error. It happens because two transactions each locked a row and then asked for the row the other holds, so neither can proceed. Lock rows in a fixed order such as ascending id, lock all rows in one statement where possible, and retry the transaction the database chose as the victim.
Lock queue becomes the bottleneck
- You notice throughput on one operation capped at roughly one divided by the lock hold time, however many servers you add. It happens because a single row (a global counter, one inventory record) serialises every update. Shard the counter into N rows and sum them, or move the operation to an atomic in-memory increment.
Waiting forever
- You notice requests hanging indefinitely when one holder is stuck. It happens because no lock timeout was set, and the holder is itself waiting on something else. Set lock_timeout and statement_timeout so waiters fail after a bounded time, and keep transactions short so the holder cannot be stuck for long.
Lost lock on connection pooler
- You notice a lock that seems to disappear between two statements. It happens because the pooler is in transaction-level mode and the statements were not inside one explicit transaction, or the code used a session-level advisory lock, so a later statement ran on a different connection that does not hold the lock. Wrap the lock and the writes in one explicit transaction, use transaction-scoped advisory locks (pg_advisory_xact_lock), or use session pooling for that code path.
Interviewer follow-ups
Answer out loud before you open each one.
When would you choose optimistic over pessimistic locking?
When conflicts are rare or when the read and the write are separated by time you cannot hold a lock across, such as a user editing a form. Optimistic costs nothing on the happy path and only pays on conflict; pessimistic pays a lock on every attempt but never wastes work on a conflict.
How does SKIP LOCKED make a job queue safe?
Each worker selects one pending row with FOR UPDATE SKIP LOCKED, so rows another worker has locked are skipped rather than waited on. Every worker gets a distinct job without any coordination beyond the database, and a crashed worker simply releases its lock on rollback.
What is the maximum throughput on one locked row?
Roughly one divided by the lock hold time, since holders are serialised. A 4 ms critical section caps a single row at about 250 updates per second. If a row needs more, shard it or move the operation to an atomic increment.
How do you avoid deadlocks when locking two rows?
Always lock in the same global order, for example lower id first, or lock both in one statement with ORDER BY id FOR UPDATE. Combine that with a lock timeout and a retry on the deadlock error, since the database will detect and break the rare cycle.
Connections
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Trip service | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon Aurora | Postgres | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |