Skip to content

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 forGo to
Two tables you can memorise in a minuteEverything in one minute
The 1981 paper, read/validate/write, backward vs forward validationWhere it comes from
Why two strategies exist and the trade-offWhy two strategies exist
Version column, compare-and-set, rows-affected, retry loop, conflict rateOptimistic locking, concept by concept
FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE, NOWAIT, SKIP LOCKED, lock durationPessimistic locking, concept by concept
Edit forms, ETag, If-Match, 412, 428Across two requests: HTTP
PostgreSQL, MySQL, SQL Server, Oracle, SQLite, MongoDB, Redis, DynamoDB, CockroachDB, Spanner, HibernateWhat each product does
Exact knobs, SQLSTATE and error codesMechanics
SQL + Go + Laravel for each classic problemSolving the classic problems
Retry wrapper and error tableRetries and failure handling
Which strategy for which workloadChoosing a strategy
Replicas, caches, microservices, scalingIn architecture
Reproduce it in two terminalsLab
Wrong beliefs, cheat sheet, every term definedMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The two strategies side by side.

OptimisticPessimistic
BetConflicts are rareConflicts are likely
While readingNo lockRow lock (FOR UPDATE)
Who waitsNobody; the loser retriesThe second writer, in a queue
Detected byUPDATE ... WHERE version = ? affecting 0 rowsThe lock itself; no detection needed
Cost on a collisionWasted work plus a retryWaiting time and a held connection
Cost with no collisionOne extra column and one WHEREA lock taken and released for nothing
Spans several HTTP requestsYes (carry the version in an ETag)No (a lock cannot outlive its transaction)
Failure you handleZero rows affected, 412, 40001Lock timeout 55P03, deadlock 40P01

The vocabulary in one table.

TermIn plain wordsWhere explained
Version columnAn integer on the row that increases with every writeVersion column
Compare-and-set (CAS)"Write only if it is still what I read"Compare-and-set
Rows-affected checkA zero count is the only conflict signalRows-affected check
Retry loop, backoff, jitterRedo the work, with growing random pausesRetry loop
FOR UPDATE and three weaker modesRow locks of four strengthsRow-lock modes
NOWAIT, SKIP LOCKEDDo not wait; or skip the busy rowNOWAIT and SKIP LOCKED
ETag, If-Match, 412The version carried over HTTPHTTP
HybridRead without a lock, lock only to writeHybrid

The three things to do.

SituationDo this
Changing one counter or balanceOne atomic UPDATE ... SET x = x - 1 WHERE ... AND x >= 1; neither strategy needed
A user edits a record for minutesVersion column plus ETag/If-Match; answer 412 on a stale write
Workers draining a queue tableSELECT ... 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:

ConditionMeaning
1Ti completes its write phase before Tj starts its read phase (no overlap at all)
2Ti's write set does not intersect Tj's read set, and Ti finishes writing before Tj starts writing
3Ti'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 holdCorrect by detection: a changed row makes your write fail
Pays on every transaction, even with no contentionPays only when a collision happens
Waiting scales with queue length on a hot rowWasted work scales with collision rate
Needs a transaction held open for the whole decisionNeeds only a short transaction at the end
Can deadlockCan starve under heavy contention
Cannot span a user's think timeCan 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 ​

  1. "Optimistic means no locks." The UPDATE itself takes a row lock while it runs. PostgreSQL documents that FOR 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.
  2. "A transaction already protects me." A plain SELECT takes no lock in PostgreSQL, InnoDB or Oracle. Two transactions can both read stock 1 and both write 0. Wrapping read-modify-write in BEGIN ... COMMIT does not stop that at Read Committed.
  3. "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.

text
     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 again

Real 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.

ProductVersion tokenConflict signal
PostgreSQLversion column, or xmin0 rows affected
MySQL InnoDBversion column0 rows (see the FOUND_ROWS trap in Rows-affected check)
SQL Serverrowversion column (8 bytes, auto-increments)0 rows
OracleORA_ROWSCN (coarse unless the table uses ROWDEPENDENCIES) or a version column0 rows
SQLiteversion column0 rows; one writer at a time anyway
MongoDBversion field, or Mongoose __v with optimisticConcurrencynull from findOneAndUpdate, or matchedCount == 0
DynamoDBversion attribute in a ConditionExpressionConditionalCheckFailedException
Hibernate / JPA@Version fieldOptimisticLockException (StaleObjectStateException in Hibernate)

Fix / how to use it:

sql
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.

text
     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 overwrite

Real 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.

ProductCAS primitive
Any SQL databaseUPDATE ... WHERE version = ? and the row count
RedisWATCH key then MULTI/EXEC; EXEC returns nil if the key changed; or a Lua script
MongoDBfindOneAndUpdate({_id, version}, {$set, $inc: {version: 1}})
DynamoDBPutItem/UpdateItem with ConditionExpression
HTTPIf-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).

StackWhere the count isTrap
Go database/sqlres.RowsAffected()Some drivers return an error if unsupported; always check it
Go pgxCommandTag.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 countEloquent's save() hides it; use the builder
Laravel EloquentModel::query()->whereKey($id)->where('version', $v)->update([...])Same count
PostgreSQL UPDATE ... RETURNINGZero rows returnedAlternative signal, also yields the new version in one trip
sql
UPDATE products SET stock = stock - 1, version = version + 1
WHERE id = 42 AND version = 7
RETURNING stock, version;   -- no row returned means a conflict

Real 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.

text
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 / 412

Real scenarios: an inventory service under a sale; a collaborative editor autosaving; a leaderboard with a score per player; a quota counter per tenant.

RuleWhy
Cap attempts (3 to 6)A hot row is a spin loop otherwise
Re-read inside every attemptThe decision depends on fresh state
Full jitter, exponential ceilingBreaks lockstep retries
Honour the request contextA 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 conflictsThe 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 caseLock acquisitions, pessimistic
111
232
5155
105510
50127550

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.

SignalMeaningAction
Conflict rate under ~1%Optimistic is fineKeep it
Conflict rate 5 to 20%Contention risingAdd backoff; look for a hot row
Retries exhausting oftenHot rowAtomic UPDATE, shard the counter, or switch to a lock
Same row, many writers, short critical sectionLock is cheaperPessimistic 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.

text
     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 released

Real 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 ​

T1 (lock holder)T2T3T4holds the row lockwaits (connection busy)holdswaits (connection busy)holdswaits (connection busy)holdstimeCost on a hot row: throughput = 1 / hold time, latency grows with queue lengthAll four transactions occupy a pooled connection from BEGIN to COMMIT; waiting ones do no work.FOR UPDATE NOWAIT fails fast, SKIP LOCKED passes the row to the next worker, lock_timeout bounds the wait.

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."

ModeBlocks (other transactions' attempts)Taken automatically by
FOR UPDATEAll four modes, UPDATE, DELETEDELETE; UPDATE that changes a key column
FOR NO KEY UPDATEFOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, plus UPDATE and DELETEUPDATE that does not change a key
FOR SHAREFOR UPDATE, FOR NO KEY UPDATE, UPDATE, DELETE (not other FOR SHARE/FOR KEY SHARE)Nothing
FOR KEY SHAREFOR UPDATE, DELETE, and an UPDATE that changes key valuesForeign-key checks on the referenced row
ProductSyntax
PostgreSQLFOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE
MySQL InnoDB 8FOR UPDATE, FOR SHARE (older LOCK IN SHARE MODE); no key-level variants
SQL ServerHints: UPDLOCK, HOLDLOCK, ROWLOCK, XLOCK, READPAST
OracleFOR UPDATE [OF col] [NOWAIT | WAIT n | SKIP LOCKED]
SQLiteNone; one writer for the whole database (BEGIN IMMEDIATE)
CockroachDBFOR UPDATE, FOR SHARE (the NO KEY/KEY SHARE spellings are accepted and behave as the stronger forms), with NOWAIT/SKIP LOCKED
SpannerRead-write transactions lock automatically; FOR UPDATE is supported in GoogleSQL for explicit locks
MongoDB, Redis, DynamoDBNo 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.

text
     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 row

Fix / 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.

text
     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.

OptionBehaviourUse for
(none)Wait (until lock_timeout or forever)Short, hot critical sections
NOWAITError 55P03 at onceA user-facing request that should say "busy"
SKIP LOCKEDLocked rows are invisible to this statementWork queues, claim-one-of-many
lock_timeoutWait at most N ms, then 55P03A 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.

text
     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 wait

Real 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.

text
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
LayerKnobEffect
Go database/sqlSetMaxOpenConns, SetConnMaxLifetime, context deadlinesBounds the pool; a deadline cancels a waiter
PgBouncer (transaction mode)default_pool_size, query_wait_timeoutA server connection is pinned from BEGIN to COMMIT
PostgreSQLlock_timeout, statement_timeout, idle_in_transaction_session_timeout, max_connectionsEnds waits and idle transactions
MySQLinnodb_lock_wait_timeout (default 50 s)Error 1205 after the wait
LaravelPHP-FPM workers each hold one connection; DB::transactionPool 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.

ApproachWorks across requests?Notes
Transaction open between requestsNoPins a connection, blocks others, dies on disconnect
pg_advisory_lock (session)Only on a dedicated connectionLost on pool reuse; invisible leak
Lock row with expiry (lease): locked_by, locked_untilYesA "soft lock" you implement; Fowler's Pessimistic Offline Lock idea; needs expiry and a release path
Version carried in ETag/hidden fieldYesOptimistic 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.)

text
     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
StatusWhen
200/204Tag matched, write done, new ETag returned
412 Precondition FailedIf-Match present and stale
428 Precondition RequiredYou require If-Match and the client sent none (RFC 6585)
409 ConflictA business-level conflict that is not a header check (also the usual code for a retried-out CAS)
304 Not ModifiedIf-None-Match on a GET (caching, not locking)
HeaderRole
ETagThe validator in a response (strong "7" or weak W/"7")
If-MatchWrite only if current tag matches (strong comparison)
If-None-Match: *Create only if the resource does not exist
If-Unmodified-SinceSame 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 ​

ProductDefault concurrencyOptimistic toolPessimistic toolNotes
PostgreSQLMVCC; Read Committedversion column, xminFOR UPDATE family, NOWAIT, SKIP LOCKED, advisory locksAt Repeatable Read, a locked row changed since the snapshot raises 40001
MySQL InnoDBMVCC; Repeatable Readversion columnFOR 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 ServerLocking Read Committed (or RCSI)rowversionUPDLOCK, XLOCK, READPAST, HOLDLOCKSnapshot isolation raises error 3960 on a write conflict
OracleMVCC; Read CommittedORA_ROWSCN, version columnFOR UPDATE [NOWAIT / WAIT n / SKIP LOCKED]ORA-00054 resource busy; serializable raises ORA-08177
SQLiteOne writer, serializableVersion columnBEGIN IMMEDIATE takes the write lockSQLITE_BUSY instead of row waits; busy_timeout
MongoDBDocument-level atomic writesfindOneAndUpdate with a version filter; Mongoose optimisticConcurrencyNo row locks; transactions abort on WriteConflictMulti-document transactions retry with TransientTransactionError
RedisSingle command threadWATCH/MULTI/EXEC, Lua scriptsSET key val NX PX leases (a lock service, not a row lock)EXEC returns nil if a watched key changed
DynamoDBItem-level atomic writesConditionExpression on versionNone (transactions via TransactWriteItems)ConditionalCheckFailedException
CockroachDBSerializableThe same version columnSELECT ... FOR UPDATE (reduces retries)Retryable errors 40001; client retry loop expected
SpannerStrict serializableVersion columnRead-write transactions lock; ABORTED on contentionClient libraries retry the transaction function
Hibernate / JPAPersistence context@VersionLockModeType.PESSIMISTIC_WRITE (adds FOR UPDATE), OPTIMISTIC_FORCE_INCREMENTOptimisticLockException; 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).

EngineSerializable isFailure signal
PostgreSQLOptimistic (SSI)40001 serialization_failure
MySQL InnoDBPessimistic (2PL, locks every read)1213 deadlock, 1205 timeout
CockroachDBOptimistic-style with write intents and timestamp pushes40001 restart
SQL ServerPessimistic (range locks)Deadlock 1205
OracleSnapshot 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.

text
     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
// 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"
js
// 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)
text
DynamoDB UpdateItem
  UpdateExpression:    SET stock = :new, version = :next
  ConditionExpression: version = :expected
  -> ConditionalCheckFailedException on a stale write

Real 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 ​

Session ASession BRow products.id = 42version 7 to 80 rows affected: conflict1. SELECT stock, versionreturns stock = 5, version = 7 (no lock taken)2. SELECT stock, versionreturns stock = 5, version = 73. UPDATE ... WHERE version = 71 row affected: B wins4. UPDATE ... WHERE version = 75. re-read: version 8retry with jittered backoff

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 productUPDATE ... WHERE version = ? losesSELECT FOR UPDATE on a row changed after the snapshot
PostgreSQL Read CommittedWaits, re-evaluates WHERE, 0 rowsWaits, returns the latest row
PostgreSQL Repeatable Read40001 "could not serialize access due to concurrent update"40001
MySQL InnoDB Repeatable ReadWaits, then re-evaluates against latest committed; 0 rowsReads latest committed (not the snapshot)
SQL Server SnapshotError 3960 (update conflict)Not applicable (locks are taken)
Oracle Read CommittedWaits, restarts statementWaits
CockroachDB Serializable40001 restartWaits in the lock table

So the retry wrapper must catch both "0 rows" and "serialization failure".

Error codes and knobs Must-know ​

ProductConditionCode or messageRetry?
PostgreSQLSerialization failureSQLSTATE 40001Yes, whole transaction
PostgreSQLDeadlock40P01Yes, whole transaction
PostgreSQLNOWAIT hit a lock, or lock_timeout expired55P03 lock_not_availableMaybe: report "busy" or retry with backoff
PostgreSQLstatement_timeout57014 query_canceledUsually no
MySQLDeadlock1213 (SQLSTATE 40001)Yes
MySQLLock wait timeout (innodb_lock_wait_timeout, default 50 s)1205Maybe
MySQLNOWAIT hit a lock3572Maybe
SQL ServerSnapshot update conflict3960Yes
SQL ServerDeadlock victim; lock timeout1205; 1222Yes; maybe
OracleNOWAIT hit a lockORA-00054Maybe
OracleCannot serializeORA-08177Yes
ApplicationVersion mismatch0 rows affected, your typed errorYes, with re-read
HTTPStale If-Match412Client reloads, user merges
MongoDBTransaction write conflictWriteConflict, label TransientTransactionErrorYes
DynamoDBStale conditionConditionalCheckFailedExceptionYes, re-read
RedisWatched key changedEXEC returns nil (redis.TxFailedErr in go-redis)Yes
KnobDefaultUse
lock_timeout (PostgreSQL)0 (wait forever)Bound the lock wait; error 55P03
statement_timeout0Bound any statement
idle_in_transaction_session_timeout0Kill a session that sits in an open transaction
deadlock_timeout1 sWhen the deadlock check starts
innodb_lock_wait_timeout50 sMySQL lock wait
SET LOCK_TIMEOUT (SQL Server)-1 (infinite)Same idea
busy_timeout (SQLite)0Wait for the write lock

Solving the classic problems ​

ProblemSolutionHowAdvantageCost or limit
Lost update on a counterAtomic UPDATE x = x - 1One statement, no readNo lock held, no retryOnly when the change is a function of the current value
Lost update on a recordVersion columnWHERE version = ?No lock across readsRetry or conflict path
Same, hot rowFOR UPDATELock then writeNo wasted workQueue and connection use
Edit formETag/If-MatchVersion over HTTPSpans minutesUser must resolve 412
Job claimFOR UPDATE SKIP LOCKEDEach worker gets a free rowNo waitingHandler holds a connection
Rule across rowsLock parent in a fixed order, or SerializableOne row guards the ruleCorrectContention on the parent
Slow decision, short writeHybridVersion check under a short lockBest of bothTwo code paths
Fail fast for usersNOWAITError 55P03No queueCaller handles "busy"

Lost update: version column and FOR UPDATE Must-know ​

The bug (a read-modify-write with no protection):

go
// 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:

sql
-- 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.

go
// 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.

go
// 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
<?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
<?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
<?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
<?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
<?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
<?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:

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
<?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) ​

sql
-- 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.

go
// 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
<?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 ​

go
// 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 ​

go
// 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(&current); 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.

sql
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 ​

FailureMeaningRetry?
0 rows affectedLost the version raceYes: re-read, re-decide
40001 serialization failureConcurrent update at RR/SerializableYes: whole transaction
40P01 deadlockLock cycle; you were the victimYes: whole transaction
55P03NOWAIT or lock_timeoutReport busy, or retry later
412Stale If-MatchNo: user decision
Out of stock, not foundBusiness answerNever

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 ​

SituationRecommendedExtra techniqueReason
Counter, balance deltaAtomic UPDATECHECK (balance >= 0)No read, no lock held
User edit form, API PUTOptimistic (ETag)412/428, show a diffThink time is minutes
Hot row (flash sale, one global counter)Pessimistic or atomic updateNOWAIT, lock_timeout, shard the counterRetries amplify contention
Worker queueSKIP LOCKEDShort handlers, retry count columnNo waiting, no double work
Long computation, short writeHybridVersion check under lockDo not hold a lock while computing
Rule across rowsLock parent, or SerializableFixed lock orderA row version guards one row
Low contention, many rows (CMS)OptimisticConflict metricsNo lock overhead
Financial ledgerPessimistic or SerializableAppend-only ledger, idempotency keysOne anomaly costs more than waiting
Multi-region, distributed SQLOptimistic with retry (client loop)SELECT FOR UPDATE to cut restartsLocks 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.

text
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 events

An 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 ​

SettingWhat breaksFix
Read replicaReading the version from a lagging replica gives a stale tag; the write on the primary then fails with 412 for no real reasonRead the version from the primary for the form that will write
Cache in frontA cached ETag outlives the dataInvalidate on write, or key the cache by version
Sharded databaseA lock is per shard; cross-shard rules need two-phase commit or a sagaKeep the rule within one shard key
CockroachDB, SpannerCross-node commits conflict more; transactions abort and restartWrap the transaction in a retry function; use SELECT FOR UPDATE on the hot row to cut aborts
Multi-primary or CRDT systemsNo single order for writesVersion vectors, merges; out of scope here (see Eventual Consistency)

Scaling path: 1×, 10×, 100× ​

LoadTypical 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):

sql
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.

text
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 here

Experiment 2: the FOR UPDATE queue.

text
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 once

Experiment 3: NOWAIT and lock_timeout.

text
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.

text
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 pending

Experiment 5 (optional): Repeatable Read and 40001.

text
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 ​

BeliefReality
Optimistic locking uses no locksThe 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 updatesNot at Read Committed; a plain SELECT takes no lock
No exception means the conditional UPDATE workedZero rows is success from the database's point of view; check the count
Retrying the same UPDATE will eventually passYou must re-read to get the new version
Pessimistic locking is always safeDeadlocks, 40001 at Repeatable Read, queues and pool exhaustion
SKIP LOCKED is fine for reportsIt returns an inconsistent view by design
FOR SHARE only readsIt blocks every writer of the row
A version column protects an invariant across rowsIt guards one row; use a parent lock, FORCE_INCREMENT, or Serializable
updated_at is a good versionEqual timestamps hide writes; use an integer or rowversion
A transaction can stay open while the user editsLocks hold until commit; use ETag/If-Match
WATCH locks the Redis keyIt only marks it; EXEC fails if it changed
Serializable in PostgreSQL blocks like lockingSSI is optimistic: it aborts with 40001

Cheat sheet ​

TopicWhat to remember
OptimisticVersion column; UPDATE ... WHERE id = ? AND version = ?; 0 rows is a conflict
PessimisticSELECT ... FOR UPDATE in a transaction; lock lasts until COMMIT
CountersPrefer SET x = x - 1 WHERE x >= 1; neither strategy
RetryRe-read, bounded attempts, full jitter, re-decide
ContentionOptimistic wastes work on a hot row (n(n+1)/2 worst case); a lock queues linearly
Lock modesFOR UPDATE > FOR NO KEY UPDATE > FOR SHARE > FOR KEY SHARE
NOWAITError 55P03 (PostgreSQL), 3572 (MySQL), ORA-00054 (Oracle)
SKIP LOCKEDQueues only; PostgreSQL 9.5+, MySQL 8.0.1+; SQL Server READPAST
PoolEvery waiter holds a connection; set lock_timeout, short transactions
HTTPETag out, If-Match back, 412 stale, 428 missing
Two requestsA DB lock cannot span them; carry the version
Redis/Mongo/DynamoWATCH; filter on version; ConditionExpression
SSIPostgreSQL Serializable is optimistic; retry on 40001
HybridRead without lock, check version under a short lock

Self-check: questions & answers ​

Show:
  • 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 ​

TermOne line
Optimistic concurrency control (OCC)Run without locks, validate at the end, abort and retry on conflict
Pessimistic lockingLock before use, hold until the transaction ends
Read / validation / write phaseKung 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 columnInteger incremented on every write of a row
Compare-and-set (CAS)Atomic "write only if still equal to what I read"
Rows-affected checkUsing the update count as the conflict signal
Retry loopBounded re-read and re-decide cycle
BackoffGrowing pause between retries
JitterRandomisation of that pause
StarvationOne transaction losing validation repeatedly
Hot rowA row many transactions write at once
FOR UPDATEExclusive row lock until commit
FOR NO KEY UPDATEExclusive but does not block FOR KEY SHARE
FOR SHAREShared row lock; blocks writers
FOR KEY SHAREWeakest row lock; blocks key changes and deletes; used by foreign keys
NOWAITFail immediately if the row is locked
SKIP LOCKEDIgnore locked rows; queue primitive
lock_timeoutPostgreSQL limit on lock wait
55P03SQLSTATE lock_not_available
40001SQLSTATE serialization_failure
Connection pool exhaustionAll pooled connections busy, often waiting on a lock
ETagValidator for a representation, here the version
If-MatchConditional header; write only if the tag matches (strong comparison)
412 Precondition FailedResponse for a failed If-Match
428 Precondition RequiredResponse when a conditional request is demanded but absent
Strong vs weak validatorByte-exact vs semantically equivalent tags
Hybrid lockingOptimistic read, pessimistic short write
@VersionJPA/Hibernate version attribute
WATCHRedis optimistic marker on a key
ConditionExpressionDynamoDB write condition
findOneAndUpdateMongoDB atomic update returning a document, with a version filter
SSISerializable Snapshot Isolation; optimistic serializability
READPASTSQL Server hint equivalent to SKIP LOCKED
LeaseA lock with an expiry time

References ​

Built by Morteza Negahi