Location · Design 24

Design Food delivery

Design a food delivery app like DoorDash in a 45-minute interview: restaurant search, the order state machine, courier assignment, ETAs, payments and a three-sided marketplace.

IntermediateInterview priority: High55 min
On this page
  1. How to use this page
  2. 1. Clarify the requirements
  3. 2. Back-of-the-envelope estimates
  4. 3. API
  5. 4. Data model
  6. 5. High-level design
  7. 6. Deep dives
  8. 7. Bottlenecks, failures and monitoring
  9. 8. Follow-up questions
  10. Quiz

How to use this page

This page follows the order of a real system design interview. At each step there is a Your turn box: write your own answer first (it stays in your browser), then open ours and compare. Reading a finished design feels easy; producing one under time pressure is the skill you are practising.

PhaseTime in a 45-min interviewWhat you produce
1. Clarify requirements5 minWhat each of the three sides needs, targets, what's out of scope
2. Estimate5 minOrders/s at peak, browse requests/s, courier updates/s
3. API5 minCustomer, restaurant and courier calls
4. Data model5 minCatalog, orders, events, courier locations, ledger
5. High-level design10 minBrowse, order and dispatch flows
6. Deep dives10–15 minSearch, the order state machine, dispatch timing, ETAs, payments
7. Wrap up2–3 minBottlenecks, failures, what you would monitor

Customers browse nearby restaurants and menus, place and pay for an order, and track it live. Restaurants accept and prepare orders. The system assigns a courier who picks up and delivers. Show accurate ETAs. Skip grocery delivery, reviews, loyalty programmes and restaurant onboarding.

1. Clarify the requirements

Your turn: scope it

The interviewer says: "Design a food delivery app." Write down your questions and the requirements, grouped by who needs them: customer, restaurant, courier.

Compare with our answer

The questions that matter most: Do we own the couriers or does the restaurant deliver? One city or many? Do we show an ETA before ordering? Can a courier carry two orders? How are restaurants and couriers paid? Grouping by side is the point: a three-sided marketplace (customers, restaurants and couriers all participating, each with their own app) means three sets of requirements that the platform has to coordinate.

A strong answer mentions: browse and search nearby restaurants · order and pay · restaurant accept with a prep time · courier assignment, pickup and drop-off · live tracking and ETAs · never lose or double an order · lunch and dinner peaks.

Functional: what it must do

  • Browse nearby restaurants: Filtered by distance, open now, delivery time
  • View menus and order: Cart, address, payment
  • Restaurant accepts and prepares
  • Courier assignment and delivery: Pickup, then drop-off
  • Live tracking and ETAs: Order status and courier on the map

Out of scope

Grocery deliveryRatings and reviewsLoyalty programmesRestaurant onboarding

Non-functional: how well it must work

QualityTargetWhy
Browse latency< 300 ms for restaurant listsHungry people are impatient
Order reliabilityAn accepted order must never be lost or doubledMoney and food are involved
Peak handling5× traffic at lunch and dinner
ETA accuracyWithin a few minutesBad ETAs drive cancellations
Availability99.95%+Restaurants depend on the orders

2. Back-of-the-envelope estimates

Your turn: the numbers

5 M orders a day, a dinner peak 5× the average, about 20 restaurant list views per order, and 300 K couriers online at peak sending a position every 5 s. Work out peak orders/s, peak browse requests/s, courier updates/s, and order status events per day.

Compare with our answer
  • Orders: 5 M ÷ 86,400 ≈ 58/s average; × 5 = ~290/s at peak.
  • Browsing: 5 M × 20 = 100 M list views a day ≈ 1,160/s; × 5 = ~5,800/s at peak. About 20× the order rate, and very cacheable.
  • Couriers: 300 K ÷ 5 s = 60 K updates/s: an in-memory geo index again.
  • Events: ~8 status changes per order × 5 M = 40 M events/day (~460/s average): easy for Kafka.

A strong answer mentions: peak factor for meal times · browse vs order ratio · courier updates as the largest write rate · events per order · that order volume is modest but each order touches many services.

Assumptions: orders per day 5 M; peak vs average 5; restaurant list views per order 20; couriers online at peak 300 K; seconds between courier location updates 5.

NumberEstimateWhy it matters
Orders per second (peak)289 / s≈ 290/s at peak: modest, but each order touches many services.
Browse requests per second (peak)5.79 K / s≈ 5,800/s: cache restaurant lists by area.
Courier location updates per second60 K / s60 K/s: an in-memory geo index again.
Order events per day40 M~8 status changes per order: placed, accepted, preparing, ready, picked up, delivered…
  • Browsing is ~20× the order rate and is cacheable per area; orders are few but need care.
  • Peaks are short and sharp: plan for the peak, autoscale for it.

The key insight: three workloads with different shapes. Browsing is thousands of cacheable reads a second; orders are a few hundred careful, money-carrying writes a second; courier locations are tens of thousands of throwaway writes a second. Each gets a different store.

3. API

Your turn: the API

Write the main calls for each of the three apps. Which call needs an idempotency key, and which call can lose a race to another courier?

Compare with our answer

A strong answer mentions: restaurant list by location (cached) · menu by restaurant · place order with an idempotency key · restaurant accept with a prep time, and mark ready · courier accept offer (409 if taken), pickup and deliver · order status and courier position by WebSocket or polling.

CallRequestResponseNotes
GET /v1/restaurants?lat=&lng=&cuisine=–{ restaurants[] with eta, fee }Cached per area (geo cell)
GET /v1/restaurants/{id}/menu–{ categories[], items[] }Cached; changes rarely
POST /v1/orders{ restaurantId, items[], addressId, paymentMethodId }201 { orderId, eta }Idempotency-Key header
POST /v1/restaurant/orders/{id}/accept{ prepMinutes }200Restaurant tablet app
POST /v1/courier/offers/{id}/accept–200 or 409
GET /v1/orders/{id}–{ status, courierLocation, eta }Or a WebSocket for live tracking

The idempotency key on POST /v1/orders matters more here than in most shops: a duplicate order means two kitchens cooking and two couriers dispatched, not just a refund. See duplicates and idempotency for how the key is stored and checked.

4. Data model

Your turn: the tables

What stores do you need for restaurants and menus, for orders, for the status history, for courier positions and for money? Pick a database for each.

Compare with our answer

A strong answer mentions: SQL as the source of truth for restaurants and menus, plus a search index and caches · orders in strongly consistent SQL with a status column · an event log for status changes · courier positions in memory · a double-entry ledger for charges, payouts and fees.

restaurants and menus SQL (source of truth) + search index + cache

  • restaurant_id, name, location, hours, cuisines
  • menu_items(item_id, restaurant_id, name, price, available)

Edited rarely, read constantly; search by location, cuisine and dish name needs a search engine.

orders Strongly consistent SQL (sharded by region)

  • order_id, customer_id, restaurant_id, courier_id
  • status, items, totals
  • placed_at, ready_at, delivered_at

A state machine with money attached: transactions and conditional updates.

order events Event log (Kafka)

  • order_id, event, ts, actor

Every status change is an event that drives notifications, tracking, ETAs and payouts.

courier locations In-memory geo index

  • cell → courier_ids
  • courier_id → lat, lng, status

Like Uber: only the latest position matters for dispatch.

payments and payouts Ledger (SQL, double-entry)

  • entry_id, account, amount, order_id

Charge the customer, pay the restaurant and courier, keep the platform fee. Must reconcile exactly.

Two terms worth defining here:

  • A double-entry ledger records every money movement as two equal and opposite entries (customer account −€30, platform clearing +€30). The sum of all entries is always zero, which makes errors detectable and every payout auditable.
  • The order events log is not the source of truth for the order's state (the orders table is); it is how every other service hears about changes.

5. High-level design

Your turn: draw it

Sketch the services and trace one order from "Place order" to "courier assigned". Which service owns the order's state, and how do the others learn about changes?

Compare with our answer

Compare with the figure. The things people forget: the order service as the only owner of order state, an event stream connecting everything else, the ETA service feeding both browsing and dispatch, and that dispatch does not assign a courier immediately.

The architecture, then browsing and placing an order

  1. The architecture: a catalog and search service for browsing, an order service that owns the order state machine, and an event stream that connects everything else. Dispatch listens to order events, uses a courier geo index and an ETA service, and payments handle charges and payouts.
  2. The customer browses restaurants near their address, served from cached search results with ETAs. Placing the order saves it, authorises payment, and publishes an “order placed” event.
ComponentWhat it does
Catalog + searchRestaurants and menus, searchable by area, cuisine and dish; cached per geo cell
Order serviceThe order state machine; source of truth
Order events (Kafka)Placed, accepted, ready, picked up, delivered… drive everything else
DispatchChooses and times courier assignments; can batch orders
Courier geo indexLatest courier positions in memory
ETA servicePrep time + travel time models
PaymentsAuthorise, capture, refunds, payouts via a ledger

The restaurant accepts, then dispatch times a courier

  1. The restaurant’s tablet receives the order and accepts it with an estimated preparation time. That prep time is the key input for when to send a courier.
  2. Dispatch doesn’t send a courier immediately. It times the assignment so the courier arrives as the food is ready: it finds couriers nearby, estimates their travel time, and offers the job a few minutes before the food is done.

Trace the order out loud:

  1. The customer places the order with an idempotency key. The order service authorises the card (reserves the money without charging it), saves the order as placed, and writes an order.placed event via an outbox (a table written in the same transaction, published by a relay).
  2. The restaurant's tablet is notified and accepts with a prep time of 15 minutes; the order becomes accepted.
  3. Dispatch hears order.accepted, looks up couriers near the restaurant, asks the ETA service for their travel times, and waits until the right moment to offer the job.
  4. A courier accepts; a conditional update assigns them (only if no courier is assigned yet), and the customer sees the courier on the map.

6. Deep dives

Your turn: the hard parts

Before reading on: how do you make "restaurants near me that deliver here and are open" fast? When exactly should a courier be assigned? What stops a cancelled order from being delivered, or a delivered order from being cancelled?

Compare with our answer

A strong answer mentions:

  • A search index with geo filters on delivery zones, cached per area cell, with live "open/busy" flags.
  • A state machine with one owner per transition and conditional updates.
  • Just-in-time dispatch: assign at ready time minus travel time minus a buffer; batching when the detour is small.
  • An ETA made of prep + courier-to-restaurant + restaurant-to-customer, each predicted separately.
  • Authorise at order, capture at delivery; a ledger that splits the money three ways.

The query is "restaurants that deliver to this address, are open now, match 'pizza' or a cuisine filter, sorted by a mix of delivery time, rating and relevance".

OptionHowCatch
SQL with distance mathsWHERE distance(lat, lng, ?) < 5 km per requestSlow and repeated thousands of times for the same area; weak text search
Search index (Elasticsearch/OpenSearch)Restaurants and dishes indexed with location, delivery-zone polygon, cuisine, hoursAnother system to keep in sync with SQL (via change events)
Plus a cache per area cellCache the unpersonalised list per geo cell for a minute; re-rank per user on topUp to a minute stale; "busy" or "closed" flags must override it

Choice: SQL as the source of truth, a search index fed from change events, and a cache keyed by geo cell (for example a geohash of about 1 km). Each restaurant has a delivery zone polygon rather than a radius, because a river or a motorway changes who it can reach in time. Menus change rarely and are cached per restaurant; item availability ("out of avocado") is a small, separate flag that the restaurant toggles and that skips the cache.

The order state machine

The order state machine and its guards

The order service is the only writer of an order's status. Each transition has one owner and a precondition:

TransitionWhoPrecondition
placed → acceptedRestaurantPayment authorised; within the accept timeout
accepted → preparing → readyRestaurantCurrent status matches
ready → picked upCourierCourier is the assigned one
picked up → deliveredCourierCourier is the assigned one; near the address
any → cancelledCustomer, restaurant, supportStatus is before picked up

Each transition is one conditional update (WHERE status = <expected>) plus an event written through the outbox in the same transaction. Duplicate or late events, such as a retried "ready" after pickup, match no row and are ignored.

Courier assignment: when, and who?

Dispatch timing: arrive as the food is ready

  1. Deep dive: dispatch timing. Send the courier so they arrive just as the food is ready, using predicted prep and travel times.

A worked example. The order is accepted at 19:00 with a 15-minute prep time, so the food should be ready at 19:15. Courier A is 6 minutes from the restaurant. Assign at about 19:15 − 6 − 2 (buffer) = 19:07.

OptionCourier waitsFood waits
Assign at 19:00 (on order)~9 min at the restaurant, earning nothing0
Assign at 19:15 (when ready)0~6 min, getting cold
Assign at 19:07 (just in time)~2 min (the buffer)~0 if prep is on time

Dispatch re-plans every few seconds, because positions and predictions change. Real systems treat it as an assignment problem: every 10–30 seconds, take all waiting orders and available couriers in an area and solve for the pairing with the lowest total cost (lateness + courier idle time + distance), instead of greedily giving each order the nearest courier.

Batching: if two orders from the same restaurant (or neighbouring ones) go in a similar direction, one courier can carry both, as long as the first customer's extra delay stays under a limit such as 5 minutes. At peak this significantly raises deliveries per courier hour.

Live tracking

Once a courier is assigned, the customer wants to watch them move. The courier app already sends its position every 5 seconds to the location service, which updates the geo index. For tracking, the location service also publishes the position to a per-order channel (for example a Redis pub/sub topic named after the order), and the customer's app, connected by WebSocket to a tracking server, receives it. The fan-out is tiny (one courier, one or two watchers), so this is cheap; the work is holding the open connections, about one per active order. If the WebSocket drops, the app falls back to polling GET /v1/orders/{id} every 10 seconds, which is good enough for a map. It is the same push-or-poll trade-off as in WhatsApp, at a far smaller scale.

ETAs: three predictions added together

The ETA shown to the customer is prep time + courier to restaurant + pickup handling + restaurant to customer. Each part is predicted separately (prep from restaurant history, travel from a routing engine with live traffic, handling from history per restaurant, such as parking at a mall) and combined. Show it as a range ("25–35 min") and update it at every state change. Monitor the ETA error (predicted minus actual) per city and hour: a model that is wrong in one direction erodes trust faster than one that is noisy.

Payments in a three-sided marketplace

  1. At order: authorise the total (food + fees + tip) on the card.
  2. At delivery: capture the final amount, which may be lower if an item was unavailable (a partial capture, so no refund is needed).
  3. In the ledger: record the capture and split it: restaurant payout (food minus commission), courier earnings (fee plus tip), platform revenue.
  4. Payouts: batched daily or weekly to restaurants and couriers from ledger balances.

Every call to the payment provider carries an idempotency key derived from the order ID, so a retried capture never charges twice. A failed capture after delivery is retried and, if it keeps failing, flagged on the account; the food has already been eaten, so the ledger must record what is owed.

Why not charge at order time?

Charging immediately and refunding later works, but refunds cost fees, take days to reach the customer and look bad on a statement. Authorisation holds the money, and capture happens only for what was delivered. Authorisations expire (often after about 7 days for cards), which is never a problem for a meal delivered within the hour.

Balancing a three-sided marketplace

The platform only works if all three sides stay: customers need short, reliable delivery times; restaurants need orders their kitchen can cook; couriers need enough jobs per hour to earn. Each lever helps one side at another's expense:

LeverHelpsCosts
Higher delivery fee in a busy cell (surge)Fewer orders, so ETAs hold; more courier payCustomers who order less
Courier incentives ("+€2 per delivery 19:00–21:00 in the centre")Supply where demand isPlatform margin
Shrink a restaurant's delivery radius at peakFaster deliveries for nearer customersRestaurant sales
More batchingCourier earnings per hourA few minutes for some customers
Pause a restaurant ("busy")Accurate ETAsRestaurant sales

The system that turns these into numbers is the same as Uber's surge: per area cell and per few minutes, compare demand (orders, app opens) with supply (idle couriers from the geo index) and adjust fees, radius and incentives, smoothed so they don't flicker. In an interview, naming the three-way tension is worth more than any formula.

Events instead of calls

Every status change is an event

  1. Every status change is published as an event. Dispatch, tracking, notifications and payouts each subscribe.

The order service doesn't call dispatch, notifications, tracking and payouts directly; it publishes events and each subscribes. Partition the topic by order ID, so all events for one order are consumed in order, and make consumers idempotent (de-duplicate by event ID), because the outbox relay publishes at least once.

7. Bottlenecks, failures and monitoring

Scaling bottlenecks

BottleneckFix
Dinner peaksAutoscale stateless services; cache browse heavily; pre-warm before known peaks
Hot restaurant (100 orders in 10 min)Throttle intake or extend ETAs; surface “busy” status
Courier locationsIn-memory geo index sharded by city
Event fan-outPartition order events by order id to keep per-order order

When things fail

FailureWhat happens
Restaurant tablet offlineEscalate: phone call / SMS; auto-cancel and refund if not accepted in time
Courier cancels mid-routeOrder goes back to dispatch with higher priority
Payment capture fails after deliveryRetry; flag the account; the ledger keeps it auditable
Order service region outageFail over to replica region; in-flight orders resume from the event log

What to monitor

Orders per minute vs forecastRestaurant acceptance timeCourier wait time at restaurantsETA error (predicted vs actual)Cancellation ratePayment failures

8. Follow-up questions

Your turn: the interviewer pushes

Answer in order: 1) A courier's app crashes after pickup and doesn't come back. What happens to the order? 2) It starts raining at 19:00 on a Friday: orders double and a third of couriers log off. What does the system do? 3) Add grocery delivery with 50-item orders and substitutions. What changes?

Compare with our answer

A strong answer mentions:

  1. The order stays picked up; a missing-heartbeat timeout alerts support, who contact the courier and customer; never auto-reassign food that is physically with someone.
  2. Surge delivery fees and courier incentives in busy cells, longer quoted ETAs, a smaller delivery radius, throttling restaurants, more batching.
  3. Picking becomes its own state with per-item status; substitutions need customer approval; capture the final amount after picking; inventory freshness matters for search.
How do you predict prep time?

Learn per restaurant from history (time of day, items, current queue); update when the restaurant taps “ready”.

How are restaurants and couriers paid?

A double-entry ledger records the customer charge and splits it into restaurant payout, courier earnings and platform fee; payouts batch daily or weekly.

How do you handle a sudden rainstorm?

Demand spikes and couriers drop: surge delivery fees, extend ETAs, limit radius, incentivise couriers in busy cells.

Food delivery on one page
  • Three sides: customer, restaurant, courier; the kitchen sets the pace.
  • Numbers: ~290 orders/s at peak, ~5,800 browse/s, ~60 K courier updates/s, ~40 M events/day.
  • Browse: search index with delivery-zone polygons, open-now and cuisine; cached per geo cell; live "busy" and item availability bypass the cache.
  • Orders: one owner (order service); state machine with conditional updates; timeouts for stuck states.
  • Events: outbox → Kafka, partitioned by order ID; idempotent consumers.
  • Dispatch: just in time (ready − travel − buffer); periodic batch assignment; batch orders when the detour is small.
  • ETA: prep + to restaurant + handling + to customer; show a range; track the error.
  • Payments: authorise at order, capture at delivery (partial if items missing), ledger splits money three ways, idempotency keys.
Mock interviewPractise it as a mock interview: scope, size and the big decisionsOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. Food will be ready at 19:15 and the best courier is 6 minutes from the restaurant. When should dispatch offer the job?

2. A restaurant taps "cancel" after the courier has picked up the food. How should the order service behave?

3. Thousands of users near one shopping centre open the app at 19:00. What makes the restaurant list fast?

4. Restaurants' own prep-time estimates are often 10 minutes too short at peak. What is the best fix?

5. Why authorise the card at order time and capture at delivery?

6. Dispatch, notifications and payouts must react to every order status change. Which design is most robust?

7. An order has been in "placed" for 6 minutes because the restaurant's tablet is offline. What should the system have?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.