SysDesignAtlas

Stream Processing

Event time versus processing time, watermarks, windowing, and what "exactly-once" actually means — the machinery for computing over data that never stops arriving.

HLDHard13 min readdatastreamingflinkexactly-once
Confidence

#The shift from batch to stream

A batch job has a luxury it never acknowledges: the data is complete. When you run yesterday's report, yesterday is over. Every record that will ever belong to that window has arrived. You can sort, join, aggregate, and know the answer is final.

Streaming removes that. Data arrives continuously, out of order, sometimes hours late, and you have to produce answers before you know whether more input is coming.

Every hard problem in stream processing follows from that one difference.

#The two clocks

Event time • When the thing actually happened • Embedded in the record by the producer • Results are deterministic and reproducible • But you must wait for stragglers Processing time • When your operator saw the record • Trivial to implement, always available • Low latency, no waiting • Replay gives different answers every time
Which clock you group by determines whether your results are correct or merely prompt.
   A mobile app buffers events offline. The user goes into a tunnel
   at 09:58 and reconnects at 10:47.

     Event time of the click:       09:58
     Processing time at your job:   10:47

   "Clicks in the 09:55-10:00 window" is a question about event time.
   Answering it in processing time puts the click in the 10:45 bucket
   and the answer is simply wrong.

Almost every business question is an event-time question. Revenue per hour, sessions per user, fraud within a 5-minute window — all of these mean when it happened, not when we found out. Processing time is only acceptable for questions genuinely about your own system, like throughput monitoring.

The cost of event time is that you must decide how long to wait for late data. That decision is a watermark.

#Watermarks

A watermark is an assertion the system makes to itself:

"I believe I have now seen all events with timestamp ≤ T."

It is a guess, not a fact — nothing can prove no more events are coming. But a stream never ends, so without some rule for declaring "enough", you could never publish a result at all. The watermark is that rule: the point at which a time window is considered complete enough to report on.

   Records arriving (event times, out of order):

     10:03  10:01  10:04  10:02  10:07  10:05  [10:02 ← LATE]  10:09

   Watermark strategy: "max event time seen minus 5 minutes"

     after 10:07 → watermark = 10:02
     after 10:09 → watermark = 10:04

   When watermark passes 10:05, the 10:00-10:05 window fires.
   The late 10:02 record arrives AFTER that. Now what?

That last question has exactly three answers, and choosing among them is a product decision, not a technical one:

StrategyBehaviourRight for
DropDiscard records past the watermarkMonitoring, approximate dashboards
Side outputRoute late records to a separate stream for inspection or manual handlingAnything where you need to know how much you're losing
Allowed lateness + retractKeep window state open longer; re-emit a corrected result that supersedes the earlier oneBilling, analytics that must eventually be exact

"Retract" means withdrawing a result you already published. If the 10:00–10:05 window first reported 41 clicks and the late record arrives, you send "ignore 41, the answer is 42" — so anything downstream must be able to overwrite a number it has already received.

#Windows

Unbounded streams have to be cut into finite chunks before you can aggregate. Four shapes cover nearly everything:

   TUMBLING (fixed, non-overlapping)
     [00-05][05-10][10-15]        "revenue per 5 minutes"
     each event in exactly one window

   SLIDING / HOPPING (fixed size, overlapping)
     [00────05]
        [01────06]
           [02────07]             "5-minute average, updated each minute"
     each event in size/slide windows → 5× the state

   SESSION (dynamic, gap-based)
     [ev ev ev]......[ev ev]      "user session = activity with
     gap > 30 min closes it        no 30-minute gap"
     windows have data-dependent boundaries

   GLOBAL (one window, custom trigger)
     [everything]                 "every 1,000 events" or a custom rule

Sliding windows are a state multiplier people miss. A 1-hour window sliding every minute means each event belongs to 60 windows, so you hold 60× the state. At scale this is the difference between a job that fits in memory and one that doesn't. If you need per-minute updates over an hour, it's usually far cheaper to keep one-minute tumbling totals and add up the latest 60 of them each minute. Each event then touches one small counter instead of 60 windows.

Session windows are the expensive ones because boundaries are data-dependent — you cannot know a session has ended until the gap elapses. Worse, a late event can merge two previously separate sessions. Say a user was active 09:00–09:20 and 09:45–10:00, so you reported two sessions; then a late event stamped 09:35 arrives and closes the gap. Now you must retract both results and emit one combined session.

#State, and why it dominates operations

A stateless step — one that transforms each event on its own, like converting a currency field or dropping bot traffic — is easy. Everything interesting in streaming is stateful, meaning it must remember something between events: aggregations, joins, deduplication, session tracking. That state can be enormous — a job tracking 100 million users' sessions holds 100 million entries — and it must survive failure.

Local state store RocksDB on local disk, read and written per event Changelog every mutation appended to a durable log Checkpoint / snapshot periodic consistent cut to object storage Recovery restore snapshot, replay log from that offset
State management is most of what a stream processor does for you.

The critical property is that the state snapshot and the input offset must be consistent with each other. The input offset is your position in the input stream — "I've processed up to message 5,000,000 in partition 3". After a crash you restore the saved state and resume reading from the saved offset, so the two must describe the same moment. Restoring state from 10:00 while resuming input from 10:05 silently loses five minutes of updates; resuming from 09:55 double-counts five minutes. The snapshot must record exactly which offsets it includes.

Flink does this with the Chandy–Lamport distributed snapshot algorithm. It injects a special marker record, a barrier, into the input streams. Each operator saves its state at the moment the barrier reaches it, then passes the barrier on. Because every operator saves "everything before the barrier, nothing after it", the saved pieces together form a consistent cut — a snapshot of the whole distributed job at one logical point in the stream — without stopping it. This is the same idea as a consistent snapshot in a database, applied to a dataflow graph.

#"Exactly-once" — what it actually means

The most misunderstood phrase in streaming. Let's be precise, because the imprecision causes real bugs.

**You cannot have exactly-once delivery.** It's impossible in an asynchronous network with failures — the sender can never know whether a lost acknowledgement means the message arrived or didn't, so it must either risk losing it or risk duplicating it. This is a theorem, not a limitation of current tools.

**You can have exactly-once effects:** a record may physically arrive and be processed several times, but the job's stored results look exactly as though it happened once. The delivery is messy; the outcome isn't. That distinction — between how many times something ran and how many times it counted — is the whole of what the machinery below buys you.

   What the machinery gives you:

     input offsets + operator state + output commit
       all move together, atomically, at each checkpoint

     On failure: roll back to the last checkpoint,
     replay from those offsets, recompute.
     Internal state ends up identical.

   What it does NOT give you:

     Any guarantee about side effects your code performs
     directly — an HTTP POST, an email, a payment.
     Those happen on every replay.

#Stream joins

Joining two unbounded streams raises a question a batch join never has to answer: how long do you keep a record around waiting for its partner?

Join typeMechanismCost
Stream–stream (windowed)Buffer both sides for a bounded interval; emit matches within itState proportional to window × rate on both sides
Stream–tableEnrich each event from a materialised lookup tableTable must be copied to every parallel task; watch for skew (a few very hot keys overloading one task)
Temporal / versioned joinJoin against the version of the table as of the event's timestampRequires versioned state; the correct choice for prices, rates, and config

The temporal join is the one that's usually needed and rarely used. If you join an order stream against a currency_rates table, joining against the current rate is wrong — you want the rate that was in effect when the order was placed. Replaying the job a month later with a plain lookup gives different (and incorrect) results; a temporal join gives the same answer forever. Reproducibility on replay is the test for whether your join is correct.

#Choosing an engine

SystemModelWhere it fits
Kafka StreamsLibrary, no cluster; state in RocksDB + changelog topicsKafka-native services; deploy as a normal app
FlinkTrue streaming, event time, sophisticated state and snapshotsThe most complete engine; complex jobs, large state
Spark Structured StreamingMicro-batch (continuous mode exists but is limited)Teams already on Spark; batch/stream code sharing
Materialize / RisingWaveIncremental view maintenance over SQL"Keep this SQL query's result always up to date"
A consumer loop you wroteWhatever you buildGenuinely fine for stateless or small-state transforms — don't reach for a cluster to filter a topic

#Exercise

#Check yourself

Event time versus processing time — which do business questions need?Show answer
Event time — when it happened. Processing time (when your job saw it) is easy but gives different answers on replay and misplaces late events; it's only fine for questions about your own system.
What is a watermark?Show answer
The system's assertion "I've probably seen every event up to time T" — a heuristic, not a fact — which decides when a window is complete enough to emit.
Name the three ways to handle data that arrives after the watermark.Show answer
Drop it (dashboards), send it to a side output to measure and inspect, or allow lateness and emit a corrected result that supersedes the earlier one (billing).
What trade-off does the watermark delay control?Show answer
Latency against completeness: a short delay is fast but misses late data, a long delay is complete but slow. The mature design emits an early result and then corrections, and consumers must handle retractions.
Why are sliding windows expensive?Show answer
Each event belongs to size ÷ slide windows — a 1-hour window sliding every minute keeps 60× the state. Incremental aggregation over tumbling windows is usually cheaper.
What must a checkpoint keep consistent?Show answer
Operator state, input offsets and output commit, all at the same cut. Restore state from 10:00 but resume input at 10:05 and you silently lose five minutes; resume at 09:55 and you double-count.
What does "exactly-once" actually mean in stream processing?Show answer
Exactly-once effects on framework-managed state and transactional sinks — not delivery, which is impossible. Side effects your code performs directly, like HTTP calls or emails, repeat on replay unless idempotent.
Why use a temporal join for currency rates?Show answer
Join each order to the rate in effect at the order's event time, not the current rate. Then replaying the job a month later gives the same answer; reproducibility on replay is the correctness test.

#What to carry forward

  • Event time versus processing time is the root distinction. Business questions are almost always event time.
  • Watermarks are heuristics that trade completeness for latency. Decide the late-data policy explicitly.
  • Sliding windows multiply state; session windows can retroactively merge.
  • State + input offset + output commit must move atomically — that's what checkpointing buys.
  • "Exactly-once" means state semantics, not delivery. External side effects need transactional sinks or idempotency.
  • Temporal joins, not current-value lookups, are what make a job reproducible on replay.
  • A five-minute batch job is often the correct answer. Make streaming justify itself.
00:00
/ 13m