KatInterview

Designing a Bounded-Memory Sliding-Window Top-K Stream Ranker

System DesignModel answer
MediumModel answerSystem Designstreamingapproximate-algorithmscount-min-sketch

Last 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

  1. Sustain millions of updates per second with low query latency.
  2. Rankings must reflect only events inside a sliding window of length T.
  3. Memory usage must be bounded and independent of how many distinct IDs appear.
  4. State clearly how ties between equal-frequency IDs are resolved.
  5. 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() and get_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.