Optimistic Concurrency Control - Complete Deep Dive
Prerequisites: Transactions and Isolation, Distributed Locking, Idempotency Used in: BookMyShow, Digital Wallet, Stock Broker
What is Optimistic Concurrency Control?
Optimistic concurrency control (OCC) is a way of letting many writers work on the same data at once without any of them taking a lock. Each writer reads the current state, notes a version of it, does its work, and then attempts the write conditionally — “apply this only if the version is still what I read.” If someone else got there first the version has moved, the write is rejected, and the loser reads the fresh state and tries again.
The word “optimistic” describes the bet: conflicts are assumed to be rare, so paying nothing up front and occasionally redoing work is cheaper than making everyone queue. Pessimistic concurrency control makes the opposite bet — take a lock first so the conflict cannot happen.
Real-world analogy: Two people are editing the same shared shopping list on paper. The pessimistic approach is to keep the list in a locked drawer: whoever holds the key edits, everyone else waits outside, and if that person wanders off to lunch holding the key, nobody can do anything. The optimistic approach is to let both take a photo of the list, go shopping, and come back to write their changes — but before writing, each compares the list in front of them against their photo. If it has changed, they tear up their edit, take a new photo, and redo it. Nobody waits for anybody. The cost is that the second person sometimes repeats their work.
The Lost Update Problem
Everything OCC exists for is visible in a four-step race. Two users withdraw from the same wallet, which holds ₹100.
Time Request A Request B
---- ------------------------------ ------------------------------
t1 read balance -> 100
t2 read balance -> 100
t3 compute 100 - 80 = 20
t4 compute 100 - 70 = 30
t5 write balance = 20
t6 write balance = 30 <-- A's withdrawal vanished
The final balance is ₹30. The user withdrew ₹150 from an account holding ₹100 and the account is still in credit. This is a lost update: B’s write was computed from a value that was already stale, and it silently overwrote A’s.
The hazard is the gap between reading and writing — the classic check-then-act race. 💡 Check-then-act means you verify a condition and then take an action based on it, with a window in between where the condition can stop being true. Any logic shaped like “read a value, decide something from it, write a value back” has this hole, including:
| Operation | What is checked | What is lost when it races |
|---|---|---|
| Withdraw from a balance | Sufficient funds | The account overdraws |
| Reserve the last seat | Seat is free | Two tickets, one seat |
| Decrement stock | Stock above zero | Oversell |
| Edit a document | Current text | One author’s paragraph disappears |
Notice that wrapping each request in a transaction does not fix this at the default isolation level most databases ship with. Read Committed happily permits the interleaving above, because neither write is reading dirty data — B’s read of 100 was committed and true at the time. Isolation level alone is not the answer; the write must become conditional.
Version Columns, Row Versions and ETags
The mechanism is one extra piece of data travelling with the record: a token that changes on every write. Three common forms.
| Form | Where you see it | How it changes |
|---|---|---|
| Version column | Application-managed integer in a row | version = version + 1 on every update |
| Row version | Database-managed, e.g. Postgres xmin, SQL Server rowversion |
Automatically, by the engine |
| ETag | HTTP APIs, object stores | Server recomputes on each new representation |
An ETag 💡 (entity tag — an opaque identifier for one version of a resource) is just this idea exposed over HTTP. The client receives ETag: "v7" on a GET and sends If-Match: "v7" on the PUT; the server responds 412 Precondition Failed if the resource has moved on. Same bet, same mechanism, expressed as a header.
Whichever form you pick, the version must satisfy two properties: it changes on every write, including one that happens to set the same values, and it never repeats. A monotonically increasing integer gives you both for the price of one column.
Conditional Updates in SQL
In SQL the entire pattern is one statement plus one check.
-- Step 1: read, and remember the version you saw.
SELECT balance, version FROM wallets WHERE id = 'w-1';
-- -> balance = 100, version = 7
-- Step 2: write conditionally. The WHERE clause is the whole guarantee.
UPDATE wallets
SET balance = 20,
version = 8
WHERE id = 'w-1'
AND version = 7;
Step 3: check the affected-row count. This is the part people forget.
1 row updated -> you won. Your write is applied.
0 rows updated -> you lost. Someone else wrote first. Re-read and retry.
The affected-row count is the success signal, and ignoring it converts a correct design into a silent data-loss bug. The statement does not raise an error when it matches nothing; it reports zero rows and commits happily. Every ORM and driver exposes this count — rowcount, rowsAffected, the int returned by executeUpdate. Read it, and treat zero as a conflict.
You can condition on the value instead of a version — WHERE balance = 100 — which works but is vulnerable to the ABA problem described further down. You can also fold the arithmetic into the statement — SET balance = balance - 80 WHERE balance >= 80 — which removes the read-then-write gap entirely. That is the best fix for a plain counter, and it stops working as soon as the new value depends on logic the database cannot express.
Conditional Writes Outside SQL
OCC is not a SQL feature; it is a property of the write primitive. Every serious store offers one.
DynamoDB uses a ConditionExpression. The write is applied only if the condition holds, atomically, and fails with ConditionalCheckFailedException otherwise.
{
"TableName": "wallets",
"Key": { "id": { "S": "w-1" } },
"UpdateExpression": "SET balance = :new, version = :nextV",
"ConditionExpression": "version = :curV",
"ExpressionAttributeValues": {
":new": { "N": "20" },
":curV": { "N": "7" },
":nextV": { "N": "8" }
}
}
Redis gives you three options, in increasing order of preference:
| Redis primitive | What it does | Use for |
|---|---|---|
WATCH key then MULTI and EXEC |
Marks a key; if anyone writes it before EXEC, the transaction aborts and returns nil |
Textbook OCC, implemented in the protocol |
SET key value with the NX flag |
Writes only when the key is absent; pair it with a time to live | Claiming a resource exactly once |
| A small Lua script | Runs read and write atomically on the server, so there is no window to lose | Conditions richer than one equality check |
Everything else follows the same shape: etcd and ZooKeeper compare a revision or znode version, S3 offers conditional writes on an object’s ETag, Cassandra has lightweight transactions with IF, MongoDB matches a version field in the update filter. If a store cannot express “write only if”, you cannot build OCC on it and you need a lock instead.
Retry Loops Done Properly
A rejected write is not an error to surface — it is a signal to redo the work on fresh state. That requires a loop, and the loop needs three guards.
def withdraw(wallet_id, amount, max_attempts=5):
for attempt in range(max_attempts):
row = db.read(wallet_id) # fresh read EVERY attempt
if row.balance < amount:
raise InsufficientFunds() # business failure, do not retry
updated = db.update_if_version(
wallet_id,
new_balance=row.balance - amount,
expected_version=row.version,
)
if updated: # affected rows == 1
return
sleep(backoff_with_jitter(attempt)) # lost the race, back off
raise TooMuchContention() # bounded: give up and say so
Four rules this encodes:
- Re-read inside the loop. Retrying with the stale version you already lost with will fail forever. This is the most common bug in hand-written OCC.
- Bound the attempts. An unbounded retry loop under contention becomes an infinite loop that holds a connection and a thread. Five attempts is a reasonable default; failing loudly after that is better than hanging.
- Add jitter to the backoff. 💡 Jitter means randomising the wait so retriers stop marching in step. Without it, every loser from round one retries at the same instant and collides again. See Retry and Backoff.
- Separate conflict from business failure. “Someone else wrote first” is retryable. “Not enough money” is not, and retrying it burns capacity to produce the same answer.
Where OCC Breaks Down: The Retry Storm
OCC’s bet is that conflicts are rare. When they are not, the bet inverts and the mechanism actively makes things worse.
flowchart LR
W["200 writers<br/>on one row"] --> A["All read version 7"]
A --> B["All attempt the conditional write"]
B --> C["1 wins<br/>199 rejected"]
C --> D["199 re-read and retry"]
D --> E["Work done grows<br/>throughput falls"]
E --> B
New components:
- 199 rejected: every rejected attempt consumed a read, a write attempt and a round trip, and produced nothing. This is pure waste, and it scales with the number of contenders.
- The loop back into the write step: the feedback edge is the problem. More contention causes more retries, which cause more contention — livelock. 💡 Livelock means everyone is busy and making no progress, unlike deadlock where everyone is stopped.
With N writers on one row, OCC does roughly O(N²) work to complete N updates. Throughput peaks at modest contention and then declines as you add load.
Pessimistic locking wins here, and the reason is unintuitive but simple: a lock queue is fair and work-conserving. Each waiter does its work exactly once, in turn, and the only cost is waiting.
| Situation | Use | Why |
|---|---|---|
| Conflicts rare, say under 5% of writes | OCC | No lock overhead on the 95% that never conflict |
| Many writers on one row | Pessimistic lock | Each writer works once; no wasted retries |
| Human-paced edits, long think time | OCC | A lock held across a user’s coffee break is unusable |
| Short critical section inside one database | SELECT FOR UPDATE |
Cheap, and the engine already arbitrates it |
| Contention on one hot row | Redesign | See Hot Partitions — change the key, do not fight the lock |
A useful interview move: name the conflict rate as the thing that decides. Below a few percent, optimistic; above it, pessimistic. If you cannot estimate it, instrument it — the retry counter is the conflict rate.
The ABA Problem
Conditioning on the value instead of a version has a specific hole. The value changes from A to B and back to A while you were not looking; your comparison sees A, concludes nothing happened, and proceeds on a false premise.
t1 A reads balance = 100
t2 B withdraws 50 -> balance = 50
t3 C deposits 50 -> balance = 100
t4 A writes conditionally: WHERE balance = 100 -> SUCCEEDS
The condition held. But two transactions happened in between,
and anything A decided from "nothing has changed" is wrong.
For a plain integer balance this may be harmless — the arithmetic still adds up. It stops being harmless whenever the write depends on history rather than the current value: an audit rule like “no two withdrawals within a minute,” a state machine where PENDING -> CONFIRMED -> PENDING must not be mistaken for “still pending,” or a free-list pointer in lock-free code where the node was recycled.
A monotonically increasing version has no ABA. Because it only ever goes up, version = 7 means exactly one thing: nothing has been written since you read. A version column is strictly stronger than a value comparison at the cost of one integer, which is why it is the default advice. This is the same monotonic-counter trick used by Fencing Tokens to reject a stale lock holder’s write.
OCC vs MVCC vs SELECT FOR UPDATE vs Distributed Locks
Four mechanisms get confused with each other constantly. They sit at different layers and guarantee different things.
| Mechanism | Who enforces it | Blocks writers | Fails with |
|---|---|---|---|
| OCC (version check) | Your WHERE clause or condition expression |
No | Zero rows updated; you retry |
| MVCC | The database engine | No | Serialisation error at high isolation |
SELECT FOR UPDATE |
The database engine | Yes, for the transaction’s life | Lock wait timeout or deadlock |
| Distributed lock | An external service — Redis, etcd, ZooKeeper | Yes, until TTL or release | Lock expiry while you still believe you hold it |
MVCC 💡 (multi-version concurrency control — the engine keeps several versions of each row so readers never block writers) is what makes a SELECT in Postgres or MySQL cheap while writes are happening. It is not a substitute for OCC: under Read Committed, MVCC gives each statement a consistent snapshot and still permits the lost update from the top of this page. Only Repeatable Read or Serializable will abort one of the two transactions, and then you are back to writing a retry loop — the database has simply detected the conflict for you instead of your WHERE clause doing it.
SELECT FOR UPDATE is the right tool for a short critical section inside one database, and the wrong tool across a network boundary or across a user’s thinking time. Distributed locks carry a failure mode the other three do not: the lock can expire while the holder still believes it holds it, which is why a lock without a fencing token is not a correctness guarantee. If you are reaching for one to protect a single row, OCC on that row is simpler and safer.
Relationship to Idempotency
OCC and idempotency are mentioned together constantly and solve adjacent, distinct problems. OCC answers “two different writers raced on the same data — who wins, and how does the loser find out?” Idempotency answers “the same writer sent the same request twice after a timeout — how do we apply it once?”
They compose, and a payment path wants both: an Idempotency-Key header to deduplicate the retry, and WHERE version = 7 to arbitrate between distinct requests. Without the key, a client retry after a network timeout looks like a genuinely new withdrawal and OCC will cheerfully apply it, because from the database’s point of view it is a valid new write. Without the version check, two users racing on one wallet lose an update. Each covers a case the other cannot see.
Common Interview Questions
Q1: What is the lost update problem and does a transaction fix it?
Two writers read the same value, each computes a new value from it, and the second write overwrites the first — so one update silently disappears. Wrapping each in a transaction at the default Read Committed isolation does not fix it, because neither read was dirty; both read committed data that was true at the time. The fixes are to make the write conditional on the version you read, to push the arithmetic into the database so there is no read-then-write gap, or to raise isolation to Repeatable Read or Serializable and handle the abort the engine gives you.
Q2: How do you actually detect that an optimistic write lost?
By the affected-row count, not an exception.
UPDATE ... WHERE version = 7that matches nothing updates zero rows and commits successfully — no error is raised. So the code must readrowcountor its equivalent and treat zero as a conflict. Outside SQL the signal is explicit: DynamoDB throwsConditionalCheckFailedException, RedisEXECreturns nil after a watched key changed, and an HTTPIf-Matchreturns412 Precondition Failed.
Q3: When is pessimistic locking the better choice?
When the conflict rate is high. With N writers contending on one row, OCC does roughly O(N²) work to complete N updates, because each loser spends a read and a write attempt to achieve nothing, and throughput falls as you add load — livelock. A lock queue is work-conserving: each writer does its work exactly once and only pays waiting time. The rule of thumb is conflicts under a few percent favour optimistic, sustained contention on one row favours a lock, and genuinely extreme contention on one row means the data model is wrong and the key needs splitting.
Q4: What is the ABA problem and how does a version column avoid it?
If you condition on the value —
WHERE balance = 100— the value can change from 100 to 50 and back to 100 while you are away. Your condition passes, so you conclude nothing happened, but two writes did happen and any decision that depended on history is now wrong. A monotonically increasing version cannot do this: it only goes up, soversion = 7proves no write has occurred since your read. It costs one integer per row and removes the whole class of bug.
Q5: Do idempotency keys make OCC unnecessary?
No, they solve a different race. An idempotency key deduplicates the same request arriving twice, typically because a client timed out and retried. OCC arbitrates between two different requests racing on the same data. A duplicate charge needs the key; two users draining one wallet need the version check. A payment path should carry both, because the key cannot tell two distinct writers apart and the version check cannot tell a retry from a new intention.
Navigation
| ← Transaction Isolation Levels | Tries → |
| All Concepts | HLD Designs |