10 minute read

Beam’s stateless transforms cover parsing, filtering, and projection. Stateful processing begins when an element’s result depends on records seen earlier for the same key. That is necessary for sessionization, deduplication, rolling anomaly detection, incomplete-transaction assembly, and inactivity alerts.

State and timers are powerful because they are durable with the Beam runtime. They are also an explicit operational liability: every active key consumes persistent storage, every timer schedules future work, and a bad retention policy can turn one year of traffic into one year of state.

Beam keyed state and timer lifecycle

State is per key, window, and transform

A stateful DoFn must run in a keyed windowed context. Each state specification has a unique name and a type and is bound to the current key and window. A pipeline with one million active keys has one million logical copies of each configured state cell, even if most are empty.

Python Beam exposes the following commonly used state forms:

State Behavior Production use
ValueStateSpec One value per key/window Latest record, sequence number, status
BagStateSpec Collection of independently added values Small bounded session or out-of-order buffer
CombiningValueStateSpec Mergeable aggregate Count, sum, min, or max without retaining every event
MapStateSpec Keyed map when supported by the SDK/runner Bounded per-order or per-partition structures
SetStateSpec Distinct value set when supported by the SDK/runner Small deduplication set with a cleanup horizon

Feature availability can vary by Beam version and runner. Use only state specs and coders validated in the pinned SDK and Dataflow environment. Prefer a value or combining state when a bag is not required; serializing and reading an ever-growing bag on every event is a common source of worker skew.

Choose a key with bounded cardinality

State makes the business key physically significant. A field that is high cardinality, random, or frequently changes can produce unbounded partitions and weak cache locality. Before implementation, measure:

  • distinct keys per retention horizon;
  • p50, p95, and p99 events per key;
  • hot-key concentration;
  • time from first to last event;
  • serialized value bytes, not Python object estimates.

A global "all" key forces all state and every timer into one worker. Sharding can distribute a global aggregate, but it changes semantics: the pipeline must include a second aggregation or accept partial state. Likewise, using an unbounded request ID for a never-expiring value is an eventual state leak even if the value is small.

Event timers and processing timers

An event-time timer follows Beam timestamps and watermarks. It is deterministic for replay when event timestamps and windows are stable. It is appropriate for inactivity expiry, window-end cleanup, and delayed-time policies.

A processing-time timer follows wall-clock worker time. It is appropriate for health checks, bounded liveness, and external-system polling where deterministic replay is not a semantic requirement. After a replay, a processing timer may fire at a different point relative to events.

Do not use a processing timer solely because setting time.time() is familiar. For session closure, an event-time timer is the normal choice: event T resets expiry to T + gap, and an expiry past the watermark means the logical session is complete under the pipeline’s watermark and lateness policy.

Timer callbacks are replays and may happen after an upgrade. Stable state spec names, timer spec names, window strategy, coder schema, and transform identity are part of a stateful application’s migration contract.

A session inactivity DoFn

This example maintains the latest account session:

  • last_event: latest event-time timestamp;
  • event_count: combining count;
  • amount_cents: combining sum;
  • event_ids: a bounded bag for diagnostics;
  • session_expiry: an event-time timer reset on each event.

It emits one logical session when the watermark reaches the latest event plus the inactivity gap. A durable deduplication mechanism remains the downstream consumer’s responsibility if the output sink is not transactional.

import datetime
import json
from typing import Dict

import apache_beam as beam
from apache_beam import coders
from apache_beam.transforms.timeutil import TimeDomain
from apache_beam.transforms.userstate import (
    BagStateSpec,
    CombiningValueStateSpec,
    TimerSpec,
    ValueStateSpec,
    on_timer,
)
from apache_beam.transforms.window import TimestampedValue


class ParseEvent(beam.DoFn):
    def process(self, payload):
        try:
            if isinstance(payload, bytes):
                payload = payload.decode("utf-8")
            record = json.loads(payload)
            account_id = str(record["account_id"])
            event_id = str(record["event_id"])
            event_ms = int(record["event_epoch_ms"])
            amount_cents = int(record["amount_cents"])
            if not account_id or not event_id or amount_cents < 0:
                return
            yield TimestampedValue(
                (
                    account_id,
                    {
                        "event_id": event_id,
                        "account_id": account_id,
                        "event_epoch_ms": event_ms,
                        "amount_cents": amount_cents,
                    },
                ),
                event_ms / 1000.0,
            )
        except (KeyError, TypeError, ValueError, UnicodeDecodeError):
            return


class SessionState(beam.DoFn):
    GAP_SECONDS = 30 * 60
    MAX_DIAGNOSTIC_IDS = 100

    last_event = ValueStateSpec(
        "last-event-ms-v1",
        coders.VarIntCoder(),
    )
    event_count = CombiningValueStateSpec(
        "event-count-v1",
        coders.VarIntCoder(),
        sum,
    )
    amount_cents = CombiningValueStateSpec(
        "amount-cents-v1",
        coders.VarIntCoder(),
        sum,
    )
    recent_ids = BagStateSpec(
        "recent-event-ids-v1",
        coders.StrUtf8Coder(),
    )
    expiry = TimerSpec("session-expiry-v1", TimeDomain.WATERMARK)

    def process(
        self,
        item,
        last_event=beam.DoFn.StateParam(last_event),
        event_count=beam.DoFn.StateParam(event_count),
        amount_cents=beam.DoFn.StateParam(amount_cents),
        recent_ids=beam.DoFn.StateParam(recent_ids),
        expiry=beam.DoFn.TimerParam(expiry),
    ):
        account_id, record = item
        event_ms = record["event_epoch_ms"]
        previous_ms = last_event.read()
        if previous_ms is None or event_ms >= previous_ms:
            last_event.write(event_ms)

        event_count.add(1)
        amount_cents.add(record["amount_cents"])

        current_ids = list(recent_ids.read())
        recent_ids.add(record["event_id"])
        if len(current_ids) >= self.MAX_DIAGNOSTIC_IDS:
            recent_ids.clear()
            recent_ids.add("truncated")

        expiry.set((max(previous_ms or event_ms, event_ms) / 1000.0)
                   + self.GAP_SECONDS)

    @on_timer(expiry)
    def close_session(
        self,
        last_event=beam.DoFn.StateParam(last_event),
        event_count=beam.DoFn.StateParam(event_count),
        amount_cents=beam.DoFn.StateParam(amount_cents),
        recent_ids=beam.DoFn.StateParam(recent_ids),
        window=beam.DoFn.WindowParam,
        key=beam.DoFn.KeyParam,
    ):
        start_ms = window.start.micros // 1000
        yield {
            "account_id": key,
            "event_count": event_count.read(),
            "amount_cents": amount_cents.read(),
            "last_event_epoch_ms": last_event.read(),
            "window_start_epoch_ms": start_ms,
            "diagnostic_event_ids": list(recent_ids.read())[:100],
        }

        last_event.clear()
        event_count.clear()
        amount_cents.clear()
        recent_ids.clear()

The state parameter references in a real module should be declared using the class attribute name expected by Beam’s Python SDK. Current Python Beam examples use string specifications directly in the parameter default, for example:

def process(
    self,
    item,
    last_event=beam.DoFn.StateParam(SessionState.last_event),
):

Keep this naming consistent with the installed SDK and validate at pipeline construction. The code also deliberately caps diagnostic IDs: Bag state should not become the source of a permanent event archive. If the bag is allowed to grow, the size and memory bound are application responsibilities.

Session windows already merge elements after an inactivity gap. For this illustrative DoFn, use a deliberately long global or fixed session horizon compatible with the event-time timer. In production, prefer Beam’s Sessions(gap_seconds) for ordinary inactivity aggregation and use a stateful DoFn only for rules that native session combining does not express.

A simpler value-plus-timer state machine

For a durable alert that fires once after 15 minutes without a new measurement, a compact state machine is clearer:

class InactivityAlert(beam.DoFn):
    last_value = ValueStateSpec("last-value-v1", coders.Int64Coder())
    expiry = TimerSpec("inactivity-v1", TimeDomain.WATERMARK)

    def process(
        self,
        item,
        state=beam.DoFn.StateParam(last_value),
        timer=beam.DoFn.TimerParam(expiry),
        timestamp=beam.DoFn.TimestampParam,
    ):
        key, value = item
        state.write(value)
        timer.set(timestamp + 15 * 60)

    @on_timer(expiry)
    def emit(
        self,
        state=beam.DoFn.StateParam(last_value),
        key=beam.DoFn.KeyParam,
    ):
        value = state.read()
        if value is not None:
            yield {"key": key, "last_value": value, "reason": "inactive"}
            state.clear()

This snippet requires ValueStateSpec and TimestampParam from the selected Beam release. It illustrates timer replacement: another event sets the same timer family to a newer timestamp. A timer callback is therefore a transition in a state machine, not a scheduled cron command.

Combine state instead of retaining every element

Stateful code is often written first with a bag and later rewritten for scalability. If the output is a count or sum, a CombiningValueStateSpec records the aggregate directly:

event_count = CombiningValueStateSpec(
    "event-count-v1",
    coders.VarIntCoder(),
    sum,
)
amount_cents = CombiningValueStateSpec(
    "amount-cents-v1",
    coders.VarIntCoder(),
    sum,
)

Use a deterministic associative combiner. A sum is safe under grouping; an operation based on arrival order is not. For latest-value state, write a record containing both a business timestamp and value, then ignore or handle an older event according to an explicit policy.

Windowing is part of the state key

Beam state for a stateful DoFn is scoped to the current window. Fixed or sliding windows clear their state as windows expire. A GlobalWindow does not expire in the ordinary window lifecycle, so the application must clear state with a timer or another proved lifecycle event.

For an account session, choose the Beam Sessions strategy and allowed lateness carefully. Multiple overlapping sliding windows multiply state. One logical account appearing in 60 ten-second sliding windows has 60 state cells, not one shared Python object.

Expiry, cleanup, and replay

Every state cell needs an answer to four questions:

  1. Which event or timer extends its lifetime?
  2. What emits when it expires?
  3. Which cells are cleared?
  4. What prevents stale timer callbacks from deleting newer state?

A single-value expiry record can prevent old generation cleanup:

generation = ValueStateSpec(
    "cleanup-generation-v1",
    coders.VarIntCoder(),
)
expiry = TimerSpec("cleanup-v1", TimeDomain.WATERMARK)

On every relevant event, increment or update the expected generation and timer. A timer callback verifies that the state still represents the scheduled generation before clearing it. Beam timer replacement makes a stale callback uncommon, but versioned state and fencing are still prudent when schema migrations or external side effects are involved.

Dataflow checkpoints state and progress for managed recovery. Replaying source records can invoke process again after the last durable checkpoint. The stateful transform must produce the same state transition and output policy, and external sinks must accept duplicates. A stable event ID, idempotent sink key, or transactional table is usually required.

Timers and allowed lateness

An event-time timer is not an excuse to ignore late-data policy. If an element arrives after a session’s watermark-driven timer fires, Beam may be able to reopen the window only while allowed lateness permits it. Once the window and state are discarded, the normal pipeline no longer remembers the old session.

For production sessionization:

  • choose an inactivity gap from observed user or device behavior;
  • choose allowed lateness from the tail of source delay;
  • emit pane metadata if provisional sessions can change;
  • define a correction or too-late stream for arrivals after expiry;
  • make downstream session merges idempotent and ordered by a generation.

A processing-time timer can continue to fire during an event-time stall, but that is not evidence that the input is complete. Use it for a heartbeat or alert and never mislabel it as final event-time output.

Cardinality and hot-key controls

Monitor active state counts, bytes, timers, and callback rates. A hot key with ten million events does not become faster with more Dataflow workers because state belongs to one keyed partition.

If the business key is truly hot:

  • split random shards for commutative sums;
  • use a two-stage local and global combine;
  • repartition by a bounded hash only if output identity permits it;
  • rate-limit bag growth;
  • replace list retention with a compact count, sketch, or aggregate where approximation is acceptable.

Sketches and sharding are semantic decisions. Do not silently approximate a billing or entitlement total because the exact key is expensive.

Output and failure semantics

A timer can emit and then the external sink write can fail. Dataflow may retry the bundle or callback. The application therefore needs one of:

  • an idempotent output key and upsert;
  • a transactional sink that ties commit to the pipeline’s delivery mechanism;
  • a reconciliation table that records duplicate generations;
  • an explicit at-least-once contract accepted by downstream consumers.

Keep user-visible side effects out of a stateful process method. Emit a command, then use a connector or controlled sink step. Sending an email directly from the timer creates an external effect that Beam’s state checkpoint cannot make atomic.

Test timer behavior deterministically

Use TestStream for event-time timer tests:

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

stream = (
    TestStream()
    .advance_watermark_to(0)
    .add_elements([TimestampedValue(("device-7", 42), 10)])
    .advance_watermark_to(901)
    .advance_watermark_to_infinity()
)

with TestPipeline() as pipeline:
    alerts = (
        pipeline
        | stream
        | beam.WindowInto(beam.window.FixedWindows(24 * 60 * 60))
        | beam.ParDo(InactivityAlert())
    )
    assert_that(
        alerts,
        equal_to([
            {"key": "device-7",
             "last_value": 42,
             "reason": "inactive"}
        ]),
    )

Add tests that reset the timer with a newer event, deliver an old event without moving it backward, expire at the exact threshold, and arrive after the window is closed. Also restore test state through a representative Dataflow update process before release.

Deployment and state compatibility

Changing a stateful transform is a migration, not just a code deploy. Record:

  • transform and state spec names;
  • key coder and value coder schemas;
  • timer time domain and timestamp calculation;
  • global window or fixed/session window strategy;
  • Beam SDK and runner version;
  • last successful job snapshot and source positions;
  • previous state schema retained for rollback.

For a compatible rolling update on Dataflow, use the update workflow supported for that job type and test whether the change is permitted. For semantic changes to state, launch a parallel version that reads a separate subscription or replay range and compare outputs. Draining an old job publishes final progress but does not convert old Python object formats into a new layout.

Pin IAM to the minimum source, staging, worker, sink, and log permissions. State access is mediated by Dataflow, so the greater risk is often a stale worker service account that can read more production data than the stateful application needs.

Production checklist

Before enabling timers and state:

  • state is keyed, windowed, and bounded by an explicit expiry;
  • no bag grows with the complete history of a long-lived key;
  • timers use event time when deterministic replay matters;
  • process-time timers have a clear non-final use;
  • every timer callback clears all owned state;
  • duplicate event IDs and replay behavior are tested;
  • pane and generation metadata reach the output sink;
  • cardinality, hot-key, state-size, and timer-rate metrics are visible;
  • schema and state-spec compatibility is tested across the oldest supported job;
  • a rollback path identifies the Dataflow job, source subscription, and output generation.

Stateful Beam is most reliable when treated as a small distributed state machine with bounded keys and explicit transitions. Timers define the transitions that no future event may trigger; they do not remove the need to reason about watermarks, late data, and external delivery.