Real-Time Heavy Hitters Pipeline for a High-Volume Event Stream
System DesignModel answerLast 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
- API for querying rankings and configuring windows.
- State and algorithm choices: exact counting versus approximate structures, and how the error parameter is set.
- Architecture: ingestion, local aggregation, global merge, partitioning.
- How old data leaves a sliding window efficiently.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Sizing and framing
- Ingress: 1M events/s x 200 B = about 200 MB/s, roughly 17 TB/day. One hour holds about N = 3.6B events.
- Exact state: 100M keys x ~100 B (key, counter, map overhead) is about 10 GB per window. A one-hour window sliding every 10 s has 360 panes, and exact per-pane maps would reach terabytes. Exact counting is practical only for coarse tumbling windows on a sharded store or in batch.
- Ask whether bounded error is acceptable. Usually yes for live dashboards and no for billing or official reports. That motivates a hybrid: an approximate real-time path with provable bounds plus an exact batch path.
2. API
POST /v1/trackers
{ "dimension": "api_endpoint",
"window": {"type": "sliding", "size": "1h", "slide": "10s"},
"k_max": 1000, "epsilon": 1e-5, "mode": "approx" }
GET /v1/trackers/{id}/topk?k=100&at=<timestamp>
-> { "window_start", "window_end", "watermark", "approximate": true,
"items": [ {"id", "count", "max_error"}, ... ] }
- Order by
count DESC, id ASCfor deterministic ties. - Omitting
atreturns the latest snapshot. Supplying it reads a stored historical one. - Returning
max_errorlets clients treatcount - max_erroras a guaranteed lower bound.
3. Algorithms and error configuration
| Approach | Memory | Guarantee | Notes |
|---|---|---|---|
| Hash map + size-K min-heap | O(distinct), ~10 GB | Exact | Needs key-partitioned shuffle, so hot keys hurt |
| Count-Min Sketch + heap | (e/eps)*ln(1/delta) counters | Overestimate at most eps*N with prob. 1-delta | Linear: mergeable and subtractable |
| Space-Saving (m counters) | O(m) | Error at most N/m, any item with frequency above N/m is kept | Mergeable, not subtractable |
| Lossy Counting | O((1/eps) log(eps*N)) | Error at most eps*N | Usually beaten by Space-Saving |
With eps = 1e-5 and N = 3.6B per hour, the error bound is 36K counts, negligible against a genuine top-100 key.
- CMS: width = ceil(e/eps), about 272K, depth 5 (delta under 1%). That is about 1.4M counters, around 11 MB.
- Space-Saving: m = 1/eps = 100K counters, a few MB.
Chosen combination: Space-Saving yields the candidate set (guaranteed recall of heavy hitters); CMS yields counts that can be windowed by subtraction. Rank candidates by CMS estimate, optionally capping each by the Space-Saving upper bound.
4. Architecture
Producers -> Kafka (~200 partitions, NOT keyed by entity)
-> Stage 1 local aggregators (~100 tasks)
per 10 s pane: Space-Saving + CMS in memory
-> pane summaries (partition, pane_id, SS, CMS) every 10 s
-> Stage 2 global merger per tracker -> window state -> top-K
-> publisher -> Redis (latest) + Cassandra/S3 (by tracker, window_end)
-> Query service (reads precomputed snapshot)
Kafka -> S3 -> hourly exact batch job (salted keys) for tumbling reports
Hot keys: because events are not partitioned by key, a tenant producing 80% of traffic only raises one counter on each worker. Local pre-aggregation works as a combiner, so only small sketches cross the network. Each worker sees about 10K events/s, which is trivial. In the exact batch path, use two-stage salting: aggregate on (key, salt), then on key.
Query latency: queries do no computation. The ranking is materialized each slide, so a request is a single Redis read (or one row for history), well under 50 ms.
5. Window expiry
Per-event timestamps are too costly, so the window is a ring of panes (360 for 1 h / 10 s). At each slide the merger:
- Updates
CMS_window += CMS_new - CMS_expired. Linearity makes expiry exact, costing O(wd) per slide rather than O(360w*d). - Maintains a ref-counted map of
id -> number of panes whose Space-Saving summary lists it; adds the new pane's ids, decrements the expired pane's, and removes ids at zero. - Estimates every candidate with
CMS_window, ranks, and publishes the top K.
Why no heavy hitter is missed: a key whose window frequency exceeds epsN must exceed epsN_i in at least one pane, so that pane's summary captured it.
Memory is tens of MB per tracker. A tumbling window is the case slide = size: emit the pane and reset.
Late data: use event-time panes with watermarks. Events within allowed lateness update their pane and trigger a recompute. Anything later goes to a side output and is reconciled by the exact batch job.
6. Fault tolerance and idempotency
- Use aligned checkpoints (barrier-based, Flink style) every ~30 s. Persist sketch state and Kafka offsets atomically to durable storage. After a crash, restore and rewind to those offsets, giving exactly-once state over at-least-once delivery.
- Make outputs idempotent: snapshots are upserted by
(tracker_id, window_end); pane summaries are keyed by(source_partition, pane_id)so a replayed pane replaces the old one instead of being added again. - Avoid per-event dedup by ID at 1M/s; offset-based exactly-once is far cheaper.
7. Trade-offs and pitfalls
- Approximate path: fresh, tiny, bounded error. Exact path: correct but delayed and expensive. Offer both and label responses with
approximate. - Larger K or smaller eps grows memory linearly, which is cheap here.
- Common mistakes:
- Merging each worker's local top-K lists. This misses keys that are moderately frequent everywhere but never in any single local top-K. Merge summaries, not truncated lists.
- Partitioning by entity key and letting one hot partition fall over.
- Using Space-Saving alone for sliding windows, since it cannot subtract expired data.
- Computing rankings at query time.
- Checkpointing state and offsets separately, which causes double counting or loss on replay.
- Not exposing error bounds to consumers.