Live Metrics Pipeline for a Global Food-Ordering Platform
System DesignModel answerLast updated
Design a streaming backend that serves order counts, revenue and best-selling dishes over 1-hour, 1-day and 7-day windows at 100K orders/s with data no more than 5 seconds stale.
Design a Live Metrics Backend for a Food-Ordering Platform
You are building the backend behind an operations dashboard for a worldwide food-ordering marketplace. Restaurant owners and internal staff use it to watch three numbers: how many orders came in, how much revenue they generated, and which dishes sell best. Each number must be available for the last 1 hour, the last 1 day and the last 7 days.
Constraints
- Throughput: about 100,000 new orders per second across the whole platform.
- Freshness: a new order must show up in dashboard widgets within 5 seconds.
- Scope: every metric must be queryable for a single restaurant and for the whole platform.
- Durability: short bursts of traffic must never cause order events to be lost.
Your answer should address
- Ingestion pipeline: how events travel from the order service to the aggregation layer, including buffering and stream processing.
- Long-term storage: a table design for the durable store and how you partition it for a heavy write load.
- Windowing: how you compute the three windows, and how you deal with late or out-of-order events and watermarks.
- Serving cache: a Redis key layout that lets the dashboard fetch any window at either scope cheaply.
- Resilience: how the system survives failures, and how you rebuild the cache if it drifts from the truth.
State your assumptions (event size, number of restaurants, accuracy expectations) and back them with rough numbers.
Hints
Hint 1
Start with back-of-envelope numbers: bytes per event, events per item line, restaurants active per second. They tell you where the real bottleneck is (write rate to the cache and hot keys, not raw ingest).
Hint 2
Avoid native sliding windows with a tiny slide. Pre-aggregate into small fixed time buckets (for example per minute and per hour) and build each window as a sum of buckets, adding new deltas and subtracting expired buckets.
Hint 3
A single global key is a hot spot. Aggregate in two stages (restaurant, then region, then global) and ship absolute values rather than increments to the cache so that retries and replays are harmless.
Hint 4
Think about what must be exact (counts, revenue, per-restaurant dishes) versus what may be approximate (platform-wide top dishes), and which data structure suits the approximate part.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size the problem
Assumptions to state
- Peak 100k orders/s, about 1 KB per event: roughly 100 MB/s ingest and about 8.6 TB/day raw.
- About 3 dish lines per order, so around 300k dish-level updates/s.
- Roughly 1M restaurants, of which at most about 100k change in any given second; about 10M distinct dishes.
- Windows use event time (the order's placement timestamp). Revenue is normalised to a single currency in minor units at ingest. A cancellation reverses the order's contribution in the window it belongs to.
- Correctness: counts and revenue are exact once data settles; per-restaurant top dishes are exact (menus are small); platform-wide top dishes may be approximate.
2. Read API
GET /dashboard?scope=restaurant:{id}|region:{r}|global&window=1h|1d|7d returns orders, revenue, top dishes, plus as_of and watermark so the UI can display freshness.
3. Ingestion pipeline
Order service → outbox/CDC → Kafka → stream processor → Redis + wide-column/OLAP store + object-store archive.
- Transactional outbox: the order row and its event are written in one transaction, then relayed (for example by CDC) to Kafka. This prevents lost events if the broker or producer fails.
order_idserves as the idempotency key. - Kafka: topic keyed by
restaurant_id, about 512 partitions (~200 events/s each), replication factor 3,acks=all,min.insync.replicas=2, idempotent producers, 7-day retention so the largest window can be replayed. Kafka absorbs spikes; consumers lag briefly rather than events being dropped. - Stream processor (Flink-style):
- Deduplicate by
order_idusing keyed state with TTL. - Key by restaurant and add events into event-time buckets.
- Emit results to the sinks.
- Deduplicate by
4. Windowing, lateness, watermarks
Bucketing instead of sliding windows. A sliding window with a small slide copies each event into thousands of windows. Instead keep:
- 1-minute buckets (60 of them make the 1h window),
- 1-hour buckets (24 for 1d, 168 for 7d).
Each bucket stores orders, revenue, cancels and per-dish counts. A window total is maintained as a running sum: add incoming deltas, subtract a bucket when a per-minute timer expires it. Reads never merge anything.
Watermark: bounded out-of-orderness, max_event_time - 10s.
Meeting the 5 s target: waiting for the watermark would be too slow, so fire speculative results every second on processing time. Each emission is an absolute value per key, making Redis writes idempotent overwrites.
Late events: within allowed lateness they update their bucket and trigger a re-emit. Beyond it they go to a side topic, and a correction job patches the durable store and recomputes affected keys.
Clock skew: clamp event timestamps to ingest time ± 5 minutes and count how often clamping happens.
Hot key avoidance: two-stage aggregation. Restaurant-level operators emit per-second partials to a region key, then to global, which sees only a few hundred partial updates per second.
5. Top dishes
- Per restaurant (exact): a
dish_id → countmap per bucket; about 100 items per menu, so cheap. Publish the top 10. - Platform-wide (approximate): per-operator Count-Min Sketch per hour bucket plus a Space-Saving candidate list (top ~1000). Sketches merge by addition, so a 7-day sketch is the sum of 168 hourly ones. The global stage merges candidates, re-estimates them on the merged sketch and keeps the top 10. Count-Min only overestimates, by at most about εN with ε ≈ e/width. A nightly batch job can compute the exact list for reconciliation.
6. Durable storage
| Tier | Store | Role |
|---|---|---|
| Raw log | Kafka, then object store (Parquet/Iceberg by date/hour/region) | Replay, audit, backfill |
| Source of truth | Orders DB sharded by order_id | Transactions |
| Aggregates | Cassandra or ClickHouse | History and cache rebuild |
| Serving | Redis Cluster | Sub-ms reads |
Example tables, with partitions bounded by day so they cannot grow forever:
restaurant_metrics_minute((restaurant_id, day), minute_ts, orders, revenue, cancels)dish_counts_minute((restaurant_id, day), minute_ts, dish_id, count)
Writes are upserts of absolute values (replay-safe). Because buckets are flushed once per minute per active restaurant, the store sees at most about 100k rows per minute instead of 100k events per second.
7. Redis layout
Use hash tags so every key for one scope lands on the same slot:
dash:{restaurant:ID}:1h→ HASH (orders,revenue,as_of,wm)dash:{restaurant:ID}:1h:top→ ZSET (dish → count, capped at 10)- Same pattern for
regionandglobal, and for1d/7d. - A
dash:versionpointer enables atomic switch-over during rebuilds.
Reads are one HGETALL plus one ZREVRANGE 0 9, both effectively O(1). Write load: ~100k changed scopes/s × 3 windows × 2 keys ≈ 600k ops/s, coalesced per second and pipelined across roughly a dozen shards with replicas. TTL about 8 days; idle restaurants are still refreshed by the per-minute timers so their windows roll forward.
8. Failures and recovery
- Processor crash: checkpoint state and Kafka offsets together every ~30 s to object storage; restore and replay. Absolute-value sinks make the output effectively exactly-once.
- Redis node loss: replica failover; Redis is derived data only.
- Drifted cache: rebuild into a new key namespace (for example
v43) from the aggregate store or by replaying Kafka/archive, verify against spot checks, then flip the version pointer. Old keys expire on TTL. This is a blue/green swap with no dashboard downtime. - Regional outage: run the pipeline per region and merge at the global stage; the dashboard marks stale regions using
as_of.
9. Trade-offs and common mistakes
- Using native sliding windows (state explosion) rather than bucketed sums.
- Writing increments to Redis, which double-counts on retry; prefer absolute values.
- One global key receiving every update (hot shard).
- Relying only on the watermark and missing the 5 s target.
- Unbounded Cassandra partitions keyed only by restaurant.
- Promising exact global top-N without acknowledging the memory cost; sketches trade a small, bounded error for large savings.
- Ignoring cancellations, currency conversion, or duplicates from at-least-once delivery.