Designing a Production Stall Detector for Streaming Jobs
System DesignModel answerLast updated
Design a distributed service that watches start, heartbeat and end messages per job and emits exactly one stall signal when a deadline passes, covering time semantics, sharding, recovery and testing.
A prototype service tracks long-running units of work (for example batch jobs, uploads, or sensor streams). Each unit is identified by an event_id and sends three kinds of messages: start, ping (a liveness update), and end. If no qualifying message arrives within the configured timeout after the last one, the service must report that unit as timed out, once.
The prototype is a single process holding a dictionary and a heap. Your task is to turn it into a production-ready, distributed service. In your answer, cover:
- Requirements and scale. State your assumptions: message rate, number of concurrently active events, range of timeout values, accuracy of firing, and delivery guarantees.
- API and data model. Define the ingest interface, message schema, per-event state record, and idempotency keys for both input and output.
- Time semantics. Compare event time with processing time, explain how you would compute deadlines, and describe how you deal with clock skew between producers and the detector.
- Architecture. Explain how you shard by
event_id, where state lives, what consistency reads offer, and how a failed worker is recovered. - Performance. Choose a timer structure (timer wheel versus heap, and where LRU does or does not fit), and discuss batching, backpressure, memory limits, and very long timeouts.
- Edge cases. Late, dropped, duplicated, and reordered messages; very large timeouts; long silences; restarts.
- Operations. How you would test, monitor, alert, and roll the service out.
Be explicit about trade-offs and about the alternatives you rejected.
Hints
Hint 1
Start by writing down numbers (messages per second, active keys, timeout range, allowed firing delay). They drive every later choice, such as in-memory versus external state.
Hint 2
Think about what goes wrong with a pure event-time clock during a long silence, and with a pure processing-time clock after a consumer backlog. A hybrid with a lag guard is the usual answer.
Hint 3
Pings reset timers constantly. Ask which timer structure makes a reset cheap, and whether you can store a deadline in the timer and validate it against durable state when it fires.
Hint 4
For correctness under failure, combine single-writer ownership per partition, epoch fencing, and a deterministic output key such as (event_id, deadline) so duplicate firings are harmless.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Requirements and assumptions
I would confirm requirements first, then commit to numbers:
- Load: about 200k messages/s at peak, about 50M concurrently active events.
- Timeouts: from 1 s up to 7 days, so the long tail needs its own treatment.
- Accuracy: never fire before the deadline; fire within about 1 s of it at p99.
- Delivery: at-least-once input, effectively-once output (deduplicated by a deterministic key).
- State size: about 200 B per event, so roughly 10 GB hot state. This fits across a sharded cluster with durable backing.
API and data model
Ingest goes through a partitioned log (Kafka or similar), not synchronous RPC, which gives buffering and replay. A thin control API handles queries.
- Message:
{event_id, tenant_id, type: START|PING|END|CANCEL, seq, event_time, timeout_ms?, attrs}. - State:
{status: ACTIVE|DONE|TIMED_OUT, deadline, timeout_ms, last_seq, last_event_time, version}. - Read:
GET /events/{id}returns status, deadline and last sequence. - Output topic
timeouts:{event_id, deadline, fired_at, last_seq, epoch}.
Idempotency. Input is deduplicated by (event_id, seq): if seq <= last_seq, the message is a no-op. Output uses (event_id, deadline) as a deterministic key, so a re-fire after a crash is dropped downstream. Terminal states are sticky, and a tombstone is kept for longer than the maximum lateness so a delayed ping cannot revive a finished event.
Time semantics and skew
- A pure event-time design never fires during silence, because the watermark does not advance when nothing arrives. That is exactly the case we must detect.
- A pure processing-time design produces false timeouts after ingest lag, because everything looks old at once.
Hybrid: deadline = max(event_time, ingest_time - skew_bound) + timeout, fired against the detector's own clock, but only while the partition's consumer lag is below a threshold. When lag is high, pause firing for that partition and let it catch up.
Skew handling: producer clocks are untrusted, so clamp event_time into [ingest_time - max_lateness, ingest_time + max_future_skew] and count every clamp as a metric. Use the broker append timestamp as the consistent ingest clock, run NTP with skew alarms, and use monotonic clocks for local scheduling and wall-clock only for persisted deadlines.
Ordering is decided by seq, not timestamps. A lower seq is dropped. A gap is tolerated, since a higher-seq ping still proves liveness.
Architecture
Producers -> log partitioned by hash(event_id) -> detector workers (one owner per partition)
worker: timer wheel + embedded KV store + changelog + snapshots
-> timeouts topic -> consumers / alerting
long-timeout tier: deadline-bucketed durable table
Sharding. hash(event_id) mod P with P of 256 to 1024, much larger than the worker count. Rebalancing moves whole partitions. Single ownership per key means no distributed locks. A hot event is not a problem since one event is one key; a hot tenant can be salted.
State store. Embedded RocksDB per partition, backed by a compacted changelog and periodic snapshots to object storage. Alternative: a remote store (DynamoDB or Cassandra) with conditional writes on version. It is easier to operate but adds a network hop per message, which is costly at 200k/s. Redis is fast but has weaker durability. I pick embedded state plus changelog for throughput.
Reads. The owner is linearizable for its keys. Strong reads route to the owner; otherwise serve from a materialized replica with a documented staleness of a few seconds.
Recovery.
- A new owner loads the latest snapshot.
- It replays the changelog from the snapshot offset.
- It rebuilds timers from persisted deadlines.
- Only then does it resume consuming.
Deadlines that passed during downtime fire immediately, flagged fired_late. Fence zombie owners with an epoch on every write. Where possible, commit input offsets, state update and output atomically with transactions; otherwise rely on deterministic output keys.
Performance
Timers. A heap is O(log n) and, because pings reschedule constantly, needs decrease-key or lazy deletion that leaves stale entries. A hierarchical timing wheel gives O(1) insert and cancel for millions of timers (1 s ticks, cascading wheels for minutes, hours, days). Combine it with lazy validation: the wheel stores (event_id, deadline), and on fire we compare against the stored deadline and skip if it changed. LRU is a cache eviction policy, not a timer; use it only to bound the in-memory state cache in front of RocksDB.
Long timeouts. Do not hold 7-day timers in RAM. Persist them in a deadline-bucketed (per minute) table and have a loader promote the next buckets into the wheel shortly before they are due.
Batching. Poll 500 to 5,000 records, coalesce pings per key within a batch (keep max seq), group-commit writes, and emit timeouts in batches.
Backpressure and memory. Stop polling when the output buffer or store write stalls pass thresholds. Cap in-memory events per worker, spill the rest to RocksDB, and alert on usage.
Edge cases
- Duplicates: ignored via
seq. - Reordered: lower
seqdropped; anENDalways wins over a ping. - Late after timeout: record a
late_arrivalmetric; policy decides whether to revive or ignore (default: keepTIMED_OUTand emit a correction event). - Dropped: indistinguishable from silence, which is the point of the detector; heartbeat intervals should be well below the timeout (for example a third).
- Restart / long silence: covered by durable deadlines and rebuild.
- Huge or changing timeouts: validate against a maximum; a new
timeout_msapplies from the next message.
Testing, monitoring and rollout
- Tests: property-based tests of the state machine under random duplication and reordering; a simulated clock for deterministic timer tests; chaos tests that kill workers mid-batch and verify exactly one distinct timeout per event; load tests at 2x peak.
- Metrics: firing delay (deadline to emission), consumer lag, active-event count, clamp rate, late-arrival rate, replay time on recovery, timer wheel size.
- Alerts: p99 firing delay over 1 s, lag above threshold, any early firing (should be zero), skew alarms.
- Rollout: shadow mode comparing outputs with the old detector, then canary by tenant, then full cutover with a kill switch that pauses emission but keeps state updating.
Common mistakes
- Using only event time and never firing in silence.
- Firing during consumer lag and flooding downstream with false alarms.
- Putting multi-day timers in memory.
- Trusting producer timestamps or wall-clock for ordering.
- Using a heap with no plan for rescheduling.
- Forgetting fencing, so two owners both emit.