Designing a Bounded-Memory Sliding-Window Top-K Stream Ranker
System DesignModel answerLast updated
Design a memory-bounded structure that ranks the most frequent events over a sliding time window under millions of events per second, covering windowing, sketches, ties, and complexity.
Problem
You own a service that ingests a firehose of events (for example, user search queries) and must continuously expose the K most frequent event IDs over the last T minutes. The stream arrives at millions of events per second, and you are not allowed to keep the entire history in memory.
Required interface
track(event_id)— record one occurrence of an event.get_top_k()— return today's ranking of the K most frequent IDs within the current window.
Requirements
- Sustain millions of updates per second with low query latency.
- Rankings must reflect only events inside a sliding window of length T.
- Memory usage must be bounded and independent of how many distinct IDs appear.
- State clearly how ties between equal-frequency IDs are resolved.
- Compare an exact-count design with an approximate one (Count-Min Sketch, Space-Saving/heavy-hitters), and justify your choice.
Deliverables
- A concrete data-structure design that trades off memory against query performance.
- A mechanism for expiring old events from the window.
- Complexity analysis of
track()andget_top_k(), plus the expiration cost.
There is no single correct answer; the interviewer wants you to pin down the numbers, defend the trade-offs, and show that your design actually meets the wall-clock and memory constraints.
Hints
Hint 1
Start by estimating the volume inside one window (events/s × window seconds) and the number of distinct IDs; that number decides whether exact counting is even possible.
Hint 2
The enemy of accuracy is eviction, not insertion. Consider slicing the window into fixed time buckets so an expired chunk can be subtracted wholesale instead of tracking per-event timestamps.
Hint 3
An approximate counter is linear: the sketch for a window equals the sum of its bucket sketches, which is what makes rolling subtraction cheap.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing the problem
Before designing anything, I want concrete numbers, because they decide whether exact counting is viable. Assume ~5M events/s with a 5-minute window: about 1.5B events per window. Search-query frequencies are long-tailed, so distinct IDs per window could easily reach 10^8. K is small, typically 10–1,000. I also ask: is a result a few seconds stale acceptable (almost always yes)? Must counts be exact, or is a relative-error guarantee fine? And what does "time" mean — event time or arrival time — and how are late events treated?
The key realization: any structure that stores a counter per distinct ID costs O(distinct) memory, which violates the bounded-memory requirement at 10^8 keys. Exact counting is out; we need approximation, but an approximation with a provable error bound.
Why a naive hash map + heap fails
Keep a hash map of counts and a min-heap of the top K. Each track() mutates one count, which is fine, but expiration is the killer: as events age out, counts decrease, and an ID that fell out of the heap can't be recovered without scanning the whole map. You can fix the heap with an LFU-style bucket list (a doubly linked list of frequency groups) where ±1 updates are O(1) and get_top_k is O(K) — but memory is still O(distinct keys). That dead end is the pivot to approximation.
Proposed design: time buckets + Count-Min Sketch + Space-Saving
Window partitioning. Split T into B fixed buckets (e.g., T = 300s, bucket = 5s → B = 60) held in a ring buffer. Each bucket owns two structures:
- A Count-Min Sketch with d rows × w counters. It gives a one-sided overestimate: with probability 1−δ the estimate is at most εN above the true count, where w = ⌈e/ε⌉ and d = ⌈ln(1/δ)⌉. Crucially, a CMS is linear — sums of sketches are sketches of sums.
- A Space-Saving summary of m counters, which guarantees every item with bucket frequency > n_b/m appears in it.
Why the candidate set is complete. If an item's window count exceeds N/m (N = total events in the window), then by pigeonhole it exceeds n_b/m in at least one bucket, so it is present in that bucket's Space-Saving summary. Union of the per-bucket summaries therefore contains every true heavy hitter. We rank that candidate union using the global CMS estimates.
Expiration. Bucket id = ⌊timestamp / bucket_seconds⌋. On each call, advance the ring; when a bucket falls out of the window, subtract its CMS from a running global sketch (O(d·w)) and drop its summary. Because sketches are linear, the global sketch is always the exact sum of live buckets — no recomputation. This cost lands once per bucket rotation, amortized to roughly nothing against millions of events per bucket.
Ties. Define a deterministic order, e.g. sort by (−estimated_count, event_id) so output is stable for clients and tests. I'd also report the error bound εN, since items whose estimates differ by less than that are statistically tied.
Memory. O(B · (d·w + m)), independent of cardinality. With d = 4, w = 2^14, 4-byte counters, m = 1,000: ~256KB per bucket, ~16MB for the whole window. That fits comfortably.
Complexity
| Operation | Exact (LFU structure) | Proposed |
|---|---|---|
track() | O(1) | O(d) CMS + O(1) Space-Saving (O(log m) with a heap) |
| expiration | O(keys expiring) | O(d·w) per rotation, ~0 amortized per event |
get_top_k() | O(K) | O(B·m·d + B·m·log K); O(K) if cached per rotation |
| memory | O(distinct) | O(B·(d·w + m)) |
Hitting millions of events/s
- Shard by hash(event_id) across threads so each shard owns its structures lock-free.
- Pre-aggregate in a small per-thread map for ~100ms, then flush — hot keys cost one sketch update per flush instead of one per event.
- Cache the top-K list and recompute only on bucket rotation, so
get_top_kis an O(K) read.
Common mistakes
- Jumping to a heap without addressing how decreasing counts (expiration) invalidate it.
- Forgetting that CMS overestimates, so reported counts are upper bounds — say so.
- Ignoring time semantics and late-arriving events, which can silently corrupt the window.
- Claiming bounded memory while still storing per-key state.
The answer I'd give: pin down volume and cardinality, explain why exact is infeasible, propose bucketed linear sketches plus a heavy-hitter summary with a pigeonhole completeness argument, amortize expiration to bucket boundaries, state ties deterministically, and shard/cache to hit the throughput target. That demonstrates both the data-structure reasoning and the systems judgment the question is probing.