Design food delivery
Coordinate customers, restaurants and couriers so that food is found, ordered, cooked, collected and tracked, with search, an order state machine, timed dispatch and peak-hour load.
The problem
Platforms such as DoorDash, Deliveroo and Uber Eats look like ride-sharing with a meal as the passenger. Build it that way and it fails on the first busy evening.
Picture the first version. A customer orders, and the system at once sends the nearest free courier to the restaurant, as it would send a driver to a rider. The courier arrives in 4 minutes. The food takes 20. The courier stands at the counter for 16 minutes, and so do forty other couriers at forty other restaurants, while new orders find nobody free. Meanwhile one restaurant’s tablet has been switched off since lunch. Its customers have paid and are watching a screen that says “preparing”.
A ride has two parties and starts now. A delivery has three parties, and it only works if their timings line up: the restaurant must see and accept the order, the kitchen must finish at about the moment the courier walks in, and the customer must be told the truth throughout. Any of the three can go silent.
Requirements
Functional
- Customers search restaurants that deliver to their address, browse menus, place and pay for an order, and track it.
- Restaurants receive orders, accept or reject them, and mark them ready.
- Couriers go online, receive delivery offers, and confirm pickup and delivery.
- Each side is notified when the order changes state.
- The customer sees an ETA before ordering and a live one afterwards.
Out of scope unless asked: ratings and reviews, promotions, menu management tools, customer support and courier pay.
Non-functional
- Search latency: p99 under 300 ms. Browsing is most of the traffic.
- Order integrity: an accepted order is never lost and never duplicated. The order path targets 99.99% availability.
- Tracking freshness: the courier’s position on the map is at most about 10 seconds old.
- Peaks: lunch and dinner bring several times the daily average, every day, per time zone.
- Scale: 5 million orders a day, 500,000 restaurants, 300,000 couriers online at peak.
Capacity estimates
| Quantity | Working | Result |
|---|---|---|
| Average orders | 5M a day / 86,400 | about 58 per second |
| Peak orders | 60% of orders in two 2-hour windows: 3M / 14,400 | about 210 per second |
| Peak browsing | 50 search and menu requests per order x 210 | about 10,000 per second |
| Courier locations | 300,000 couriers / 5 seconds | 60,000 writes per second |
| Orders in flight | 210 per second x 35 minutes | about 440,000 |
| Catalogue | 500,000 restaurants x 100 items x 500 bytes | about 25 GB |
Three workloads come out of this. Browsing is 10,000 reads a second over 25 GB that changes slowly, so it belongs in a search index and caches. Courier locations are 60,000 writes a second of data that is stale in seconds, so they belong in memory, exactly as in ride-sharing. Orders are only a few hundred writes a second, but each one is money and a promise, so they belong in a transactional database. And every order is local, which makes the city a natural partition.
API
GET /v1/restaurants?lat=51.5033&lng=-0.1196&q=ramen
GET /v1/restaurants/{restaurant_id}/menu
POST /v1/orders
Idempotency-Key: 9c1d...
{ "restaurant_id": "rst_204", "items": [{ "item_id": "itm_17", "quantity": 2 }],
"address_id": "adr_3", "payment_method": "pm_tok_3fa9" }
201 Created
{ "order_id": "ord_8841", "status": "PLACED", "eta": { "earliest": "19:35", "latest": "19:50" } }
POST /v1/orders/{order_id}/accept restaurant, with a preparation time
POST /v1/orders/{order_id}/ready restaurant
POST /v1/offers/{offer_id}/accept courier
POST /v1/orders/{order_id}/picked-up courier
POST /v1/orders/{order_id}/delivered courier
GET /v1/orders/{order_id}/tracking customer, or a WebSocket subscription
The server prices the basket from its own menu data. It never trusts a total sent by the client. The idempotency key stops a retried request on a weak mobile connection creating two orders.
Data model
Orders, in a relational store partitioned by region:
| Column | Notes |
|---|---|
order_id, customer_id, restaurant_id |
|
items |
a snapshot of names and prices at the time of ordering |
kitchen_status |
PLACED, ACCEPTED, READY, or REJECTED |
delivery_status, courier_id |
UNASSIGNED, ASSIGNED, PICKED_UP, DELIVERED |
payment_id, version |
version guards conditional updates |
The items are copied into the order because menus change, and a receipt must show what was bought at the price charged.
Two status columns, not one, because cooking and courier assignment run in parallel. A courier may be assigned before or after the food is ready. The tracks meet at pickup, which requires READY and ASSIGNED. Either track can end in CANCELLED before pickup.
Restaurants have a location, a delivery zone, opening hours and a menu. Live restaurant state (open, paused, current preparation time) sits in a key-value store. Courier positions sit in an in-memory cell index, with history appended to a log.
High-level architecture
Browse path. The customer app calls the search service through the gateway. Search finds candidate restaurants for the customer’s map cell from the search index, overlays live state and returns a ranked list. Menus come from a cache keyed by restaurant and menu version.
Order path. The order service validates the basket, authorises the payment, writes the order and an outbox row in one transaction, and publishes an “order placed” event to the log. The notification service pushes the order to the restaurant’s tablet over its open connection. The restaurant accepts with a preparation time.
Courier path. Courier apps send positions to the location service, which keeps the latest in the geo index. The dispatch service consumes order events, decides when each order needs a courier, queries the geo index for candidates and sends an offer through the gateway.
Tracking and notifications. The notification service consumes order events and courier positions. It sends state changes by push notification and streams the courier’s position to the one customer waiting for that order.
Deep dives
Restaurant search by location
“Nearby” is the wrong question. A restaurant 1 km away across a river may not deliver to you, and one 4 km away along a main road may. Each restaurant has a delivery zone, a radius or a polygon, often drawn by travel time. The question is: which open restaurants have a zone that contains this address?
Running a point-in-polygon test against 500,000 restaurants on every search is wasteful. Restaurants are static, so precompute. Divide the map into cells with a geohash or H3 grid, a few hundred metres across. For each cell, store the list of restaurants whose zone covers it. A search rounds the customer’s position to a cell and reads one list. Everyone in the same cell gets the same list, so it caches extremely well, where exact coordinates never repeat.
Text queries and filters (“ramen”, “vegetarian”) run in a search engine such as Elasticsearch or OpenSearch, which supports geo filters alongside full-text matching.
Split what changes slowly from what changes fast. Names, cuisines and locations live in the index and are cached for minutes. Whether a restaurant is open, paused or running slow changes within seconds, so it lives in a key-value store and is merged into the results at read time. The order service checks the same live state again at order time. A stale results page can show a paused restaurant, but it cannot place an order with one.
Order lifecycle and courier dispatch
Placing an order is a saga, because it spans the order service, the payment service and a restaurant that may never answer.
- Validate the basket, price it, and check the restaurant is open and the address is in its zone.
- Authorise the payment, without capturing it.
- Write the order as
PLACEDand publish the event. - The restaurant accepts, and the payment is captured.
Each step has a compensation. If the restaurant rejects, or stays silent past a deadline despite reminders (a tablet alarm, then an automated phone call), the order is cancelled and the authorisation is voided. Every transition is a conditional update on the current status and version, so a duplicate tap or a retried request changes nothing.
Dispatch borrows its machinery from ride-sharing: a cell index of courier positions, candidates ranked by travel time, an offer with a timeout, and an atomic compare-and-set on the courier’s status so one courier cannot be given two conflicting jobs. The difference is timing. The target is for the courier to arrive as the food is ready:
dispatch time ≈ predicted ready time − courier travel time to the restaurant
Until that moment the order waits in the dispatch pool. Waiting also lets the dispatcher batch: two orders from the same or neighbouring restaurants, heading the same way, go to one courier. If a courier drops out, the order returns to the pool with higher priority.
Live tracking, ETA and notifications
Tracking has a narrow fan-out. One courier’s position goes to the one or two customers whose orders that courier carries, unlike a news feed, where one post goes to millions. The notification service keeps a map from courier to subscribed connections and forwards each position. A WebSocket or server-sent event stream suits this, with polling every few seconds as a fallback. The volume is bounded by what couriers send: 60,000 positions a second at peak, each forwarded to one or two customers, spread across cities. The app interpolates between points so the marker moves smoothly.
ETA is a sum of predicted parts:
ETA = max(preparation time left, courier travel to restaurant)
+ handover + travel to customer + drop-off
Preparation time is predicted per restaurant from history, time of day and basket size. Travel times come from a routing service with live traffic. The estimate is shown as a range and recomputed at every state change.
State-change notifications are driven by the event log, and deduplicated by order and event type so a redelivered event does not buzz a phone twice. The notification service case study covers delivery through APNs, FCM and SMS.
Bottlenecks and failure modes
- Meal-time peaks. They are predictable, so scale on a schedule before each one, not in reaction to it. Under pressure, shed in order: personalised ranking first, then search freshness (serve cached lists for longer), then tracking frequency. Never order placement or state updates. The event log between the order service and its consumers absorbs short bursts.
- Regional isolation. Partition orders, the courier index and dispatch by city. An overload in one city at 7 pm does not reach a city where it is mid-afternoon.
- Restaurant tablet offline. The order is not acknowledged, the deadline passes, and the saga cancels and voids. After repeated misses the restaurant is marked unavailable so search stops offering it.
- No courier available. The order waits and its ETA grows. The better defence is earlier: when courier supply in an area is short, shrink delivery zones and quote longer ETAs before accepting orders that cannot be delivered.
- Courier loses signal. Tracking shows the last known position. Pickup and delivery confirmations queue on the device and are retried with idempotency keys.
- Event log lag. Dispatch and notifications fall behind while orders are still accepted. Alert on consumer lag, because a 3-minute delay here is cold food.
- A promoted restaurant is swamped. Cap accepted orders per restaurant per interval, based on kitchen capacity.
Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Search | Per-cell lists plus live overlay | Geo query on every request | Cacheable and fast; needs validation at order time |
| Dispatch timing | Delayed to match preparation | Assign at order time | Less courier waiting; depends on good predictions |
| Assignment | Greedy with atomic reservation | City-wide batch optimisation | Simple and explainable; uses couriers less efficiently |
| Payment | Authorise at order, capture on acceptance | Capture at order | Rejection is a void, not a refund; needs a saga |
| Partitioning | By city | By order id | Isolation and locality; shards differ in size |
45-minute interview script
A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.
- 0:00 to 5:00
Requirements 5 min
Name the three sides and one or two actions for each. Ask about order volume, peak shape, whether couriers are the platform's own and what is out of scope. State targets for search latency, order durability and tracking freshness.
- 5:00 to 9:00
Capacity estimates 4 min
Derive peak orders per second, browse requests per second, courier location writes and orders in flight. Say the conclusion, which is that there are three different workloads and all of them are local to a city.
- 9:00 to 12:00
API 3 min
Search restaurants by location, get a menu, place an order with an idempotency key, then the restaurant and courier actions that move the order on. Tracking by subscription or polling.
- 12:00 to 16:00
Data model 4 min
The order row with an item snapshot and two status tracks (kitchen and delivery), restaurants with a delivery zone, and the in-memory courier index.
- 16:00 to 24:00
High-level design 8 min
Draw the three apps and the gateway, then browse, order and courier paths, joined by the event log. Narrate one order from search to doorstep.
- 24:00 to 30:00
Deep dive: restaurant search by location 6 min
Delivery zones, not nearest neighbours. Per-cell candidate lists that cache well, static data in the index, dynamic state overlaid at read time, validation again at order time.
- 30:00 to 38:00
Deep dive: order lifecycle and dispatch 8 min
The saga from payment authorisation to restaurant acceptance, what happens when the restaurant is silent, why dispatch is delayed to match preparation time, reserving a courier atomically, batching.
- 38:00 to 43:00
Peaks, failure modes and trade-offs 5 min
Scheduled scaling for meal times, what to shed first, regional isolation, an offline tablet, no couriers, a courier losing signal. ETA as a sum of predicted parts.
- 43:00 to 45:00
Wrap-up 2 min
Summarise in three sentences and name what you would build next, such as batched orders or courier incentives.
Key takeaways
- Food delivery is three workloads in one product. Browsing is read-heavy and cacheable, courier locations are write-heavy and ephemeral, and orders are few but must never be lost or duplicated.
- Restaurant search asks "who delivers to this address and is open now", not "who is nearest". Precompute candidates per map cell and overlay live state.
- An order has two tracks, the kitchen and the delivery, that advance independently and meet at pickup.
- Dispatch is timed so the courier arrives as the food is ready. Sending the nearest courier immediately wastes courier time.
- Authorise payment when the order is placed and settle the outcome with a saga, so a restaurant rejection is a void and not a refund.
- Meal-time peaks are predictable and local. Scale ahead of them, shed browsing before orders and partition by city.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What are the three workloads inside a food delivery platform?
Read-heavy browsing of restaurants and menus, write-heavy ephemeral courier locations, and a low-volume but critical order path.
How is restaurant search different from "find nearby drivers"?
Restaurants are static, and the question is whether the customer's address falls inside each restaurant's delivery zone and whether it is open. The candidate set can be precomputed per map cell and cached.
Why does an order have two status tracks?
Cooking and courier assignment proceed in parallel. The kitchen track goes placed, accepted, ready. The delivery track goes unassigned, assigned, picked up, delivered. They meet at pickup.
How is a delivery ETA built?
The larger of the remaining preparation time and the courier's travel time to the restaurant, plus handover, plus travel to the customer, plus drop-off. Each part is predicted from history and recomputed at every state change.
When should a courier be dispatched?
At roughly the predicted food-ready time minus the courier's travel time to the restaurant, so that the courier and the food arrive at the counter together.
Why partition a food delivery system by city?
Every order involves a customer, restaurant and courier in the same area, so no request crosses regions. Regional shards isolate failures and let each city scale for its own meal times.