Design a Real-Time Sliding Leaderboard for Popular Merchants
System DesignModel answerLast updated
Architect a high-throughput stream processing pipeline to track top-10 global and per-city merchants over a 60-minute trailing window with low latency.
Design an analytics system that tracks and serves the top 10 most popular merchants (by completed order count) across the entire platform as well as per city over a rolling 60-minute time window.
Functional Requirements
- Top Merchants API: Expose an endpoint
getTopMerchants(scope, location_id, limit)returning the current top 10 merchants (globally or for a specific city) in the trailing hour. - Real-time Updates: Process order events continuously to maintain up-to-date rankings.
- Late-Arriving Events: Gracefully handle out-of-order and slightly delayed event arrivals using event timestamps.
Non-Functional Requirements
- Scale: Ingest up to 100,000 order events per second globally across ~1,000,000 distinct merchants.
- Freshness & Latency: Rankings must reflect state within 5 seconds of event receipt. Read endpoints should respond within 10 milliseconds.
- Fault Tolerance & Resilience: The system must sustain worker node failures without losing state or outputting incorrect results over time.
Tasks
- Detail the ingestion and processing pipeline architecture.
- Explain the temporal aggregation and window sliding strategy (evaluating exact vs. approximate techniques).
- Describe how late-arriving data, state persistence, and fault tolerance are handled.
- Demonstrate how the architecture scales out to handle per-city metrics cleanly.
Hints
Hint 1
Consider total key space size before defaulting to probabilistic algorithms like Count-Min Sketch. Is 1M keys manageable in memory?
Hint 2
Avoid native sliding windows in stream processing engines—sliding a 60-minute window every second multiplies state management work by 3,600x. Use fixed 1-minute buckets inside a running aggregator instead.
Hint 3
Combine local top-K extraction at partition workers before sending candidates to a global merger to prevent network bottlenecks.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. System Requirements & Capacity Estimation
Functional Requirements
GET /v1/leaderboard?scope=global|city&city_id={id}&limit=10: Returns top merchants over the last 60 minutes.- Process continuous stream of order events with low stale-window lag.
- Handle late-arriving stream records via event-time windows.
Scale & Back-of-the-Envelope Calculations
- Throughput: 100,000 orders/sec peak.
- Event Size: ~200 bytes per event (
order_id,merchant_id,city_id,timestamp,status). - Ingress Bandwidth: $100,000 \times 200 \text{ B} = 20 \text{ MB/s}$ (well within capacity for standard message brokers like Kafka).
- Hourly Data Volume: $100,000 \times 3,600 \text{ seconds} = 360,000,000 \text{ events/hour}$.
- Key Cardinality: ~1M active global merchants across ~2,000 cities.
Exact vs. Approximate Aggregation
A common trap is jumping to Count-Min Sketch or Heavy Hitters (Space-Saving) algorithms. However, evaluating the key space:
- 1 million total active merchants globally.
- Store 60 minute-level integer counts per merchant.
- Memory: $1,000,000 \times 60 \text{ buckets} \times 4 \text{ bytes} \approx 240 \text{ MB}$.
Because the key space ($10^6$) is fixed and small relative to streaming memory budgets, exact in-memory state aggregation is completely feasible and cheap.
2. API Specification
Endpoint Definition
GET /v1/leaderboard?scope=global&limit=10
GET /v1/leaderboard?scope=city&city_id=NYC&limit=10
Response Payload
{
"scope": "city",
"city_id": "NYC",
"as_of": "2023-10-27T10:15:05Z",
"window_start": "2023-10-27T09:15:00Z",
"window_end": "2023-10-27T10:15:00Z",
"rankings": [
{ "rank": 1, "merchant_id": "m_9812", "name": "Joe's Pizza", "order_count": 1420 },
{ "rank": 2, "merchant_id": "m_3341", "name": "Taco Express", "order_count": 1105 }
]
}
3. High-Level Architecture
┌──────────────────────────────────────────────────┐
│ Stream Processing Engine │
│ (Apache Flink) │
│ │
┌──────────────┐ ┌─────────┐ │ ┌──────────────┐ ┌─────────────────────────┐ │ ┌─────────────┐
│ Order Event ├──►│ Kafka ├─┼─►│ Ingestion & ├───►│ Keyed State Aggregator │ │──►│ In-Memory │
│ Publishers │ │ Cluster │ │ │ Parsing │ │ (60-min Ring Buffers) │ │ │ Data Store │
└──────────────┘ └─────────┘ │ └──────────────┘ └────────────┬────────────┘ │ │ (Redis) │
│ │ │ └──────┬──────┘
│ ┌────────────▼────────────┐ │ │
│ │ Two-Tiered Local-Global │ │ ▼
│ │ Top-K Merger │ │ ┌─────────────┐
│ └─────────────────────────┘ │ │ API Gateway │
└──────────────────────────────────────────────────┘ └──────┬──────┘
│
▼
Clients
Architecture Pipeline Components
- Event Producers: Order Services publish
OrderCreatedevents to Kafka. - Kafka Event Log: Partitioned by
merchant_idto ensure ordering and equal load distribution across workers. - Stream Worker Cluster (Apache Flink): Maintains ring buffers per key, handles watermark progression, and performs two-tiered Top-K aggregation.
- Cache Layer (Redis): Stores pre-computed leaderboards (Global + per-city key pairs) for $O(1)$ read latency.
- API Gateway / Read Service: Fetches ranked arrays directly from Redis with high cache efficiency.
4. Deep Dive: Windowing & Aggregation Engine
Efficient Windowing Strategy: Ring Buffer vs. Naive Sliding Windows
-
Naive Sliding Window Flaw: Defining a 60-minute window sliding every 1 second in a framework like Flink forces every event to be indexed into $60 \times 60 = 3,600$ overlapping windows. At 100K ops/sec, this creates $3.6 \times 10^8$ internal write operations per second, causing massive state inflation and write amplification.
-
Optimized Bucketing Strategy:
- Bin events into 1-minute fixed tumbling buckets.
- Maintain a 60-slot Ring Buffer array per merchant, alongside a scalar
running_total. - Every second, process new records and increment the count in the slot corresponding to
(event_timestamp_minute % 60)and incrementrunning_total. - When an event-time watermark advances past a minute boundary $M$, flush slot $(M - 60) \pmod{60}$ from
running_totaland reset that bucket slot to 0.
Minute Pointer (Current: Minute 15)
│
▼
┌────┬────┬──────────┬────┬──────────┬────┐
│ 0 │ 1 │ ... │ 15 │ ... │ 59 │ <-- 60-element Ring Buffer
└────┴────┴──────────┴────┴──────────┴────┘
▲ ▲
│ │
Expired Bucket Active Bucket (New counts added)
(Subtracted from (Reflects minute 15)
running_total)
Two-Tiered Top-K Reduction (Local to Global)
Computing global/city-wide Top-10 across 1 million keys every 1 second directly on a single thread would create a severe bottleneck. Instead, use a parallel map-reduce reduction:
- Step 1: Partitioned Local Top-K
Workers process partition subsets keyed by
(city_id, merchant_id). Every 1 second, each worker outputs only its top $K$ ($K=10$) candidate merchants per city to a downstream merger task. If there are 32 subtasks, only $32 \times 10 = 320$ records per city travel across the network instead of millions. - Step 2: City Leaderboard Merge A dedicated reducer node per city receives candidate Top-10 updates from all workers, merges the counts, sorts them, and pushes the consolidated city Top-10 to Redis.
- Step 3: Global Leaderboard Merge
A single global merger accepts the candidate Top-10 sets from all cities, computes the combined global Top-10, and updates the
top:globalRedis key.
Processing-Time vs. Event-Time & Late Data Strategy
- Event-Time Processing: Windows rely on the event's embedded
event_timestamp, not wall-clock processing time. - Watermark Policy: Generate bounded out-of-orderness watermarks allowing up to 15 seconds of delay.
- If event time $T_{event} \ge T_{watermark} - 60\text{ min}$, add to the corresponding ring-buffer minute bucket.
- If event time $T_{event} < T_{watermark} - 60\text{ min}$ (severely late data), route the event to a Dead Letter Queue (DLQ) side-output for auditing without mutating historical snapshot leaderboards.
5. Storage Schema & Serving Layer
Leaderboards are stored in Redis using Sorted Sets (ZSET) or raw JSON keys (since $K=10$ is extremely small).
# City Top-10 Redis Key
KEY: top:city:NYC
TYPE: ZSET
SCORE: order_count | MEMBER: merchant_id
# Global Top-10 Redis Key
KEY: top:global
TYPE: ZSET
To eliminate unnecessary network overhead and JSON serialization costs on every single read query:
- Output the top 10 list every second to Redis as a single stringified JSON object:
SET top:global "{\"items\": [...]}". - Read services simply execute a single
GET top:globaloperation ($O(1)$ time complexity), serving traffic in under 2 milliseconds.
6. Edge Cases, Failover & Scalability
1. Data Skew / Hot Key Handling
A single city (e.g., New York City) or merchant might experience massive order spikes.
- Mitigation: Keying by
(city_id, merchant_id)guarantees data for a specific merchant stays together. If a single city experiences excessive volume, increase partition counts on Kafka and scale out Flink parallel subtasks.
2. Stream Processor Failures & State Recovery
- RocksDB State Backend: Flink stores ring-buffer accumulators in RocksDB locally on worker nodes.
- Incremental Checkpointing: Checkpoint state snapshot asynchronously to object storage (e.g., AWS S3) every 10 seconds.
- Recovery: On node failure, restart task manager, pull the latest checkpoint state from S3, resume consumption from the recorded Kafka offset, and replay buffered logs to recover accurate exact counts.
3. Redis Downtime
- If primary Redis goes down, serving nodes fail over to read replicas.
- API service layers implement short in-memory local caching (TTL = 1 second) to shield Redis from load during traffic spikes.