Skip to main content

Worked design: late and out-of-order events

Real-time metrics with late and out-of-order events

System designhardsenior · lead45 min
#stream-processing#watermarks#late-arriving-data

A delivery company computes "orders delivered per city per 5 minutes" for an operations wall and for courier bonuses. Courier phones buffer events when offline: 95% of events arrive within 30 seconds, 99.9% within 2 hours, and a few arrive the next day. Events from one courier can arrive out of order.

Design the streaming computation. The ops wall wants speed; bonuses must be exact.

Hint 1

One pipeline can't be both instantly final and exactly right. What gives?

Hint 2

What does a watermark promise, and what happens to events behind it?

Show solution

Use event-time windows (5-minute tumbling, keyed by city) in Flink / Spark Structured Streaming, with a watermark of max event time minus 2 minutes. Each window emits an early result for the ops wall when the watermark passes, then updates (allowed lateness up to 2 hours) as late events arrive. The sink is an upsert keyed by (city, window_start), so corrections overwrite rather than duplicate.

Events later than allowed lateness go to a side output (late table), not to /dev/null. Bonuses don't come from the stream at all. A daily batch job recomputes the previous days exactly from the raw event log (including the late table), which is the source of truth. Ops reads the stream; payroll reads the batch.

State size grows with keys × windows × allowed lateness. That's the cost dial. Dedup on event_id inside the window, because offline phones resend.

What a strong answer covers

  • Uses event time (not processing time) windows and explains why (weight 3)
  • Explains watermarks and allowed lateness, and the speed/completeness trade-off (weight 3)
  • Upsert/retraction sink so updated windows correct earlier results (weight 2)
  • Side output for too-late events plus a batch recompute as the source of truth for money (weight 3)
  • Dedup of resent events, and state size as a cost driver (weight 1)

Follow-ups

  • The ops wall flickers because numbers change after they're shown. How do you present provisional data?

    Show the numbers as provisional, for example a lighter style or a '~' until the window's watermark passes, then mark them final. Or update less often (every 30 seconds) and show the time the data is complete up to. Set expectations so people know recent numbers can change.

  • A city has almost no traffic at night, so its watermark stalls. What happens, and how do you fix it?

    With a per-partition or per-key watermark, a quiet city's watermark doesn't advance, so its windows never close. Use an idle-source timeout so idle partitions don't hold back the watermark, or emit heartbeat events, or advance on processing time when no events arrive.

Further reading

1. Requirements​

  • Metric: deliveries per city per 5-minute window.
  • Consumers: an ops wall (fast, approximate is OK) and courier bonuses (exact, can wait until tomorrow).
  • Lateness profile: 95% within 30s, 99.9% within 2h, a long tail up to the next day. Events can arrive out of order.

The requirements already show the answer: one pipeline can't be both instant and final. Design two paths that share the raw log.

2. Data contracts​

Each event carries a unique event_id, the event_ts from the device, the courier and the city. The device clock can be wrong, so the collector also stamps received_at and rejects or flags events with event_ts far in the future.

3. Ingestion​

Events go into Kafka keyed by courier (per-courier order is preserved within a partition, but not across partitions). The same topic is also written to the raw lake table, which is the batch path's source.

4. Storage and format​

  • Stream state: in Flink or Spark Structured Streaming, the open windows per city.
  • Serving table: deliveries_5min(city, window_start, count, is_final, updated_at), upserted.
  • Raw log and late table: append-only lake tables.

5. Transform: the streaming path​

  • Event-time windows, 5-minute tumbling, keyed by city. Processing time is wrong here: a burst of buffered events would all land in "now".
  • Watermark = max seen event_ts minus 2 minutes. It says "I don't expect events older than this". When the watermark passes a window's end, emit a first result.
  • Allowed lateness: 2 hours. Late events within that update the window, and the sink upserts on (city, window_start), so the correction overwrites instead of adding a row.
  • Too late (beyond 2h): send to a side output into a late-events table. Never drop silently.
  • Dedup by event_id within the window state, because offline phones resend.

6. Serving​

The ops wall reads deliveries_5min and shows provisional windows differently (for example lighter color until is_final), so people don't act on a number that will change.

7. The batch path is the source of truth​

A daily batch job recomputes the previous days from the raw log plus the late table, exactly, with dedup. Bonuses read only the batch output. The batch also reports how far the stream's numbers were off, which tells you whether the watermark and lateness settings are right.

8. Quality​

  • Share of events that are late, and too late, per hour.
  • Stream versus batch difference per day, alerted if above a threshold.
  • Watermark lag per partition (an idle partition can hold the watermark back).

9. Failure modes​

FailureEffectMitigation
Quiet city at nightWatermark doesn't advance, windows never closeIdle-source timeout so idle partitions don't hold the watermark
Device clock in the futureWatermark jumps ahead and everything else looks lateClamp or reject future timestamps at the collector
Job restartDuplicate emissionsCheckpointed state plus upsert sink makes outputs idempotent
Allowed lateness too longState grows, memory pressureSize it from the measured lateness distribution

10. Cost​

State size is about keys × open windows × allowed lateness. Doubling allowed lateness roughly doubles state. That's the main dial, along with checkpoint frequency.

11. What changes at 10×​

More cities and finer windows mean more state. Use a state backend on disk (RocksDB), scale out by key, and pre-aggregate per courier before the city window. The two-path design stays.