Skip to content

Concurrency Control and Database Locking

Advanced 43 min read Part 5 of 18

Race conditions and lost updates; pessimistic locks (FOR UPDATE, shared/exclusive) vs optimistic version checks; deadlocks, lock granularity and lock types.

Summary#

When several transactions change the same data at once, race conditions appear, the most common being the lost update. Databases offer two families of protection. Pessimistic locking takes a lock before changing data (SELECT ... FOR UPDATE), so others wait; it is safe under heavy contention but reduces concurrency and can deadlock. Optimistic locking lets everyone proceed and checks at write time that nothing changed (a version column with compare-and-set); it is cheap when conflicts are rare but needs retries when they are not. Locks come in shared (read) and exclusive (write) modes and at different granularities (row, page, table). Choose by contention level and the cost of retrying.

Why It Exists#

Isolation levels alone do not stop every race. Under the default levels in PostgreSQL and MySQL, two requests that read a value, compute in application code and write it back can overwrite each other. These bugs cause oversold tickets, negative inventory and wrong balances, and they only appear under load, so they slip through testing. Explicit concurrency control lets you protect exactly the data that matters. This page builds on ACID and Isolation Levels.

How It Works#

Race conditions and lost updates#

A race condition is a bug where the result depends on the timing of concurrent operations. The classic database race is the read-modify-write cycle:

Request A: SELECT seats_left FROM events WHERE id = 7;    -- 1
Request B: SELECT seats_left FROM events WHERE id = 7;    -- 1
Request A: UPDATE events SET seats_left = 0 WHERE id = 7; -- books the last seat
Request B: UPDATE events SET seats_left = 0 WHERE id = 7; -- also books it: oversold

Both requests saw one seat left, and both succeeded. The simplest fix, when possible, is to make the database do the check and change in one atomic statement:

UPDATE events SET seats_left = seats_left - 1
WHERE id = 7 AND seats_left > 0;        -- 0 rows updated means sold out

When the logic is too complex for one statement (check several rows, call pricing code, then write), you need locking.

Race conditions in depth#

How a race plays out. Picture a sold-out tour with exactly one seat left. Two fans press "Buy" in the same instant. Each request runs the obvious logic: read the seat count, check that it is above zero, take payment, and write the count back minus one. Request A reads 1. A fraction of a millisecond later, before A has written anything, request B also reads 1. Both pass the check, both charge a card, and both commit. If each writes seats_left = seats_left - 1, the count ends at −1. If each writes the value it computed (seats_left = 0), the count looks fine, but two people own the same seat. Either way, two customers turn up holding tickets for one seat, and support has to refund someone.

Why testing misses it. The bug needs two requests to land inside the same small window: the time between the read and the write. If that window is 5 ms and a row receives one request a second, overlaps are rare enough to escape testing. During an on-sale, the same row may get 2,000 requests a second. Then about 10 requests sit inside each 5 ms window, and a collision is almost certain. Races are load-dependent, so they surface in production at the worst moment.

The family of concurrency anomalies. The lost update is the most common race, but several related shapes appear in databases:

AnomalyWhat happensExample
Lost updateTwo read-modify-write cycles overlap. One overwrites the other's change.Two edits to a profile; the first is silently lost.
Dirty readA transaction reads data another transaction has not committed, which is then rolled back.Showing a balance that never really existed. Prevented by Read Committed and above.
Non-repeatable readReading the same row twice in one transaction gives different values.A report that adds up inconsistent numbers.
PhantomA query re-run in one transaction returns new rows that another transaction inserted."No booking overlaps 2-3 pm" is true at check time but false at commit.
Write skewTwo transactions read the same set of rows, each updates a different row, and together they break a rule.Two on-call doctors each see the other is on duty and both go off call.

The last two are the hard ones. Locking the row you update does not help, because the conflict is about rows you read, or rows that do not exist yet. They need range locks, a materialised conflict row, a constraint, or Serializable isolation. See ACID and Isolation Levels.

Check-then-act vs read-modify-write. These are two shapes of the same bug. Read-modify-write computes a new value from an old one (balance minus 50). Check-then-act decides whether to act from what it read ("the username is free, so insert it"). Both go wrong when the world changes between the read and the write, which is sometimes called a time-of-check to time-of-use (TOCTOU) gap. Every fix closes that gap. Either the database does the check and the write as one atomic step, or nothing can change the data in between because of a lock, or the write fails if something did change, which is the version check.

Atomic statements, in more depth. The best fix is often to let the database do the whole thing in one statement, because a single statement is atomic and the database handles concurrency inside it.

-- Decrement only if stock remains; RETURNING tells us what happened
UPDATE products SET stock = stock - 1
WHERE id = 42 AND stock > 0
RETURNING stock;            -- no row returned means sold out
 
-- Claim a username: the UNIQUE constraint is the concurrency control
INSERT INTO usernames (name, user_id) VALUES ('alice', 7)
ON CONFLICT (name) DO NOTHING
RETURNING user_id;          -- no row means someone else got it first
 
-- No overlapping room bookings, enforced by PostgreSQL itself
ALTER TABLE bookings ADD CONSTRAINT no_overlap
  EXCLUDE USING gist (room_id WITH =, during WITH &&);

Why is the conditional UPDATE safe under the default Read Committed level? When two transactions update the same row, the second one waits for the first to commit. In PostgreSQL, the second one then re-checks its WHERE clause against the new row version. If stock is now 0, the condition fails, and it updates nothing. MySQL InnoDB behaves the same way for updates, because they read the latest committed version. So the check and the change cannot be split apart. Constraints are even stronger. A UNIQUE index or an exclusion constraint is checked inside the engine under its own locks, so no interleaving of transactions can break it. Use them whenever a rule can be phrased as "no two rows may ...".

The same idea exists outside SQL. Redis INCR and DECR are atomic, and a short Lua script runs atomically on one Redis node. DynamoDB UpdateItem with a ConditionExpression such as stock > :zero checks and writes in one step. Cassandra's lightweight transactions (UPDATE ... IF stock = 3) run a Paxos round to compare-and-set one partition. Normal Cassandra writes are last-write-wins, with no locks at all, so concurrent read-modify-write there silently loses updates unless you use these.

How isolation levels change the picture. A plain SELECT followed by an UPDATE with a computed value behaves differently by level:

  • Read Committed (default in PostgreSQL, SQL Server and Oracle): the lost update happens. Each statement sees the latest committed data, but nothing ties the read to the write.
  • Repeatable Read in PostgreSQL: the second writer gets a serialization error ("could not serialize access due to concurrent update") and must retry. The lost update is prevented, at the cost of a retry.
  • Repeatable Read in MySQL InnoDB (its default): a plain SELECT reads the snapshot, but the UPDATE writes over the latest version. So the computed-value lost update can still happen unless you use FOR UPDATE or an atomic expression.
  • Serializable: every anomaly in the table above is prevented, through aborts that the application must retry.

Do not rely on the default level to save a read-modify-write. Make the protection explicit with one of the methods on this page.

Pessimistic locking#

Pessimistic locking assumes conflicts will happen and prevents them by locking first.

Row locks with SELECT ... FOR UPDATE. Inside a transaction, this reads rows and takes an exclusive lock on them until commit. Any other transaction trying to lock or update those rows waits.

BEGIN;
SELECT status FROM seats WHERE event_id = 7 AND seat_no = 'A12' FOR UPDATE;
-- application checks status = 'free'
UPDATE seats SET status = 'held', held_by = 42, held_until = now() + interval '10 minutes'
WHERE event_id = 7 AND seat_no = 'A12';
COMMIT;   -- lock released

Useful options: FOR UPDATE NOWAIT fails immediately instead of waiting, and FOR UPDATE SKIP LOCKED skips rows locked by others. SKIP LOCKED is a common way to build a work queue in a table: each worker grabs the next unlocked job.

Shared vs exclusive locks. A shared (S) lock allows other shared locks but blocks exclusive ones: many readers, no writers. An exclusive (X) lock blocks everything else on that item. FOR SHARE takes shared row locks ("make sure this parent row is not deleted while I insert a child"); FOR UPDATE and normal UPDATE/DELETE take exclusive ones.

Held \ RequestedSharedExclusive
SharedGrantedWaits
ExclusiveWaitsWaits

With MVCC, plain SELECT statements take no row locks at all; they read a snapshot. Only writes and locking reads block each other.

Table locks. Some operations lock a whole table: LOCK TABLE explicitly, and many schema changes (ALTER TABLE) take an exclusive table lock. A long schema change waiting for its lock can block every query queued behind it, a frequent cause of outages.

Pessimistic locking in depth#

How long a lock lives. A row lock taken by FOR UPDATE, UPDATE or DELETE is held until the transaction ends, at commit or rollback, not until the statement ends. So the transaction's duration is the lock's duration. Anything slow inside the transaction holds every lock it has taken: a network call, a slow query, a user deciding. That one fact explains most locking incidents.

The tempting bad design: lock while the user decides. A common first idea for ticket booking is to open a transaction when the user picks a seat, SELECT ... FOR UPDATE the seat row, and keep the transaction open during the 5-minute checkout. Commit if they pay, roll back if they leave. It seems neat, because the database guarantees exclusivity. It fails in several ways:

  • Database locks are built for milliseconds, not minutes. Every open transaction pins a connection, and in PostgreSQL it also holds back VACUUM, so dead rows pile up across the whole database.
  • Connections run out. With a pool of 100 connections and 2,000 users in checkout, the pool is exhausted after 100 users, and every other request queues.
  • Abandonment is messy. If a user closes the tab, the lock stays until a session timeout fires, or forever if the app server crashes in a way that leaves the connection half-open.
  • Waiting is not a user experience. Other buyers who touch the seat block until the lock is freed. Setting lock_timeout turns their wait into an error, which is not a graceful "this seat is held" message.
  • Deadlocks and contention grow with hold time. A user who picks two seats in different orders from another user can deadlock with them.

The better design: lock briefly, record the hold as data. Use a lock only for the instant of the state change, and store the reservation itself as a row value:

BEGIN;
UPDATE seats
SET status = 'held', held_by = 42, held_until = now() + interval '10 minutes'
WHERE event_id = 7 AND seat_no = 'A12'
  AND (status = 'free' OR (status = 'held' AND held_until < now()))
RETURNING seat_no;          -- no row: someone else holds or bought it
COMMIT;                     -- the lock lasted a few milliseconds

The transaction lasts milliseconds. The hold lasts 10 minutes as data, with an expiry that every later query respects, so an abandoned checkout frees itself with no cleanup job needed for correctness. A sweeper can still reset old holds for tidiness. Payment happens outside any database transaction. On success, a second short transaction sets the seat to sold if held_by = 42. Some designs keep the hold in Redis with a TTL (SET seat:7:A12 42 NX EX 600) and the final sale in the database. That works, but it adds a second system that must agree with the first. See Distributed Locking.

Row lock strengths in PostgreSQL. PostgreSQL has four row-lock modes, not two, mainly so that foreign keys do not block unrelated updates:

ModeTaken byBlocks
FOR UPDATEDELETE, updates of key columns, explicit FOR UPDATEAll other row locks
FOR NO KEY UPDATEOrdinary UPDATEs that do not change a key columnFOR UPDATE, FOR SHARE, other FOR NO KEY UPDATE
FOR SHAREExplicit locking readsUpdates and deletes
FOR KEY SHAREForeign-key checks when inserting a child rowOnly deletes and key updates of the parent

So inserting an order line (which checks the parent orders row with FOR KEY SHARE) does not block a concurrent update of the order's status (FOR NO KEY UPDATE). Before PostgreSQL 9.3 introduced these weaker modes, foreign-key checks took stronger locks and caused many unexpected blocking chains and deadlocks.

Work queues with SKIP LOCKED. A job table becomes a safe multi-worker queue with a single statement:

WITH next AS (
  SELECT id FROM jobs
  WHERE status = 'ready' AND run_at <= now()
  ORDER BY run_at
  LIMIT 10
  FOR UPDATE SKIP LOCKED
)
UPDATE jobs SET status = 'running', locked_by = 'worker-3', locked_at = now()
FROM next WHERE jobs.id = next.id
RETURNING jobs.id, jobs.payload;

Each worker takes up to 10 ready jobs that no other worker currently holds. It never waits behind another worker, and two workers never get the same job. A partial index on (run_at) WHERE status = 'ready' keeps the scan tiny. A worker that crashes mid-job leaves status = 'running', so a reaper resets jobs whose locked_at is too old. The job handlers must be idempotent, because a reset job may run twice. See Idempotency. This pattern serves thousands of jobs a second on one PostgreSQL primary. Beyond that, or when you need fan-out and replay, a dedicated queue fits better.

NOWAIT for fail-fast paths. FOR UPDATE NOWAIT raises an error immediately if the row is locked. It suits user-facing actions where "someone else is editing this right now, try again" is better than a spinning request. lock_timeout = '200ms' is the middle ground: wait briefly, then fail.

Throughput limits of a hot lock. If each transaction holds a row lock for t milliseconds, that row handles at most 1000 / t transactions a second, however big the server is. At 2 ms, the ceiling is 500 per second. At 50 ms, because someone added an HTTP call inside the transaction, it is 20 per second. Queued waiters also hold connections. With 200 requests a second arriving for a row that can serve 20, the queue grows by 180 a second until the pool is exhausted and unrelated requests start failing. This is a lock convoy, and it is why the hold time of hot locks is a key metric.

Optimistic locking#

Optimistic locking assumes conflicts are rare. It takes no locks while the user or code works; it detects conflicts at write time.

Version column with compare-and-set. Each row carries a version number (or an updated-at timestamp). The update succeeds only if the version is unchanged since it was read, and it increments the version:

-- Read
SELECT id, title, body, version FROM documents WHERE id = 55;   -- version = 8
-- Write: compare-and-set on the version
UPDATE documents
SET title = 'New title', body = '...', version = version + 1
WHERE id = 55 AND version = 8;
-- 1 row updated: success.  0 rows: someone else saved first; reload, merge or retry.

This is compare-and-set (CAS): "set the new value only if the current value is still what I expect". The same idea appears outside SQL: DynamoDB conditional writes (ConditionExpression), HTTP ETags with If-Match (412 Precondition Failed on conflict), Redis WATCH/MULTI, and etcd transactions comparing a key's revision. ORMs such as Hibernate/JPA (@Version) and Rails (lock_version) implement it automatically.

Optimistic locking works across long "think time": a user can open an edit form for 10 minutes without holding any database lock.

Optimistic locking in depth#

Where it comes from. H. T. Kung and John T. Robinson set out the idea in "On Optimistic Methods for Concurrency Control" (ACM Transactions on Database Systems, 1981). A transaction runs in three phases. In the read phase, it works on private copies without locking. In the validation phase, it checks whether anything it read was changed by a transaction that committed meanwhile. In the write phase, it publishes its changes only if validation passed, and otherwise restarts. The version-column pattern is the same idea shrunk to one row: the read records the version, and the conditional UPDATE validates and writes in one atomic step.

Version numbers vs timestamps vs value comparison. There are three ways to detect change:

  • A version integer incremented on every write: exact, cheap and unambiguous. This is the default choice.
  • An updated_at timestamp: convenient, but two writes in the same clock tick can share a value, clocks on different app servers can disagree, and a timestamp set by the application can go backwards. Use database-generated timestamps with fine resolution if you must, but a version number is safer.
  • Comparing the old values themselves (WHERE balance = 100): needs no extra column, but it suffers from the ABA problem. The value goes from A to B and back to A between your read and your write. The comparison passes, although the row was changed twice in between, and anything derived from the intermediate state is now wrong. Take a stock count that drops from 5 to 4 (a sale) and returns to 5 (a refund). A value-compare update would treat the row as untouched, although history moved underneath it. A version number only ever increases, so it can never come back to an old value, and ABA cannot happen.

Compare-and-set across systems. The same pattern appears in many places:

// DynamoDB: update only if the version we read is still current
await ddb.update({
  TableName: "documents",
  Key: { id: "doc-55" },
  UpdateExpression: "SET body = :b, version = :next",
  ConditionExpression: "version = :expected",
  ExpressionAttributeValues: { ":b": newBody, ":next": 9, ":expected": 8 },
});
// On ConditionalCheckFailedException: reload, merge or tell the user

Over HTTP, the server returns an ETag header holding the resource version. The client sends it back in If-Match when saving, and the server answers 412 Precondition Failed if the resource has moved on. Redis offers WATCH key, then MULTI ... EXEC, and the transaction aborts if the watched key changed. etcd and ZooKeeper attach a revision to every key, and writes can be made conditional on it. Git's push is the same thing: the remote rejects a non-fast-forward push because your base commit is no longer the tip.

What to do on conflict. A failed compare-and-set needs a plan:

  1. Retry automatically when the change can be recomputed from fresh data: increment a counter, add an item to a cart, recompute a total. Reload, re-apply and try again, with a small random delay (jitter) and a cap of a few attempts.
  2. Merge when changes touch different fields. If the other writer changed the title and you changed the body, apply both. This needs field-level change tracking.
  3. Ask the user when changes truly collide. Show "this document changed while you were editing" with both versions. Never silently overwrite.

Retry math and the contention cliff. Suppose each attempt has probability p of conflicting. The expected number of attempts is 1 / (1 − p). At p = 0.1 that is 1.11 attempts, barely noticeable. At p = 0.5 it is 2. At p = 0.9 it is 10, and each failed attempt did the whole read and compute for nothing. The conflict rate itself rises with load, because more writers overlap each window. So optimistic schemes degrade sharply on hot rows: throughput can fall as load rises, because most work is thrown away. That is the contention cliff, and the reason optimistic locking is chosen for data where conflicts are genuinely rare.

Long think time is where optimistic wins. A support agent opens a ticket, reads for 4 minutes and saves. Holding a lock for those 4 minutes would block every colleague and pin a connection. With a version column, nothing is held. The save either succeeds or reports a conflict, and the database spends nothing while the agent reads. This is why web forms, admin tools, collaborative editors and REST APIs use optimistic concurrency almost everywhere.

Deadlocks and detection#

A deadlock happens when transactions wait for each other in a cycle, so none can continue:

Databases detect deadlocks by building a wait-for graph (who waits for whom) and looking for cycles. InnoDB checks when a transaction starts waiting and rolls back the transaction with the least work. PostgreSQL checks after a lock has been waited on for deadlock_timeout (1 second by default) and aborts one participant. The application must retry the aborted transaction.

Prevention:

  • Lock in a consistent order: for a transfer, always lock the lower account ID first. Two transfers between the same accounts then queue instead of deadlocking.
  • Keep transactions short and avoid user or network waits inside them.
  • Lock everything you need up front in one statement (WHERE id IN (...) ORDER BY id FOR UPDATE).
  • Set lock timeouts (lock_timeout in Postgres, innodb_lock_wait_timeout in MySQL) so stuck waits fail fast.

Deadlocks in depth#

The four conditions. Coffman, Elphick and Shoshani's 1971 paper "System Deadlocks" (ACM Computing Surveys) showed that a deadlock needs four conditions at once:

  1. Mutual exclusion: a resource can be held by only one party at a time.
  2. Hold and wait: a party holds some resources while waiting for more.
  3. No preemption: resources cannot be taken away; only the holder releases them.
  4. Circular wait: a cycle of parties, each waiting for the next.

Each prevention technique breaks one of them. Consistent lock ordering breaks circular wait. Locking everything up front in one statement breaks hold and wait. A database aborting a victim is preemption. Optimistic schemes avoid mutual exclusion during the work itself.

Three strategies: detect, prevent or time out.

  • Detection (PostgreSQL, InnoDB, SQL Server): let deadlocks happen, find cycles in the wait-for graph, and abort one transaction. This is cheap when deadlocks are rare, and the application must retry.
  • Prevention by ordering (wait-die and wound-wait): give each transaction a timestamp at start. In wait-die, an older transaction may wait for a younger one, but a younger one that would wait for an older one aborts ("dies") instead. In wound-wait, an older transaction that needs a lock held by a younger one forces the younger one to abort ("wounds" it), while a younger one simply waits. Neither scheme can ever form a cycle, because waits always point in one direction of age. Both come from Rosenkrantz, Stearns and Lewis's 1978 work on concurrency control for distributed databases. Google's Spanner uses wound-wait, because detecting cycles across many machines is expensive.
  • Timeouts: any wait longer than N seconds fails. It is simple and works across systems that cannot see each other's locks, but it is slow to resolve real deadlocks and can abort transactions that were merely slow.

Deadlocks you did not write. Many deadlocks come from locks taken implicitly:

  • Foreign-key checks. Inserting a child takes a share lock on the parent. Two transactions that insert children of the same parents, and then update those parents in different orders, can form a cycle.
  • Index order. An UPDATE ... WHERE status = 'x' locks rows in the order of the index it scans. Another statement scanning a different index can lock the same rows in a different order.
  • Gap and insert-intention locks in InnoDB. Two transactions that each run SELECT ... FOR UPDATE on a missing key (taking a gap lock), then both try to insert into that gap, deadlock with each other. Gap locks are compatible with each other, but each insert must wait for the other's gap lock. "Check if it exists, then insert" under Repeatable Read is a classic source of this. INSERT ... ON DUPLICATE KEY UPDATE, or a unique constraint plus error handling, avoids it.
  • Batch updates in arbitrary order. UPDATE accounts SET ... WHERE id IN (7, 3, 9) may lock in whatever order the plan visits rows. Sort IDs in the application, or lock with SELECT ... WHERE id IN (...) ORDER BY id FOR UPDATE first.

Reading deadlock reports. PostgreSQL logs "deadlock detected" with each process, the lock it waited for, and the query. Set log_lock_waits = on to also log waits longer than deadlock_timeout. InnoDB's SHOW ENGINE INNODB STATUS includes a "LATEST DETECTED DEADLOCK" section with both transactions, the locks they held and wanted (record, gap or next-key, with the index name) and the victim. innodb_print_all_deadlocks writes every deadlock to the error log. The pattern to look for is two code paths touching the same tables in opposite orders. That is usually fixed by changing one of them.

A retry wrapper. Deadlocks and serialization failures are normal events in a busy database, not bugs to be stamped out completely. Every transaction that can hit them should run inside a retry helper:

async function withRetry<T>(fn: () => Promise<T>, attempts = 5): Promise<T> {
  for (let i = 1; ; i++) {
    try {
      return await db.transaction(fn);         // BEGIN ... COMMIT
    } catch (e: any) {
      // 40P01 deadlock_detected, 40001 serialization_failure (PostgreSQL)
      const retryable = e.code === "40P01" || e.code === "40001";
      if (!retryable || i === attempts) throw e;
      const backoff = Math.min(1000, 10 * 2 ** i) * Math.random();
      await new Promise((r) => setTimeout(r, backoff));
    }
  }
}

The whole transaction must be retried, not only the failed statement, because the database has already rolled back everything. Any side effects outside the database, such as emails or API calls, must not happen inside fn. Otherwise they repeat on each retry.

When detection itself costs too much. With thousands of sessions waiting on the same few hot rows, InnoDB's deadlock detector can use a lot of CPU walking long wait queues. MySQL 8.0 provides innodb_deadlock_detect = OFF, which relies on innodb_lock_wait_timeout instead. It is a last resort for extreme hot-row workloads. The better fix is to remove the hot row, as described in the Choosing section below.

Lock granularity#

Granularity is how much data one lock covers:

GranularityConcurrencyOverheadTypical use
Row (record)HighestMore locks to trackOLTP updates
Page or rangeMediumMediumSome engines; range locks to block phantoms
TableLowestOne lockSchema changes, bulk loads, LOCK TABLE
DatabaseNoneMinimalRare (some maintenance)

Finer locks allow more parallel work but cost more memory and bookkeeping. Some databases (SQL Server) escalate many row locks into a table lock to save memory, which can suddenly block other users. Intention locks make mixed granularity efficient: before locking a row exclusively, a transaction places an "intention exclusive" mark on the table, so a request for a full table lock can see the conflict without checking every row.

Lock granularity in depth#

Multiple-granularity locking. Jim Gray and colleagues described locking at several levels at once (database, table, page, row) with intention modes in "Granularity of Locks and Degrees of Consistency in a Shared Data Base" (1976). To lock a row in mode S or X, a transaction first takes IS or IX on the table that contains it. A transaction that wants to lock the whole table checks only the table-level locks. If it sees an IX, it knows some row below is being written, without scanning millions of row locks. The compatibility rules:

Held \ RequestedISIXSSIXX
ISYesYesYesYesNo
IXYesYesNoNoNo
SYesNoYesNoNo
SIXYesNoNoNoNo
XNoNoNoNoNo

SIX ("shared with intention exclusive") means "I am reading the whole table and will update a few rows", which suits a scan that updates as it goes. InnoDB uses IS and IX table locks in exactly this way. They almost never block anything except explicit LOCK TABLES or DDL.

Where locks are stored, and why it matters.

  • SQL Server keeps locks in a memory-based lock manager. Too many row locks use too much memory, so once a single statement holds about 5,000 locks on one table, the engine tries to escalate to a table lock. A large UPDATE can therefore suddenly block every other user of the table. Batching large updates into chunks below the threshold avoids this.
  • InnoDB stores row locks as compact bitmaps per page in its lock system, so it can hold millions of locks without escalation. But it locks every index record it scans, not just the ones it changes. An UPDATE without a usable index can lock the whole table row by row.
  • PostgreSQL records row locks in the row itself, in the tuple header's xmax field. When several transactions share a lock, it uses a "MultiXact" structure. There is no lock table to fill up and no escalation. The cost is that taking a row lock writes to the row's page, which creates WAL and dirty pages even for SELECT ... FOR UPDATE.

Choosing the grain in your own design. Granularity is also a modelling decision. Suppose a whole shopping cart row is locked to add one item. Two tabs adding items then serialise for no reason, whereas one row per cart item would let them proceed in parallel. In the other direction, a single inventory row per product makes every sale contend on it, while splitting stock into 10 "bucket" rows of 100 units each lets 10 sales proceed at once. Finer grain means more concurrency but more rows to manage, and some rules, such as a total stock count, are now spread across rows. Pick the smallest unit that one business operation must change atomically.

Coarse locks on purpose. Sometimes one big lock is the right answer. A nightly billing job that must not run twice can take a single advisory lock or table lock. A migration that rewrites a table can lock it briefly during the final swap. Coarse locks are simple and easy to reason about. Their cost only matters when they are held often or for a long time.

Types of database locks#

Lock typePurposeExample
Shared (S)Read; blocks writersSELECT ... FOR SHARE
Exclusive (X)Write; blocks all othersUPDATE, SELECT ... FOR UPDATE
Intention (IS, IX)Table-level marker of row locks belowInnoDB, SQL Server
Record lockLock one index recordInnoDB row lock
Gap lockLock the space between index records, so no one inserts thereInnoDB at Repeatable Read
Next-key lockRecord plus the gap before it; prevents phantomsInnoDB locking reads
Table lock modesFrom ACCESS SHARE (plain reads) to ACCESS EXCLUSIVE (DROP, many ALTERs)PostgreSQL
Metadata lockProtects table definitions during queriesMySQL (schema changes wait for running queries)
Advisory lockApplication-defined lock on an arbitrary numberpg_advisory_lock(42)
Predicate lock (SIREAD)Tracks what a serializable transaction read, without blockingPostgreSQL SSI

Advisory locks are handy for "only one worker runs this nightly job" within one database. For locks across many services and machines, see Distributed Locking.

Lock types in depth#

PostgreSQL's table lock ladder. PostgreSQL has eight table-level lock modes. Ordinary statements take the weakest ones, and they rarely conflict:

ModeTaken byConflicts with
ACCESS SHARESELECTOnly ACCESS EXCLUSIVE
ROW SHARESELECT ... FOR UPDATE/SHAREEXCLUSIVE, ACCESS EXCLUSIVE
ROW EXCLUSIVEINSERT, UPDATE, DELETESHARE and stronger
SHARE UPDATE EXCLUSIVEVACUUM, CREATE INDEX CONCURRENTLY, ANALYZEItself and stronger
SHARECREATE INDEX (non-concurrent)ROW EXCLUSIVE and stronger, so it blocks writes
SHARE ROW EXCLUSIVESome triggers and constraintsROW EXCLUSIVE and stronger
EXCLUSIVERare (REFRESH MATERIALIZED VIEW CONCURRENTLY)Everything except ACCESS SHARE
ACCESS EXCLUSIVEDROP, TRUNCATE, most ALTER TABLEEverything, including plain SELECT

The ALTER TABLE outage, step by step. This pattern takes down production databases surprisingly often:

  1. A long analytics query is reading orders, holding ACCESS SHARE for 10 minutes.
  2. A deploy runs ALTER TABLE orders ADD COLUMN note text. The change itself is instant, but it needs ACCESS EXCLUSIVE, so it waits for the analytics query.
  3. Every new query on orders, even a plain SELECT, now queues behind the waiting ALTER, because lock requests are granted in order.
  4. Within seconds, all connections are stuck waiting, and the application is down, though nothing is actually running.

The fix is to run DDL with SET lock_timeout = '2s' and retry in a loop. If the lock cannot be taken quickly, the ALTER gives up and lets traffic through, then tries again a moment later. Also cap analytics queries with statement_timeout, or move them to a replica. MySQL has the same trap with metadata locks: DDL waits for running transactions on the table, and new queries queue behind the waiting DDL.

Advisory locks. These are locks on an application-chosen number, which the database never takes by itself:

-- Transaction-scoped: released automatically at COMMIT or ROLLBACK
SELECT pg_advisory_xact_lock(hashtext('billing-run:2026-12'));
 
-- Session-scoped, non-blocking: returns false if someone else holds it
SELECT pg_try_advisory_lock(42);
-- ... do the job ...
SELECT pg_advisory_unlock(42);

They suit "only one instance runs this cron job", "serialise all changes to tenant 17's settings", or "one migration at a time". Transaction-scoped locks are safer, because they cannot leak if the code forgets to unlock. Session-scoped locks are freed if the connection drops, which is good for crash safety. But with a pooler such as PgBouncer in transaction mode, a "session" may be shared with other clients, so session-level advisory locks behave unpredictably there. MySQL's equivalent is GET_LOCK('name', timeout).

Locks vs latches. Databases also use latches: very short-lived internal mutexes that protect in-memory structures such as a B-tree page or a buffer-pool entry for a few microseconds. Latches are not visible to users, are not held until commit, and are not part of deadlock detection. When a database shows "lock waits", that means transaction locks. Latch contention shows up instead as CPU time spent spinning and as "LWLock" waits in PostgreSQL's pg_stat_activity.

Predicate locks (SIREAD) in PostgreSQL Serializable. Under Serializable, PostgreSQL records what each transaction read, as row, page or relation ranges, in SIREAD locks that block nothing. On commit, it checks for a dangerous pattern of read-write dependencies between concurrent transactions, and if it finds one, aborts one of them. This is serializable snapshot isolation. It catches write skew and phantoms without the blocking of two-phase locking, at the cost of retries and some memory for the tracked ranges.

Choosing pessimistic vs optimistic#

PessimisticOptimistic
AssumesConflicts are likelyConflicts are rare
Cost when no conflictLock overhead, others may waitAlmost none
Cost on conflictWaitingRetry or user merge
DeadlocksPossibleNot from this mechanism
Long user editsBad (locks held for minutes)Good
FitsHot rows: seat booking, inventory in a flash sale, account balancesProfile edits, documents, admin forms, low-contention updates

Under very high contention on one row (thousands of buyers for one item), both approaches struggle: pessimistic locks serialise everyone, and optimistic retries waste work. Then the design must change: queue requests, split the counter into shards, or reserve stock in batches. See Pattern: Dealing with Contention.

Choosing in practice: six common cases#

CaseContentionRecommended approachWhy
Decrement stock in a normal shopLow to mediumAtomic UPDATE ... WHERE stock > 0One statement, no explicit lock, safe under Read Committed
Flash sale: 50,000 buyers, 1,000 unitsExtreme on one rowQueue or admission control, then atomic decrements on split stock rowsAny single-row approach caps at hundreds of transactions a second
Seat booking with a 10-minute checkoutHigh per seatShort conditional UPDATE to held with held_until, and payment outside the transactionNo lock held during user think time
Bank transfer between two accountsMediumFOR UPDATE both rows in ascending ID order, short transactionMulti-row invariant, deadlock-free ordering
Wiki or CMS page editLowVersion column, 409 or 412 on conflict, show a diffLong think time, conflicts rare
Background job claimingHigh across rows, low per rowFOR UPDATE SKIP LOCKEDWorkers never wait for each other

Throughput comparison on one hot row. A row receives 1,000 update attempts a second. Each transaction's database work takes 2 ms.

  • Pessimistic: the row serialises at 1 / 2 ms = 500 a second. The other 500 a second queue, so the wait grows without bound, and timeouts and pool exhaustion follow. Shortening the hold time to 0.5 ms with one atomic statement raises the ceiling to 2,000 a second, enough for this load.
  • Optimistic: attempts overlap constantly. With dozens of writers inside each 2 ms window, most validations fail, and retries add load, so useful throughput can drop well below 500 a second.
  • Atomic statement: the database serialises the row internally for only the update itself, typically tens of microseconds. That is the best of the three when the logic fits in one statement.
  • Redesigned: splitting the row into 10 sub-rows, or batching updates through a queue that applies them in groups of 100, removes the single-row ceiling entirely.

The general lesson: the choice between pessimistic and optimistic matters most at moderate contention. At low contention both work. At extreme contention neither does, and the data model or the flow has to change. See Pattern: Dealing with Contention and Pattern: Scaling Writes.

Across services and databases. Row locks protect data inside one database. When a booking spans an inventory service and a payment service, use a saga with compensating actions, a reservation with an expiry as above, and idempotency keys. Do not try to stretch a database lock across network calls. See Distributed Transactions.

Worked example: selling the last seat, three ways#

Take one concert seat, seat 14C, and two buyers, Asha and Ben, who click "Buy" within 5 ms of each other. The checkout has three steps. The buyer picks a seat, then spends up to 10 minutes on the payment page, then the payment provider confirms. Here are three designs and how each behaves under that collision.

Design 1: lock the row for the whole checkout. The server runs SELECT ... FOR UPDATE on the seat when Asha picks it, and keeps the transaction open until payment returns. Ben's request blocks on the row lock. Correctness is fine, but the cost is severe. Each in-progress checkout pins one database connection for up to 10 minutes. With a pool of 100 connections and 1,000 people in checkout during an on-sale, 900 requests queue or time out. Worse, if Asha closes her browser, the lock lasts until the application notices or a timeout fires. If the app server crashes mid-transaction, the database rolls back only when it detects the dead connection, which can take minutes with default TCP keepalive settings. This is the design to name and then reject in an interview.

Design 2: short lock plus a reservation with expiry. Picking the seat runs one short transaction:

UPDATE seats
SET status = 'held', held_by = :user, held_until = now() + interval '10 minutes'
WHERE seat_id = '14C'
  AND (status = 'available' OR (status = 'held' AND held_until < now()));
-- 1 row updated: you hold it. 0 rows: someone else does.

The row lock lasts about a millisecond. Asha's update wins, and Ben's update waits that millisecond, re-checks the WHERE clause against the new row version, matches zero rows, and returns "seat taken". When payment succeeds, a second short transaction sets status = 'sold' only WHERE held_by = :user AND held_until > now(). If Asha abandons the page, the hold simply expires. No sweeper is needed for correctness, because every query treats an expired hold as available. A background job may still clear old holds so that dashboards look tidy. The hold is now data, not a lock, so it survives crashes, can be inspected with a query, and costs no connection while the user types a card number.

Design 3: optimistic version check. The seat row carries version. Both buyers read version 7. Asha writes ... SET status='held', version=8 WHERE seat_id='14C' AND version=7 and succeeds. Ben's identical statement matches zero rows, so his client re-reads, sees held, and shows "seat taken". This behaves much like Design 2 for a single seat. It shines when the read and write are far apart, for example a mobile app that loaded the seat map a minute ago.

What changes at scale. For a stadium on-sale with 50,000 buyers aiming at the best 500 seats, the database row is not the real bottleneck. The contention is. Most attempts fail, and each failure costs a round trip and a re-render. Ticketing systems therefore add a virtual waiting room in front of checkout, admitting buyers at a rate the inventory service can serve. They also cache seat-map availability in Redis with short TTLs, and accept that the map can be a second stale because the final reservation update is the source of truth. The lock design stays the same. What changes is how many requests are allowed to reach it.

Concurrency control outside the relational database#

The same three ideas of locking, version checks and atomic operations appear in every data store, under different names.

Redis. Single commands such as INCR, HINCRBY and SET key value NX PX 30000 are atomic, because Redis runs commands one at a time on a single thread per shard. For multi-step logic there are two tools. WATCH key followed by MULTI ... EXEC is optimistic: if a watched key changed before EXEC, the transaction is dropped and the client retries. A Lua script, or a Redis Function, runs atomically on the server, which turns read-check-write into a single step with no retry loop. Use scripts for hot keys, because WATCH retries collapse under the same contention math as any optimistic scheme.

DynamoDB. A write can carry a ConditionExpression, for example attribute_not_exists(pk) for create-if-absent, or version = :v for optimistic updates. A failed condition returns ConditionalCheckFailedException and consumes write capacity. TransactWriteItems groups up to 100 items in one all-or-nothing request, and is about twice the cost of plain writes. A single partition key also has a throughput ceiling, about 1,000 write units a second, so hot items need sharding no matter which concurrency style you choose.

Cassandra. Ordinary writes are last-write-wins by timestamp, so concurrent updates to the same cell silently keep one value. Lightweight transactions (INSERT ... IF NOT EXISTS, UPDATE ... IF col = x) run a Paxos round across replicas and give compare-and-set semantics. They cost about four round trips, so use them only for rare uniqueness checks such as claiming a username.

The single-writer principle. The most scalable answer to contention is often to remove it. Route every update for a key to one owner, such as a Kafka partition consumer, an actor, or one shard leader, and apply updates sequentially in memory. No locks are needed because no two writers exist. The cost is that throughput per key is bounded by one thread, and failover must hand ownership over cleanly, which is where fencing tokens come in.

Testing and observing concurrency bugs#

Race conditions rarely appear in unit tests, because tests run one request at a time. A race needs two operations to overlap inside a window that may be a few milliseconds wide. Several techniques make races visible before production does.

Force the interleaving. Open two database sessions in a test and drive them step by step. Session A reads, session B reads, session A writes and commits, then session B writes. Assert that B's write fails or that the final state is correct. This deterministic test catches lost updates every time, unlike a load test that might hit the window once in a thousand runs. PostgreSQL's own test suite uses this "isolation tester" style, with scripted permutations of steps across sessions.

Hammer a single key. Run 100 concurrent workers that each increment the same counter 1,000 times, then check that the final value is exactly 100,000. Any smaller number proves a lost update. Run the same test with a unique constraint and many concurrent inserts of the same key, to confirm that the application handles the duplicate-key error instead of crashing.

Inject delays. Add a configurable sleep between the read and the write in staging builds. A 200 ms pause turns a microsecond race window into one that ordinary manual testing hits easily. Fault-injection frameworks and chaos tools generalise this by pausing processes, dropping packets or killing a node mid-transaction.

Check isolation claims, do not assume them. The Jepsen project by Kyle Kingsbury has repeatedly found databases that did not provide the isolation or consistency their documentation claimed under partitions and crashes. Its analyses are a good reminder to test the actual guarantee you rely on, at the isolation level you actually run.

Watch locks in production. In PostgreSQL, pg_stat_activity shows sessions with wait_event_type = 'Lock', and pg_blocking_pids(pid) returns which sessions block a given one, which lets you walk a blocking chain to its root. Setting log_lock_waits = on logs any wait longer than deadlock_timeout (1 second by default), so slow lock waits appear in logs with the statements involved. In MySQL, performance_schema.data_locks and data_lock_waits show held and waited-for row locks, and SHOW ENGINE INNODB STATUS prints the most recent deadlock. Useful alerts are: lock wait time at p99, deadlocks per minute, the age of the oldest open transaction, and connections in "idle in transaction" state. A rising oldest-transaction age is often the first sign of a stuck lock holder.

Make retries visible. Count optimistic-lock conflicts, serialization failures and deadlock retries as metrics, labelled by operation. A conflict rate that climbs from 0.1% to 10% during a promotion tells you a hot row has formed long before users report errors. That gives you time to split the row or move the operation to a queue.

When to Use It#

  • Any read-modify-write on shared data: balances, stock, seats, counters with business rules.
  • Check-then-act logic across several rows (booking a slot if no overlap exists).
  • Work queues in a relational database (SKIP LOCKED).
  • Concurrent edits to the same record by users (optimistic).

When NOT to Use It#

  • When one atomic SQL statement or a unique constraint already enforces the rule.
  • Do not hold database locks while calling external APIs or waiting for user input.
  • Do not use database row locks to coordinate work across different databases or services; use a distributed lock or a workflow.

How to Implement It#

  1. Prefer atomic statements and constraints (SET x = x - 1 WHERE x > 0, UNIQUE, CHECK).
  2. For hot, short operations, use SELECT ... FOR UPDATE inside a short transaction; lock rows in a fixed order.
  3. For low-contention or long edits, add a version column and compare-and-set on update.
  4. Handle failures: retry deadlocks and serialization errors with backoff; show a conflict message for user edits.
  5. Set lock and statement timeouts, and run schema changes with low lock timeouts and retries.
  6. Monitor lock waits, deadlock counts and long transactions (pg_locks, performance_schema, InnoDB status).

Trade-offs#

ChoiceGainCostPick when
Atomic UPDATESimplest, no explicit lockOnly for logic expressible in one statementCounters, stock decrement
Pessimistic lockCorrect under heavy contentionWaiting, deadlocks, lower throughputHot rows, short critical sections
Optimistic lockHigh concurrency, no deadlocksRetries and wasted work under contentionRare conflicts, long edits
Serializable isolationCovers complex invariants automaticallyAborts and retriesMulti-row invariants
Reservation with expiry (held_until)No lock during user think time, self-healingExpiry logic in every query, a sweeper for tidinessMulti-step checkouts
SKIP LOCKED queueMany workers, no blocking, one databasePolling cost, idempotent handlers neededUp to thousands of jobs a second
Constraint or exclusion constraintEngine-guaranteed rule, no race possibleOnly for rules expressible as constraintsUniqueness, no-overlap bookings
Split hot rowRemoves the per-row throughput ceilingReads must sum, invariants spread across rowsCounters, flash-sale stock

Common Pitfalls#

  • Read-modify-write in application code with no lock, version or atomic statement.
  • Locking rows in different orders in different code paths, causing deadlocks.
  • Holding a FOR UPDATE lock while calling a payment provider.
  • Forgetting that optimistic locking needs a retry path; failed updates silently ignored.
  • ALTER TABLE waiting for a lock and blocking all traffic behind it.
  • Using a value comparison instead of a version number and falling into the ABA problem.
  • Holding a transaction open across user think time, pinning connections and blocking VACUUM.
  • Retrying only the failed statement after a deadlock instead of the whole transaction.
  • Sending emails or calling APIs inside a retried transaction, so side effects repeat.
  • Session-level advisory locks behind a transaction-mode connection pooler.

Real-World Examples#

PostgreSQL and MySQL 8.0 both support FOR UPDATE SKIP LOCKED, which job-queue libraries built on relational databases use to let many workers take jobs without blocking each other.

Hibernate/JPA's @Version annotation and Rails' lock_version column implement optimistic locking automatically, raising an error when an update finds a changed version.

Google's Spanner paper (OSDI 2012) describes using wound-wait to avoid deadlocks in its distributed two-phase locking, rather than detecting cycles across machines.

PostgreSQL 9.3 introduced the FOR KEY SHARE and FOR NO KEY UPDATE row-lock modes to stop foreign-key checks from blocking ordinary updates of parent rows.

In the Interview#

Handling contention questions in an interview#

Recognise the signal. Any requirement with "only one", "no double", "last item", "first come first served" or "balance never negative" is a concurrency question. Seat booking, auctions, inventory, ride matching (one driver, one rider), coupons with limited uses, and username claims all fall here. Say early that you will protect it, and name how.

Climb the ladder of solutions. Start simple and add machinery only as contention grows:

  1. A constraint or an atomic conditional statement.
  2. A short pessimistic transaction with consistent lock order.
  3. Optimistic versions for long edits.
  4. Reservations with expiry for multi-step flows.
  5. Queues, admission control or split rows for extreme hot spots.
  6. Distributed locks or sagas only when the data spans systems.

Interviewers like seeing you stop at the simplest step that works.

Do not overcomplicate. If the system is a single PostgreSQL database and conflicts are modest, a WHERE stock > 0 condition or a FOR UPDATE is the complete answer. Reaching for Redis locks or ZooKeeper adds failure modes without adding safety.

Follow-ups to expect.

  • "What if the app crashes while holding the lock?" Database locks die with the transaction or connection. Redis locks need a TTL. Holds stored as data need an expiry.
  • "What is the ABA problem?" A value changed and changed back passes a value comparison. Use a version number that only increases.
  • "Everyone wants the same item. Now what?" Admission control or a virtual waiting room, plus short atomic updates. Explain the per-row throughput ceiling with numbers.
Deep Dive: Two-phase locking, MVCC and locks across systemsShow

Two-phase locking (2PL). The classic way to achieve serializability: a transaction acquires locks as it goes (growing phase) and releases them only at the end (shrinking phase). Strict 2PL holds all locks until commit. It is correct but readers block writers, so most modern databases combine MVCC for reads with locks only for writes, and use techniques like SSI for full serializability.

Phantoms and gap locks. Locking existing rows does not stop someone inserting a new matching row (a phantom). InnoDB prevents this for locking reads with gap and next-key locks on the index range; PostgreSQL relies on Serializable (SSI) or on constraints such as exclusion constraints. Without a suitable index, InnoDB may lock far more than you expect, because it locks every record it scans.

Lock contention as a scaling limit. A single hot row (a global counter, a popular item) caps throughput at roughly one transaction per lock hold time: with 5 ms per transaction, about 200 updates per second on that row, regardless of hardware. Fixes: shorten the hold time, split the row (counter shards summed on read), or batch updates.

Beyond one database. Row locks only work inside one database. Across services, use idempotent operations plus a saga, a distributed lock with fencing tokens, or a single owner per key that serialises updates. See Distributed Locking.

Deep Dive: How MVCC and locks interact inside PostgreSQL and InnoDBShow

Two mechanisms, two jobs. MVCC (multi-version concurrency control) lets readers see a consistent snapshot without blocking writers. Locks stop two writers from changing the same row at once. In both PostgreSQL and InnoDB, a plain SELECT takes no row locks. It reads whichever version its snapshot allows. Writers and locking reads take row locks on the latest version.

PostgreSQL's update path. When transaction T2 updates a row that T1 has already updated but not committed, T2 sees T1's ID in the row's xmax, and waits on T1's transaction lock rather than on a row-lock table entry. If T1 commits, then under Read Committed T2 follows the update chain to the newest version and re-checks its WHERE clause. That is the "EvalPlanQual" re-check that makes conditional updates safe. Under Repeatable Read or Serializable, T2 instead fails with a serialization error, because its snapshot is older than the row it would overwrite. If T1 rolls back, T2 proceeds on the original row.

InnoDB's update path. InnoDB updates rows in place and writes the previous version to the undo log. Readers needing an older snapshot rebuild it from undo. Row locks live in the lock system, attached to index records. Under Repeatable Read, locking reads and updates also take gap or next-key locks on the scanned index range, which prevents phantoms for those statements. That is why InnoDB's Repeatable Read blocks some inserts that PostgreSQL's would allow. It is also why a missing index can turn a one-row update into a near-table lock.

Long transactions hurt both. PostgreSQL cannot vacuum row versions that an old snapshot might still need, so tables and indexes bloat. InnoDB cannot purge undo that an old read view needs, so the undo log (the "history list length") grows, and reads slow down as they walk longer version chains. A forgotten open transaction in an idle session is a classic source of both. Monitor transaction age, and set idle_in_transaction_session_timeout in PostgreSQL.

Hot-row techniques the engine cannot do for you. For counters, append deltas to a separate table and roll them up periodically, or shard the counter. For balances, use an append-only ledger of entries with a periodically materialised balance, validated by a constraint on each entry. For inventory, pre-split stock into buckets. Each changes the data model so that concurrent writers touch different rows, which is the only way past the per-row lock ceiling.

Key Takeaways#

  • Read-modify-write without protection causes lost updates; prefer atomic conditional statements when possible.
  • Pessimistic locking (FOR UPDATE, shared/exclusive locks) blocks others and suits hot, short critical sections.
  • Optimistic locking (version column, compare-and-set) avoids locks and suits rare conflicts and long edits, with retries.
  • Deadlocks come from cycles of waits; prevent them with consistent lock order and short transactions, and retry when detected.
  • Finer lock granularity gives more concurrency; know your database's lock types, from row and gap locks to advisory locks.
  • Races need overlap inside the read-write window, so they scale with load and hide in tests.
  • Database locks live until commit, so keep transactions short. Store long holds as data with an expiry.
  • Version numbers avoid the ABA problem. Optimistic retries cost 1 / (1 − p) attempts and collapse under hot contention.
  • Deadlocks need all four Coffman conditions. Break circular wait with lock ordering, and always retry the whole transaction.
  • A hot row caps at about 1 / hold-time transactions per second. Beyond that, change the model with split rows, queues or batching.