Optimistic vs Pessimistic Locking
"The methods used are “optimistic” in the sense that they rely mainly on transaction backup as a control mechanism, “hoping” that conflicts between transactions will not occur." — H. T. Kung and John T. Robinson, On Optimistic Methods for Concurrency Control, ACM Transactions on Database Systems 6(2), June 1981
Summary: Two answers to "two writers want one row": lock first and make the others wait (pessimistic), or let everyone run, check at write time that nothing moved, and retry the loser (optimistic). Focus: version column and compare-and-set, the rows-affected check, retry with backoff, SELECT ... FOR UPDATE and its siblings, NOWAIT and SKIP LOCKED, lock duration and pool exhaustion, edit forms and ETag/If-Match, and the same ideas in Redis, MongoDB, DynamoDB, CockroachDB and Spanner. Learning goal: pick the strategy from contention, transaction length and who is waiting (a user or a worker), write both versions correctly in SQL, Go and Laravel, and know the error codes each one raises.
This page is the complete reference for choosing between optimistic and pessimistic concurrency control on application data. It teaches the strategy and the code. It does not re-teach its neighbours: the lock modes and their full conflict table are in Locks & Concurrency; the anomalies these techniques fix (lost update, write skew) and the isolation levels are in Isolation Levels; how row versions work inside PostgreSQL is in MVCC, VACUUM & Bloat; deadlock detection and lock ordering are in Deadlocks; and the pool that long locks exhaust is in Connection Pooling.
Page map
| If you are looking for | Go to |
|---|---|
| Two tables you can memorise in a minute | Everything in one minute |
| The 1981 paper, read/validate/write, backward vs forward validation | Where it comes from |
| Why two strategies exist and the trade-off | Why two strategies exist |
| Version column, compare-and-set, rows-affected, retry loop, conflict rate | Optimistic locking, concept by concept |
FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE, NOWAIT, SKIP LOCKED, lock duration | Pessimistic locking, concept by concept |
Edit forms, ETag, If-Match, 412, 428 | Across two requests: HTTP |
| PostgreSQL, MySQL, SQL Server, Oracle, SQLite, MongoDB, Redis, DynamoDB, CockroachDB, Spanner, Hibernate | What each product does |
| Exact knobs, SQLSTATE and error codes | Mechanics |
| SQL + Go + Laravel for each classic problem | Solving the classic problems |
| Retry wrapper and error table | Retries and failure handling |
| Which strategy for which workload | Choosing a strategy |
| Replicas, caches, microservices, scaling | In architecture |
| Reproduce it in two terminals | Lab |
| Wrong beliefs, cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The two strategies side by side.
| Optimistic | Pessimistic | |
|---|---|---|
| Bet | Conflicts are rare | Conflicts are likely |
| While reading | No lock | Row lock (FOR UPDATE) |
| Who waits | Nobody; the loser retries | The second writer, in a queue |
| Detected by | UPDATE ... WHERE version = ? affecting 0 rows | The lock itself; no detection needed |
| Cost on a collision | Wasted work plus a retry | Waiting time and a held connection |
| Cost with no collision | One extra column and one WHERE | A lock taken and released for nothing |
| Spans several HTTP requests | Yes (carry the version in an ETag) | No (a lock cannot outlive its transaction) |
| Failure you handle | Zero rows affected, 412, 40001 | Lock timeout 55P03, deadlock 40P01 |
The vocabulary in one table.
| Term | In plain words | Where explained |
|---|---|---|
| Version column | An integer on the row that increases with every write | Version column |
| Compare-and-set (CAS) | "Write only if it is still what I read" | Compare-and-set |
| Rows-affected check | A zero count is the only conflict signal | Rows-affected check |
| Retry loop, backoff, jitter | Redo the work, with growing random pauses | Retry loop |
FOR UPDATE and three weaker modes | Row locks of four strengths | Row-lock modes |
NOWAIT, SKIP LOCKED | Do not wait; or skip the busy row | NOWAIT and SKIP LOCKED |
ETag, If-Match, 412 | The version carried over HTTP | HTTP |
| Hybrid | Read without a lock, lock only to write | Hybrid |
The three things to do.
| Situation | Do this |
|---|---|
| Changing one counter or balance | One atomic UPDATE ... SET x = x - 1 WHERE ... AND x >= 1; neither strategy needed |
| A user edits a record for minutes | Version column plus ETag/If-Match; answer 412 on a stale write |
| Workers draining a queue table | SELECT ... FOR UPDATE SKIP LOCKED |
Where it comes from
Kung and Robinson opened their 1981 paper by describing the status quo: "Most current approaches to concurrency control in database systems rely on locking of data objects as a control mechanism." Their proposal was to drop locks for some workloads and check at the end whether anything went wrong. Each transaction has "two or three phases: a read phase, a validation phase, and a possible write phase".
The three phases. In the read phase the transaction reads shared data and writes only to private copies. In the validation phase the system checks that the transaction's reads and writes are consistent with a serial order. In the write phase, entered only if validation succeeds, the private copies become public. Validation uses a unique transaction number t(i) assigned at the end of the read phase, and a transaction Tj passes if, for every earlier Ti (t(i) < t(j)), one of three conditions holds:
| Condition | Meaning |
|---|---|
| 1 | Ti completes its write phase before Tj starts its read phase (no overlap at all) |
| 2 | Ti's write set does not intersect Tj's read set, and Ti finishes writing before Tj starts writing |
| 3 | Ti's write set intersects neither Tj's read set nor its write set, and Ti finishes its read phase before Tj finishes its read phase |
"If validation does fail, the transaction will be backed up and start over again as a new transaction."
Backward vs forward validation Good to know. The paper's check looks backward: the committing transaction is compared against transactions that already finished. The later literature names this backward-oriented validation (BOCC) and contrasts it with forward-oriented validation (FOCC), where the committing transaction's write set is checked against the read sets of transactions that are still running, so the system may abort the running reader or the committer. I did not read the paper that introduced those two names (Härder, 1984), so treat the names as textbook vocabulary, not as a quotation from Kung and Robinson.
Starvation. The paper's conclusion is the sentence to remember:
"(3) The major difficulty in locking approaches is deadlock, which can be solved by using backup; in an optimistic approach, the major difficulty is starvation, which can be solved by using locking."
Their fix for a transaction whose validation keeps failing is to restart it while holding the commit critical section, "equivalent to write-locking the entire database". A real application does the same on a small scale: after N conflicts, take a row lock.
Version column vs the paper. The paper validates serial equivalence with transaction numbers and read/write sets, not with a version column. The version column is a practical way to run the same check on one row: the "read set" is the row at version v, and the validation is WHERE version = v. The word "pessimistic" does not appear in the parts I read; I have not traced its first use.
HTTP got there too. RFC 9110 defines conditional requests with entity tags, the same compare-and-set between separate requests (HTTP). Fowler's Patterns of Enterprise Application Architecture names the application-level versions Optimistic Offline Lock and Pessimistic Offline Lock; I cite them from memory of the book, not from a fetched page.
Why two strategies exist
Both strategies answer one question: what do you do when two transactions want the same row? Running them one at a time is always correct and always slow. Locking and validation are two ways to get most of the parallelism and still be correct.
| Pessimistic (lock first) | Optimistic (check last) |
|---|---|
| Correct by construction: nobody else can change what you hold | Correct by detection: a changed row makes your write fail |
| Pays on every transaction, even with no contention | Pays only when a collision happens |
| Waiting scales with queue length on a hot row | Wasted work scales with collision rate |
| Needs a transaction held open for the whole decision | Needs only a short transaction at the end |
| Can deadlock | Can starve under heavy contention |
| Cannot span a user's think time | Can span minutes or days |
The analogy we reuse on this page: a train-seat counter. Pessimistic: the clerk puts the seat on hold; nobody else can book it until you pay or the hold expires. You can take as long as you like, but the queue behind you waits. Optimistic: you look at the seat map, note its revision, and hand over your request with that revision. The clerk checks the map has not changed. If it has, you choose again. Nobody waits in line; the people who lose the race come back to the counter.
Three common misunderstandings, up front
- "Optimistic means no locks." The
UPDATEitself takes a row lock while it runs. PostgreSQL documents thatFOR NO KEY UPDATE"is also acquired by any UPDATE that does not acquire a FOR UPDATE lock". Optimistic locking avoids holding a lock across the read and the decision, not during the write. - "A transaction already protects me." A plain
SELECTtakes no lock in PostgreSQL, InnoDB or Oracle. Two transactions can both read stock1and both write0. Wrapping read-modify-write inBEGIN ... COMMITdoes not stop that at Read Committed. - "Pessimistic is the safe default." It can still fail under Repeatable Read and Serializable, it can deadlock, and on a hot row it turns your database into a single-file queue.
Optimistic locking, concept by concept
Version column Must-know
In plain words: a number on each row that goes up by one every time the row is written. You remember the number you read, and your write says "only if it is still that number".
Common misunderstanding: "The version column protects the whole record graph." It protects exactly one row. A rule that spans an order and its lines, or two warehouses, is not guarded unless every writer also bumps one shared row (the aggregate root), or you lock, or you use Serializable (write skew).
Definition: a column version bigint NOT NULL DEFAULT 0 incremented in every UPDATE of that row, and tested in the WHERE clause of every conditional write. Alternatives that play the same role: updated_at with microsecond precision (weak: two writes in one tick collide), a content hash, SQL Server rowversion, Oracle ORA_ROWSCN, PostgreSQL's hidden xmin (used as a concurrency token by some ORMs, but it changes on any rewrite of the tuple, including some no-op updates), MongoDB's __v in Mongoose, DynamoDB's own attribute.
Session A Session B
1 SELECT stock, version FROM products
WHERE id = 42; -- 5, 7
2 SELECT stock, version FROM products
WHERE id = 42; -- 5, 7
3 UPDATE products SET stock = 4, version = 8
WHERE id = 42 AND version = 7; -- 1 row
4 UPDATE products SET stock = 4, version = 8
WHERE id = 42 AND version = 7; -- 0 rows: B got there first
5 -- re-read (stock 4, version 8) and decide againReal scenarios: a CMS page edited by two admins; a product price changed by a pricing job and by a human; a settings JSON saved from two browser tabs; a shopping cart merged from two devices; a Kanban card dragged by two teammates.
| Product | Version token | Conflict signal |
|---|---|---|
| PostgreSQL | version column, or xmin | 0 rows affected |
| MySQL InnoDB | version column | 0 rows (see the FOUND_ROWS trap in Rows-affected check) |
| SQL Server | rowversion column (8 bytes, auto-increments) | 0 rows |
| Oracle | ORA_ROWSCN (coarse unless the table uses ROWDEPENDENCIES) or a version column | 0 rows |
| SQLite | version column | 0 rows; one writer at a time anyway |
| MongoDB | version field, or Mongoose __v with optimisticConcurrency | null from findOneAndUpdate, or matchedCount == 0 |
| DynamoDB | version attribute in a ConditionExpression | ConditionalCheckFailedException |
| Hibernate / JPA | @Version field | OptimisticLockException (StaleObjectStateException in Hibernate) |
Fix / how to use it:
ALTER TABLE products ADD COLUMN version bigint NOT NULL DEFAULT 0;
-- every write bumps it
UPDATE products SET stock = stock - 1, version = version + 1
WHERE id = 42 AND version = 7;The Go and Laravel versions are in Solving: lost update.
Compare-and-set Must-know
In plain words: the database compares and writes in one indivisible step. Either the row is still what you saw and your write lands, or it is not and nothing happens.
Common misunderstanding: "I can do the compare in my application: SELECT, if version == v, then UPDATE." That is a check-then-act race: another writer can slip in between your if and your UPDATE. The comparison must live inside the same statement as the write.
Definition: CAS(location, expected, new): if location == expected then location = new, atomically. In SQL it is UPDATE ... WHERE key = ? AND version = ?. The row lock taken by the UPDATE makes the test and the write atomic: a concurrent writer waits for the lock, then re-evaluates the WHERE on the newly committed row (PostgreSQL at Read Committed does exactly this) and finds the version changed.
Session A Session B
1 BEGIN; BEGIN;
2 UPDATE products SET version = 8, stock = 4
WHERE id = 42 AND version = 7; -- row locked, 1 row
3 UPDATE products SET version = 8, stock = 4
WHERE id = 42 AND version = 7; -- WAITS
4 COMMIT; -- wakes, re-checks WHERE: version is 8 now
5 -- 0 rows affected, no overwriteReal scenarios: the same primitive appears as Redis WATCH, DynamoDB conditional writes, MongoDB's filter on findOneAndUpdate, etcd transactions with a revision compare, HTTP If-Match, and the CPU CMPXCHG instruction.
| Product | CAS primitive |
|---|---|
| Any SQL database | UPDATE ... WHERE version = ? and the row count |
| Redis | WATCH key then MULTI/EXEC; EXEC returns nil if the key changed; or a Lua script |
| MongoDB | findOneAndUpdate({_id, version}, {$set, $inc: {version: 1}}) |
| DynamoDB | PutItem/UpdateItem with ConditionExpression |
| HTTP | If-Match with an entity tag |
Fix / how to use it: put the condition in the WHERE; never in an if on the application side.
Rows-affected check Must-know
In plain words: the number of rows your UPDATE changed is the only message that tells you whether you won.
Common misunderstanding: "The UPDATE did not throw, so it worked." A conditional UPDATE that matches nothing succeeds with zero rows. No exception, no warning. If your code ignores the count, you have no conflict detection at all, and the lost update is back.
Definition: read the affected-row count from the driver and treat 0 as a conflict (or a missing row).
| Stack | Where the count is | Trap |
|---|---|---|
Go database/sql | res.RowsAffected() | Some drivers return an error if unsupported; always check it |
Go pgx | CommandTag.RowsAffected() | None |
| MySQL protocol | "affected rows" | By default MySQL reports rows changed, not rows matched. Because version = version + 1 always changes the row, it works; if you ever rewrite the same value you get 0 and a false conflict. Drivers expose CLIENT_FOUND_ROWS (Go clientFoundRows=true, PDO PDO::MYSQL_ATTR_FOUND_ROWS) to count matched rows |
| Laravel query builder | ->update([...]) returns the count | Eloquent's save() hides it; use the builder |
| Laravel Eloquent | Model::query()->whereKey($id)->where('version', $v)->update([...]) | Same count |
PostgreSQL UPDATE ... RETURNING | Zero rows returned | Alternative signal, also yields the new version in one trip |
UPDATE products SET stock = stock - 1, version = version + 1
WHERE id = 42 AND version = 7
RETURNING stock, version; -- no row returned means a conflictReal scenario: a team added version columns but used Eloquent's save(); the column grew, nothing was ever checked, and lost updates continued for a year.
Retry loop, backoff and jitter Must-know
In plain words: when you lose, read the row again, redo the decision, try again, but not immediately and not forever.
Common misunderstanding: "Just retry the UPDATE." You must re-read and re-decide, because the facts changed (stock may now be 0). Retrying the same UPDATE with the same version can never succeed.
Definition: a bounded loop of read, decide, conditional write. Between attempts sleep for a full-jitter delay: random in [0, min(cap, base * 2^attempt)]. Without jitter, contenders that lost together retry together and collide again. After the last attempt return a typed conflict error that the caller maps to 409 Conflict or 412 Precondition Failed.
attempt 1: read v7 ── decide ── UPDATE ... v7 ── 0 rows ── sleep rand(0..20ms)
attempt 2: read v8 ── decide ── UPDATE ... v8 ── 0 rows ── sleep rand(0..40ms)
attempt 3: read v9 ── decide ── UPDATE ... v9 ── 1 row ── done
attempt 6: give up ── ErrConflict ── HTTP 409 / 412Real scenarios: an inventory service under a sale; a collaborative editor autosaving; a leaderboard with a score per player; a quota counter per tenant.
| Rule | Why |
|---|---|
| Cap attempts (3 to 6) | A hot row is a spin loop otherwise |
| Re-read inside every attempt | The decision depends on fresh state |
| Full jitter, exponential ceiling | Breaks lockstep retries |
| Honour the request context | A cancelled request must stop sleeping |
| Keep side effects out of the loop (or idempotent) | The loop runs your code more than once |
| Count and log conflicts | The conflict rate is the health metric of this strategy |
Fix / how to use it: the full Go loop (optimistic/main.go) and Laravel retry() version (Optimistic.php) are in Solving: lost update.
Conflict rate and when optimistic loses Must-know
In plain words: optimistic locking is cheap when collisions are rare and expensive when everyone wants the same row.
Common misunderstanding: "Retries are cheap, so optimistic scales." Each lost round throws away a full read, a decision and a write attempt. On a hot row, if n clients all retry in lockstep, one wins per round, so the total attempts are n + (n-1) + ... + 1 = n(n+1)/2. Pessimistic locking makes the same n clients take n turns with no wasted attempts.
Concurrent writers on one row (n) | Attempts, optimistic, lockstep worst case | Lock acquisitions, pessimistic |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 3 | 2 |
| 5 | 15 | 5 |
| 10 | 55 | 10 |
| 50 | 1275 | 50 |
Jitter and backoff spread the retries and cut the real number well below the worst case, but the shape stays: the work wasted grows faster than linearly with contention, while the queue on a lock grows linearly. Starvation (the paper's word) is also real: an unlucky transaction can lose many rounds in a row.
Real scenarios where optimistic loses: one global counter row; a "current auction price" row during the last seconds; one inventory row in a flash sale; a single sequence row; a job-claim table. All of them want an atomic UPDATE ... SET x = x + 1, a lock, or SKIP LOCKED, not a retry loop.
| Signal | Meaning | Action |
|---|---|---|
| Conflict rate under ~1% | Optimistic is fine | Keep it |
| Conflict rate 5 to 20% | Contention rising | Add backoff; look for a hot row |
| Retries exhausting often | Hot row | Atomic UPDATE, shard the counter, or switch to a lock |
| Same row, many writers, short critical section | Lock is cheaper | Pessimistic FOR UPDATE |
Hybrid: optimistic read, pessimistic write Important
In plain words: read and think without holding anything, then take the lock only for the instant you write, and re-check the version under that lock.
Common misunderstanding: "Pick one strategy per system." Real systems mix: optimistic across a long think time, pessimistic for the short commit, atomic updates for counters.
Definition: phase 1 reads the row and its version with no lock; phase 2 does the slow work (a pricing engine, a call to another service); phase 3 opens a short transaction, locks the row (FOR NO KEY UPDATE), compares the version, writes, commits. A changed version means phase 2's result is stale and is discarded.
Worker Database
1 SELECT price, version FROM products ... ──▶ -- v7, no lock
2 compute new price (2 seconds) -- nothing held
3 BEGIN; SELECT version ... FOR NO KEY UPDATE ─▶ -- lock, short
4 if version != 7 -> ROLLBACK, redo or report
5 UPDATE ... SET version = 8; COMMIT; ──▶ -- lock releasedReal scenarios: repricing, report generation that writes a summary row, a checkout that calls a payment provider before finalising the order, an import that validates against reference data.
Fix / how to use it: hybrid/main.go in Solving: hybrid.
Pessimistic locking, concept by concept
Row-lock modes: FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE Must-know
In plain words: four strengths of "I am using this row". The stronger the lock, the more other transactions it blocks.
Common misunderstanding: "FOR UPDATE is the only lock, and FOR SHARE is just a read." FOR SHARE blocks every writer of the row. And the weakest mode, FOR KEY SHARE, is taken automatically on the referenced row by foreign-key checks, so ordinary inserts take row locks you never wrote.
Definition (PostgreSQL):
"FOR UPDATE causes the rows retrieved by the SELECT statement to be locked as though for update. This prevents them from being locked, modified or deleted by other transactions until the current transaction ends."
"Behaves similarly to FOR UPDATE, except that the lock acquired is weaker: this lock will not block SELECT FOR KEY SHARE commands that attempt to acquire a lock on the same rows. This lock mode is also acquired by any UPDATE that does not acquire a FOR UPDATE lock."
| Mode | Blocks (other transactions' attempts) | Taken automatically by |
|---|---|---|
FOR UPDATE | All four modes, UPDATE, DELETE | DELETE; UPDATE that changes a key column |
FOR NO KEY UPDATE | FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, plus UPDATE and DELETE | UPDATE that does not change a key |
FOR SHARE | FOR UPDATE, FOR NO KEY UPDATE, UPDATE, DELETE (not other FOR SHARE/FOR KEY SHARE) | Nothing |
FOR KEY SHARE | FOR UPDATE, DELETE, and an UPDATE that changes key values | Foreign-key checks on the referenced row |
| Product | Syntax |
|---|---|
| PostgreSQL | FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE |
| MySQL InnoDB 8 | FOR UPDATE, FOR SHARE (older LOCK IN SHARE MODE); no key-level variants |
| SQL Server | Hints: UPDLOCK, HOLDLOCK, ROWLOCK, XLOCK, READPAST |
| Oracle | FOR UPDATE [OF col] [NOWAIT | WAIT n | SKIP LOCKED] |
| SQLite | None; one writer for the whole database (BEGIN IMMEDIATE) |
| CockroachDB | FOR UPDATE, FOR SHARE (the NO KEY/KEY SHARE spellings are accepted and behave as the stronger forms), with NOWAIT/SKIP LOCKED |
| Spanner | Read-write transactions lock automatically; FOR UPDATE is supported in GoogleSQL for explicit locks |
| MongoDB, Redis, DynamoDB | No row locks; use CAS (or WATCH) |
Prefer FOR NO KEY UPDATE when you are not changing a key column: it does not block foreign-key inserts that only need FOR KEY SHARE on the row, which removes a classic source of lock waits on parent tables.
Real scenarios: FOR UPDATE on an account before debit; FOR NO KEY UPDATE on an order that has children being inserted; FOR SHARE on a currency row that a batch must see unchanged; automatic FOR KEY SHARE on a customers row when orders are inserted.
T1 T2
1 BEGIN;
2 SELECT * FROM accounts WHERE id = 1
FOR UPDATE; -- lock held
3 UPDATE accounts SET owner = 'x' WHERE id = 1; -- WAITS
4 UPDATE accounts SET balance = balance - 100
WHERE id = 1;
5 COMMIT; -- T2 resumes, sees the committed rowFix / how to use it: Solving: lost update, pessimistic variant.
NOWAIT and SKIP LOCKED Must-know
In plain words: NOWAIT says "if the row is busy, fail now". SKIP LOCKED says "if the row is busy, pretend it is not there".
Common misunderstanding: "SKIP LOCKED is a safe way to read." It returns a deliberately incomplete answer. PostgreSQL warns:
"Skipping locked rows provides an inconsistent view of the data, so this is not suitable for general purpose work, but can be used to avoid lock contention with multiple consumers accessing a queue-like table."
Definition:
"With NOWAIT, the statement reports an error, rather than waiting, if a selected row cannot be locked immediately."
NOWAIT and SKIP LOCKED apply only to the row locks; the table-level ROW SHARE lock is still taken the ordinary way. NOWAIT raises SQLSTATE 55P03 in PostgreSQL, 3572 in MySQL, ORA-00054 in Oracle. SKIP LOCKED is in PostgreSQL 9.5+, MySQL 8.0.1+, MariaDB 10.6+, Oracle, CockroachDB; SQL Server's equivalent is the READPAST hint.
Worker 1 Worker 2 Worker 3
1 BEGIN; BEGIN; BEGIN;
2 SELECT id FROM jobs WHERE status='pending'
ORDER BY id LIMIT 1
FOR UPDATE SKIP LOCKED; -- job 1
3 SELECT ... SKIP LOCKED; -- job 2 (job 1 skipped)
4 SELECT ... SKIP LOCKED; -- job 3
5 UPDATE jobs SET status='done' ...; COMMIT; ... ...Real scenarios: the Laravel database queue; email outbox relays; payment-capture batches; a pool of crawlers claiming URLs; a report scheduler that must not double-run.
| Option | Behaviour | Use for |
|---|---|---|
| (none) | Wait (until lock_timeout or forever) | Short, hot critical sections |
NOWAIT | Error 55P03 at once | A user-facing request that should say "busy" |
SKIP LOCKED | Locked rows are invisible to this statement | Work queues, claim-one-of-many |
lock_timeout | Wait at most N ms, then 55P03 | A safety net on every transaction |
Fix / how to use it: worker/main.go, nowait/main.go and JobClaim.php in Solving: job queue.
Lock duration equals transaction length Must-know
In plain words: a row lock is released only when the transaction ends, not when your statement ends.
Common misunderstanding: "I locked the row, read it, and moved on; the lock is gone after the SELECT." It stays until COMMIT or ROLLBACK, however long your code (HTTP calls, queue publishes, sleeps) takes in between. PostgreSQL says: "Once acquired, a lock is normally held until the end of the transaction." The one exception: a lock taken after a savepoint is released if that savepoint is rolled back to.
Definition: the lock's lifetime is BEGIN to COMMIT/ROLLBACK; an abandoned connection ends it only when the server notices the disconnect, or when idle_in_transaction_session_timeout kills the session.
T1 (slow handler) T2..T20 (same row)
1 BEGIN; SELECT ... FOR UPDATE; each: SELECT ... FOR UPDATE -- WAIT
2 call payment API (1.8 s) each holds a pooled connection
3 UPDATE ...; COMMIT; the first resumes; 18 still waitReal scenarios: a handler that calls Stripe or an email API inside DB::transaction; an admin screen that opens a transaction on page load; an ORM session left open in a long job.
Fix / how to use it: do remote calls before BEGIN or after COMMIT; set lock_timeout and idle_in_transaction_session_timeout; keep the critical section a few milliseconds.
Long-held locks and connection-pool exhaustion Must-know
In plain words: every transaction waiting on a lock is also holding a database connection. Enough waiters and nobody else, even readers of other tables, can get a connection.
Common misunderstanding: "Only the locked row is affected." A queue of waiters on one row can use every connection in the pool, so requests that touch unrelated tables time out waiting for a connection. The outage looks like "the database is down" while the database is idle.
pool size 10, hot row held 1 s, 100 requests/s hitting it
t=0 10 connections: 1 holds the lock, 9 wait
t=1s 100 more requests queue for a connection; every other endpoint times out| Layer | Knob | Effect |
|---|---|---|
Go database/sql | SetMaxOpenConns, SetConnMaxLifetime, context deadlines | Bounds the pool; a deadline cancels a waiter |
| PgBouncer (transaction mode) | default_pool_size, query_wait_timeout | A server connection is pinned from BEGIN to COMMIT |
| PostgreSQL | lock_timeout, statement_timeout, idle_in_transaction_session_timeout, max_connections | Ends waits and idle transactions |
| MySQL | innodb_lock_wait_timeout (default 50 s) | Error 1205 after the wait |
| Laravel | PHP-FPM workers each hold one connection; DB::transaction | Pool size equals worker count |
Fix / how to use it: short transactions, NOWAIT or lock_timeout on user-facing paths, a separate pool for batch work, and atomic updates for hot counters. See Connection Pooling.
Why a database lock cannot span two requests Must-know
In plain words: a form is loaded in one HTTP request and submitted in another, and a database lock cannot live between them.
Common misunderstanding: "Open the transaction when the form loads and commit when it is submitted." Each HTTP request normally gets its own connection from a pool, there is no guarantee the next request reaches the same process, the user may never come back, and PostgreSQL's own manual says "it is a bad idea for applications to hold transactions open for long periods of time (e.g., while waiting for user input)". A session-level advisory lock is tied to a pooled connection and has the same problem.
| Approach | Works across requests? | Notes |
|---|---|---|
| Transaction open between requests | No | Pins a connection, blocks others, dies on disconnect |
pg_advisory_lock (session) | Only on a dedicated connection | Lost on pool reuse; invisible leak |
Lock row with expiry (lease): locked_by, locked_until | Yes | A "soft lock" you implement; Fowler's Pessimistic Offline Lock idea; needs expiry and a release path |
Version carried in ETag/hidden field | Yes | Optimistic offline lock; the standard answer |
Fix / how to use it: Across two requests: HTTP.
Across two requests: HTTP
ETag, If-Match and 412 Precondition Failed Must-know
In plain words: the server hands the form a version stamp (the ETag). The browser sends it back with the save (If-Match). If the stamp is stale the server refuses with 412.
Common misunderstanding: "ETag is only for caching." It is the same validator, but If-Match turns it into optimistic concurrency for writes. Also: a weak tag (W/"7") does not work for it, because the server must use the strong comparison.
Definition:
"If-Match is most often used with state-changing methods (e.g., POST, PUT, DELETE) to prevent accidental overwrites when multiple user agents might be acting in parallel on the same resource (i.e., to prevent the "lost update" problem)."
RFC 9110 also says an origin server "MUST use the strong comparison function when comparing entity tags for If-Match". If the condition is false the server must not perform the method and responds 412 (Precondition Failed). (It may instead answer 2xx if the change already appears applied.)
Browser A Server Browser B
1 GET /articles/42 ─────▶ 200, ETag: "7"
2 GET /articles/42 ─▶ 200, ETag: "7"
3 PUT /articles/42
If-Match: "7" ──▶ 200, ETag: "8"
4 PUT /articles/42
If-Match: "7" ─────▶ 412 Precondition Failed
5 reload, show diff, let the user merge| Status | When |
|---|---|
200/204 | Tag matched, write done, new ETag returned |
412 Precondition Failed | If-Match present and stale |
428 Precondition Required | You require If-Match and the client sent none (RFC 6585) |
409 Conflict | A business-level conflict that is not a header check (also the usual code for a retried-out CAS) |
304 Not Modified | If-None-Match on a GET (caching, not locking) |
| Header | Role |
|---|---|
ETag | The validator in a response (strong "7" or weak W/"7") |
If-Match | Write only if current tag matches (strong comparison) |
If-None-Match: * | Create only if the resource does not exist |
If-Unmodified-Since | Same idea with a date; second-granular, weaker |
Build the tag from the version column, not from updated_at alone: two writes in the same second would share a tag and the lost update returns.
Real scenarios: a REST/JSON admin API; a wiki page editor; a configuration service; S3-style object stores; Kubernetes resourceVersion on updates (same mechanism: a stale resourceVersion gives 409).
Fix / how to use it: etag/main.go and ArticleEtagController.php in Solving: edit form.
What each product does
| Product | Default concurrency | Optimistic tool | Pessimistic tool | Notes |
|---|---|---|---|---|
| PostgreSQL | MVCC; Read Committed | version column, xmin | FOR UPDATE family, NOWAIT, SKIP LOCKED, advisory locks | At Repeatable Read, a locked row changed since the snapshot raises 40001 |
| MySQL InnoDB | MVCC; Repeatable Read | version column | FOR UPDATE, FOR SHARE, NOWAIT, SKIP LOCKED (8.0.1+) | Locking reads see the latest committed row, not the snapshot; gap locks can block inserts |
| SQL Server | Locking Read Committed (or RCSI) | rowversion | UPDLOCK, XLOCK, READPAST, HOLDLOCK | Snapshot isolation raises error 3960 on a write conflict |
| Oracle | MVCC; Read Committed | ORA_ROWSCN, version column | FOR UPDATE [NOWAIT / WAIT n / SKIP LOCKED] | ORA-00054 resource busy; serializable raises ORA-08177 |
| SQLite | One writer, serializable | Version column | BEGIN IMMEDIATE takes the write lock | SQLITE_BUSY instead of row waits; busy_timeout |
| MongoDB | Document-level atomic writes | findOneAndUpdate with a version filter; Mongoose optimisticConcurrency | No row locks; transactions abort on WriteConflict | Multi-document transactions retry with TransientTransactionError |
| Redis | Single command thread | WATCH/MULTI/EXEC, Lua scripts | SET key val NX PX leases (a lock service, not a row lock) | EXEC returns nil if a watched key changed |
| DynamoDB | Item-level atomic writes | ConditionExpression on version | None (transactions via TransactWriteItems) | ConditionalCheckFailedException |
| CockroachDB | Serializable | The same version column | SELECT ... FOR UPDATE (reduces retries) | Retryable errors 40001; client retry loop expected |
| Spanner | Strict serializable | Version column | Read-write transactions lock; ABORTED on contention | Client libraries retry the transaction function |
| Hibernate / JPA | Persistence context | @Version | LockModeType.PESSIMISTIC_WRITE (adds FOR UPDATE), OPTIMISTIC_FORCE_INCREMENT | OptimisticLockException; Rails has lock_version and StaleObjectError |
Serializable Snapshot Isolation as database-level OCC Important
In plain words: PostgreSQL's Serializable level is optimistic locking done by the database for you: nothing blocks, and a transaction that would break serial order is aborted.
Common misunderstanding: "Serializable means pessimistic and slow." In PostgreSQL, SSI adds read-dependency tracking (SIReadLocks that never block) on top of Repeatable Read and aborts one participant of a dangerous structure with 40001. It is the same bargain as a version column, applied to every read.
Definition: the application cost is the same as ours: catch 40001 and retry the whole transaction. The database detects conflicts across rows and predicates, which a single version column cannot (write skew). InnoDB's Serializable is the opposite design (two-phase locking: reads take shared locks).
| Engine | Serializable is | Failure signal |
|---|---|---|
| PostgreSQL | Optimistic (SSI) | 40001 serialization_failure |
| MySQL InnoDB | Pessimistic (2PL, locks every read) | 1213 deadlock, 1205 timeout |
| CockroachDB | Optimistic-style with write intents and timestamp pushes | 40001 restart |
| SQL Server | Pessimistic (range locks) | Deadlock 1205 |
| Oracle | Snapshot isolation (not truly serializable) | ORA-08177 |
Fix / how to use it: see Isolation Levels and the retry wrapper in Retries.
Other stores: Redis, MongoDB, DynamoDB Important
In plain words: key-value and document stores have no row locks, so optimistic compare-and-set is the primary tool.
Common misunderstanding: "WATCH locks the key." It does not. It marks the key; if anyone modifies it before EXEC, the whole transaction is abandoned and EXEC returns nil.
Client A Client B
1 WATCH stock:42
2 GET stock:42 -- "5"
3 SET stock:42 4
4 MULTI
5 SET stock:42 4
6 EXEC -- nil: the watched key changed, nothing executed// go-redis: Watch runs fn; errOutOfStock is an application error defined elsewhere.
// redis.TxFailedErr means a watched key changed, and retrying is up to the caller.
err := rdb.Watch(ctx, func(tx *redis.Tx) error {
n, err := tx.Get(ctx, "stock:42").Int()
if err != nil {
return err
}
if n <= 0 {
return errOutOfStock
}
_, err = tx.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.Set(ctx, "stock:42", n-1, 0)
return nil
})
return err
}, "stock:42") // err == redis.TxFailedErr means "someone changed it: retry"// MongoDB: version in the filter, returnDocument "after"
const doc = await db.collection("products").findOneAndUpdate(
{ _id: 42, version: 7 },
{ $set: { stock: 4 }, $inc: { version: 1 } },
{ returnDocument: "after" }
); // doc === null: somebody else moved the version (a conflict)DynamoDB UpdateItem
UpdateExpression: SET stock = :new, version = :next
ConditionExpression: version = :expected
-> ConditionalCheckFailedException on a stale writeReal scenarios: rate limiters and counters in Redis; shopping carts in DynamoDB; profile documents in MongoDB.
Fix / how to use it: for a simple counter in Redis use INCR/DECR (atomic) or a Lua script; use WATCH when the new value depends on a read.
Mechanics
What an UPDATE does to the row, and what a lock costs Important
In plain words: a conditional UPDATE already locks the row for the instant it runs; FOR UPDATE just makes that lock last until commit.
Common misunderstanding: "Row locks live in a lock table in memory." In PostgreSQL the row lock is recorded in the tuple header (the xmax of the row version), with a heavyweight lock only taken on the transaction ID when someone has to wait. Locking many rows therefore writes to pages, not just to memory; SELECT ... FOR UPDATE over a million rows dirties a million tuples. Using FOR UPDATE as a "reservation system" on big scans is expensive. (See MVCC, VACUUM & Bloat.) InnoDB keeps record locks in an in-memory lock structure instead.
Definition: at Read Committed in PostgreSQL, a SELECT ... FOR UPDATE that waits on a row locks and returns the updated version of that row (or no row if it was deleted); at Repeatable Read or Serializable the same situation raises 40001: "an error will be thrown if a row to be locked has changed since the transaction started."
Isolation level changes what a conflict looks like Must-know
| Level and product | UPDATE ... WHERE version = ? loses | SELECT FOR UPDATE on a row changed after the snapshot |
|---|---|---|
| PostgreSQL Read Committed | Waits, re-evaluates WHERE, 0 rows | Waits, returns the latest row |
| PostgreSQL Repeatable Read | 40001 "could not serialize access due to concurrent update" | 40001 |
| MySQL InnoDB Repeatable Read | Waits, then re-evaluates against latest committed; 0 rows | Reads latest committed (not the snapshot) |
| SQL Server Snapshot | Error 3960 (update conflict) | Not applicable (locks are taken) |
| Oracle Read Committed | Waits, restarts statement | Waits |
| CockroachDB Serializable | 40001 restart | Waits in the lock table |
So the retry wrapper must catch both "0 rows" and "serialization failure".
Error codes and knobs Must-know
| Product | Condition | Code or message | Retry? |
|---|---|---|---|
| PostgreSQL | Serialization failure | SQLSTATE 40001 | Yes, whole transaction |
| PostgreSQL | Deadlock | 40P01 | Yes, whole transaction |
| PostgreSQL | NOWAIT hit a lock, or lock_timeout expired | 55P03 lock_not_available | Maybe: report "busy" or retry with backoff |
| PostgreSQL | statement_timeout | 57014 query_canceled | Usually no |
| MySQL | Deadlock | 1213 (SQLSTATE 40001) | Yes |
| MySQL | Lock wait timeout (innodb_lock_wait_timeout, default 50 s) | 1205 | Maybe |
| MySQL | NOWAIT hit a lock | 3572 | Maybe |
| SQL Server | Snapshot update conflict | 3960 | Yes |
| SQL Server | Deadlock victim; lock timeout | 1205; 1222 | Yes; maybe |
| Oracle | NOWAIT hit a lock | ORA-00054 | Maybe |
| Oracle | Cannot serialize | ORA-08177 | Yes |
| Application | Version mismatch | 0 rows affected, your typed error | Yes, with re-read |
| HTTP | Stale If-Match | 412 | Client reloads, user merges |
| MongoDB | Transaction write conflict | WriteConflict, label TransientTransactionError | Yes |
| DynamoDB | Stale condition | ConditionalCheckFailedException | Yes, re-read |
| Redis | Watched key changed | EXEC returns nil (redis.TxFailedErr in go-redis) | Yes |
| Knob | Default | Use |
|---|---|---|
lock_timeout (PostgreSQL) | 0 (wait forever) | Bound the lock wait; error 55P03 |
statement_timeout | 0 | Bound any statement |
idle_in_transaction_session_timeout | 0 | Kill a session that sits in an open transaction |
deadlock_timeout | 1 s | When the deadlock check starts |
innodb_lock_wait_timeout | 50 s | MySQL lock wait |
SET LOCK_TIMEOUT (SQL Server) | -1 (infinite) | Same idea |
busy_timeout (SQLite) | 0 | Wait for the write lock |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost or limit |
|---|---|---|---|---|
| Lost update on a counter | Atomic UPDATE x = x - 1 | One statement, no read | No lock held, no retry | Only when the change is a function of the current value |
| Lost update on a record | Version column | WHERE version = ? | No lock across reads | Retry or conflict path |
| Same, hot row | FOR UPDATE | Lock then write | No wasted work | Queue and connection use |
| Edit form | ETag/If-Match | Version over HTTP | Spans minutes | User must resolve 412 |
| Job claim | FOR UPDATE SKIP LOCKED | Each worker gets a free row | No waiting | Handler holds a connection |
| Rule across rows | Lock parent in a fixed order, or Serializable | One row guards the rule | Correct | Contention on the parent |
| Slow decision, short write | Hybrid | Version check under a short lock | Best of both | Two code paths |
| Fail fast for users | NOWAIT | Error 55P03 | No queue | Caller handles "busy" |
Lost update: version column and FOR UPDATE Must-know
The bug (a read-modify-write with no protection):
// Package before shows a read-modify-write with no concurrency control.
// It is wrong under concurrency: it is a lost update in waiting.
package before
import (
"context"
"database/sql"
"errors"
)
var ErrOutOfStock = errors.New("out of stock")
// Reserve reads the stock level, checks it in Go, and writes back a value
// computed in Go. Two callers can both read 1, both pass the check, and both
// write 0, so one reservation is silently lost.
func Reserve(ctx context.Context, db *sql.DB, id int64) error {
var stock int64
if err := db.QueryRowContext(ctx,
`SELECT stock FROM products WHERE id = $1`, id).Scan(&stock); err != nil {
return err
}
if stock <= 0 {
return ErrOutOfStock
}
_, err := db.ExecContext(ctx,
`UPDATE products SET stock = $1 WHERE id = $2`, stock-1, id)
return err
}SQL fixes, in order of preference:
-- 1. Atomic update: the best answer for a counter. No SELECT at all.
UPDATE products SET stock = stock - 1 WHERE id = 42 AND stock >= 1; -- 0 rows: out of stock
-- 2. Version column: compare-and-set.
UPDATE products SET stock = stock - 1, version = version + 1 WHERE id = 42 AND version = 7;
-- 3. Pessimistic: lock, check, write, commit.
BEGIN;
SELECT stock FROM products WHERE id = 42 FOR UPDATE;
UPDATE products SET stock = stock - 1 WHERE id = 42;
COMMIT;Go, optimistic: it re-reads on every attempt, uses the version as the guard, treats zero rows as a conflict and retries with jittered backoff. The context cancels the waits.
// Package optimistic reserves stock with a version column and compare-and-set.
// No row lock is held between the read and the write. A conflicting writer
// makes the UPDATE match zero rows, and the caller retries.
package optimistic
import (
"context"
"database/sql"
"errors"
"math/rand/v2"
"time"
)
var (
ErrOutOfStock = errors.New("out of stock")
// ErrConflict means every attempt lost the race. An HTTP handler can map it
// to 409 Conflict, or to 412 Precondition Failed when the client sent If-Match.
ErrConflict = errors.New("optimistic: version conflict, attempts exhausted")
)
const maxAttempts = 5
type Store struct {
DB *sql.DB
}
// Reserve decrements stock by one. It returns sql.ErrNoRows if the product
// does not exist, ErrOutOfStock if nothing is left, and ErrConflict if the
// row kept changing under us.
func (s *Store) Reserve(ctx context.Context, id int64) error {
for attempt := 1; attempt <= maxAttempts; attempt++ {
var stock, version int64
if err := s.DB.QueryRowContext(ctx,
`SELECT stock, version FROM products WHERE id = $1`, id).Scan(&stock, &version); err != nil {
return err
}
if stock <= 0 {
return ErrOutOfStock
}
res, err := s.DB.ExecContext(ctx,
`UPDATE products SET stock = stock - 1, version = version + 1
WHERE id = $1 AND version = $2`, id, version)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 1 {
return nil
}
// n == 0: another writer bumped the version after our read.
// If the row was deleted meanwhile, the next read returns sql.ErrNoRows.
if err := sleep(ctx, backoff(attempt)); err != nil {
return err
}
}
return ErrConflict
}
// backoff returns a full-jitter delay that grows with the attempt number.
func backoff(attempt int) time.Duration {
ceiling := time.Duration(10<<attempt) * time.Millisecond
return rand.N(ceiling)
}
func sleep(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}Go, pessimistic: every statement runs on tx, not db, so the lock and the check belong to one transaction; the deferred Rollback releases the lock on every error path.
// Package pessimistic reserves stock by locking the row for the whole
// transaction. Other writers wait at SELECT ... FOR UPDATE until we commit.
package pessimistic
import (
"context"
"database/sql"
"errors"
)
var ErrOutOfStock = errors.New("out of stock")
// Reserve holds the row lock from the read until Commit. Every statement runs
// on tx, not on db, so the lock and the check belong to one transaction.
func Reserve(ctx context.Context, db *sql.DB, id int64) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
// Rollback after a successful Commit returns sql.ErrTxDone and does nothing.
defer tx.Rollback()
var stock int64
if err := tx.QueryRowContext(ctx,
`SELECT stock FROM products WHERE id = $1 FOR UPDATE`, id).Scan(&stock); err != nil {
return err
}
if stock <= 0 {
return ErrOutOfStock
}
if _, err := tx.ExecContext(ctx,
`UPDATE products SET stock = stock - 1 WHERE id = $1`, id); err != nil {
return err
}
return tx.Commit()
}Laravel, the bug (save() writes the value PHP computed):
<?php
// Read-modify-write through Eloquent. Under concurrency two requests can both
// load stock = 1, both decrement it in PHP, and both save 0: one sale is lost.
namespace App\Services;
use App\Models\Product;
final class StockBefore
{
public function reserve(int $productId): void
{
$product = Product::query()->findOrFail($productId);
if ($product->stock > 0) {
$product->stock--;
$product->save(); // UPDATE products SET stock = 0 WHERE id = ...
}
}
}Laravel, optimistic with the query builder and retry():
<?php
// Optimistic reservation: a version column and compare-and-set. No row lock is
// held between the read and the write. Zero affected rows means another writer
// won the race, so we back off and retry.
namespace App\Services;
use App\Exceptions\OutOfStockException;
use App\Exceptions\StockConflictException;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Throwable;
final class OptimisticStock
{
private const MAX_ATTEMPTS = 5;
public function reserve(int $productId): void
{
retry(
self::MAX_ATTEMPTS,
fn () => $this->attempt($productId),
// Full jitter: a random sleep up to an exponentially growing ceiling.
fn (int $attempt, Throwable $e): int => random_int(0, 10 * (2 ** $attempt)),
// Retry only on a lost race. Out of stock and missing rows are final.
fn (Throwable $e): bool => $e instanceof StockConflictException,
);
}
private function attempt(int $productId): void
{
$row = DB::table('products')
->select('stock', 'version')
->where('id', $productId)
->first();
if ($row === null) {
throw new RuntimeException("Product {$productId} not found.");
}
if ($row->stock <= 0) {
throw new OutOfStockException("Product {$productId} is out of stock.");
}
$affected = DB::table('products')
->where('id', $productId)
->where('version', $row->version)
->update([
'stock' => DB::raw('stock - 1'),
'version' => DB::raw('version + 1'),
]);
if ($affected === 0) {
throw new StockConflictException("Version {$row->version} of product {$productId} changed.");
}
}
}Both reservation classes import their exceptions from one file:
<?php
// app/Exceptions/StockExceptions.php: shared by the optimistic and pessimistic
// reservation classes. Both files import them from here.
namespace App\Exceptions;
use RuntimeException;
// Lost the compare-and-set race. Retryable.
final class StockConflictException extends RuntimeException {}
// Final answer, never retried.
final class OutOfStockException extends RuntimeException {}Laravel, pessimistic: lockForUpdate() inside DB::transaction, so a failure rolls back and releases the lock. sharedLock() is for a reader that must not see the row change but need not exclude other readers.
<?php
// Pessimistic reservation: lock the row for the whole transaction. A second
// caller blocks at lockForUpdate() until this transaction commits or rolls back.
namespace App\Services;
use App\Exceptions\OutOfStockException;
use Illuminate\Support\Facades\DB;
use RuntimeException;
final class PessimisticStock
{
public function reserve(int $productId): void
{
DB::transaction(function () use ($productId): void {
// SELECT ... FOR UPDATE: exclusive row lock until the transaction ends.
$product = DB::table('products')
->select('id', 'stock')
->where('id', $productId)
->lockForUpdate()
->first();
if ($product === null) {
throw new RuntimeException("Product {$productId} not found.");
}
if ($product->stock <= 0) {
throw new OutOfStockException("Product {$productId} is out of stock.");
}
DB::table('products')->where('id', $productId)->decrement('stock');
});
}
// A read that must not change under us, but that does not need to block
// writers forever: sharedLock() blocks UPDATE and DELETE, not other readers.
public function stockForAudit(int $productId): int
{
return DB::transaction(function () use ($productId): int {
return (int) DB::table('products')
->where('id', $productId)
->sharedLock()
->value('stock');
});
}
}Eloquent models: save() cannot add a version to its WHERE. An updateOrFail-style method on the model, built on the builder, throws when the count is zero:
<?php
// Optimistic update for an Eloquent model. save() cannot do compare-and-set
// because it issues UPDATE ... WHERE id = ?. A query on the model's builder can
// add the version to the WHERE clause and returns the affected-row count.
namespace App\Models;
use App\Exceptions\StaleModelException;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $fillable = ['title', 'body'];
/**
* Update this article only if the row still has the version we loaded.
*
* @param array<string, mixed> $attributes
*/
public function updateIfCurrent(array $attributes): void
{
$affected = static::query()
->whereKey($this->getKey())
->where('version', $this->version)
->update($attributes + ['version' => $this->version + 1]);
if ($affected === 0) {
// Either the version moved on or the row is gone.
throw new StaleModelException(static::class, $this->getKey(), $this->version);
}
$this->forceFill($attributes + ['version' => $this->version + 1])->syncOriginal();
}
}<?php
// app/Exceptions/StaleModelException.php: thrown when a compare-and-set on a
// model matched zero rows. Map it to 409 or 412 in the exception handler.
namespace App\Exceptions;
use RuntimeException;
final class StaleModelException extends RuntimeException
{
public function __construct(string $model, mixed $key, int $version)
{
parent::__construct("{$model} #{$key} is no longer at version {$version}.");
}
}Edit form across two requests
The version travels in an ETag. GET returns it; PUT requires it and answers 428 if missing, 412 if stale. Go:
// Package etag exposes optimistic concurrency over HTTP. GET returns the row
// version as a strong ETag. PUT requires If-Match and answers 412 Precondition
// Failed when the version has moved on (RFC 9110, section 13.1.1).
package etag
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
)
type Product struct {
ID int64 `json:"id"`
Name string `json:"name"`
Version int64 `json:"-"`
}
type Handler struct {
DB *sql.DB
}
// quote turns a version into a strong entity tag such as "7".
func quote(version int64) string { return `"` + strconv.FormatInt(version, 10) + `"` }
// parse accepts exactly one strong entity tag. Weak tags (W/"7") never match
// for If-Match, because RFC 9110 requires the strong comparison function.
func parse(header string) (int64, bool) {
header = strings.TrimSpace(header)
if len(header) < 3 || header[0] != '"' || header[len(header)-1] != '"' {
return 0, false
}
v, err := strconv.ParseInt(header[1:len(header)-1], 10, 64)
return v, err == nil
}
// Get returns the product and its current version as the ETag header.
func (h *Handler) Get(w http.ResponseWriter, r *http.Request, id int64) {
var p Product
err := h.DB.QueryRowContext(r.Context(),
`SELECT id, name, version FROM products WHERE id = $1`, id).
Scan(&p.ID, &p.Name, &p.Version)
if errors.Is(err, sql.ErrNoRows) {
http.NotFound(w, r)
return
}
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("ETag", quote(p.Version))
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(p)
}
// Put renames a product only if If-Match names the current version.
//
// missing If-Match -> 428 Precondition Required (RFC 6585)
// stale If-Match -> 412 Precondition Failed
// success -> 200 with the new ETag
func (h *Handler) Put(w http.ResponseWriter, r *http.Request, id int64) {
header := r.Header.Get("If-Match")
if header == "" {
http.Error(w, "If-Match required", http.StatusPreconditionRequired)
return
}
version, ok := parse(header)
if !ok {
http.Error(w, "malformed If-Match", http.StatusBadRequest)
return
}
var in struct {
Name string `json:"name"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "bad body", http.StatusBadRequest)
return
}
// The whole check is one statement: compare-and-set on the version.
res, err := h.DB.ExecContext(r.Context(),
`UPDATE products SET name = $1, version = version + 1
WHERE id = $2 AND version = $3`, in.Name, id, version)
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
n, err := res.RowsAffected()
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
if n == 0 {
// Either the version is stale or the row is gone. One extra read tells
// them apart so the client gets 404 or 412, not a vague error.
var exists bool
if err := h.DB.QueryRowContext(r.Context(),
`SELECT EXISTS (SELECT 1 FROM products WHERE id = $1)`, id).Scan(&exists); err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
if !exists {
http.NotFound(w, r)
return
}
http.Error(w, "stale version", http.StatusPreconditionFailed)
return
}
w.Header().Set("ETag", quote(version+1))
fmt.Fprintln(w, "ok")
}Laravel:
<?php
// HTTP optimistic concurrency in Laravel: the version travels as a strong ETag.
// GET returns it, PUT must send it back in If-Match, and a stale tag gets
// 412 Precondition Failed (RFC 9110, section 13.1.1).
namespace App\Http\Controllers;
use App\Exceptions\StaleModelException;
use App\Models\Article;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final class ArticleEtagController
{
public function show(Article $article): JsonResponse
{
return response()
->json($article->only(['id', 'title', 'body']))
->header('ETag', '"'.$article->version.'"');
}
public function update(Request $request, Article $article): JsonResponse
{
$header = $request->header('If-Match');
if ($header === null) {
// RFC 6585: the server requires the request to be conditional.
return response()->json(['message' => 'If-Match required'], 428);
}
// Strong tags only: W/"3" must not match for If-Match.
if (preg_match('/^"(\d+)"$/', trim($header), $m) !== 1) {
return response()->json(['message' => 'Malformed If-Match'], 400);
}
// Pretend the client loaded the version named in its header.
$article->version = (int) $m[1];
$data = $request->validate([
'title' => ['required', 'string', 'max:200'],
'body' => ['required', 'string'],
]);
try {
$article->updateIfCurrent($data);
} catch (StaleModelException) {
return response()->json(['message' => 'The article changed. Reload it.'], 412);
}
return response()->json(['ok' => true])->header('ETag', '"'.$article->version.'"');
}
}If you need a visible "someone is editing" notice, add a lease row (locked_by, locked_until) as advice only, and still enforce the version on save.
Job queue without double processing (SKIP LOCKED)
-- claim one job; a second worker running the same statement gets a different row
SELECT id, payload FROM jobs
WHERE status = 'pending' ORDER BY id LIMIT 1
FOR UPDATE SKIP LOCKED;Go: the worker holds the lock and a pooled connection for as long as the handler runs, so keep the handler short.
// Package worker claims one pending job per call. FOR UPDATE SKIP LOCKED lets
// many workers pull from the same table without queuing behind each other.
package worker
import (
"context"
"database/sql"
"errors"
)
type Job struct {
ID int64
Payload string
}
// RunOne claims the oldest pending job, runs handle, and marks it done in the
// same transaction. It returns false when no job was available.
//
// The row lock and the pooled connection are held for as long as handle runs.
// Keep handle short, or move slow work out of the transaction.
func RunOne(ctx context.Context, db *sql.DB, handle func(context.Context, Job) error) (bool, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return false, err
}
defer tx.Rollback()
var job Job
err = tx.QueryRowContext(ctx, `
SELECT id, payload
FROM jobs
WHERE status = 'pending'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED`).Scan(&job.ID, &job.Payload)
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
if err != nil {
return false, err
}
// If handle fails, Rollback releases the lock and the job stays pending.
if err := handle(ctx, job); err != nil {
return false, err
}
if _, err := tx.ExecContext(ctx,
`UPDATE jobs SET status = 'done' WHERE id = $1`, job.ID); err != nil {
return false, err
}
return true, tx.Commit()
}Laravel's own database queue picks the lock by engine: FOR UPDATE SKIP LOCKED on MySQL 8.0.1+, MariaDB 10.6+, PostgreSQL 9.5+ and Vitess 19+; the readpast hint on SQL Server; plain lockForUpdate elsewhere (source: DatabaseQueue.php). Your own claim code:
<?php
// Claim one pending job with FOR UPDATE SKIP LOCKED, the same lock string that
// Illuminate\Queue\DatabaseQueue picks on PostgreSQL 9.5+ and MySQL 8.0.1+.
// Concurrent workers each get a different row instead of waiting in line.
namespace App\Services;
use Illuminate\Support\Facades\DB;
final class JobClaim
{
/**
* Run $handle on the oldest pending job. Returns false when none is free.
* The row lock and the connection are held while $handle runs.
*
* @param callable(object): void $handle
*/
public function runOne(callable $handle): bool
{
return DB::transaction(function () use ($handle): bool {
$job = DB::table('jobs')
->where('status', 'pending')
->orderBy('id')
->limit(1)
->lock('FOR UPDATE SKIP LOCKED')
->first();
if ($job === null) {
return false;
}
$handle($job); // an exception rolls back and the job stays pending
DB::table('jobs')->where('id', $job->id)->update(['status' => 'done']);
return true;
});
}
// NOWAIT variant: fail fast instead of queueing behind the lock holder.
// PostgreSQL raises SQLSTATE 55P03; MySQL 8 raises error 3572.
public function tryLock(int $id): ?object
{
return DB::table('jobs')->where('id', $id)->lock('FOR UPDATE NOWAIT')->first();
}
}Fail fast with NOWAIT
// Package nowait takes a row lock without waiting. SELECT ... FOR UPDATE
// NOWAIT fails at once with SQLSTATE 55P03 (lock_not_available) when another
// transaction holds the row, so a request can answer "busy" instead of
// parking a pooled connection in the lock queue.
package nowait
import (
"context"
"database/sql"
"errors"
)
var (
ErrOutOfStock = errors.New("out of stock")
// ErrBusy means another transaction holds the row right now.
ErrBusy = errors.New("row is locked by another transaction")
)
// sqlStater matches pgx's *pgconn.PgError and lib/pq's *pq.Error without
// importing either driver.
type sqlStater interface{ SQLState() string }
const lockNotAvailable = "55P03"
// Reserve locks the product with NOWAIT. lock_timeout is set locally so that
// even a statement that does wait (the UPDATE after a lock upgrade, for
// example) cannot hold a connection for longer than 2 seconds.
func Reserve(ctx context.Context, db *sql.DB, id int64) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
// SET LOCAL lasts until the end of this transaction.
if _, err := tx.ExecContext(ctx, `SET LOCAL lock_timeout = '2s'`); err != nil {
return err
}
var stock int64
err = tx.QueryRowContext(ctx,
`SELECT stock FROM products WHERE id = $1 FOR UPDATE NOWAIT`, id).Scan(&stock)
if err != nil {
var st sqlStater
if errors.As(err, &st) && st.SQLState() == lockNotAvailable {
return ErrBusy
}
return err
}
if stock <= 0 {
return ErrOutOfStock
}
if _, err := tx.ExecContext(ctx,
`UPDATE products SET stock = stock - 1 WHERE id = $1`, id); err != nil {
return err
}
return tx.Commit()
}Hybrid: slow decision, short write
// Package hybrid reads without a lock, does slow work, then takes the lock
// only for the short write. The version read at the start is re-checked under
// the lock, so the slow work is never applied to a row that moved on.
package hybrid
import (
"context"
"database/sql"
"errors"
)
// ErrStale means the row changed while the slow work ran. The caller redoes
// the work from a fresh read, or shows the user a conflict.
var ErrStale = errors.New("hybrid: row changed during preparation")
// Reprice reads the product and its version without a lock, runs compute
// (a pricing engine, a call to another service, minutes of human review),
// and then writes inside one short transaction.
func Reprice(ctx context.Context, db *sql.DB, id int64,
compute func(context.Context, int64) (int64, error)) error {
var price, version int64
if err := db.QueryRowContext(ctx,
`SELECT price_cents, version FROM products WHERE id = $1`, id).Scan(&price, &version); err != nil {
return err
}
newPrice, err := compute(ctx, price) // no lock and no transaction held here
if err != nil {
return err
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
// Pessimistic part: short, and the version check happens under the lock.
var current int64
if err := tx.QueryRowContext(ctx,
`SELECT version FROM products WHERE id = $1 FOR NO KEY UPDATE`, id).Scan(¤t); err != nil {
return err
}
if current != version {
return ErrStale
}
if _, err := tx.ExecContext(ctx,
`UPDATE products SET price_cents = $1, version = version + 1 WHERE id = $2`,
newPrice, id); err != nil {
return err
}
return tx.Commit()
}A rule across several rows
A version on each child row does not protect "the order total is at most the credit limit". Pick one: lock the parent (FOR UPDATE on the customer row, always in the same order to avoid deadlock; see Deadlocks), or add a version to the parent and bump it on every child write (Hibernate calls this OPTIMISTIC_FORCE_INCREMENT), or run Serializable and retry.
BEGIN;
SELECT credit_used FROM customers WHERE id = 7 FOR UPDATE; -- the guard row
INSERT INTO orders (customer_id, total) VALUES (7, 120);
UPDATE customers SET credit_used = credit_used + 120 WHERE id = 7;
COMMIT;Retries and failure handling
| Failure | Meaning | Retry? |
|---|---|---|
| 0 rows affected | Lost the version race | Yes: re-read, re-decide |
40001 serialization failure | Concurrent update at RR/Serializable | Yes: whole transaction |
40P01 deadlock | Lock cycle; you were the victim | Yes: whole transaction |
55P03 | NOWAIT or lock_timeout | Report busy, or retry later |
412 | Stale If-Match | No: user decision |
| Out of stock, not found | Business answer | Never |
Rules: retry the whole transaction, not one statement; cap attempts; add jittered backoff; make side effects idempotent or move them after commit; log every conflict. Laravel's DB::transaction($cb, $attempts) retries only deadlocks, so use retry() around it for lost races, as OptimisticStock does. Go's database/sql retries nothing: its ErrTxDone documentation says it "is returned by any operation that is performed on a transaction that has already been committed or rolled back", which is why defer tx.Rollback() after a successful Commit is safe.
Choosing a strategy
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| Counter, balance delta | Atomic UPDATE | CHECK (balance >= 0) | No read, no lock held |
User edit form, API PUT | Optimistic (ETag) | 412/428, show a diff | Think time is minutes |
| Hot row (flash sale, one global counter) | Pessimistic or atomic update | NOWAIT, lock_timeout, shard the counter | Retries amplify contention |
| Worker queue | SKIP LOCKED | Short handlers, retry count column | No waiting, no double work |
| Long computation, short write | Hybrid | Version check under lock | Do not hold a lock while computing |
| Rule across rows | Lock parent, or Serializable | Fixed lock order | A row version guards one row |
| Low contention, many rows (CMS) | Optimistic | Conflict metrics | No lock overhead |
| Financial ledger | Pessimistic or Serializable | Append-only ledger, idempotency keys | One anomaly costs more than waiting |
| Multi-region, distributed SQL | Optimistic with retry (client loop) | SELECT FOR UPDATE to cut restarts | Locks cost a network round trip |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One transaction can hold a lock and the decision together. Start with atomic updates and FOR UPDATE on hot rows; add a version column to anything edited by humans. Example: a shop where checkout does UPDATE products SET stock = stock - 1 WHERE id = ? AND stock >= 1 and the admin product page uses a version column and ETag.
Modular monolith and multiple databases
Each module owns its tables and their versions; no module locks another module's rows. A cross-module rule becomes an API call plus the owner's own optimistic or pessimistic check. Example: the billing module exposes reserveCredit(customerId, amount) and runs its own FOR UPDATE on customers; orders never lock that row.
Microservices: no lock crosses a boundary
A database lock lives inside one service's transaction; it cannot span an HTTP or message call. Locks held while calling another service turn its latency into your lock time. Use versions in API payloads (ETag, version fields), idempotency keys for retries, and sagas for multi-service flows.
Client → Order service: PUT /orders/9 If-Match: "4"
Order service → DB: UPDATE orders ... WHERE id = 9 AND version = 4 (1 row)
Order service → Outbox: OrderUpdated v5 (same transaction)
Inventory service: applies it, compares its own version, ignores stale eventsAn event consumer applies an event only if the event's version is newer than the stored one (compare-and-set on the read model), which also makes redelivery safe.
Distributed data: replicas, caches, distributed SQL
| Setting | What breaks | Fix |
|---|---|---|
| Read replica | Reading the version from a lagging replica gives a stale tag; the write on the primary then fails with 412 for no real reason | Read the version from the primary for the form that will write |
| Cache in front | A cached ETag outlives the data | Invalidate on write, or key the cache by version |
| Sharded database | A lock is per shard; cross-shard rules need two-phase commit or a saga | Keep the rule within one shard key |
| CockroachDB, Spanner | Cross-node commits conflict more; transactions abort and restart | Wrap the transaction in a retry function; use SELECT FOR UPDATE on the hot row to cut aborts |
| Multi-primary or CRDT systems | No single order for writes | Version vectors, merges; out of scope here (see Eventual Consistency) |
Scaling path: 1×, 10×, 100×
| Load | Typical design |
|---|---|
| 1× | Atomic updates, a version column on edited records, FOR UPDATE on rare critical rows |
| 10× | Conflict-rate metrics; lock_timeout everywhere; SKIP LOCKED for queues; a pool per workload |
| 100× | Hot rows sharded (N counter rows summed on read), queues moved to a broker, reservations via a lease with a short TTL, cross-shard rules replaced by sagas |
Lab
Setup (PostgreSQL, two psql terminals, A and B):
CREATE TABLE products (id int PRIMARY KEY, stock int NOT NULL, version int NOT NULL DEFAULT 0);
INSERT INTO products VALUES (42, 5, 7);
CREATE TABLE jobs (id serial PRIMARY KEY, status text NOT NULL DEFAULT 'pending');
INSERT INTO jobs SELECT g, 'pending' FROM generate_series(1, 3) g;Experiment 1: version-column race.
A: SELECT stock, version FROM products WHERE id = 42; -- 5, 7
B: SELECT stock, version FROM products WHERE id = 42; -- 5, 7
B: UPDATE products SET stock = 4, version = 8 WHERE id = 42 AND version = 7; -- UPDATE 1
A: UPDATE products SET stock = 4, version = 8 WHERE id = 42 AND version = 7; -- UPDATE 0 (conflict)
A: SELECT stock, version FROM products WHERE id = 42; -- 4, 8: retry from hereExperiment 2: the FOR UPDATE queue.
A: BEGIN; SELECT * FROM products WHERE id = 42 FOR UPDATE; -- returns row
B: BEGIN; SELECT * FROM products WHERE id = 42 FOR UPDATE; -- hangs
C: SELECT pid, wait_event_type, wait_event, state, query FROM pg_stat_activity WHERE state <> 'idle';
-- B shows wait_event_type = Lock, wait_event = transactionid
C: SELECT locktype, mode, granted FROM pg_locks WHERE NOT granted; -- the waiting request
A: COMMIT; -- B returns at onceExperiment 3: NOWAIT and lock_timeout.
A: BEGIN; SELECT * FROM products WHERE id = 42 FOR UPDATE;
B: SELECT * FROM products WHERE id = 42 FOR UPDATE NOWAIT;
-- ERROR: could not obtain lock on row in relation "products" (SQLSTATE 55P03)
B: SET lock_timeout = '500ms'; SELECT * FROM products WHERE id = 42 FOR UPDATE;
-- ERROR: canceling statement due to lock timeout (SQLSTATE 55P03)Experiment 4: SKIP LOCKED job claim.
A: BEGIN; SELECT id FROM jobs WHERE status='pending' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; -- 1
B: BEGIN; SELECT id FROM jobs WHERE status='pending' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; -- 2
A: UPDATE jobs SET status='done' WHERE id=1; COMMIT;
B: ROLLBACK; -- job 2 stays pendingExperiment 5 (optional): Repeatable Read and 40001.
A: BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT stock FROM products WHERE id = 42;
B: UPDATE products SET stock = stock - 1, version = version + 1 WHERE id = 42;
A: SELECT * FROM products WHERE id = 42 FOR UPDATE;
-- ERROR: could not serialize access due to concurrent update (SQLSTATE 40001)Solutions. Experiment 1 proves the zero-row signal. Experiment 2 shows the waiter holds a session: count rows in pg_stat_activity while ten sessions queue. Experiment 3 gives 55P03 from two different mechanisms. Experiment 4 shows two workers receive different jobs without blocking. Experiment 5 proves that pessimistic locking can still raise 40001.
Common misconceptions
| Belief | Reality |
|---|---|
| Optimistic locking uses no locks | The UPDATE takes a row lock while it runs; only the read-to-write gap is lock-free |
| A transaction around read-modify-write prevents lost updates | Not at Read Committed; a plain SELECT takes no lock |
No exception means the conditional UPDATE worked | Zero rows is success from the database's point of view; check the count |
Retrying the same UPDATE will eventually pass | You must re-read to get the new version |
| Pessimistic locking is always safe | Deadlocks, 40001 at Repeatable Read, queues and pool exhaustion |
SKIP LOCKED is fine for reports | It returns an inconsistent view by design |
FOR SHARE only reads | It blocks every writer of the row |
| A version column protects an invariant across rows | It guards one row; use a parent lock, FORCE_INCREMENT, or Serializable |
updated_at is a good version | Equal timestamps hide writes; use an integer or rowversion |
| A transaction can stay open while the user edits | Locks hold until commit; use ETag/If-Match |
WATCH locks the Redis key | It only marks it; EXEC fails if it changed |
| Serializable in PostgreSQL blocks like locking | SSI is optimistic: it aborts with 40001 |
Cheat sheet
| Topic | What to remember |
|---|---|
| Optimistic | Version column; UPDATE ... WHERE id = ? AND version = ?; 0 rows is a conflict |
| Pessimistic | SELECT ... FOR UPDATE in a transaction; lock lasts until COMMIT |
| Counters | Prefer SET x = x - 1 WHERE x >= 1; neither strategy |
| Retry | Re-read, bounded attempts, full jitter, re-decide |
| Contention | Optimistic wastes work on a hot row (n(n+1)/2 worst case); a lock queues linearly |
| Lock modes | FOR UPDATE > FOR NO KEY UPDATE > FOR SHARE > FOR KEY SHARE |
NOWAIT | Error 55P03 (PostgreSQL), 3572 (MySQL), ORA-00054 (Oracle) |
SKIP LOCKED | Queues only; PostgreSQL 9.5+, MySQL 8.0.1+; SQL Server READPAST |
| Pool | Every waiter holds a connection; set lock_timeout, short transactions |
| HTTP | ETag out, If-Match back, 412 stale, 428 missing |
| Two requests | A DB lock cannot span them; carry the version |
| Redis/Mongo/Dynamo | WATCH; filter on version; ConditionExpression |
| SSI | PostgreSQL Serializable is optimistic; retry on 40001 |
| Hybrid | Read without lock, check version under a short lock |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why must the version comparison be inside the same UPDATE as the write? Must-know
Answer
Answer: Otherwise another writer can commit between your if and your UPDATE. The statement's row lock makes the test and the write one atomic step.
2 — An UPDATE ... WHERE version = ? returns without error. How do you know whether you won? Must-know
Answer
Answer: By the affected-row count (or RETURNING): 1 means you won, 0 means a conflict or a deleted row. On MySQL remember changed vs matched rows.
3 — Why does a retry loop need jitter and a cap? Important
Answer
Answer: Without jitter, losers retry together and collide again; without a cap, a hot row becomes a spin loop and the caller never gets an answer.
4 — Ten clients all update one hot row. Compare the work done under optimistic retries and under FOR UPDATE. Important
Answer
Answer: Worst case optimistic: 55 attempts (n(n+1)/2); pessimistic: 10 lock acquisitions in a queue. Contention favours locking or an atomic update.
5 — What is the difference between FOR UPDATE and FOR NO KEY UPDATE? Important
Answer
Answer: FOR NO KEY UPDATE does not block FOR KEY SHARE, which foreign-key checks take on the parent row, so child inserts do not wait. Use it when you do not change key columns.
6 — What do NOWAIT and SKIP LOCKED each do, and which one is for queues? Must-know
Answer
Answer: NOWAIT raises 55P03 immediately if a row is locked; SKIP LOCKED leaves busy rows out of the result. SKIP LOCKED is the queue primitive and is not for consistent reads.
7 — How can a lock on one row cause an outage on other endpoints? Important
Answer
Answer: Waiters each hold a pooled connection, so enough of them exhaust the pool and unrelated requests time out waiting for a connection.
8 — Why can you not hold a database lock while a user edits a form? Must-know
Answer
Answer: A lock lasts until the transaction ends, requests use separate pooled connections, and the user may disappear. Use a version in an ETag.
9 — Which status codes belong to HTTP optimistic concurrency? Important
Answer
Answer: 412 Precondition Failed for a stale If-Match, 428 Precondition Required when you demand one and it is missing, and 409 for a business conflict.
10 — In what sense is PostgreSQL's Serializable level optimistic? Good to know
Answer
Answer: SSI takes non-blocking read tracking locks and aborts one transaction of a dangerous structure with 40001; the application retries, like a version conflict.
Glossary
| Term | One line |
|---|---|
| Optimistic concurrency control (OCC) | Run without locks, validate at the end, abort and retry on conflict |
| Pessimistic locking | Lock before use, hold until the transaction ends |
| Read / validation / write phase | Kung and Robinson's three phases |
| Backward validation (BOCC) | Check the committer against transactions that already finished |
| Forward validation (FOCC) | Check the committer against transactions still running |
| Version column | Integer incremented on every write of a row |
| Compare-and-set (CAS) | Atomic "write only if still equal to what I read" |
| Rows-affected check | Using the update count as the conflict signal |
| Retry loop | Bounded re-read and re-decide cycle |
| Backoff | Growing pause between retries |
| Jitter | Randomisation of that pause |
| Starvation | One transaction losing validation repeatedly |
| Hot row | A row many transactions write at once |
FOR UPDATE | Exclusive row lock until commit |
FOR NO KEY UPDATE | Exclusive but does not block FOR KEY SHARE |
FOR SHARE | Shared row lock; blocks writers |
FOR KEY SHARE | Weakest row lock; blocks key changes and deletes; used by foreign keys |
NOWAIT | Fail immediately if the row is locked |
SKIP LOCKED | Ignore locked rows; queue primitive |
lock_timeout | PostgreSQL limit on lock wait |
55P03 | SQLSTATE lock_not_available |
40001 | SQLSTATE serialization_failure |
| Connection pool exhaustion | All pooled connections busy, often waiting on a lock |
ETag | Validator for a representation, here the version |
If-Match | Conditional header; write only if the tag matches (strong comparison) |
412 Precondition Failed | Response for a failed If-Match |
428 Precondition Required | Response when a conditional request is demanded but absent |
| Strong vs weak validator | Byte-exact vs semantically equivalent tags |
| Hybrid locking | Optimistic read, pessimistic short write |
@Version | JPA/Hibernate version attribute |
WATCH | Redis optimistic marker on a key |
ConditionExpression | DynamoDB write condition |
findOneAndUpdate | MongoDB atomic update returning a document, with a version filter |
| SSI | Serializable Snapshot Isolation; optimistic serializability |
READPAST | SQL Server hint equivalent to SKIP LOCKED |
| Lease | A lock with an expiry time |
References
- H. T. Kung and John T. Robinson, "On Optimistic Methods for Concurrency Control", ACM Transactions on Database Systems 6(2), June 1981. PDF
- PostgreSQL documentation (current), Explicit Locking: Row-Level Locks
- PostgreSQL documentation, SELECT: The Locking Clause
- RFC 9110, HTTP Semantics, section 13.1.1 If-Match
- Laravel 13 documentation, Query Builder: Pessimistic Locking and Helpers: retry
- Laravel framework source,
DatabaseQueue.php - Go documentation,
database/sqlandmath/rand/v2