KatInterview

Real-Time Heavy Hitters Pipeline for a High-Volume Event Stream

System DesignModel answer
MediumModel answerSystem Designstreamingtop-kcount-min-sketch

Last updated

Design a distributed streaming service that reports the K most frequent keys over sliding and tumbling windows, with fast queries, hot-key tolerance and replay-safe results.

Problem

A multi-tenant SaaS platform emits a constant flow of activity events: API calls, record changes and user actions. Design a service that keeps an up-to-date ranking of the K most frequent keys (for example API endpoints, tenant IDs or object types) over an endless stream.

Dashboards need live rankings. Analysts also need to look at rankings as they were at an earlier moment. The service must survive worker crashes and duplicate message delivery without distorting counts.

Functional requirements

  • Continuous ranking: consume an unbounded stream and maintain the top K keys (K usually 10 to 1,000, e.g. 100).
  • Window types: support sliding windows (such as the last hour, refreshed every 10 seconds) and tumbling windows (such as each calendar hour).
  • Query and snapshots: return the current ranking with counts. Ties must break deterministically (for example by key in lexical order). Clients can also request the ranking at a past point in time.
  • Replay: reprocessing from an earlier offset (after a failure or a backfill) must not double count or corrupt results.

Non-functional requirements

  • High write throughput with low ingestion latency.
  • Top-K queries answered in under 50 ms.
  • Tolerate severe skew: a handful of keys may account for around 80% of traffic, and this must not starve partitions or exhaust memory.
  • State the accuracy trade-off between exact counting and approximate heavy-hitter methods, including error bounds.

Scale

  • 1,000,000 events per second
  • Up to 100,000,000 distinct keys active per day
  • About 200 bytes per event

What to cover

  1. API for querying rankings and configuring windows.
  2. State and algorithm choices: exact counting versus approximate structures, and how the error parameter is set.
  3. Architecture: ingestion, local aggregation, global merge, partitioning.
  4. How old data leaves a sliding window efficiently.
  5. Checkpointing, snapshot storage and replay handling.

Hints

Hint 1

Do the arithmetic first: bytes per second, events per hour, and the memory needed to hold one counter per distinct key. This tells you whether exact counting is realistic for a sliding window.

Hint 2

Avoid partitioning the real-time path by the key itself. Spread events evenly, aggregate locally into small summaries, then merge the summaries. Think about which sketch properties make merging and expiring old data cheap.

Hint 3

Split the window into fixed time panes. Ask which structure can have an old pane subtracted, which one guarantees that no frequent key is lost, and how to make both state updates and published outputs safe to replay.