LearnSystem design

Delivery-time (ETA) prediction for a food-delivery marketplace

Predict, at checkout and continuously after ordering, when the food will arrive; also expose ETA signals to the rider-dispatch system.

ML engineering8 parts

Contents

Constraints

  • 1M orders/day in a country
  • ~50 ETA requests per order (~600 QPS average, 5k peak)
  • p99 budget 100 ms

What to cover

Sketch your own design first. A complete answer has these parts; the notes say what each should settle.

  1. RequirementsPredict, at checkout and continuously after ordering, when the food will arrive; also expose ETA signals to the rider-dispatch system.
  2. Estimates1M orders/day in a country, ~50 ETA requests per order across browse, checkout and tracking (~600 QPS average, 5k peak); p99 budget 100 ms.
  3. API
  4. Data model
  5. ArchitectureDecompose into food prep time, rider assignment wait, rider-to-restaurant travel, pickup wait, and restaurant-to-customer travel.; Routing engine as a base estimate, with an ML layer predicting the residual on top of it.; Features: restaurant load, live orders in kitchen, historical prep distribution, rider supply, weather, time, traffic.; Quantile outputs (P50/P90).; Online updates as events arrive; feedback from actual timestamps.
  6. Deep dives
  7. Trade-offsaccuracy vs latency; a point estimate vs ranges shown to customers; optimism (conversion) vs lateness (complaints); a single model vs per-segment models; graph models of road networks (GNNs over road segments) vs tree models.
  8. EvaluationOffline: MAE and P90 absolute error by segment, % of orders late by more than 10 minutes, interval coverage.; Online: A/B or switchback (shared riders) on lateness complaints, conversion, refunds.; Monitor bias drift by city and hour.

Reference design

One way to answer it, part by part. Open a part once you have your own version of it.

Requirements

Functional

  • Browse and checkout: show a delivery-time range per restaurant before ordering (no order or rider yet).
  • After ordering: update the ETA continuously as events arrive (restaurant accepts, rider assigned, picked up) and as the rider moves.
  • Dispatch signals: expose predicted food-ready time and its uncertainty so dispatch can time rider arrival and avoid riders waiting at restaurants.

Non-functional: p99 ≤ 100 ms per request; graceful fallback (historical averages per restaurant and zone) if features or the routing engine are unavailable.

What “good” means: customers care about lateness more than earliness; the business cares about conversion (optimistic ETAs sell) and complaints and refunds (late orders cost). So we need calibrated ranges, not only a point estimate, and we evaluate lateness explicitly.

Assumptions to confirm: one country; ~1M orders/day; restaurants mostly prepare their own food; we own the riders and the dispatch system; customers see a range (“25–35 min”) at checkout and a single time when tracking.

Estimates

Stack · 6 layersLatency budget for a 100 ms p99 ETA request

  1. Feature fetch is budgeted at 20 ms.

  2. Cached routing is budgeted at 20 ms; a cache miss keeps routing calls to ~10–20 ms.

  3. The model is budgeted at 5 ms.

  4. Quantile assembly and business rules are budgeted at 5 ms.

  5. Overhead and network are budgeted at 20 ms.

  6. The remaining headroom is ~30 ms.

The 100 ms p99 budget is split into feature fetch, cached routing, model, quantile assembly and business rules, overhead and network, plus ~30 ms headroom.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
  • Requests: 1M orders/day × ~50 ETA requests per order (browse, checkout, tracking refreshes) = 50M/day ÷ 86,400 ≈ 580 QPS average, ~5k QPS at the dinner peak (about 9× average).
  • Browse fan-out: a restaurant list shows ~30 restaurants, so browse requests are batched — one call scores 30 restaurants; the per-item work is what scales.
  • Inference: a GBDT with ~150 features scores in well under 1 ms on CPU; even if all 5k QPS scored 30 items each, 150k predictions/s needs only tens of cores.
  • Routing: travel-time lookups cached by (origin cell, destination cell, 15-minute bucket) on an H3 grid; a high cache hit rate keeps routing calls to ~10–20 ms when they do happen.
  • Training data: 1M orders/day × 365 = 365M orders/year, each with ~8 lifecycle timestamps; prediction logs of 50M/day × ~1 KB ≈ 50 GB/day.
  • Latency budget (p99 100 ms): feature fetch 20 ms, routing (cached) 20 ms, model 5 ms, quantile assembly and business rules 5 ms, overhead and network 20 ms, ~30 ms headroom.

API

POST /v1/eta
  {stage: "browse"|"checkout"|"tracking", restaurant_ids: [...] | restaurant_id,
   customer_cell, order_id?, basket: {items, value}?, requested_at}
  → {estimates: [{restaurant_id, p50_min, p90_min, display_range: [25, 35],
      components: {prep, rider_wait, to_restaurant, pickup_wait, to_customer},
      model_version, fallback: false}]}

GET /v1/eta/dispatch-signal?order_id=…
  → {predicted_ready_at, ready_p90_at, predicted_pickup_wait_s}

Events consumed (Kafka): order_placed, restaurant_accepted, rider_assigned,
  rider_arrived_restaurant, picked_up, rider_location (every ~5 s), delivered, cancelled

Browse calls are batched per restaurant list, so one request returns ~30 estimates. Responses carry fallback: true when served from historical averages, so clients and monitoring can tell degraded answers apart, and each prediction is logged with a request id for joining to actual timestamps.

Data model

  • OrderLifecycle: order_id, restaurant, customer cell, placed/accepted/ready/assigned/arrived/picked-up/delivered timestamps, rider, basket size and value, cancellation reason.
  • RestaurantFeatures: historical prep-time distribution by hour and basket size, orders in the kitchen now, orders accepted in the last 15 minutes, recent prep-time deviation, tablet acceptance latency.
  • ZoneFeatures (H3 cell, 1–5 minute freshness): available riders, open orders, recent assignment wait, weather.
  • RiderState: location, status, current orders.
  • TravelTimeCache: (origin cell, destination cell, time bucket) → routing estimate.
  • PredictionLog: request_id, order_id, stage, feature snapshot, component predictions, quantiles, model version, timestamp — joined later with actual timestamps to create labels per component.

Architecture

Flow · 4 stepsETA prediction architecture

ETA prediction architectureClients and dispatch call the ETA service, which fetches features from the online store and asks the routing engine for base travel times. The routing engine supplies the baseline; component GBDTs predict prep time, rider assignment wait, rider-to-restaurant travel, pickup wait, and the restaurant-to-customer residual over the routing estimate, with only travel modelled as a residual. Quantiles are combined, business rules round and cap the output, and the response is logged while lifecycle events re-predict remaining components.Clients / dispatchbrowse, checkout,trackingEvent streamlifecycle eventsETA serviceorchestrates the requestOnline storerestaurant load, zonesupply, weatherRouting enginecached base travel timesComponent modelsGBDT, quantile objectivesCombinetotal-time P50 and P90Business layerrounding, ranges, caps, fallbackResponse + prediction loglogged with request ideventsfetchfeaturestravel timesbase + ML residualcomponent predictionsP50 / P90response + log1234InputComputeOutput
  1. Request and features Clients and dispatch call the ETA service; features are fetched from the online store.
  2. Base estimate and components Routing gives the base estimate; component GBDTs predict prep, rider wait, rider-to-restaurant travel, pickup wait, and the restaurant-to-customer residual.
  3. Quantiles and business rules Component predictions are combined into total-time P50 and P90; business rules round, range, cap and fall back.
  4. Response, log and re-predict The response and prediction log are returned; lifecycle events re-predict remaining components.

Requests flow from clients and dispatch through feature fetch, routing and component models to a calibrated P50/P90 response with a prediction log.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Request and featuresClients and dispatch call the ETA service; features are fetched from the online store.
2Base estimate and componentsRouting gives the base estimate; component GBDTs predict prep, rider wait, rider-to-restaurant travel, pickup wait, and the restaurant-to-customer residual.
3Quantiles and business rulesComponent predictions are combined into total-time P50 and P90; business rules round, range, cap and fall back.
4Response, log and re-predictThe response and prediction log are returned; lifecycle events re-predict remaining components.

Source: This page's text

Boxes
BoxGroupDetail
Clients / dispatchInputbrowse, checkout, tracking
Event streamInputlifecycle events
Online storeInputrestaurant load, zone supply, weather
ETA serviceComputeorchestrates the request
Routing engineComputecached base travel times
Component modelsComputeGBDT, quantile objectives
CombineComputetotal-time P50 and P90
Business layerComputerounding, ranges, caps, fallback
Response + prediction logOutputlogged with request id

Source: This page's text

Clients / dispatch ─► ETA service
   ├─ Feature fetch: online store (restaurant load, zone supply/demand, weather)
   ├─ Routing engine: base travel times (restaurant ↔ rider ↔ customer), cached
   ├─ Component models (GBDT, quantile objectives):
   │     prep time │ rider assignment wait │ rider → restaurant │ pickup wait
   │     │ restaurant → customer residual over the routing estimate
   ├─ Combine: total-time quantile model over the component predictions
   │     (or simulation) for P50 and P90, since quantiles do not add
   ├─ Business layer: rounding, ranges, caps, fallback when inputs are missing
   └─ Response + prediction log
Stream processor ─► online features (orders in kitchen, zone supply) every minute
Event stream ─► tracking path: re-predict remaining components on each event,
                smooth to avoid jumpy ETAs
Nightly: join predictions with actuals ─► retrain ─► evaluation gates ─► deploy

Deep dives

Decomposing into components. Each stage has different drivers: prep time depends on the kitchen’s load and the basket; assignment wait on rider supply; travel legs on roads and traffic. Separate models make errors diagnosable and let tracking drop finished components. The routing engine provides a physically grounded baseline and the ML layer learns the residual (parking, building access, restaurant pickup queues) as a post-processing correction.

Labels and censoring. The label for each component comes from lifecycle timestamps; restaurant “ready” taps are unreliable, so infer readiness from rider pickup when the rider waited. Cancelled orders are censored, not dropped silently.

Feedback loop with dispatch. The predicted ready time decides when a rider is sent, which changes rider wait and therefore future labels. Track it, and test changes with switchbacks rather than user-level A/B because treated and control orders share the same riders.

Trade-offs

  • Accuracy vs latency: richer features and a neural model help tail accuracy, but browse needs 30 predictions in 100 ms; use the GBDT on the browse path and a heavier model only for the single order being tracked.
  • Point estimate vs ranges shown to customers: ranges set honest expectations and reduce complaints; a too-wide range looks unreliable. Show P50–P90-style ranges at checkout and a single updating time during tracking.
  • Optimism (conversion) vs lateness (complaints): shading ETAs down lifts conversion but increases late orders and refunds; choose the displayed quantile per market by measuring both in experiments.
  • Single model vs per-segment models: one global model with city, zone and restaurant-type features shares data and generalises to new cities; per-segment models fit local quirks but multiply maintenance.
  • Graph models of road networks vs tree models: GNNs over road segments capture traffic propagation, but we can buy most of that from the routing engine and spend modelling effort on kitchens and riders, where our own data is unique.

Evaluation

  • Offline: MAE and P90 absolute error overall and by segment (city, hour, restaurant type, distance band); percentage of orders delivered more than 10 minutes after the shown ETA; interval coverage (P90 should cover ~90%); per-component errors to locate problems; time-based splits only.
  • Online: switchback experiments (alternating treatment by zone and time window, because orders share riders) measuring lateness complaints, conversion, refunds, rider wait at restaurants and cancellations; plain customer A/B only for display-only changes.
  • Monitoring: signed error (bias) by city and hour of day, coverage drift, feature freshness, routing cache hit rate, fallback rate, latency p99; alert when bias exceeds ±2 minutes in a city for an hour, which usually means a supply shock or a broken feature.

What a strong design shows

  • Decomposes delivery time into stages and uses the routing engine as a baseline with an ML residual.
  • Produces calibrated quantiles and reasons about the asymmetric cost of lateness vs optimism.
  • Updates ETAs online as lifecycle events arrive and exposes ready-time signals to dispatch.
  • Recognises interference through shared riders and uses switchback experiments.
  • Evaluates by segment with lateness and coverage metrics and monitors bias drift by city and hour.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.