Windowing turns an unbounded PCollection into finite logical subsets. Watermarks estimate when the runner can stop expecting records before a particular event time. Triggers decide when a window is evaluated, and the allowed-lateness policy decides how long a closed window can be reopened. These are separate controls; changing one does not replace the others.

Most streaming data problems become operationally clear when the pipeline states an explicit event-time contract. For each record, define which timestamp is authoritative, what clock skew is plausible, which delay is late, and how downstream consumers interpret revised results.

Beam event-time, watermark, trigger, and late-data timeline

Event time is not processing time

Event time is when something happened in the producer’s domain. Processing time is when a worker observes it. A mobile action generated at 12:00:02 but uploaded at 12:01:30 has the first timestamp as event time and the second as pipeline arrival time.

Every Beam element has an intrinsic timestamp. Source connectors establish one when they know it; otherwise the pipeline can explicitly assign it:

from apache_beam.transforms.window import TimestampedValue

def timestamp_record(record):
    event_ms = int(record["event_epoch_ms"])
    return TimestampedValue(record, event_ms / 1000.0)

events = (
    pipeline
    | "Decode" >> beam.ParDo(ParseEvent())
    | "AssignEventTime" >> beam.Map(timestamp_record)
)

Choose a timestamp in UTC and validate its range. Reject implausibly old or future values according to the domain. Silently substituting the current processing time for a missing event timestamp destroys the meaning of the window and the watermark.

Watermarks are estimates, not arrival barriers

The watermark says the runner does not expect additional elements with event timestamps earlier than the mark under its current estimate. In a distributed source, Dataflow combines progress from every partition or shard. One quiet or stuck partition can hold the global watermark back. A fast partition does not prove that all earlier records have arrived.

A heuristic watermark may advance while a badly delayed producer still has old data. That data is late. The pipeline’s contract must say whether late data is dropped, retained in a dead-letter stream, or causes an updated aggregate pane.

Track the following independently:

  • source system and Pub/Sub backlog;
  • current input watermark age;
  • count of events with timestamps behind the watermark;
  • time from event timestamp to processing;
  • pane count and pane-finality revisions;
  • output records arriving after their window’s first pane.

A watermark delay may indicate desired protection for variable arrival times, or it may indicate a source partition that stopped making progress. Do not tune allowed lateness to hide an ingestion incident.

Fixed, sliding, and session windows

Fixed windows partition time into non-overlapping intervals. A one-minute window is useful for operational volume and traffic metrics:

from apache_beam.transforms.window import FixedWindows

minute_events = events | "MinuteWindows" >> beam.WindowInto(
    FixedWindows(60)
)

Every element belongs to one fixed window. Window boundaries are deterministic, but always document the epoch and offset when business reporting uses local-time boundaries.

Sliding windows are overlapping intervals with a size and period. A ten-minute count emitted every minute gives continuous movement:

from apache_beam.transforms.window import SlidingWindows

rolling_events = events | "TenMinuteWindow" >> beam.WindowInto(
    SlidingWindows(10 * 60, 60)
)

An event belongs to every overlapping window that contains it. A sink expecting one record per event will therefore see multiple contributions. Size the window and period deliberately because fan-out multiplies aggregation input and output.

Session windows group events separated by less than a gap. They are suitable for user activity or device conversations:

from apache_beam.transforms.window import Sessions

session_events = (
    events
    | "KeyForSessions" >> beam.WithKeys(lambda row: row["account_id"])
    | "SessionWindows" >> beam.WindowInto(Sessions(30 * 60))
)

Sessions are dynamic. An event can merge two prior windows, which makes output updates important: an early pane can be replaced or superseded by a later pane as sessions join. Never publish a session finalization as irrevocably final before the watermark and allowed-lateness interval have expired.

Allowed lateness defines the cleanup horizon

The following policy keeps window state for five minutes after the watermark passes the end:

from apache_beam.transforms.trigger import (
    AccumulationMode,
    AfterCount,
    AfterWatermark,
    Repeatedly,
)
from apache_beam.transforms.window import FixedWindows, WindowInto

window_policy = WindowInto(
    FixedWindows(60),
    trigger=AfterWatermark(
        early=AfterCount(1000),
        late=Repeatedly(AfterCount(1)),
    ),
    accumulation_mode=AccumulationMode.ACCUMULATING,
    allowed_lateness=5 * 60,
)

Read this as:

  • calculate an early speculative pane after 1,000 records;
  • emit at the end-of-window watermark;
  • emit a revised accumulation after each later record during allowed lateness;
  • stop revising the window after five minutes past its end watermark.

This policy favors freshness at the cost of repeated downstream revisions. DISCARDING changes the accumulation semantics: each firing emits only the elements since the prior firing. AccumulationMode.ACCUMULATING emits the running cumulative value, making an upsert-style sink easier to reason about.

The correct mode is a consumer contract. A dashboard may upsert a cumulative pane by window and key. A ledger may require discarding deltas and a commutative aggregate. Mixing a discarding producer with a sink that treats each record as an append duplicates totals.

Triggers are scheduling policy

An end-of-window watermark is often the best default. Add an early trigger only when the application has a concrete freshness target and its consumer can identify non-final panes. A processing-time trigger is useful for emitting liveness, but it does not make event-time data complete.

Triggers can fire repeatedly:

AfterWatermark(
    early=AfterProcessingTime(30),
    late=AfterProcessingTime(10),
)

In this arrangement, early and late processing-time triggers are cadence choices. They do not prove that all records for a key have arrived. A window may yield many panes. Always include pane metadata if consumers need to order corrections:

class AddPaneInformation(beam.DoFn):
    def process(self, value, pane=beam.DoFn.PaneInfoParam):
        yield {
            "value": value,
            "is_first": pane.is_first,
            "is_last": pane.is_last,
            "timing": str(pane.timing),
            "index": pane.index,
        }

PaneInfo helps consumers interpret output, but an arbitrary file sink may not preserve delivery order. A stable window key, pane index, and generation-aware merge remain important.

An end-to-end Python transform

This concise transform assigns event time, windows by account, and counts each minute:

import datetime
import json

import apache_beam as beam
from apache_beam.transforms import window
from apache_beam.transforms.trigger import (
    AccumulationMode,
    AfterCount,
    AfterProcessingTime,
    AfterWatermark,
)


class ParseJson(beam.DoFn):
    def process(self, payload):
        try:
            if isinstance(payload, bytes):
                payload = payload.decode("utf-8")
            record = json.loads(payload)
            if not record.get("account_id"):
                return
            event_time = int(record["event_epoch_ms"]) / 1000.0
            yield window.TimestampedValue(
                (record["account_id"], 1),
                event_time,
            )
        except (KeyError, TypeError, ValueError, UnicodeDecodeError):
            return


class CountShape(beam.DoFn):
    def process(
        self,
        item,
        interval=beam.DoFn.WindowParam,
        pane=beam.DoFn.PaneInfoParam,
    ):
        key, count = item
        yield {
            "account_id": key,
            "event_count": count,
            "window_start": datetime.datetime.fromtimestamp(
                interval.start.micros / 1e6,
                tz=datetime.timezone.utc,
            ).isoformat(),
            "window_end": datetime.datetime.fromtimestamp(
                interval.end.micros / 1e6,
                tz=datetime.timezone.utc,
            ).isoformat(),
            "pane_timing": str(pane.timing),
            "pane_is_last": pane.is_last,
        }


def aggregate_events(events):
    return (
        events
        | "ParseAndTimestamp" >> beam.ParDo(ParseJson())
        | "MinutePolicy"
        >> beam.WindowInto(
            window.FixedWindows(60),
            trigger=AfterWatermark(
                early=AfterProcessingTime(30),
                late=AfterProcessingTime(10),
            ),
            accumulation_mode=AccumulationMode.ACCUMULATING,
            allowed_lateness=5 * 60,
        )
        | "CountByAccount" >> beam.CombinePerKey(sum)
        | "AttachWindow" >> beam.ParDo(CountShape())
    )

The one-element AfterCount example earlier emits immediately for each late record; the processing-time policy coalesces late events into periodic panes. The latter is often cheaper but requires a consumer that can tolerate lower revision frequency.

Testing early, on-time, and late behavior

Synthetic sleeps do not prove event-time behavior. Beam’s TestStream advances event and processing time deliberately. A focused test builds a bounded window timeline:

import unittest

import apache_beam as beam
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.test_stream import TestStream
from apache_beam.testing.util import assert_that, equal_to
from apache_beam.transforms.window import TimestampedValue


class WindowTimingTest(unittest.TestCase):
    def test_early_on_time_and_late(self):
        test_stream = (
            TestStream()
            .advance_watermark_to(0)
            .add_elements([
                TimestampedValue(("account-a", 2), 10),
                TimestampedValue(("account-a", 3), 15),
            ])
            .advance_processing_time(30)
            .advance_watermark_to(61)
            .add_elements([
                TimestampedValue(("account-a", 5), 40),
            ])
            .advance_processing_time(10)
            .advance_watermark_to_infinity()
        )

        with TestPipeline() as pipeline:
            totals = (
                pipeline
                | test_stream
                | beam.WindowInto(
                    beam.window.FixedWindows(60),
                    trigger=beam.trigger.AfterWatermark(
                        early=beam.trigger.AfterProcessingTime(30),
                        late=beam.trigger.AfterProcessingTime(10),
                    ),
                    accumulation_mode=beam.trigger.AccumulationMode.ACCUMULATING,
                    allowed_lateness=5 * 60,
                )
                | beam.CombinePerKey(sum)
                | beam.Map(lambda item: item[1])
            )
            assert_that(totals, equal_to([5, 5, 10]))

The first two events are in the [0, 60) window and produce an early total of 5. Advancing the watermark past 60 fires the on-time accumulation of 5. The element at event time 40 arrives after the watermark and produces the cumulative late value 10 before allowed lateness expires. The result is therefore [5, 5, 10]: repeated totals represent early, on-time, and late panes, not duplicate input.

For robust suite design, split the three expectations into separate tests:

  1. early record at event time 10 plus processing-time advancement must emit an EARLY pane;
  2. watermark advancement to the window end must emit an ON_TIME pane;
  3. an event with event time 10 after the watermark but before allowed lateness expires must emit LATE and update the aggregate.

Also add events beyond allowed lateness and assert they never appear in the normal aggregate. Route them into a separately instrumented lateness policy if the business requires audit.

Expected timeline

Suppose a one-minute window begins at 12:00:00 and allowed lateness is five minutes:

  1. Events at 12:00:10 and 12:00:15 arrive while the watermark is 12:00:08. A processing-time trigger may emit an early count.
  2. The watermark passes 12:01:00. Beam fires the on-time pane.
  3. At 12:03:00, an event timestamped 12:00:40 arrives. The watermark is past the window but below its lateness expiration, so a late revision is valid.
  4. At 12:06:00, the window end plus five minutes has passed. A second event from that window is too late for ordinary aggregation.

The marks are event-time positions, not guarantees about wall-clock arrival. The timestamp attached to the watermark is meaningful only alongside the pipeline’s event-time domain.

Sink semantics for revisions

A trigger can publish multiple values for the same (window, key). The sink must implement one intentional policy:

Policy Suitable sink Behavior
Append every pane Event log or audit store Consumer computes the latest valid pane
Upsert latest accumulation Keyed warehouse table Latest generation replaces prior value
Replace session Table with merge procedure Merged session supersedes old rows
Publish deltas only Append-only metric system Metrics are additive and out-of-order safe

For an upsert, include a deterministic key such as account_id, window_start, and a business schema version. Add pane timing and index only as ordering evidence. If two writers can race, use a source generation or watermark-derived version that the sink transaction can compare.

Tune from observed arrival distributions

Do not select allowed lateness from the average delay. Calculate p95 and p99 event-to-processing delay by source, producer version, and region. If mobile producers can remain offline for a day, five minutes is probably not a correctness mechanism; use source-side batching plus a later batch reconciliation instead.

Long allowed lateness increases state retention. Session windows can be especially expensive because each active key can have a chain of events and mutable boundaries. Evaluate:

  • active-key cardinality;
  • bytes retained per key;
  • number of panes per window;
  • checkpoint or state size;
  • late-record ratio;
  • downstream write amplification.

A useful starting point is a watermark heuristic matching the normal p95 delay and a lateness window matching the agreed correction SLA. Measure the tail, then revise only with a corresponding sink and consumer contract.

Production checklist

Before release:

  • prove the event-time extraction against producer clock and timezone rules;
  • test fixed, sliding, or session boundaries at exact edges;
  • choose default, early, and late trigger behavior separately;
  • choose accumulating or discarding semantics deliberately;
  • set and justify allowed lateness;
  • publish pane and window metadata needed by the sink;
  • test early, on-time, late, and beyond-lateness records with TestStream;
  • alert on watermark age, late ratio, pane volume, and state growth;
  • document how replay changes or duplicates prior panes.

The goal is not to prevent every late event. It is to make the point at which a result is provisional, revised, or final explicit and testable.