Design a Real-Time Top-K Heavy Hitters System
System DesignModel answerLast updated
Design an architecture to identify top-k elements in high-throughput streams over rolling windows, covering data structures, exact vs. approximate models, and sharding.
Design a distributed system capable of reporting the top $K$ most frequent items (e.g., trending hashtags, top-viewed articles, or viral products) over streaming data across multiple time windows (e.g., 1 minute, 1 hour, 24 hours).
Expected Discussion Points
- Requirements & Scale Assumptions: Clarify functional/non-functional requirements, exact vs. approximate trade-offs, and back-of-the-envelope calculations.
- API & Data Models: Define consumer endpoints, event ingestion interfaces, and low-level data structures.
- Core Algorithmic Trade-offs: Compare streaming data structures (e.g., Min-Heap + Hash Map, Count-Min Sketch, Space-Saving) under sliding vs. tumbling windows.
- Architecture & Partitioning: Detail end-to-end streaming ingestion, parallel aggregations, key-partitioning mechanisms, and hot-key handling.
- Fault Tolerance & Queries: Explain caching strategies, data freshness guarantees, state recovery, and exact reconciliation via batch processing.
Hints
Hint 1
Consider how stream partitioning strategy (e.g., key-by item_id vs. random round-robin) affects the mathematical correctness of merging local top-K results into a global top-K list.
Hint 2
Think about how sliding time windows complicate data structures when counts can decrease—how do you handle elements falling out of the top-K bound?
Hint 3
Evaluate approximate data structures like Count-Min Sketch with Heavy Hitters heaps or the Space-Saving algorithm to constrain memory usage.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and Scale Assumptions
Functional Requirements
- Ingestion: Stream continuously arriving event records of format
(item_id, timestamp, metadata). - Queries: Expose an API returning the Top $K$ highest-ranked items across specified time windows (e.g., 1m, 1h, 24h) and optional dimensions (e.g., region, device type).
- Configurability: Support variable values of $K$ (typically $10 \le K \le 1,000$).
- Accuracy Guarantee: Support exact count tracking for billing/analytics or configurable approximate counts for consumer-facing features (allowing up to $\approx 1%$ relative error).
Non-Functional Requirements
- Throughput & Latency: Handle millions of write events/sec. Read latency for Top-$K$ queries must be $P_{99} < 50\text{ ms}$.
- Data Freshness: Stream processing lag bounded to $< 5\text{ seconds}$.
- Fault Tolerance & Availability: High write availability ($99.99%$). Zero loss of stream aggregation state across node crashes.
Scale Assumptions (Back-of-the-Envelope)
- Ingestion Volume: $1,000,000$ events/sec. Average raw payload: $100\text{ bytes}$. Net ingress bandwidth: $\sim 100\text{ MB/sec}$ ($8.6\text{ TB/day}$).
- Key Cardinality: $100\text{M}$ distinct active items per day.
- Memory Estimates (Exact Tracking):
- Each active key tracking record:
item_id($8\text{ bytes}$) +count($8\text{ bytes}$) + hash map overhead $\approx 32\text{ bytes}$. - $100\text{M}$ active items require $100\text{M} \times 32\text{ bytes} \approx 3.2\text{ GB}$ per processing node state. Across multiple dimensions and tumbling windows, total raw state reaches tens of GBs, necessitating partition sharding.
- Each active key tracking record:
- Read Throughput: $50,000\text{ QPS}$. Reads dominate precomputed cache hits rather than raw state lookups.
2. API Design
Read Top-K Endpoint
GET /v1/topk?window=1h&k=100&dimension=region:US
Response:
{
"window": "1h",
"as_of": 1717000000,
"dimension": "region:US",
"items": [
{ "item_id": "item_9921", "score": 84210 },
{ "item_id": "item_0412", "score": 79100 }
]
}
Event Ingestion (Internal Event Payload)
{
"event_id": "uuid-v4",
"item_id": "item_9921",
"timestamp": 1716999995,
"weight": 1,
"dimensions": {
"region": "US",
"device": "mobile"
}
}
3. Core Data Structures and Algorithms
Selecting the right data structure depends on accuracy tolerances, operational bounds, and window semantics.
| Data Structure | Time Complexity (Update) | Space Complexity | Supports Count Decrements? | Notes |
|---|---|---|---|---|
| Hash Map + Min-Heap | $O(\log K)$ | $O(N)$ unique keys | No (unless scans run) | Exact results. Grows unbounded with unique keys. |
| Count-Min Sketch + Min-Heap | $O(d)$ | $O(w \cdot d)$ | No (without Count-Mean-Min or sub-sketches) | Approximate overcount bound. Constant memory footprint. |
| Space-Saving / Misra-Gries | $O(1)$ amortized | $O(K')$ where $K' > K$ | No | High accuracy for skewed (Zipfian) key distributions. |
| Sliding Window Buckets | $O(1)$ add / delete | $O(W \cdot N)$ | Yes | Exact sliding window mechanics using aggregated sub-buckets. |
+----------------------------------+
| Incoming Stream of Event Items |
+----------------------------------+
|
v
+----------------------------------------------+
| Partitioning Engine (Key-by item_id) |
+----------------------------------------------+
|
v
+------------------------------------------------+
| Flink Streaming Task Workers (P Parallel Tasks) |
+------------------------------------------------+
| Local In-Memory State: |
| - Hash Map (Count Tracking per key) |
| - Bounded Min-Heap (Size K) |
+------------------------------------------------+
|
Periodically Emit Local Top-K
|
v
+------------------------------------------------+
| Global Aggregator Node |
| - Merges P Local Top-K lists |
| - Computes exact Global Top-K |
+------------------------------------------------+
|
v
+------------------------------------------------+
| Redis Cluster (Replicated In-Memory Serving) |
+------------------------------------------------+
Detailed Data Structure Mechanics
1. Exact Processing: Sharded Hash Map + Min-Heap
For absolute exactness, maintain a hash map of item_id -> count alongside a min-heap of size $K$.
- As updates arrive, update the hash map count.
- If the item is already in the min-heap, update its count and heapify-down/up ($O(\log K)$).
- If the item is not in the heap and its new count exceeds the root (minimum) of the heap, replace the root item and heapify ($O(\log K)$).
2. Approximate Processing: Count-Min Sketch (CMS) + Candidate Heap
When dynamic memory allocation for $N$ keys is impossible:
- Use a 2D array of counters of width $w$ and depth $d$, with $d$ independent hash functions.
- Width Parameter: $w = \lceil \frac{e}{\epsilon} \rceil$
- Depth Parameter: $d = \lceil \ln \frac{1}{\delta} \rceil$
- For $\epsilon = 0.0001$ and $\delta = 0.01$, set $w = 27,183$ and $d = 5$. Total memory footprint is $5 \times 27,183 \times 4\text{ bytes} \approx 543\text{ KB}$.
- Update: For an incoming
item_id, increment counters at $C[j][h_j(\text{item_id})]$ for $j \in [0..d-1]$. - Estimate: $\hat{c} = \min_j C[j][h_j(\text{item_id})]$.
- Tracking Heavy Hitters: Pair CMS with a Min-Heap of size $K$. Query the estimate $\hat{c}$ from CMS upon every update; if $\hat{c}$ exceeds the top-min element of the heap, add or update the
item_idinside the heap.
4. Architectural Implementation
High-Level End-to-End Pipeline
- Ingestion Layer: API Gateways receive events and write directly to an Apache Kafka messaging queue topic
item-events. - Partitioning Strategy: Events in Kafka are partitioned using
hash(item_id) % Num_Partitions.- Critical Partitioning Correctness: Partitioning by
item_idguarantees that all occurrences of a specific item route to the same worker instance. Therefore, if item $X$ is in the global Top $K$, its full score lives entirely on one worker. This worker's local top-$K$ list will contain item $X$. The overall global top $K$ can be derived by merging local top-$K$ sets from all $P$ parallel streams.
- Critical Partitioning Correctness: Partitioning by
- Stream Processing (Apache Flink):
- Workers maintain per-key counts using RocksDB/in-memory state backends.
- Workers run tumbling sub-windows (e.g., 1-minute aggregations).
- At the boundary of each 1-minute bucket, each of the $P$ stream workers outputs its local Top $K$ list.
- Global Aggregator:
- A single lightweight consolidation node collects the $P$ local top-$K$ lists (totaling $P \times K$ elements).
- Merges lists using a min-heap in $O(P \cdot K \log K)$ time. For $P=100$ and $K=1,000$, this merge takes $< 5\text{ milliseconds}$.
- Serving Layer:
- Output written atomically to a Redis cluster under the snapshot key
topk:{window}:{dimension}:{timestamp}. - An API layer reads cached snapshot references.
- Output written atomically to a Redis cluster under the snapshot key
Kafka Partitioning Scheme
[ Incoming Stream ] ---> Hash(item_id) % P
|
+------------------+------------------+
| |
v v
+------------------+ +------------------+
| Partition 0 | | Partition 1 |
| Items: A, A, B | | Items: C, C, C |
+------------------+ +------------------+
| |
v v
+------------------+ +------------------+
| Worker 1 | | Worker 2 |
| Local Top K: | | Local Top K: |
| [ (A, 2), (B, 1) ] | [ (C, 3) ] |
+------------------+ +------------------+
\ /
\ /
v v
+-------------------------------------+
| Global Merging Engine |
| Combined: [(C,3), (A,2), (B,1)] |
| Target Global Top-2: [(C,3), (A,2)] |
+-------------------------------------+
5. System Subcomponents and Deep Dives
Sliding Window Mechanics
Calculating exact rolling window ranks (e.g., dynamic last 1-hour metric calculated every minute) creates window sliding challenges.
1. Discrete Ring Buffer Granularity
- Break the target $1\text{-hour}$ window into 60 discrete $1\text{-minute}$ sub-buckets.
- Store per-key counts across all 60 individual sub-buckets in a ring buffer structure.
- Rolling Net Sum: $$\text{Count}{1h}(X) = \text{Count}{1h-\text{prev}}(X) + \text{Bucket}{\text{current}}(X) - \text{Bucket}{\text{current}-60}(X)$$
- When rolling off expired sub-bucket limits, expired decrements cause item counts to drop.
2. Handling Decrements in Heaps
- When counts decrease, an item currently stored inside the top-$K$ heap could drop below a non-heap candidate.
- Solution: Maintain an extended tracking buffer heap of size $K' = 3 \times K$ to $5 \times K$. If items drop out of the top $K$, candidates from the expanded buffer step up without requiring a full system state scan.
Hot-Key Mitigations
If a viral item causes partition hot-spotting (e.g., $200,000\text{ events/sec}$ for one item_id hitting a single Kafka partition):
- Two-Stage Salting Aggregation:
- Stage 1: Append a random salt identifier ($1..N$) to incoming hot key IDs:
item_id + "_" + rand(1..N). Distribute ingress streams across sub-workers. - Sub-workers aggregate these salted keys locally.
- Stage 2: Strip the salt identifier and route intermediate totals to a second stage keyed purely by the original
item_id. - This splits high-cardinality write ingestion bottlenecks while preserving exact global routing.
- Stage 1: Append a random salt identifier ($1..N$) to incoming hot key IDs:
- Client-Side Producer Batching:
- Pre-aggregate events at API gateways over 500 ms windows.
- Send consolidated counts
(item_id, count=150)downstream into Kafka instead of emitting 150 single-count events.
Fault Tolerance & State Consistency
- Streaming Recovery: Apache Flink uses Chandy-Lamport distributed snapshotting. State (including minute counts and current heap allocations) checkpoints to object storage (e.g., S3). Kafka consumer offsets commit synchronously with state checkpoints.
- Snapshot Version Pointer Invalidation:
- Serving caches store ready-to-read ranks under immutable snapshot keys (e.g.,
topk:1h:v104). - Writes to Redis populate new keys, then perform an atomic pointer flip (
SET topk:1h:current topk:1h:v104). This eliminates race conditions and ensures read clients never observe partial states during data updates.
- Serving caches store ready-to-read ranks under immutable snapshot keys (e.g.,
- Hybrid Batch-Stream Architecture (Lambda Pattern):
- Real-time paths deliver fast estimates for recent intervals.
- Hourly background Spark jobs run over raw append logs, generating exact analytical rankings. These write back to store tiers to resolve any minor errors caused by stream delays or missing late-arriving events.
6. Trade-offs and System Edge Cases
- Exact Hash Maps vs. Approximate Sketches:
- Exact Tracking: Requires memory that scales linearly with unique keys. If the long-tail key domain reaches hundreds of millions of unique items, nodes run out of memory.
- Approximate Sketches: Guarantees bounded memory footprint ($O(w \cdot d)$) at the cost of over-counting bias.
- Partitioning by
hash(item_id)vs. Random Distribution:hash(item_id)Partitioning: Guarantees mathematically exact top-$K$ results across merged worker sets. However, it risks worker CPU hot-spotting if a single item spikes in traffic.- Random Partitioning: Balances ingress load evenly across all nodes, but merging local top-$K$ results into a global top-$K$ becomes inaccurate. An item could fall just below the threshold on every single worker (e.g., ranking $K+1$ everywhere) and be dropped, even though its global sum should put it at rank 1.
- Data Stale Windows vs. Aggregator Load:
- Reducing global aggregation update intervals from 10 seconds down to 100 milliseconds dramatically increases CPU utilization and network overhead, with diminishing returns for human consumers viewing rank changes.