Two likes land at the same time: who wins the race?
FotoFlow has 100,000 users, and the like counter on a trending photo is now a battleground. Two fans tap like in the same millisecond, the counter climbs by one, and nobody notices a thing. That silence is exactly the problem.
How one like eats another
The code reads the counter, adds one, writes it back. Each request alone is correct. Run two at the same instant and both read "99 likes" before either has written, both write "100", and one like has vanished. This is a race condition, and the lost write is called a lost update.
A transaction alone does not stop a race: the default isolation level lets both reads see the same old value. Wrap the two steps in BEGIN and COMMIT and the database still lets each read see the last committed value, which is 99, twice.
Races hide in testing because you never fire two requests in the same microsecond there. In production they land exactly when traffic peaks.
Three ways to stop the race
The classic fix is a row lock. Read with SELECT ... FOR UPDATE and the first transaction locks the row until it commits; the second one waits, then reads the fresh value. Works, but locks are held until COMMIT, so keep the transaction short.
Often you can skip the read entirely. Change and check in one atomic statement: UPDATE photos SET likes = likes - 1 WHERE id = 7 AND likes > 0, then count how many rows changed. Counters, stock levels and balances are safest as one conditional UPDATE. No gap between check and change, no lock held across round trips.
When people edit things for minutes, like a caption or a profile, use optimistic concurrency instead. Each row carries a version number; the write says WHERE id = 7 AND version = 8. If someone got there first, zero rows change and the client retries. Nobody waits.
Stronger isolation has a price
Databases offer a dial. Read committed, the default, permits the race above. Snapshot and repeatable read prevent more anomalies. Serializable makes everything behave as if one transaction ran at a time, but aborts more often, so your code must catch and retry.
Two traps sit above the dial. A row that appears between your check and your write is a phantom: two transactions both check "no booking for seat 7", both insert, and the seat is sold twice. Locks cannot help because there is no row to lock yet. Serializable isolation, locking the parent row, or a unique constraint do.
Deadlocks are the other trap: two transactions each lock what the other wants next and wait forever. The database detects the cycle, aborts one, and a consistent lock order, say lowest account id first, prevents the cycle from forming at all.
What this does not solve
This post fixes races inside one database. When the same write lands in two regions at once, the winner is decided by replication and consensus, not isolation levels, and that is the subject of parts 16 and 17. Transactions also cannot save a design that holds a lock for three seconds while a payment provider responds: never wait on anything slow while holding a database lock. Replace long locks with a reservation that expires, exactly like every "seat held for 10 minutes" timer.
Two requests read the same value at the same time. Which of your counters would break first?
One UPDATE statement can replace a read, a check and a write. Which query in your app is really three queries wearing a trench coat?
If your counters only move up, this all sounds theoretical. The day you sell something limited, they stop being optional. Next in the series: Terabytes of photos: where do the actual files live?
Sources
Designing Data-Intensive Applications
PostgreSQL documentation
System Design Primer
Recommended for you
- Craft & Skills
One server, 10 million users: how does a photo app survive that?
A 40-post series that follows FotoFlow, a photo app, from one server and 100 users to 10 million users with direct messages. One problem, one fix, one honest cost at a time.
- Craft & Skills
Ten million users want direct messages: could you design the chat system?
The final design: 20 million open sockets and a promise that every message arrives, in order, exactly once. Dumb gateways, a connection registry, store-first durability and sync by cursor.
- Craft & Skills
Five million home feeds: how do you build the page everyone opens?
The home feed must load in 200 ms from two hundred followed accounts. Fan-out on read melts at 4.6 million lookups a second; fan-out on write melts on celebrities; the hybrid survives both.
- Craft & Skills
FotoFlow wants short share links: could you design one today?
The first full design walkthrough: turn a one-line brief into numbers, the simplest system, then fix codes, caching, storage and abuse one bottleneck at a time. The method is the point.
Enjoyed this article?
Subscribe for new articles. No spam. Unsubscribe anytime.
Typed live, never pasted.