The whole course ▾
System Design · Lesson 28 of 39 · Week 6
Contention: two people, one seat
Two riders tap Accept on the same order within ten milliseconds, and both are told: it's yours. Today: contention.
New System Design videos go up at 6 pm. Subscribe on YouTube so you don't miss it.
Got a doubt? Ask in the comments under the video.Subscribe
Two riders accept the same order.
QuickBite is the food delivery app we grow through the course, from one server to millions of orders.
Two riders, one order
Yesterday we found the riders near a restaurant, and offered the order to a few of them at once, to save time. Today, two of them said yes.
Order four-two-one is offered to two nearby riders. Ravi's app and Sana's app both tap Accept, ten milliseconds apart. The dispatch service handles the two requests at the same time, on two different servers. Each one reads the order from the orders DB: does it have a rider yet? No. So each one writes its own rider into the order, and each one answers: it's yours.
Both riders head to the restaurant. Sana's write landed last, so the database says Sana. Ravi arrives to find the food already gone, having ridden there for nothing, and QuickBite pays him for a wasted trip. This is a race condition: two requests read the same state, both make a decision based on it, and both write. Each step was correct on its own. Together, they're wrong.
Lock it first
The first fix is the most direct: lock the row before reading it, so nobody else can read it in between.
In SQL, inside a transaction, select the order for update. The database locks that row. Sana's request, arriving ten milliseconds later, waits for the lock. Ravi's request sees no rider, assigns Ravi, and commits, which releases the lock. Now Sana's request reads the row, sees it's taken, and answers: sorry, another rider got this one. One winner, guaranteed.
It's simple and correct, but every other request on that row waits its turn. Here that's ten milliseconds, so it's fine. But never hold a database lock while calling something slow, like a payment provider, or a whole line of requests waits behind one network call. Lesson twenty-one showed what slow calls do to everyone waiting on them.
Check, don't lock
Each row carries a version number. Both requests read the order: no rider, version seven. Each one then updates the order, where the version is still seven, setting the rider and the version to eight. The database applies those updates one at a time. Ravi's succeeds, and the version becomes eight. Sana's finds no row with version seven, so it changes nothing. Zero rows changed means someone beat you to it.
Optimistic is faster when conflicts are rare, because nobody waits. Pessimistic is better when they're common, because optimistic would mean lots of failed attempts. And for riders and orders, there's an even simpler version: one conditional update, set the rider where the rider is still empty. The database guarantees only one request can find it empty.
Holding a spot
Some contention lasts minutes, not milliseconds. A customer choosing what to buy can't hold a database lock while they think.
QuickBite runs a festival offer: only fifty special thalis tonight. When a customer taps order, the offer service doesn't sell a thali yet. It places a hold: thali number thirty-one, reserved for this customer, expiring in ten minutes, written with a condition so only one customer can hold each thali. The customer goes on to payment. Pay in time, and the hold becomes a sale. Abandon the checkout, and the hold simply expires, and the thali goes back on offer.
Three details make holds work. Holds expire on their own, with a time to live, so a closed app never blocks a thali forever. A payment confirms the sale only while the hold is still valid, and the same conditional write rejects a late one. And the customer sees a countdown: nine minutes left to pay. Cinemas, airlines and ticket sites all work exactly like this.
Distributed locks, carefully
Sometimes the thing you're protecting isn't a database row, and people reach for a distributed lock.
Say only one worker should send tonight's payout file. You take a lock in a shared system, like Redis or ZooKeeper, with a lease that expires, so a crashed worker can't hold it forever. That stops two workers doing the same job, most of the time. But a worker that freezes for longer than its lease, during a long garbage collection pause, can wake up believing it still holds the lock, while another worker has taken it. The protection is a fencing token: a number that grows with every new lock, which the storage checks, rejecting writes that carry an older one.
So here's the rule. Whenever you can, use the database's own guarantees: a conditional write, a unique key, a version check. They're simpler, and correct even when machines pause. Reach for a distributed lock only when there's no single place to enforce the rule, and then use leases and fencing tokens.
In the interview
Contention is the heart of booking questions: tickets, hotels, seats, ride matching, and limited stock.
Say it like this: for quick races, a conditional write, like set the rider where the rider is empty, or a version check, so exactly one request wins. For contention that lasts minutes, like seats during checkout, holds that expire on their own. And name what the loser sees, because that's part of the design.
Then expect these. Optimistic, or pessimistic? Optimistic when conflicts are rare, locks when they're common. What if the customer never pays? The hold expires, and the item goes back on sale. And why not just a Redis lock? Because leases can expire under a paused process, so prefer the database's guarantees, or add fencing tokens.
The common mistake: read a value, decide in code, then write, with nothing stopping another request from doing the same in between. Whenever you see read, then write, ask: what if two requests do this at once?
Quick check
Two requests each read an order, see it's free, and assign their rider. What's wrong?
Show the answer
A race: both saw "free" before either wrote. Use a conditional write or a lock.
An UPDATE … WHERE version = 7 changes 0 rows. What does that mean?
Show the answer
Someone else changed it first: re-read it, and decide again.
Remember: read-then-write races need a condition on the write. Optimistic checks suit rare conflicts, and locks suit common ones. And contention that lasts minutes uses holds that expire. Tomorrow, the last lesson of the week: big files, and long jobs.
Lessons on weekdays, the week's revision on Saturday, a mock interview on Sunday.