Real-Time Frequency Ranking System
System DesignModel answerLast updated
Build a distributed system that tracks item frequencies from a high-throughput stream and serves the most popular items with low latency.
Problem
You're building a service that processes a continuous, high-volume stream of events—each representing an item identifier (such as a search query, product view, or content tag)—and must answer queries for the most frequently occurring items within a recent time window.
Requirements
Your system must support two operations:
- record(item_id): Accept and process an incoming event indicating that
item_idwas observed. - getMostFrequent(n): Return the
nmost frequently observed items over the past 60 minutes, ordered by frequency.
Scale and Constraints
- Throughput: The system receives approximately 100,000 events per second during normal operation, with peak loads reaching 300,000 events/s.
- Response time:
getMostFrequentqueries must complete within 200 milliseconds. - Time window: Frequency counts reflect only the last 60 minutes of data; older events should not influence current rankings.
- Accuracy: Exact counts are not required. Small counting errors are acceptable if they enable better performance, but the relative ordering of genuinely popular items must be correct.
- Result size:
nwill be small, typically between 10 and 100.
What to Cover
- How you ingest and route the event stream
- Your strategy for maintaining frequency counts under memory constraints
- How you implement the sliding 60-minute window
- How you ensure
getMostFrequentqueries remain fast as traffic scales - Trade-offs between accuracy, memory usage, and latency
Hints
Hint 1
Queries should never perform computation—consider precomputing rankings continuously
Hint 2
Partitioning by item ID allows exact merging of local results from different processors
Hint 3
Probabilistic data structures can track heavy hitters in fixed memory with bounded error
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Real-Time Frequency Ranking System
Clarify Scope and Calculate Load
Begin by translating requirements into concrete numbers.
Write volume: 100K events/s average, 300K events/s at peak. Each event is roughly 100 bytes (item ID, timestamp, metadata), giving 10–30 MB/s sustained and about 108 GB of raw data per hour.
Window data: At 100K events/s, the 60-minute window contains 360 million events.
Distinct items: Expect 10–50 million unique item IDs per hour. The frequency distribution follows a power law—most items appear only once or twice, while a small fraction dominates traffic.
Read load: Dashboard queries arrive far less frequently than writes but must return in under 200 ms. The result size n stays below 100.
Acceptable lag: Rankings can be a few seconds stale. Counts may have small errors, but high-frequency items must rank correctly.
The critical insight: never compute rankings during a query. Instead, continuously precompute the top items in the background, and serve queries from a cached snapshot.
Architecture Overview
Event sources → Load balancer → Ingestion tier (stateless API servers)
↓
Kafka (partitioned by hash(item_id), 64 partitions)
↓
Stream processors (one per partition)
- Count-Min Sketch per minute bucket
- Top-N candidate heap
- 60-bucket ring for sliding window
↓
Local top-N lists every 5 seconds
↓
Aggregation service (merge partition results)
↓
Redis cluster (replicated, global top-N cache)
↓
Query API → CDN/edge cache → Clients
Ingestion tier: Normalizes item IDs (lowercasing, trimming), validates format, and batches events before writing to Kafka. This tier is horizontally scalable and stateless.
Kafka: Provides durable buffering between ingestion and processing. Using 64 partitions at ~5 MB/s each leaves headroom for spikes. Replication factor of 3 ensures durability. Retention of 24 hours supports failure recovery and replay.
Partitioning strategy: Events are routed by hash(item_id). This ensures all events for a given item land on the same partition, so each processor maintains complete, authoritative counts for its subset of items. Crucially, this means the global top-N is exactly the top-N of the union of each partition's local top-N candidates—no approximation in the merge step.
Counting Strategy: Probabilistic Data Structures
Writing 100K individual increments per second to disk-backed storage is inefficient when you only need the top 100 items. Instead, all counting happens in-memory within the stream processor.
Each partition maintains per-minute state:
Count-Min Sketch (CMS): Estimates any item's frequency using fixed memory. It consists of a 2D array of counters with width w and depth d (typically d=5 hash functions). When an event arrives, hash the item ID with each function and increment the corresponding counters. To query, return the minimum of the d counters.
- CMS never undercounts; it only overcounts due to hash collisions.
- With
w ≈ 270,000andd=5, each sketch uses about 5.4 MB and provides overcount error under 0.001% relative to total events. - For a 360M-event window, this means errors around ±3,600 events—negligible for items with hundreds of thousands of occurrences.
Top-N candidate heap: Maintain a min-heap of size N (e.g., N=1,000, much larger than the query size). After updating the CMS, query the sketch for the item's estimated count. If it exceeds the heap's minimum, insert or update the item in the heap.
This combination is standard for heavy-hitter detection: the sketch answers "how many?" and the heap answers "which ones?".
State durability: Processors checkpoint their in-memory state (sketches and heaps) to distributed storage (S3, HDFS) every 30–60 seconds, alongside Kafka offset commits. After a crash, the processor restores the last checkpoint and replays from the saved offset.
Sliding 60-Minute Window
Use a ring buffer of 60 one-minute buckets.
Each partition maintains:
- 60 CMS instances, one per minute
- A running aggregate sketch:
window_sketch = sum(last 60 minute sketches)
CMS supports element-wise addition and subtraction because counters are independent. On each minute boundary:
- Add the new minute's sketch to
window_sketch - Subtract the 61st-oldest sketch from
window_sketch - Clear the oldest bucket and start accumulating the new minute there
Candidate tracking: Each minute's heap contributes candidates to the window's candidate pool. Every 5 seconds, the processor:
- Collects the union of all 60 per-minute candidate sets
- Queries
window_sketchfor each candidate's estimated count - Selects the top N items
- Emits this local top-N list
Memory cost: 60 × 5.4 MB ≈ 325 MB per partition for sketches, plus ~100 KB for heaps. This fits comfortably in memory.
Boundary precision: The window is accurate to within one minute. An event from 60:30 ago is treated as either inside or outside the window depending on which bucket it landed in. This is acceptable for "recent popularity" queries. Using finer buckets (e.g., 10-second intervals) would improve precision but increase memory and computation.
Global Aggregation and Serving
Every 5 seconds, the aggregation service:
- Receives 64 local top-N lists (one per partition)
- Merges them using a heap in O(64N log n) time
- Writes the global top-100 (or top-N) to Redis with a timestamp and version number
Why merging is exact: Since partitions are keyed by item ID, each item appears in at most one partition's local list. The global top-N is simply the N highest-count items across all local lists—no overlap, no double-counting.
Query path: getMostFrequent(n) is a single O(1) lookup to Redis, returning the first n entries from the cached global ranking. Redis is replicated across availability zones, and queries can be further accelerated with CDN caching for read-heavy dashboards.
End-to-end latency: Kafka → processor → aggregator → Redis takes 5–10 seconds. Query response time is under 10 ms from Redis, well under the 200 ms requirement.
Trade-offs and Design Choices
| Dimension | Choice | Trade-off |
|---|---|---|
| Counting | CMS + heap | Fixed memory, bounded overcount, no exact tail counts |
| Window | 60 one-minute buckets | ~1-minute boundary error, efficient expiry |
| Partitioning | By item ID | Exact merge, but skewed load for hot items |
| Freshness | 5-second recompute | Slight staleness in exchange for zero query cost |
| Durability | Checkpoints + Kafka | Brief double-count risk during replay unless exactly-once is enabled |
Accuracy vs. memory: Using exact counters (hash map per item) would require memory proportional to the number of unique items (tens of GB per partition). CMS trades small overcount errors for fixed memory, which is acceptable when ranking high-frequency items.
Freshness vs. load: Recomputing every second would give fresher results but increase aggregation and Redis write load. Five-second intervals balance freshness and efficiency.
Handling Hot Items
If 90% of traffic concentrates on a few item IDs, the corresponding Kafka partition and processor handle 90K–270K events/s, while others are idle. Mitigate this with:
Pre-aggregation in ingestion tier: Before writing to Kafka, aggregate events over short windows (100 ms) and emit (item_id, count) instead of individual events. This reduces Kafka load by 10–100×.
Elastic partition scaling: Dynamically split hot partitions, or use a secondary partitioning scheme (e.g., round-robin within the hot item's key space) and merge at aggregation time.
Separate high-frequency path: Route known hot items to a dedicated, vertically scaled processor with higher memory and CPU.
Availability and Failure Handling
Read path decoupled from write path: If stream processing pauses, queries still succeed using the last good snapshot. The cached result includes a window_end timestamp so clients know data freshness.
Kafka replication: With replication factor 3, the system tolerates broker failures without data loss.
Redis replication: Primary-replica setup with automatic failover ensures query availability.
Processor recovery: After a crash, the processor restores its checkpoint and replays events from the saved Kafka offset. Enable exactly-once semantics (Flink's two-phase commit or idempotent producers) to prevent double-counting during replay.
What Interviewers Expect
- Quantitative reasoning: Derive memory requirements, partition counts, and error bounds from the stated load.
- Read-write separation: Recognize that precomputing rankings eliminates query-time computation.
- Correct partitioning: Explain why partitioning by item ID allows exact merging of local results.
- Concrete windowing: Describe the ring buffer mechanism in detail, not just "use a sliding window."
- Honest trade-offs: Acknowledge approximation error, latency, and skew, and propose mitigations.
This design scales to millions of events per second by distributing work across partitions, bounds memory with probabilistic structures, and serves queries from a precomputed cache—delivering the required throughput, latency, and accuracy under real-world constraints.