Skip to main content
← CONCEPTS / DATA ENGINEERING
An end-to-end domain learning journey

Stream Watermarks &
Late Data.

Watermarks track event-time progress in unbounded streams, telling stateful operators when a time window is complete enough to emit results—while allowed lateness and side outputs handle straggling events.
Start the journey7 sections· Last modified Oct 23, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When durability and read throughput pull in opposite directions, in Apache Flink or Spark Structured Streaming, set watermarks to max_observed_event_time - bounded_out_of_orderness, pair them with allowedLateness for corrections, and route beyond-lateness events to a side output rather than silently dropping them.

TL;DR30-second simplified summary
▾

Core Mechanics: In distributed streaming, network jitter and offline buffering scramble event arrival order.

Visual & Structural Flow: Depicts Watermark & Allowed Lateness State Machine (ON-TIME -> ALLOWED LATENESS -> SIDE OUTPUT / DLQ); Min-Across-Partitions Watermark Propagation (Partition 0 (fast) -> Partition 1 (idle) -> Window Operator -> Downstream Sink).

Trade-Offs & Production: A generous out-of-orderness bound (e.g., 60s) reduces late-data retractions and downstream upserts. Two silent killers dominate production streaming: clock-skew poisoning (a single future-dated event jumps W(t) ahead by days, dropping all subsequent traffic as late) and.

Failure Modes & Application: In Apache Flink or Spark Structured Streaming, set watermarks to max_observed_event_time - bounded_out_of_orderness, pair them with allowedLateness for corrections, and route beyond-lateness events.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Distributed & Application Caching
Caching keeps a reusable copy of data so an application can avoid repeating a database query, calculation, or network call. It can make responses faster and reduce database load. The trade-off: the copy may be out of date.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What is Stream Watermarks & Late Data.

Why this matters: The mechanism: understand how Stream Watermarks & Late Data works from first principles.

The idea In distributed streaming, network jitter and offline buffering scramble event arrival order. A watermark W(t) is a special timestamped marker injected into the data stream asserting that no further events with event_time <= t are expected. It decouples correctness (event time) from infrastructure speed (processing time), giving stateful operators a deterministic signal to fire windows and garbage-collect old state.

Core Pillars:

  • Event time (when the action happened) differs from processing time (when the Flink/Spark worker sees the record); watermarks bridge the two.
  • A watermark W(t) is a monotonic assertion that no more events with timestamp <= t are expected; when W(t) passes window_end, the window fires.
  • Bounded-out-of-orderness watermarks (maxEventTime - delta) trade latency for completeness: larger delta catches more late events but delays window emission and increases state size.
  • An idle Kafka partition stops advancing its local watermark and stalls the global min-watermark across all parallel subtasks unless withIdleness() is configured.
  • Events arriving after W(t) passes window_end + allowedLateness are dropped from state—route them to a Dead Letter / side output for batch reconciliation.
Event-Time Progress

Watermark & Allowed Lateness State Machine

W passes window endW passes end + latenessON-TIMEt_event >= WALLOWED LATENESSEmit retraction/updateSIDE OUTPUT / DLQBeyond lateness -> audit

Watermarks separate completeness from latency: on-time events update open windows, late events trigger updates or route to side outputs.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why we need Stream Watermarks & Late Data (and what fails without it).

Why this matters: The problem: see what breaks without Stream Watermarks & Late Data under real concurrency or scale.

Mobile apps, IoT sensors, and multi-region Kafka topics deliver events out of order; without event-time watermarks, tumbling windows either emit wrong counts prematurely or hold state in memory forever until OOM.

Common Pitfalls:

  • Assuming watermarks are global wall-clock timers rather than data-driven metadata flowing inside the stream.
  • Forgetting that an operator with multiple upstream inputs advances its watermark to min(input_watermarks), not max.
  • Leaving idle-partition timeouts unset on topics with uneven key distribution.
Design Trade-Off

Why we need Stream Watermarks & Late Data (and what fails without it)

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • Explicit capacity budgets
  • Isolated failure domains
  • Predictable p99 latency
Engineering Decision Framework
Problem
How to implement Stream Watermarks & Late Data without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When durability and read throughput pull in opposite directions, in Apache Flink or Spark Structured Streaming, set watermarks to max_observed_event_time - bounded_out_of_orderness, pair them with allowedLateness for corrections, and route beyond-lateness events to a side output rather than silently dropping them.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Stream Watermarks & Late Data experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

Failure Mode

Mitigation: Always configure idle-source detection (withIdleness in Flink) and alert on watermark-to-wall-clock lag.

Failure Mode

Mitigation: Clamp or quarantine future timestamps (event_time > processing_time + max_skew) at the ingestion/deserialization boundary.

Failure Mode

Mitigation: Attach a side output (lateOutputTag) to route ultra-late records to a cold-path Parquet/S3 reconciliation job.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where Stream Watermarks & Late Data is used (and where to avoid it).

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Where Stream Watermarks & Late Data is used (and where to avoid it) as the intuition layer for Stream Watermarks & Late Data: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Stream Watermarks & Late Data delivers the highest leverage at well-defined architectural boundaries. Use it for event-time aggregations (tumbling, sliding, or session windows) in Apache Flink, Apache Beam, or Spark Structured Streaming.

ChoiceWhat it buysWhat it costs
Production Fit #1Event-time aggregations (tumbling, sliding, or session windows) in Apache Flink, Apache Beam, or Spark Structured Streaming.Simple stateless per-event transformations (filtering, JSON enrichment, regex masking) that require no windowing.
Production Fit #2Out-of-order streams from mobile clients offline-buffering events, multi-AZ producers, or cross-region replication.Strict processing-time monitoring where wall-clock ingestion rate is the actual metric (e.g., raw Kafka consumer lag).
Production Fit #3Billing, fraud detection, or SLA alerting where results depend on when an event occurred rather than when the server ingested it.Batch-only workloads over bounded, already-complete daily Parquet files.
Flink 1.19 mobile telemetry 1-minute tumbling windowsRequires strict operational guardrails and observability.
Stalled watermark from an idle regional Kafka partitionRequires strict operational guardrails and observability.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

How Stream Watermarks & Late Data works under the hood & reference implementation.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Concrete walkthrough Suppose we aggregate 1-minute tumbling windows ([12:00, 12:01)) with a 10-second out-of-orderness bound (delta = 10s) and allowedLateness = 30s:

  1. Events with timestamps 12:00:15, 12:00:48, and 12:01:05 arrive. maxEventTime becomes 12:01:05, so W = 12:00:55 (window [12:00, 12:01) stays open).
  2. Event 12:01:12 arrives -> W = 12:01:02. Because W >= 12:01:00, the [12:00, 12:01) window fires its initial aggregate.
  3. Window state is retained until W reaches 12:01:30 (window_end + allowedLateness).
  4. A late event 12:00:52 arrives while W = 12:01:15: it enters the retained window and triggers an updated emission.
  5. Once W >= 12:01:30, the window state is purged; any subsequent 12:00:xx event is routed to the side output.

The idea In distributed streaming, network jitter and offline buffering scramble event arrival order. A watermark W(t) is a special timestamped marker injected into the data stream asserting that no further events with event_time <= t are expected. It decouples correctness (event time) from infrastructure speed (processing time), giving stateful operators a deterministic signal to fire windows and garbage-collect old state.

Reference implementation (Python — Transactional Outbox Relay Worker)

# Idempotent Transactional Outbox relay loop (Python)
def publish_pending_outbox_events(db_conn, kafka_producer, batch_size: int = 100) -> int:
    rows = db_conn.execute(
        "SELECT id, aggregate_id, payload FROM outbox WHERE published_at IS NULL "
        "ORDER BY id ASC LIMIT %s FOR UPDATE SKIP LOCKED",
        (batch_size,),
    ).fetchall()
    for event_id, agg_id, payload in rows:
        kafka_producer.send(topic="domain-events", key=str(agg_id), value=payload)
        db_conn.execute("UPDATE outbox SET published_at = NOW() WHERE id = %s", (event_id,))
    db_conn.commit()
    return len(rows)

Operational Guidelines

  • Core mental model: In Apache Flink or Spark Structured Streaming, set watermarks to max_observed_event_time - bounded_out_of_orderness, pair them with allowedLateness for corrections, and route beyond-lateness events to a side output rather than silently dropping them.
  • Avoid trap: Assuming watermarks are global wall-clock timers rather than data-driven metadata flowing inside the stream.
  • Avoid trap: Forgetting that an operator with multiple upstream inputs advances its watermark to min(input_watermarks), not max.
  • When to reach for it: Event-time aggregations (tumbling, sliding, or session windows) in Apache Flink, Apache Beam, or Spark Structured Streaming.
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives & trade-offs for Stream Watermarks & Late Data.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives & trade-offs for Stream Watermarks & Late Data as the intuition layer for Stream Watermarks & Late Data: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Evaluating Stream Watermarks & Late Data against alternatives requires balancing latency, operational overhead, failure blast radius, and cost. A generous out-of-orderness bound (e.g., 60s) reduces late-data retractions and downstream upserts.

Component Topology

Alternatives & trade-offs for Stream Watermarks & Late Data

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
ChoiceWhat it buysWhat it costs
Watermark delay (delta) vs. window latencyA generous out-of-orderness bound (e.g., 60s) reduces late-data retractions and downstream upserts.Every window waits 60s longer to emit and retains open RocksDB/heap state for 60s more.
Allowed lateness vs. state storage costKeeping window state open for allowedLateness lets the stream engine emit accurate updated totals for late arrivals.RocksDB state size grows linearly with lateness duration, increasing checkpoint size and recovery time.
Retractions/upserts vs. append-only sinksEmitting early speculative triggers plus late updates keeps dashboards fresh and eventually accurate.Downstream sinks must support idempotent upserts (e.g., PostgreSQL ON CONFLICT or ClickHouse ReplacingMergeTree) rather than append-only logs.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production architecture & hardening for Stream Watermarks & Late Data.

Why this matters: Production architecture: see how the components compose end to end under real load.

Failure modes Two silent killers dominate production streaming: clock-skew poisoning (a single future-dated event jumps W(t) ahead by days, dropping all subsequent traffic as late) and checkpoint backpressure (when RocksDB state swells from long allowedLateness, checkpoint barriers stall behind full buffers, causing consumer lag to spiral).

Practical checklist

  • Set boundedOutOfOrderness from the p99 arrival delay distribution, not a guess.
  • Enable withIdleness() on all multi-partition Kafka sources.
  • Clamp future client timestamps (event_time > now + 5m) before watermark assignment.
  • Always attach a sideOutputLateData sink instead of silently dropping ultra-late records.
  • Pair allowedLateness with an idempotent upsert sink (keyed by window_start, key).
Multi-Partition Watermark

Min-Across-Partitions Watermark Propagation

Partition 0 (fast)Partition 1 (idle)Window OperatorDownstream Sink1. Watermark = 10:152. Idle partition stalls W =10:01!3. Idle timeout marks P1 idle -> W=10:154. Fire [10:10, 10:15) window

A single idle input partition can stall the global min-watermark unless idle-source detection is configured.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Problems solved by Stream Watermarks & Late Data & Related Concepts.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Problems solved by Stream Watermarks & Late Data & Related Concepts as the intuition layer for Stream Watermarks & Late Data: Applied problems: connect these internals to concrete system design and debugging scenarios.

Apply Stream Watermarks & Late Data to real-world engineering problems and explore adjacent architectural concepts below.

Lifecycle & Failure Recovery

Problems solved by Stream Watermarks & Late Data & Related Concepts

admitsucceedbudget exceededInitializedProcessingInvariant MetDegraded Fallback
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

In a multi-partition stream processor (e.g., Flink or Spark), one Kafka partition receives zero events for 2 hours while other partitions are active. What happens if idle-partition handling is not enabled?

Recommended Learning Flow