A worked design, end to end
Assigning a rider to an order, taken from invariants and numbers through races and failure modes to a table of decisions another engineer can challenge.
This chapter lets you run a design review from a one-line feature request to a design another engineer can challenge line by line. We use every earlier chapter, but only where the feature needs it, and we write each decision down with its alternative and the evidence that would change it.
The feature is the one at the centre of Dabba: when a restaurant accepts an order, assign a rider to deliver it. It looks like a search (find a nearby rider) and is mostly a coordination problem (make sure one order gets one rider and one rider gets one order, while phones, networks and workers fail). It is also the feature where mistakes are most visible: food going cold on a counter, two riders arriving for one order, or a rider riding across the city for an order someone else already took.
We will go in the order a good review goes: what must be true, the numbers, the data and the flow, the places it breaks, how earlier chapters apply, and the decisions written as a table.
Write down what must stay true
The functional requirement fits in a sentence: after a restaurant accepts an order, find a rider who can reach the restaurant about when the food is ready, offer them the order, and if they decline or do not answer within 30 seconds, offer it to someone else. The customer and restaurant see the assigned rider; the rider sees the drop-off only after accepting.
The invariants matter more than the features, because they are what the design must defend under failure. We write three. An order has at most one assigned rider at any time. A rider has at most one pending offer and at most one active order (version one does not batch two orders on one trip). And no accepted order waits unassigned without someone knowing: after five minutes without a rider it is escalated to the city’s operations team.
The non-functional requirements follow from what customers and riders notice. Ninety-five per cent of orders should have a rider within two minutes of acceptance. The time to choose a candidate should be small next to the time a rider takes to respond, so a few hundred milliseconds is plenty. Crashed workers, duplicated events and slow phones must not break the invariants. And we write down what is out of scope, so the review does not drift: batching, assigning before the restaurant accepts, and machine-learned arrival times are later reviews.
Do only the arithmetic that changes the design
From the brief: about a million orders a day, 42 a second in the dinner hour with the order path designed for 150, and 50,000 riders online at peak, each sending a location every 5 seconds.
Assignments arrive at the order rate, about 42 a second nationally in the dinner hour and at most 150 at the design target. Not every offer is accepted; if roughly 60% are, an order needs about 1.7 offers on average, so around 70 offers a second, 255 at the target. Each offer and acceptance costs a handful of database writes (offer row, rider state, order state), so the assignment path writes a few hundred rows a second. That is modest for a single well-run database, so storage capacity does not drive this design.
Locations are the volume: 50,000 riders ÷ 5 seconds = 10,000 updates a second. But each update overwrites the previous one for that rider, and the current position of every rider in India is 50,000 small records, a few megabytes. That fits in memory on one machine. Locations are therefore a write-rate problem with a tiny working set, which points to an in-memory geo index (the Redis geo set in the first chapter’s list of stores), fed from the rider-locations stream keyed by rider id, rather than to a database table updated 10,000 times a second.
One more number tells us where the real pressure is. Use Little’s law on riders rather than on threads. An order takes about 35 minutes from placement to delivery, but a rider is occupied for perhaps 20 of them (1,200 seconds): riding to the restaurant, waiting, and delivering. At 42 orders a second, that is 42 × 1,200 ≈ 50,000 riders busy at once, which is the whole online fleet. Dabba is saturated in riders at an ordinary dinner peak, and a festival evening near the 150-a-second design target would need more than three times the riders it has. So the hard case is not a fast search through plenty of riders; it is a queue of orders waiting for scarce riders, at exactly the moment everything else is busiest. The design must behave well when the answer to “who is nearby and free?” is “nobody”.
The data, and the flow one arrow at a time
The order lives where the sharding chapter put it: in the logical shard of its restaurant, one of 8,192, chosen by a hash of restaurant_id. Riders are not orders, and a rider delivers for many restaurants in a day, so rider state cannot live in the order shards. It goes in a separate rider store, one database per region holding the riders of that region’s cities (50,000 riders and a few hundred writes a second fit one well-run database comfortably). Offers live next to the riders:
-- order shard (hash of restaurant_id)
orders (id, restaurant_id, status, rider_id NULL, accepted_at, ready_at, ...)
-- rider store (one per region)
riders (id, city_id, status -- OFFLINE | IDLE | OFFERED | ON_ORDER
current_offer_id NULL, current_order_id NULL)
offers (id, order_id, rider_id, status -- PENDING | ACCEPTED | DECLINED | EXPIRED
expires_at)
-- at most one live offer per order, enforced by the database:
CREATE UNIQUE INDEX one_live_offer ON offers (order_id)
WHERE status IN ('PENDING', 'ACCEPTED');That split is the most important decision in this design. The order and the rider are in different databases, so “give this order to this rider” cannot be one local transaction. A distributed transaction across the two would put a coordinator on the busiest path in the system. Instead we choose one place where both invariants are decided, the rider store, and let the order shard follow. The unique index means an order can have only one live offer, so at most one rider can ever accept it; the conditional update on the rider row means a rider can hold only one offer. Once the rider store says “rider 4411 accepted order 9182”, updating the order is a consequence, not a decision, and a consequence can be applied later and more than once.
The flow uses each earlier chapter once. When the restaurant taps “accept”, the order service updates the order and writes an OrderAccepted outbox row in the same transaction (the outbox from the streams chapter). A relay publishes it to the order-events log, whose 48 partitions are keyed by order id (the streams chapter), so every event for one order reaches the same assignment worker in order. Different workers handle different orders in parallel, and nothing about one busy city makes one partition hot.
The worker asks the geo index for idle riders within a few kilometres of the restaurant whose last update falls within the 20-second freshness window (the geospatial chapter’s cells do the lookup). It ranks them by estimated arrival at the restaurant relative to when the food will be ready, with a fairness term for riders who have been idle longest, and takes the best.
It then creates the offer and reserves the rider in one transaction on the rider store, using conditional updates so that the database, not the worker’s memory, decides whether the rider is still free:
BEGIN; -- rider store
UPDATE riders SET status = 'OFFERED', current_offer_id = :offer
WHERE id = :rider AND status = 'IDLE'; -- 0 rows: taken, try the next candidate
INSERT INTO offers (id, order_id, rider_id, status, expires_at)
VALUES (:offer, :order, :rider, 'PENDING', now() + interval '30 s');
COMMIT;
-- then: schedule "expire :offer" at +35 s, send the offer to the rider's appThe offer reaches the rider’s phone over a WebSocket with acknowledgements, the mechanism the realtime chapter chose for restaurant tablets, because here too the server needs to know that the offer arrived, separately from whether it was accepted. Riders hold that socket only for offers, on a separate dispatch pool of connection servers, so a surge of customer connections cannot delay an offer. A push notification is the fallback when the socket is down. When the rider taps accept, the accept endpoint runs one transaction on the rider store: mark the offer accepted only if it is still pending and belongs to this rider, and move the rider to ON_ORDER. If either condition fails, the transaction rolls back and the app shows “this order is no longer available”.
The same transaction writes a RiderAssigned row to the rider store’s outbox. Its consumer applies it to the order shard with UPDATE orders SET rider_id = :rider WHERE id = :order AND rider_id IS NULL, which is safe to run twice and cannot conflict, because the rider store has already made sure there is only one accepted offer. For a second or so the order shard lags the rider store; the customer’s screen shows “finding your rider” a moment longer, and the rider app, which reads from the rider store, already shows the pickup. That lag is the price of avoiding a cross-database transaction, and it is one worth paying.
Where it breaks: the races
Every arrow in the figure can be delivered twice, delivered late, or not delivered. Walk through each and check the invariants.
The OrderAccepted event is delivered twice, because the relay crashed after publishing and before marking the outbox row sent. Two workers (or one worker, twice) try to create an offer for the same order. The unique index on live offers per order lets one insert succeed; the other fails and is discarded. Invariant one holds without any lock outside the database.
Two different orders choose the same rider at once, because both restaurants are on the same street. Both workers run the conditional update on the rider. One sees one row updated; the other sees zero and moves to its next candidate. Invariant two holds.
A worker crashes after creating an offer and before sending it to the rider. The offer is in the database and the expiry job is scheduled, so in 35 seconds the offer expires, the rider is released, and the order is offered again. Nothing is lost, but the order waited 35 seconds for nothing. If that happens often, the worker can, on restart, resend its pending offers. We note it and move on; it is a latency cost, not a correctness one.
A rider taps “accept” with the countdown showing 1 second left. Their phone is on a weak network, and the request reaches Dabba 1.5 seconds later, after expires_at. At almost the same moment the expiry job runs. What should happen, and what does the rider see?
Show the worked answer
With the strict design, the accept transaction checks expires_at > now(), finds the offer expired, and fails; or the expiry job has already marked it EXPIRED and the accept finds no pending offer. Either way the rider sees “offer expired” after doing exactly what the app asked, in time by their own screen. Riders learn that the last seconds are unsafe and the effective offer window shrinks.
The fix is a grace period on the server. The app counts down 30 seconds; the server accepts until 30 + 5 seconds; the expiry job is scheduled at +35 seconds and expires the offer only if it is still pending, with the same conditional update as the restaurant-acceptance timeout in the background-work chapter. Whichever transaction commits first wins and the other finds nothing to do. The cost is that an offer nobody answers holds the order for 35 seconds instead of 30. That is the kind of trade worth writing into the review explicitly, with the measurement (accept requests arriving after the deadline) that would tune it.
One more race is human. Some riders run auto-clicker apps that accept offers within milliseconds and decline the ones they do not want, which breaks the fairness the ranking was designed for. Dabba’s defence uses earlier chapters: a per-rider rate limit on decisions, offers that are sent to one rider at a time (so there is nothing to snipe), and a monitor on accept latency distributions per rider.
Where it breaks: not enough riders
At 20:30 on a rainy evening in Bengaluru, orders arrive faster than riders free up. The worker finds no idle rider within 3 km for many orders. The first response is mechanical: the order goes back into a retry queue with a short delay, and each retry widens the search radius a little. That keeps the order alive, but it cannot create riders.
Without a further response, the unassigned queue grows for as long as demand exceeds supply, customers wait 40 minutes for food that is ready in 15, and restaurants fill their counters with cooling bags. The response belongs upstream, before more orders are accepted: the backpressure idea from the failure chapter applied to a product. As the age of the oldest unassigned order in a zone rises, the app first shows longer delivery estimates for restaurants in that zone, then adds a rain surcharge (which both slows demand and attracts riders online), then stops accepting new orders in that zone for a few minutes. Each step is a flag that operations can also trigger by hand. The metric that drives it is the same one the background-work chapter recommended for any queue: the age of the oldest item, not the count.
The rest of the toolkit, applied
Security. The offer card shows the restaurant and a rough drop-off area, not the address. The address and masked phone number become visible only when the accept transaction commits, through the same access function as every other order read. The accept endpoint checks that the offer’s rider is the caller, because offer IDs, like order IDs, will leak.
Failure. The geo index is soft state: if a city’s index process dies, a new one rebuilds from the next round of pings in five to ten seconds, and two replicas per city mean even that gap rarely shows. If the database primary for a city fails over, assignment in that city pauses for the seconds it takes; events wait in the log, and the worker resumes from its offset. If the push provider is slow, offers still reach riders over the dispatch WebSocket. The payment provider does not appear on this path at all, which is deliberate: payment is settled before the restaurant accepts.
Multi-region. Assignment for a city runs in the city’s home region, next to the region’s rider store and the logical shards of that city’s restaurants. When a city is re-homed, offers that were pending in the old region expire and are reissued, and riders’ apps reconnect to the new region. A minute of slower assignment in one city is the planned cost of a failover.
Delivery. A new ranking function is the most likely change to this feature, and the riskiest, because it changes who earns what. It first runs in shadow mode: the worker computes both the old and the new choice for every order, uses the old one, and logs both. A week of shadow data shows how the new ranking would have changed pickup waits and rider earnings before any rider is affected. Then a per-city flag turns it on in one city, and the comparison continues on real outcomes.
The decisions, written so they can be challenged
| Decision | Alternative | Why this one | What would change our mind |
|---|---|---|---|
| Offer to one rider at a time | broadcast to five, first to accept wins | fair, no wasted rider attention, nothing to snipe | assignment too slow in sparse zones; then offer to small batches there |
| Workers consume order events by order id | a matcher per city | no hot partition for a busy city; per-order ordering is all assignment needs | batching, which needs a view of a whole zone at once |
| Rider store decides; order shard follows | a cross-database transaction, or a lock in Redis | one database holds both invariants; no coordinator or lock expiry on the hot path | the order-shard lag becoming visible to customers |
| In-memory geo index fed by pings | a geo query on the database | 10,000 overwrites a second of state that is useless after a minute | needing location history; stream it to storage separately |
| 30 s offer, 35 s server deadline | longer offers, or strict 30 s | fits rider decision time; forgives weak networks | measured late accepts or long silent waits |
The last column is the most useful one in the table. It turns each decision from an opinion into a claim with a test, and it tells the next reviewer which measurements to look at before reopening the argument.
When this design would be wrong
At a tenth of the scale, most of this is unnecessary. A Dabba with one city and 300 riders could run assignment as a single process holding everything in memory, backed by one database, with a person dispatching difficult orders by hand. The event log, the separate rider store and the shadow-mode ranking would be cost without benefit.
At a different shape, parts of it change. If Dabba batched two orders per rider, the rider’s state would no longer be a single active order, the invariant would change, and the matching would become an optimisation over a time window rather than a choice per order. That is a different design, and it would get its own review. Saying which changes would invalidate a design is part of finishing it.
One feature, carried through every chapter, showed how the pieces fit. The final chapter, the problem atlas, goes the other way: it takes the well-known design problems (URL shorteners, feeds, chat, payments ledgers and others) and shows which chapters make each one hard, so a new problem can be placed on the map quickly.