What You'll Learn
- 1Distinguish event time, processing time, and watermarks, and say what each one delays
- 2Choose fixed, sliding, or session windows from the shape of the question being answered
- 3Design trigger and accumulation combinations that balance freshness against correctness
- 4Use keyed state and timers to build aggregations that survive out-of-order arrival
Streaming correctness on Dataflow reduces to three concepts: event time answers when something happened, windowing answers which buckets it counts toward, and triggers answer when the system is allowed to produce a number. Watermarks glue them together by estimating when event time has caught up. Misunderstanding any one of these produces pipelines that look fine in demos and quietly lose or duplicate data in production.
Event Time, Processing Time, and Watermarks
Event time is the timestamp the event carries; processing time is when a worker touches it. Every real pipeline has a gap between them, and that gap is where late data lives. A watermark is the pipeline's belief that all events up to some event time have arrived. For Pub/Sub sources the watermark is estimated from publish timestamps with a configurable maximum delay, so mobile clients that buffer offline events push the watermark back unless you tolerate it or stamp differently.
| Concept | Question it answers | Typical failure when ignored |
|---|---|---|
| Event time | When did it happen | Daily reports shift with ingestion lag |
| Processing time | When did we see it | Backfills rewrite history unpredictably |
| Watermark | Is more data coming | Windows close too early or never close |
Windowing Strategies
Fixed windows slice the timeline into non-overlapping buckets and suit metrics such as per-minute request counts. Sliding windows overlap by design: a one-hour window sliding every five minutes updates twelve times per hour at twelve times the state cost, which is what a moving average demands. Session windows close after a gap of silence and model user behaviour, where a session ends when the user stops rather than when the clock rolls over.
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.transforms.window import (
FixedWindows, SlidingWindows, Sessions, TimestampedValue
)
options = PipelineOptions([
"--runner", "DataflowRunner",
"--project", "my-project",
"--region", "us-central1",
"--streaming",
"--temp_location", "gs://my-bucket/temp",
])
class ParseAndStamp(beam.DoFn):
def process(self, element):
import json
event = json.loads(element.data.decode("utf-8"))
yield TimestampedValue(event, event["event_time"])
with beam.Pipeline(options=options) as pipeline:
events = (
pipeline
| beam.io.ReadFromPubSub(topic="projects/my-project/topics/clicks")
| beam.ParDo(ParseAndStamp())
)
# Fixed: one aggregate per calendar minute of event time.
per_minute = (
events
| beam.WindowInto(FixedWindows(60))
| beam.Map(lambda e: (e["user_id"], 1))
| beam.CombinePerKey(sum)
)
# Sliding: one hour of history refreshed every five minutes.
rolling = (
events
| beam.WindowInto(SlidingWindows(3600, 300))
| beam.Map(lambda e: (e["user_id"], 1))
| beam.CombinePerKey(sum)
)
# Sessions: a user's burst of activity, closed after five idle minutes.
sessions = (
events
| beam.WindowInto(Sessions(300))
| beam.Map(lambda e: (e["user_id"], e["amount"]))
| beam.CombinePerKey(sum)
)
The same event lands in three windowings of the same pipeline without re-reading the source, which is the practical argument for modelling windows in Beam rather than in downstream SQL.
Watermarks, Allowed Lateness, and Late Data
A window is complete when the watermark passes its end plus the allowed lateness. Allowed lateness is a retention budget: state for that window is held, and results can be refined, until the deadline passes, after which late elements are dropped or routed to a side output. Setting lateness to zero maximises throughput and guarantees data loss; setting it to hours guarantees correct final results at the cost of proportionally more state.
from apache_beam.transforms.window import FixedWindows
from apache_beam.transforms.trigger import AfterWatermark, AfterCount
late_tag = beam.TaggedOutput("late")
class RouteLate(beam.DoFn):
def process(self, element, window=beam.DoFn.WindowParam):
if element[2] > window.end:
yield beam.pvalue.Output(late_tag, element)
else:
yield element
(
windowed
| "Route late" >> beam.ParDo(RouteLate()).with_outputs(late_tag, main="main")
| "Late sink" >> beam.io.WriteToPubSub(
topic="projects/my-project/topics/late-events")
)
The side output pattern keeps the main aggregation clean while giving late arrivals a second life: replay them through a batch correction job at the end of the day, or merge them into a corrected table that supersedes the provisional one.
Triggers and Accumulation Modes
The default trigger fires once, when the watermark closes the window. Early triggers emit provisional results before that, and late triggers re-emit when stragglers arrive. A common production combination is AfterWatermark with an early processing-time trigger for a dashboard that needs updates every thirty seconds, plus a late trigger that fires on the first late element after the watermark.
Accumulation mode decides what each emission contains. Discarding mode clears the pane's state after each trigger, so emissions are deltas that a sink must add together. Accumulating mode keeps state, so every emission is a full recomputation of the window so far, and a sink must overwrite rather than accumulate.
| Trigger setup | Emissions | Best sink behaviour |
|---|---|---|
| Default watermark only | one final result | append |
| Early every 30 s, discarding | deltas | append and sum downstream |
| Early every 30 s, accumulating | cumulative snapshots | upsert keyed by window |
| Watermark plus late count | final plus refinements | upsert, then freeze after lateness |
Keyed State and Timers
Combiners cover most aggregations, but workflows that need memory of what came before use the state and timers API. Keyed bag state stores per-key lists, combining-value state stores an incrementally merged accumulator, and timers fire on event time or processing time to close out a key. A sessionisation DoFn, for example, holds a bag of events per user and sets an event-time timer that resets on every new element, emitting the session only when the gap timer survives.
import apache_beam as beam
from apache_beam.transforms.userstate import (
BagStateSpec, TimerSpec, on_timer, TimeDomain
)
from apache_beam.coders import PickleCoder
class Sessionise(beam.DoFn):
EVENTS = BagStateSpec("events", PickleCoder())
GAP = TimerSpec("gap", TimeDomain.EVENT_TIME)
def process(self, element, events_state=beam.DoFn.StateParam(EVENTS),
gap_timer=beam.DoFn.TimerParam(GAP)):
user_id, event = element
events_state.add(event)
gap_timer.schedule(event["event_time"] + 300)
yield ("scheduled", user_id)
@on_timer(GAP)
def close_session(self, user_id, events_state=beam.DoFn.StateParam(EVENTS)):
events = list(events_state.read())
events_state.clear()
if events:
yield (user_id, sum(e["amount"] for e in events), len(events))
State and timers are keyed by the element's key after a GroupByKey-style rekey, and they are backed by the runner's state backend, so large keys need explicit management: clear state on close, bound bag sizes, and prefer combining state over bag state whenever the aggregation is associative. Timer callbacks run in the same process as the DoFn, so side effects there must be idempotent too, because a worker failure can replay both the element and the firing. When a key's state outgrows a single worker, the runner reshards state during fusion breaking, which is correct but expensive; the cheaper fix upstream is usually to widen the key with a bucket suffix, aggregate twice, and merge the buckets, trading a little logic for state that fits comfortably.
Exactly-Once Processing
Exactly-once in streaming means each logical result reflects each input once, which Dataflow achieves through record bookkeeping in the runner plus sinks with matching guarantees. With Streaming Engine enabled, the runner persists state and bookmarks outside workers, so a worker restart replays from a consistent point instead of from the last checkpoint the job happened to make. The BigQuery Storage Write API carries per-stream ordering and deduplication that closes the loop; sinks without such guarantees, such as generic HTTP calls, require idempotency keys on your own side.
Streaming Engine and Cost Shape
Streaming Engine moves shuffle, state, and windowing off the worker VMs and bills the freed capacity separately, which decouples job stability from worker preemption and reduces the worker count needed for state-heavy pipelines. Autosharding keeps sinks fed without manual partition tuning. Cost-wise, the dominant term in a streaming job is idle worker time during quiet periods, so autoscaling with a latency target and honest min workers matters more than shaving milliseconds of CPU in the hot path. Budget reviews for streaming jobs should also examine the sink: rows written per window multiply across triggers, and an early trigger that fires every ten seconds on a five-minute window can multiply sink volume by thirty before anyone notices the bill.
Common Mistakes
Leaving allowed lateness at zero to keep state small
Fix: Measure the late-data fraction first; zero lateness silently drops everything the watermark overtook, and a side output with batch correction is cheaper than an angry stakeholder.
Mixing accumulating emissions into an append-only table
Fix: Accumulating panes resend cumulative totals; upsert them by window key or switch the trigger to discarding if the sink only appends.
Storing unbounded lists in bag state without clearing
Fix: Clear or combine state when the closing timer fires, or the state backend grows until the pipeline dies on disk pressure.
Best Practices
- Stamp event time at the producer so watermarks stay tight across the whole pipeline
- Pair every early trigger with an explicit accumulation mode and a sink that matches it
- Route late data to a side output rather than trusting allowed lateness to cover everything
Key Takeaways
- Watermarks estimate event-time progress and decide when windows may close; late data is whatever arrives after that estimate
- Session windows model behaviour, sliding windows model moving statistics, and fixed windows model calendar metrics
- Accumulating mode emits cumulative panes for upserts; discarding mode emits deltas for append sinks
- Keyed state plus event-time timers implement sessionisation and deduplication that outlive individual bundles
Interview Questions
Interview Questions
Q1: What is a watermark and what does it control?
It is the pipeline's estimate that all events up to a given event time have arrived. It controls window closure and result finality; it does not prevent late data, it only decides when the system stops waiting for it.
Q2: Fixed versus sliding windows for a moving average?
Sliding windows overlap, so each element joins several panes and the output is a smoothed series; fixed windows partition time cleanly and produce disjoint aggregates better suited to calendar reporting.
Q3: How do you handle late data end to end?
Allow bounded lateness so the window can refine, add a late trigger for stragglers after the watermark, and route anything beyond lateness to a side output that a correction job reprocesses.
Q4: When do you need state and timers instead of CombinePerKey?
When the result depends on ordered history, such as sessionisation or deduplication windows, the accumulator is not associative, or emission must wait for an idle gap rather than a watermark.