Streaming Ranking of the Busiest Users Over a Rolling Hour
System DesignModel answerLast updated
Design a fault-tolerant stream pipeline that keeps an exact, event-time ranking of the 100 users with the most events in the last 60 minutes, tolerating late data and skew.
Context
A multi-tenant cloud product needs a live "most active accounts" view. Abuse-detection and capacity-planning services poll it to see which users generated the most activity during the last hour.
Design a streaming system that consumes raw user activity records and continuously publishes the 100 users with the highest event counts over the trailing 60 minutes, measured by when events happened, not when they arrived.
Inputs and Interface
- Each record carries
(user_id, event_type, timestamp, event_id). - Consumers call
GET /v1/top-users?window=60mand receive the current ranking.
Required Properties
- Freshness: the ranking is refreshed every 10 to 60 seconds.
- Correctness: events may arrive out of order, up to 5 minutes late, and must still be counted. Retransmitted duplicates must not inflate counts.
- Durability: losing a worker must not reset or corrupt the window counts.
- Elasticity and skew: the system must absorb sudden bursts and extremely uneven per-user traffic.
Scale
- 100,000 events/s typical, 300,000 events/s at peak
- About 10 million distinct users active within any one hour
- Roughly 500 bytes per event
Your answer should address
- Ingestion and the choice of stream engine
- How the trailing-hour state is kept without recomputing from raw events on every slide
- How hot users are handled and how partial results combine into one global top 100
- Event-time handling, watermarks, deduplication and end-to-end exactly-once behavior
- State storage, checkpointing, state size estimates and recovery
Hints
Hint 1
Do the arithmetic first: bandwidth, events per hour, and per-user state size. You will find the live state is only a few GB, so exact answers are affordable.
Hint 2
A native 60-minute window sliding every 10 seconds assigns each event to 360 windows. Think about small fixed-size time buckets per user that you add to and expire incrementally.
Hint 3
Partition the first stage by something other than user_id so one noisy user cannot overload a single partition, pre-combine counts, and only then group by user_id so each user's total lives in exactly one place before ranking.
Hint 4
Separate lateness tolerance from dedup retention: the dedup state only needs to live as long as late arrivals and retransmissions can occur, not as long as the window.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
Assumptions to confirm: ranking by event count per user, in event time, over the trailing 60 minutes; results should be exact; refresh every 10 s (60 s as fallback); events up to 5 minutes late are counted, later ones go to a side output for offline reconciliation.
| Quantity | Estimate |
|---|---|
| Ingest bandwidth | 100k x 500 B = 50 MB/s (150 MB/s peak) |
| Events/hour | ~360M |
| Kafka storage, 24 h, RF=3 | ~4.3 TB/day, ~13 TB replicated |
| Per-user window state | key + 60 minute counters + total, about 300 B, so ~3 GB raw for 10M users, ~5-8 GB in RocksDB |
| Dedup state (10 min of IDs) | 60M IDs x ~40 B, about 2.4 GB (less with hashed IDs) |
Key insight: the state is small. The real difficulties are hot keys, event-time correctness and making top-K exact and cheap.
2. Architecture
Producers -> Kafka "events" (128+ partitions, keyed by event_id, RF=3, acks=all, idempotent producer)
-> Flink job (exactly-once checkpoints, RocksDB, incremental snapshots to object storage)
Stage 1: keyBy(event_id) dedup + combine per (user, minute)
Stage 2: keyBy(user_id) 60-slot ring buffer per user + local top-100
Stage 3: parallelism 1 merge P x 100 candidates -> global top-100
-> Kafka "top-users" (transactional sink) -> Redis/KV versioned snapshot -> API
Raw Kafka -> archiver -> Parquet in object storage (reconciliation, backfill)
Kafka is keyed by event_id so a single abusive user cannot saturate one partition. Flink gives keyed state, event-time watermarks, timers and exactly-once checkpoints.
3. Window state without re-aggregation
Avoid a built-in 60 min / 10 s sliding window: each event lands in 360 windows, multiplying state and CPU by 360.
Instead, use 1-minute tumbling sub-buckets in a per-user ring buffer (Stage 2 keyed state):
buckets[60]indexed byminute % 60,bucket_minute[60]to detect stale slots, and a runningtotal.- On a partial count
(user, minute m, c):buckets[m] += c; total += c. - On expiry, when the window start passes minute
m:total -= buckets[m]and clear the slot. - Avoid a timer per user: keep a per-subtask index
minute -> users with non-zero count, so each slide only touches affected users.
Local top-K: on each event-time slide timer (10 s), each subtask runs a size-100 min-heap over its ~78k users (10M/128), O(n log K), a few milliseconds. Optionally keep a ~300-entry candidate set and rescan only when a member falls below the threshold.
Trade-off: 1-minute buckets make the trailing edge move in minute steps. If exact 10 s edges are required, use 10 s buckets (360 slots, ~6x state, ~20 GB, still fine).
4. Hot keys and the aggregation hierarchy
- Stage 1 (by
event_id) spreads load evenly, dedups, and pre-aggregates(user_id, minute)counts, flushing every 1-2 s and on checkpoint barriers. A user sending 90k events/s collapses to roughly one record per subtask per flush (~128 per 2 s). - Stage 2 (by
user_id) puts each user's complete count on exactly one subtask. This makes two-phase top-K exact: any global top-100 user must be in the top 100 of its own partition, so the union of local top-100s contains the true answer. - Stage 3 merges 128 x 100 candidates and writes a versioned snapshot. This is trivial in volume.
Common mistake: salting user keys and ranking the salted partials. Partial counts must be merged by user_id before any ranking, otherwise rankings are wrong.
5. Event time, dedup, exactly-once
- Watermarks: bounded out-of-orderness of ~30 s keeps output fresh. Allowed lateness is 5 minutes: a late event updates its past bucket and the user's total, and the next slide emits a corrected ranking. Output is provisional until the watermark passes plus 5 min. Use source idleness detection so a quiet partition does not stall the watermark.
- Events later than 5 minutes go to a side output. Since lateness (5 min) is far less than the window (60 min), late events never hit an evicted bucket.
- Dedup: keyed state on
event_idwith ~10 min TTL (lateness plus retransmission window), ~2.4 GB, less if storing a 64/128-bit hash. - End to end: idempotent producers, aligned checkpoints with Kafka offsets in the checkpoint, a two-phase-commit transactional sink to the output topic, and a Redis writer that upserts by
versionso replays are harmless.
6. State backend and recovery
- RocksDB with incremental checkpoints every 30-60 s to object storage; ~10-15 GB total across 32-64 task managers on local SSD; local recovery enabled.
- On failure, restore the last checkpoint and replay from stored offsets. Counts are never reset; target recovery under 1 minute.
- Retain Kafka for at least 24 h to allow rebuilds. Use savepoints for upgrades and rescaling, with a fixed max parallelism (e.g. 1024 key groups) so the job can scale out for bursts.
- Run Kafka with RF=3 and spread task managers across zones; the job manager runs in HA mode.
7. API
GET /v1/top-users?window=60m
-> 200 { "window_start", "window_end", "watermark", "as_of", "version",
"users": [{"rank":1,"user_id":"u_9","count":48211}, ...] }
Only 60m is supported initially; anything else returns 400. The response includes window bounds and the watermark so callers know how fresh and final it is. The API reads versioned snapshots from a replicated KV store and never queries the stream processor directly.
8. Other points
- Monitor consumer lag, watermark lag, checkpoint duration, late-event rate and state size; alert on each.
- Periodically reconcile against the archived raw data to validate counts and fix side-output events.
- If exactness were relaxed, Count-Min Sketch plus a heap would cut memory, but at 3-8 GB it is unnecessary here.