Real-Time Top-K Noisy-Service Ranker Over a Rolling Window
System DesignModel answerLast updated
Design an end-to-end pipeline that ingests high-volume error events and serves a live ranking of the K noisiest services over the last five minutes.
Context
A large cloud platform runs tens of thousands of independently deployed microservices. Each service emits structured error events at very high volume. During an outage, on-call engineers need a live dashboard that answers one question: which K services are throwing the most errors right now?
You are asked to design the complete system — from log ingestion through aggregation to the query API — that powers this dashboard.
Input Schema
Each error event contains:
timestamp— event time (when the error occurred on the service)service_id— identifier for the emitting serviceerror_code— category of the errortrace_id— distributed trace identifier
API to Implement
GET /noisiest?k=10&at=<unix_seconds>
Returns the top-K services by error count over the 5-minute window ending at the requested time, along with each service's count, whether the result is final or provisional, and a staleness indicator.
Functional Requirements
- Ingest the structured events described above at peak throughput.
- Implement the
/noisiestendpoint with correct sliding-window semantics based on event time (not ingestion time). - Accept logs that arrive up to 60 seconds late. Events beyond that threshold must not be silently discarded — route them elsewhere and count them.
- Support replaying logs from durable storage to reconstruct window state after a failure.
Non-Functional Requirements
| Dimension | Target |
|---|---|
| Query latency | < 50 ms |
| Log-to-dashboard lag | < 10 s |
| Ingestion throughput | 1,000,000 events/s peak |
| Approximate log size | 500 bytes each (~500 MB/s) |
| Number of active services | 50,000 |
| Query volume | ~200 QPS |
| Window size | 5 minutes, refreshed every 10 s |
Exact error counts are preferred over probabilistic approximations. The pipeline must tolerate broker failovers and aggregation worker crashes without losing data or double-counting.
What Your Answer Should Cover
- Architecture overview — durable ingestion, stream aggregation, and serving tiers
- Windowing model — how you divide the 5-minute window into sub-buckets and maintain a running sum efficiently
- Late-arrival handling — watermarks, allowed lateness, provisional vs. final results
- Hot-key / skew mitigation — how you prevent a single noisy service from overwhelming one worker
- Top-K mechanics — how partial counts from distributed workers are merged into a correct global ranking
- Failure handling — broker outage, worker crash, state recovery, and replay
- Correctness verification — how you detect and alert on data discrepancies
Hints
Hint 1
Start with back-of-envelope math. 1M events/s × 500 B = 500 MB/s. How many Kafka partitions do you need? How much memory does a per-service count over 30 ten-second buckets actually require? Answering these questions will show you that the challenge is throughput and skew, not storage.
Hint 2
A pure sliding window that tracks every individual event is expensive to maintain. Think about approximating it with a series of fixed-width sub-buckets (tumbling micro-windows) and keeping a running sum — what granularity do those buckets need to be, and what accuracy trade-off does that introduce?
Hint 3
If you partition the raw event stream by service_id, a single noisy service gets all its traffic on one partition and one worker. What two-stage aggregation pattern avoids this? After the first stage fans traffic out by a random or trace-based key, what property of the second stage makes the final top-K merge exact rather than approximate?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Size the System Before Drawing Anything
Back-of-envelope math shapes every architectural decision.
Ingestion bandwidth: 1M events/s × 500 B = 500 MB/s. A Kafka partition saturates around 5 MB/s, so you need roughly 100–256 partitions (use 256 for headroom and clean sharding math). Set replication factor 3, min.insync.replicas=2, acks=all, and idempotent producers. A service-side agent buffers to local disk so a broker blip delays logs rather than dropping them.
Retention: 24 hours × 500 MB/s × 3 replicas ≈ 130 TB on Kafka. Archive to object storage (Parquet, hourly) as the replay source.
Window state: 5 minutes / 10-second buckets = 30 sub-buckets. 50,000 services × 30 buckets × 8 bytes per count = ~12 MB of state per aggregation shard. Exact counts are entirely affordable — the hard problem is throughput and hot keys, not memory.
Serving write volume: A new top-K snapshot every 10 s. A list of 1,000 services with counts is ~40 KB. A full day is ~350 MB — trivial for Redis or Cassandra.
2. API Design
GET /noisiest?k=10&at=1718000000
→ {
window_start: 1717999700,
window_end: 1718000000,
as_of: 1718000005,
is_final: false,
staleness_ms: 5200,
services: [
{ service_id: "checkout", error_count: 84210 },
...
]
}
at is rounded down to the nearest 10-second boundary. is_final flips to true once the watermark has advanced past window_end + 60s. staleness_ms lets the dashboard display a warning when aggregators fall behind.
3. Architecture Overview
Sidecars/agents
→ Kafka [raw-errors, 256 partitions, keyed by trace_id or round-robin]
├─→ Archiver → Object store (Parquet, hourly)
└─→ Stage 1: Pre-aggregators (Flink)
Partial (bucket, service_id) → count, flushed every 1–2 s
→ Kafka [partials, keyed by service_id]
Stage 2: Window aggregators (keyed by service_id)
Exact sliding sums, local top-Kmax heap
Stage 3: Global merger
Merges N local heaps → global top-Kmax
→ Serving store [Redis/Cassandra, keyed by (window_end, version)]
Stateless API tier → Serving store
4. Windowing Model
Use tumbling 10-second sub-buckets with a sliding sum rather than tracking individual events.
Each event is assigned to bucket floor(event_time / 10s). Stage 2 maintains, per service, a ring buffer of 30 bucket counts and a window_sum. When a new bucket arrives, add it to the sum and subtract the bucket that just fell out of the window. The update cost per slide is O(services with activity in that bucket), not O(all events in the window. A continuous per-event approach would require storing ~300M events per window and recomputing sums constantly — bucket granularity is the right abstraction here.
Watermarks and late arrivals:
- Compute a per-partition watermark as
max_event_time_seen − out-of-order_bound. Mark idle partitions explicitly so they do not stall the global watermark. - Allowed lateness: 60 seconds. A late event in bucket
binvalidates every window that containsb— roughly 7 already-published windows. Re-emit those snapshots with an incremented version number. - Events arriving more than 60 s late go to a
too-lateKafka topic, increment a monitoring counter, and are reconciled by an overnight batch job. Never silently drop them. - Use early-firing triggers every 2–5 s of processing time to publish provisional results within the 10-second SLA. Set
is_final = falseuntil the watermark clearswindow_end + 60s.
This creates a clean separation between "fast but provisional" and "slow but final", which is the central tension in any event-time streaming system.
5. Hot-Key Mitigation
The biggest mistake here is partitioning raw logs by service_id. A misbehaving service generating 800k events/s would funnel all its traffic to one Kafka partition and one Flink worker — exactly the failure mode we are trying to detect would also be the failure mode that breaks our detector.
Two-stage aggregation solves this:
Stage 1 partitions by trace_id or round-robin, distributing load uniformly regardless of which service is noisy. Each Stage 1 worker pre-aggregates (bucket, service_id) → count in memory and flushes once per bucket (or every 1–2 seconds for freshness). Output volume is bounded by the number of distinct services, not by event rate. A service generating 800k/s becomes ~200 partial records per flush — one per Stage 1 worker.
Stage 2 receives these tiny, bounded partial records keyed by service_id. Traffic to any one key is O(Stage 1 workers), which is fixed and small.
6. Top-K Computation and Merge Correctness
Stage 2 shards own disjoint sets of service_ids. Each shard's counts are therefore exact and complete for its slice of the keyspace. Each shard emits its local top-Kmax list per window_end using a min-heap.
The global merger takes N sorted lists and runs a standard N-way merge to produce the global top-Kmax. Because keys are disjoint, the global top-K must appear in some shard's local list — no candidate can be missed. This makes the merge exactly correct without any approximation, and without needing a second round-trip to re-query counts for candidates.
The result is written as an idempotent upsert keyed by (window_end, version). Full per-bucket counts are also written to an OLAP store (ClickHouse or Druid) to support arbitrary-k drill-down queries.
7. Failure Handling
Broker outage: Idempotent producers + disk-buffering sidecars mean logs are delayed, not lost. Kafka's RF=3 setup tolerates one broker loss with no interruption.
Worker crash: Flink checkpoints state (RocksDB ring buffers + Kafka offsets) to object storage every 10 seconds. On restart, the job restores from the latest checkpoint and replays from the committed offset. Exactly-once processing semantics combined with idempotent sink writes prevent double-counting.
Query availability: The serving store is replicated and completely decoupled from the stream jobs. If all aggregators die, the API continues serving the last written snapshot with an increasing staleness_ms value, letting dashboards degrade gracefully rather than returning errors.
Replay and rebuild: Re-run the same Flink job in batch mode over archived Parquet files (or directly from Kafka's beginning offsets). Write into a versioned namespace, validate counts, then atomically swap an alias — no downtime, no in-place mutations.
8. Correctness Verification
Monitoring metrics to run continuously:
- Kafka consumer lag and watermark lag per shard
- Late-drop event counter (alerts if non-zero)
- Checkpoint duration and failure count
- End-to-end freshness:
now − as_of - Count reconciliation: compare per-minute event totals derived from Kafka partition offsets against the sum of the corresponding sub-bucket counts in the serving store
An hourly Spark job recomputes sub-bucket counts from cold Parquet storage and compares them against what was served. Alert if any bucket diverges by more than 0.01%.
Common Mistakes to Avoid
- Partitioning by service_id early. This turns the hot-key problem into a hot-partition problem.
- Using arrival time instead of event time. Windows will be inaccurate whenever network or agent latency is nonuniform.
- Silently dropping late events. Always route them to a side channel and count the drops.
- Publishing only final results. The 10-second freshness SLA requires provisional early-trigger output; waiting for the watermark to clear would take up to 65 seconds.
- Skipping the verification layer. A pipeline with no count reconciliation gives you no way to detect silent data loss after a partial failure.