KatInterview

Real-Time Frequency Ranking System

System DesignModel answer
MediumModel answerSystem Designstreamingdistributed-systemsapproximation-algorithms

Last 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:

  1. record(item_id): Accept and process an incoming event indicating that item_id was observed.
  2. getMostFrequent(n): Return the n most 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: getMostFrequent queries 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: n will 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 getMostFrequent queries 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