Case Study — Design a Food Delivery Platform

Restaurant search, ordering, payments, rider matching and live tracking for a food delivery app.

Est. 50 min Updated Suggest a fix
// Part 01 — Requirements

Model Three People and One Time-Sensitive Order

Design a food-delivery platform connecting customers, restaurants, and delivery riders. A customer discovers an open restaurant, checks a menu, places an order, pays, follows restaurant preparation, and sees delivery progress. A restaurant accepts or rejects the order; the platform assigns a nearby available rider and shares location updates until delivery. A user-friendly design must still behave correctly when a restaurant rejects an order, a payment callback is delayed, or no rider is available.

Clarify delivery radius, service hours, cancellations, substitutions, tips, and partial refunds.
AreaFirst versionImportant quality goal
DiscoverySearch restaurants by location, cuisine, and availability.Results are geographically relevant and not stale for long.
OrderingCreate an order from a menu with a quoted total.Price and menu snapshot do not silently change after checkout.
PaymentAuthorize or collect payment and settle refunds on failure.Retries never charge the customer twice.
FulfilmentRestaurant accepts, prepares, and hands off to a rider.State transitions are visible and recoverable.
TrackingCustomer sees status and recent rider location.Location is fresh enough for an ETA, with privacy controls.
OperationsSupport can inspect the order timeline.Every transition has an actor, time, and reason.

Scope the first release to one city, one currency, and standard menus. Defer subscriptions and grocery delivery. Define cancellation rules and when a restaurant or rider can no longer be reassigned.

💡 Note
Keep the order total as a confirmed snapshot: item prices, quantities, taxes, delivery fee, and discounts at checkout. A restaurant's menu changing later must not rewrite a customer's existing order.
// Part 02 — Estimates

Estimate Orders, Search, and Location Separately

Use illustrative scenario assumptions. Suppose 1 million daily active customers place an average of 0.2 orders per day; that yields 200,000 orders per day, or about 2.3 average order creations per second. Meal periods create peaks well above the average, so measure lunch and dinner patterns and provision with headroom. Restaurant search and menu reads are much more frequent than order writes and should be cached carefully, while availability and menu updates need bounded staleness.

Location traffic is a different workload. If 20,000 active riders report location every few seconds, updates can outnumber orders by a wide margin. The exact interval should be tuned to movement, battery, network cost, and customer usefulness; do not broadcast every raw GPS point to every nearby client. Keep only the latest location in a fast ephemeral store, and retain longer history only when there is a clear operational or legal need.

delivery_capacity.py
python
SECONDS_PER_DAY = 86_400
daily_active_customers = 1_000_000
orders_per_customer_per_day = 0.2
active_riders = 20_000
location_interval_seconds = 5

orders_per_day = daily_active_customers * orders_per_customer_per_day
average_orders_per_second = orders_per_day / SECONDS_PER_DAY
location_updates_per_second = active_riders / location_interval_seconds

print(f"orders/day: {orders_per_day:,.0f}")
print(f"average order creates/s: {average_orders_per_second:.1f}")
print(f"illustrative location updates/s: {location_updates_per_second:,.0f}")
print("measure real peak factors, fan-out, and payload sizes before sizing")

These paths need different storage: cache menu reads, persist orders transactionally, and optimize location for frequent updates. Their freshness, durability, and cost requirements differ.

🎯 Pro Tip
Ask which traffic is a read, a durable business event, and a rapidly expiring observation. That classification often reveals the right storage boundaries more clearly than a list of fashionable databases.
// Part 03 — API

Make Checkout and State Changes Explicit

A customer first fetches nearby restaurants and menus, then submits an order with item IDs, quantities, and a client idempotency key. The server validates current menu availability and calculates the authoritative total. Restaurant, payment, and rider actions are separate authenticated commands. Tracking clients subscribe to an order they are authorized to view; they do not choose the order's status themselves.

order_api.py
python
from dataclasses import dataclass
from decimal import Decimal

@dataclass(frozen=True)
class OrderLineRequest:
    menu_item_id: str
    quantity: int

@dataclass(frozen=True)
class CreateOrderRequest:
    restaurant_id: str
    lines: tuple[OrderLineRequest, ...]
    delivery_address_id: str
    idempotency_key: str

@dataclass(frozen=True)
class PriceQuote:
    subtotal: Decimal
    delivery_fee: Decimal
    total: Decimal

# POST /v1/orders -> 201 with order_id, status, confirmed quote
# POST /v1/orders/{id}/restaurant-decision -> authorized restaurant command
# GET  /v1/orders/{id}/events -> cursor-based customer timeline

Reject invalid quantities, unavailable items, stale quotes, or out-of-area addresses. Reuse an existing order only when an idempotency key and request payload match; the server calculates prices in integer minor units or decimal.

  1. Validate identity, address, restaurant state, and item quantities.
  2. Recalculate the total from the current menu and persist the item and fee snapshot.
  3. Create the order and an outbox event in one transaction using the idempotency key.
  4. Return the stable order ID; process payment and fulfilment through explicit state transitions.
⚠️ Important
A payment timeout does not tell the application whether the provider captured money. Query or reconcile the payment using a stable provider reference before trying a new charge or issuing a refund.
// Part 04 — Data model

Keep the Order Snapshot and Timeline Durable

Orders are business records and should be durable. Keep an order header, immutable line snapshots, payment attempts, and an append-only event timeline. The state column supports current reads; the event history explains how that state was reached. Restaurant and rider data have separate ownership and lifecycles. A spatial database or geospatial index can serve restaurant and rider discovery, but do not couple the order's financial history to a volatile GPS table.

delivery_schema.sql
sql
CREATE TABLE orders (
    order_id UUID PRIMARY KEY,
    customer_id UUID NOT NULL,
    restaurant_id UUID NOT NULL,
    status VARCHAR(32) NOT NULL,
    currency CHAR(3) NOT NULL,
    subtotal_minor BIGINT NOT NULL,
    delivery_fee_minor BIGINT NOT NULL,
    total_minor BIGINT NOT NULL,
    idempotency_key VARCHAR(128) NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE (customer_id, idempotency_key)
);

CREATE TABLE order_lines (
    order_id UUID NOT NULL REFERENCES orders(order_id),
    line_number INTEGER NOT NULL,
    menu_item_id UUID NOT NULL,
    item_name_snapshot TEXT NOT NULL,
    unit_price_minor BIGINT NOT NULL,
    quantity INTEGER NOT NULL CHECK (quantity > 0),
    PRIMARY KEY (order_id, line_number)
);

CREATE TABLE order_events (
    event_id UUID PRIMARY KEY,
    order_id UUID NOT NULL REFERENCES orders(order_id),
    sequence BIGINT NOT NULL,
    event_type VARCHAR(64) NOT NULL,
    actor_id UUID,
    payload JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE (order_id, sequence)
);

Index customer history and restaurant queues based on real queries. Store payment references, not raw card details; define retention and access controls for addresses and rider location.

Location records can be ephemeral: rider ID, coordinate, observed-at time, and a short-lived assignment reference. Each update replaces the previous current-location value. The order timeline can record assignment and hand-off events without storing a complete minute-by-minute route unless the product requires it.

// Part 05 — High-level design

Separate Discovery, Order Orchestration, and Live Tracking

Customer search reads restaurant profiles, menus, and serviceability. Checkout writes an order and outbox event; orchestration coordinates payment, restaurant acknowledgement, and rider matching. Dedicated workers process retries and timeouts. A location service ingests rider updates and streams authorized, rate-limited tracking updates to the customer. Each downstream interaction is observable and can be retried or compensated where needed.

text
Customer App --> API Gateway --> Discovery Service --> Geo Index / Menu Cache
      |                 |
      |                 +--> Order Service --> Order DB + Transactional Outbox
      |                                           |
      |                                           v
      |                                      Event Broker
      |                                      /     |            |                                     v      v       v
      |                              Payment   Restaurant  Dispatch Service
      |                              Adapter    Workflow         |
      |                                                        v
      |                                                Rider Matching / Geo Index
      |                                                        ^
      | Rider App -- location stream --> Location Ingest -----+
      |                                                        |
      +<---- Authorized Tracking Stream <---- Order / Location Fan-out

These can begin as modules in one application. Split services only when scale or ownership justifies the cost; a broker does not replace state transitions or reconciliation.

// Part 06 — Deep dives

Orchestrate the Order and Match Riders Carefully

Order lifecycle and payment

A simplified lifecycle is created, payment-pending, confirmed, restaurant-accepted, preparing, ready-for-pickup, rider-assigned, picked-up, delivered, or cancelled/refunded. Not every path visits every state. Validate transitions centrally and attach an idempotency token to external payment operations. If a restaurant rejects after payment authorization, release the authorization or refund according to the provider contract and record the compensating action. A saga coordinates these steps; it is not a distributed database transaction.

order_state.py
python
ALLOWED = {
    "created": {"payment_pending", "cancelled"},
    "payment_pending": {"confirmed", "payment_failed", "cancelled"},
    "confirmed": {"restaurant_accepted", "cancelled"},
    "restaurant_accepted": {"preparing", "cancelled"},
    "preparing": {"ready_for_pickup", "cancelled"},
    "ready_for_pickup": {"rider_assigned", "cancelled"},
    "rider_assigned": {"picked_up", "cancelled"},
    "picked_up": {"delivered"},
}

def transition(current: str, target: str) -> str:
    if target not in ALLOWED.get(current, set()):
        raise ValueError(f"invalid transition: {current} -> {target}")
    return target

print(transition("preparing", "ready_for_pickup"))

Adapt this table to actual cancellation policies. Sequence transitions to reject concurrent stale updates, and reconcile orders stuck in payment or restaurant-pending states after timeouts.

Restaurant and rider workflow

Restaurants need an acceptance deadline and preparation milestones. Rider matching searches nearby available riders, ranks by ETA, workload, and constraints, then reserves a rider atomically to prevent conflicting assignments.

candidate_ranking.py
python
def rank_candidates(candidates, pickup_lat, pickup_lon):
    ranked = []
    for rider in candidates:
        distance = abs(rider["lat"] - pickup_lat) + abs(rider["lon"] - pickup_lon)
        score = distance + rider["active_orders"] * 0.5
        ranked.append((score, rider["id"]))
    return [rider_id for _, rider_id in sorted(ranked)]

candidates = [
    {"id": "r-1", "lat": 16.50, "lon": 80.64, "active_orders": 0},
    {"id": "r-2", "lat": 16.52, "lon": 80.65, "active_orders": 1},
]
print(rank_candidates(candidates, 16.51, 80.64))

This uses coordinate distance only to demonstrate ranking. Production matching needs a spatial index and a road-network ETA; straight-line distance is not a guaranteed arrival time.

Live tracking

Reject stale or unauthorized rider updates and share them only with the active order's customer and permitted staff. Show the last-updated time, reduce stationary updates, and stop sharing after delivery or cancellation.

// Part 07 — Bottlenecks and trade-offs

Protect the Marketplace During the Dinner Peak

BottleneckDesign responseTrade-off
Popular restaurant overloads search or checkout.Cache menu reads, reserve capacity, and rate-limit writes.A menu may be briefly stale; checkout must revalidate.
No nearby rider accepts.Expand search gradually, adjust incentives by policy, or offer a revised ETA.Longer assignment time or higher fulfillment cost.
Payment callback arrives late or twice.Idempotent provider reference, event deduplication, and reconciliation.More workflow states and operational tooling.
GPS updates overwhelm downstream clients.Coalesce latest location and sample authorized fan-out.Tracking is less granular but sufficient for progress.
A hot city cell attracts many searches.Partition geo indexes and cache by cell with bounded freshness.Complexity when moving between cell boundaries.

Enforce confirmed pricing, valid state transitions, and one assignment per rider capacity. Search may be eventually consistent, but checkout must revalidate. Location can be delayed; expose freshness and monitor it.

  • Measure restaurant acceptance time, payment outcomes, rider assignment latency, delivery duration, and stale location age.
  • Use circuit breakers and bounded retries around payment, mapping, and notification providers.
  • Provide operational queues for stuck orders, failed refunds, and unassigned deliveries.
  • Protect customer and rider safety: restrict precise location access to the active delivery and authorized support roles.
// Part 08 — Pitfalls

Common Food-Delivery Design Mistakes

Recomputing a historical order from the current menu

Why: Restaurants can change prices or remove items after checkout.

Fix: Persist a confirmed line-item and fee snapshot with the order.

Treating payment as a synchronous boolean

Why: Network timeouts and callbacks can leave the outcome unknown or duplicated.

Fix: Model attempts, idempotency, callbacks, and reconciliation as explicit states.

Matching riders by nearest coordinate alone

Why: Straight-line distance ignores roads, workload, vehicle capacity, and pickup readiness.

Fix: Use geo search for candidate generation, then rank with realistic ETA and constraints.

Broadcasting every raw GPS update

Why: It wastes bandwidth and can expose more location history than needed.

Fix: Coalesce updates, scope access to active orders, and expire current-location data.

// Part 09 — Practice

Trace One Failure From Checkout to Recovery

Practice

Design a recoverable order workflow

  1. Write an order state diagram that includes payment timeout, restaurant rejection, customer cancellation, and refund completion.
  2. Calculate order and location event rates using a different city scenario, then state which path needs peak capacity.
  3. Define the exact idempotency behavior for a repeated checkout request and a repeated payment callback.
  4. Choose a geo-index cell strategy for rider candidates and explain how you avoid assigning one rider twice.
  5. List the minimum order events support needs to resolve a complaint without retaining unnecessary location history.

Hint: For every external side effect, write down how the workflow knows whether it succeeded and how it safely retries or compensates.

🎯 Key Takeaways

  • ✓Clarify customer, restaurant, rider, payment, and tracking behaviors before selecting components.
  • ✓Estimate orders, discovery reads, and location updates as distinct workloads with different storage needs.
  • ✓Persist confirmed price snapshots and use idempotency keys for checkout and payment operations.
  • ✓Represent order progress as guarded state transitions backed by a durable event timeline.
  • ✓Use geospatial search to find rider candidates, then rank and reserve assignments atomically.
  • ✓Treat location as sensitive, approximate, and short-lived; keep notification and mapping failures recoverable.

Next

What comes next

You have worked through three different system shapes. Finish by practicing a repeatable interview framework, concise trade-off communication, and common question patterns.

Lesson 15 · System Design Interview — Framework and Practice Questions →

HELP US IMPROVE

How was this lesson?

Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.

Choose your feedback

Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.

Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...