Skip to content

Part 8 · Blueprint 46

Real-Time Stream Processing Engine (Apache Flink Internals)

15 min reading · Sources · Editorial review pending

Late events and replay can change an apparently finished window.

More
20px
Reading list
Page details

Published date · Last edited:

Draft edition. Editorial review and supplementary reading recommendations are still being completed.

Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Message Queues & Event Streams: Kafka vs. RabbitMQ, Time, Clocks & Distributed Ordering: Lamport to TrueTime, Change Data Capture (CDC) & Outbox Pipelines (Debezium Scale).

Sixty-second mental model

Problem: Late events and replay can change an apparently finished window.

Use: Declare lateness, deduplication and sink commit behavior.

Design boundary: Compute stateful event-time results despite late data, duplicate delivery and restart. Watermarks express progress assumptions; they are not guarantees that the world will never send an older event.

Layer 1 · Intuition

Hypothetical scenario: Northwind is designing stream processing. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one stream event means and which component owns the checkpointed operator state.

Think of a sorting office grouping reports by when events happened. Separate the requester from checkpointed operator state, then identify the retained evidence needed after failure.

Authority
The entitled state owner.
Invariant
A rule preserved across concurrency and failures.
Watermark
An event-time progress estimate used to reason about when older events may be considered late. Analogy: A marker estimating how far incoming reports have caught up.

Architecture and worked reasoning

Design boundary: Compute stateful event-time results despite late data, duplicate delivery and restart. Watermarks express progress assumptions; they are not guarantees that the world will never send an older event.

Responsibilities on the request path

Stream processing: responsibilities and request directionCompute stateful event-time results despite late data, duplicate delivery and restart. Watermarks express progress assumptions; they are not guarantees that the world will never send an older event.Event partitionsWatermark stateWindow operatorCheckpoint sink
Compute stateful event-time results despite late data, duplicate delivery and restart. Watermarks express progress assumptions; they are not guarantees that the world will never send an older event.

Workload and limiting resource

Hypothetical 1,000 events/s with a 10-minute deduplication horizon retain up to 600,000 event identities before expiry. At 32 selected bytes/identity that is 19.2 MB raw, excluding state-engine overhead. Doubling lateness can double this component under steady-rate assumptions.

Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.

Mutation or publication path

Stream processing: mutation boundaryAssign event identity and event time. Then: Update deduplicated window state. Then: Commit recoverable progress/state with the selected sink boundary.Step 1
Assign event identity and event time.
Step 2
Update deduplicated window state.
Step 3
Commit recoverable progress/state with the selected sink boundary.
Assign event identity and event time. Then: Update deduplicated window state. Then: Commit recoverable progress/state with the selected sink boundary.
  1. Assign event identity and event time.
  2. Update deduplicated window state.
  3. Commit recoverable progress/state with the selected sink boundary.

Observation and recovery path

Stream processing: observation boundaryRead a result with provisional/final semantics. Then: Apply late corrections under a bounded policy. Then: Restore checkpoints and replay retained input safely.Step 1
Read a result with provisional/final semantics.
Step 2
Apply late corrections under a bounded policy.
Step 3
Restore checkpoints and replay retained input safely.
Read a result with provisional/final semantics. Then: Apply late corrections under a bounded policy. Then: Restore checkpoints and replay retained input safely.
  1. Read a result with provisional/final semantics.
  2. Apply late corrections under a bounded policy.
  3. Restore checkpoints and replay retained input safely.

Failure that changes the decision

Hypothetical scenario: A payment click arrives after the finalization watermark. Route it to the declared correction/late-data path rather than silently changing a supposedly final result.

Attempt this decision before reading the explanation

Does a checkpoint make an arbitrary external sink exactly once?

Only if sink effects participate in a compatible commit/recovery protocol or are independently idempotent. State recovery alone does not undo duplicate remote effects.

Supporting mechanism analysis

Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.

Hypothetical scenario. Northwind’s seller dashboard needs product-view counts. A popular product concentrates increments on one key. Maya accepts an approximate display; Dev suggests using that same count to enforce a limited promotion allowance. Priya asks whether those decisions permit the same uncertainty.

Maya: “Define the event and the decision before choosing how to distribute the count.”

Atomicity protects the increment operation, not the identity of the event being delivered. A repeated event can produce another perfectly atomic increment.

This exposes the work needed for deduplication and aggregation. Then decide whether the chosen read is suitable for a display, an allowance or neither.

A view might mean an HTTP request, a rendered product, a session seeing the product or a unique authenticated viewer. These are different populations. Retries, refreshes and bots change the relationship between them. Northwind chooses accepted display events for this example and records which events qualify.

The seller dashboard can accept an explicitly delayed aggregate if that meets its product contract. A scarce promotion allowance cannot safely use an arbitrarily delayed total as if it were current authority. One derived counter can support reporting while a separate guarded decision governs allocation. Reusing a convenient number for both silently changes the safety argument.

Also decide whether corrections are possible. Duplicate removal, invalid-event filtering and deletion obligations may revise the aggregate. A monotonic display count and a corrected accounting total may therefore need distinct definitions. The interface should not promise exact uniqueness when the accepted event stream does not establish it.

Redis provides an integer increment operation for a key. That can avoid a read-modify-write race at the selected server, but it does not divide one key’s work across independent owners automatically. More shards help different keys. A single popular product still concentrates its increments unless the data model deliberately splits that aggregate.

Northwind proposes several component counters per product, with each qualifying event assigned to one component. Writers spread increments across them; a reader obtains the components and combines them. The representation distributes write work by increasing read and coordination work. It must define how events keep their assignment across retries and migration.

Hypothetical scenario. Three increment components reduce one hot writer, but a report reading them at different instants may combine values that never existed together. A point-in-time total requires a snapshot or another declared observation protocol; eventual component convergence alone is a weaker statement.

A dashboard count may tolerate lag while an inventory grant cannot. Do not grant exclusive units by reading a sum of independently changing components and then incrementing one. Escrow can allocate bounded local rights under a different protocol, but requires conserving those rights across transfer, loss and restart. The reporting counter is not that protocol.

Hypothetical worked example. Select nine hundred qualifying events per second for one hot product and three components. Under an assumed exactly even assignment, each receives 900 ÷ 3 = 300 increments per second. This is an idealized distribution; random assignment produces variation and a poor key choice can preserve the hotspot.

Choose observed component values of 120, 90 and 110. The reporting sum is 120 + 90 + 110 = 320. A reader now needs three component observations instead of one logical counter read. At a selected fifty dashboard reads per second, that is 50 × 3 = 150 logical component reads per second, before retries and caching.

If a worker increments a component and loses its reply, another delivery may increment again. Each individual increment can be atomic while the logical event is counted twice. Stable event identity and a protected transition are required where the definition counts logical events once.

One option retains processed event identities with the aggregate transition in an appropriate authoritative boundary. Another derives aggregates from retained accepted events and rebuilds them under a defined replay contract. Both have storage, retention and recovery costs. An ephemeral deduplication cache cannot promise indefinite recognition of old replayed events.

Routing an event to another component on retry introduces a further trap. Per-component deduplication can miss the repeated identity if the first attempt used a different component. Preserve assignment or enforce identity across the full operation boundary. Resharding must account for in-flight attempts and retained history, not only new traffic.

Reading components sequentially does not automatically obtain a snapshot of one instant. With transfers, resets or corrections, a combined observation can include incompatible stages. Even with only positive independent increments, the reader must explain which freshness and completeness promise it offers rather than casually labeling the result current.

Hypothetical scenario. Define a product-view report for the event-time interval [12:00:00,12:01:00). Event time is when the view was recorded at its source; processing time is when the aggregation handles it. Retain event identity, product, event timestamp and schema generation. Suppose the initial result contains events E1 and E2, so its unique count is two.

Flink’s window documentation explains retained state for allowed lateness, late firings and side outputs. This exercise adds explicit identity deduplication and a revision-aware sink; a window operator alone does not establish either. Keep source positions, deduplication state and aggregate progress in a compatible recovery boundary. Replay after that state expires needs a new complete rebuild generation or retained identity evidence. Route older corrections deliberately rather than claiming that a closed display total is permanently complete.

Redis’s INCR documentation defines the integer-key operation. It supplies a concrete building block, not an application-level promise about unique views, distributed snapshots or surviving every failure. The aggregation policy must establish those properties separately.

Hypothetical failure scenario. A promotion permits a bounded number of accepted claims. Several workers read a delayed dashboard total, each sees remaining allowance and each accepts another claim. The reporting aggregate remains internally understandable, yet the promotion limit is exceeded.

Move the scarce-rights decision to an enforcing boundary. A centralized conditional transition is one possibility. Deliberately allocated rights across owners are another, with a proof that their combined grants cannot exceed the total. A periodically summed display counter is insufficient merely because its arithmetic is correct.

Layer 3 · Internals

Apache Flink distinguishes event time from processing time and tracks progress with watermarks. A watermark is a progress estimate used by operators; it is not proof that no older event will ever arrive. Idle input partitions, clock mistakes and unequal producer delays affect when windows can close or must accept corrections.

Checkpointing records operator state and stream positions for recovery. An external sink must participate in a compatible commit or idempotency protocol before the end-to-end effect can be described as exactly once. Replaying a checkpoint into a non-idempotent HTTP endpoint can still repeat the external effect. Choose a late-data policy: update an earlier result, emit a correction, route to a separate stream, or discard with explicit accounting. State size follows retained keys and window lifetimes as well as event rate. Increasing allowed lateness therefore changes storage and recovery time, not just answer freshness. A window result used for billing needs a different finality statement from a provisional dashboard.

Trade-offs and limits

ApproachProvidesRequires
Provisional window updatesReturns useful early aggregates.Consumers must apply revisions and corrections.
Finalized horizon with late side outputCreates a clear normal-path finality boundary.Events beyond the horizon require separate accounting or rejection.

Recovery decision

Hypothetical scenario: A payment click arrives after the finalization watermark. Route it to the declared correction/late-data path rather than silently changing a supposedly final result.

Only if sink effects participate in a compatible commit/recovery protocol or are independently idempotent. State recovery alone does not undo duplicate remote effects.

Write your design before revealing the review

Does a checkpoint make an arbitrary external sink exactly once?

Evidence you can explain in your own design

Drafts and self-review are stored only in this browser. They are separate from reading completion.

Compare your decision

Only if sink effects participate in a compatible commit/recovery protocol or are independently idempotent. State recovery alone does not undo duplicate remote effects.

A payment click arrives after the finalization watermark. Route it to the declared correction/late-data path rather than silently changing a supposedly final result.

Check your understanding

Does a checkpoint make an arbitrary external sink exactly once?

Only if sink effects participate in a compatible commit/recovery protocol or are independently idempotent. State recovery alone does not undo duplicate remote effects.

How would you recover from this failure: A payment click arrives after the finalization watermark. Route it to the declared correction/late-data path rather than silently changing a supposedly final result.

Start with the exact boundary that failed. Assign event identity and event time. Update deduplicated window state. Commit recoverable progress/state with the selected sink boundary. Then recover evidence through the observation path: Read a result with provisional/final semantics. Apply late corrections under a bounded policy. Restore checkpoints and replay retained input safely. Preserve the distinction between a confirmed state change and an unavailable response.

Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?

Hypothetical 1,000 events/s with a 10-minute deduplication horizon retain up to 600,000 event identities before expiry. At 32 selected bytes/identity that is 19.2 MB raw, excluding state-engine overhead. Doubling lateness can double this component under steady-rate assumptions. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Compute stateful event-time results despite late data, duplicate delivery and restart. Watermarks express progress assumptions; they are not guarantees that the world will never send an older event.

Which component in this topology could be removed from a smaller first deployment?

Event partitions, Watermark state, Window operator, Checkpoint sink name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Assign event identity and event time.

What evidence must a caller have before relying on the observation path?

Read a result with provisional/final semantics. Apply late corrections under a bounded policy. Restore checkpoints and replay retained input safely. Only if sink effects participate in a compatible commit/recovery protocol or are independently idempotent. State recovery alone does not undo duplicate remote effects.

45-minute interview rubric

  1. 00–05: scope stream event and checkpointed operator state.
  2. 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
  3. 12–28: draw checkpointed operator state, numbered writes and reads.
  4. 28–40: challenge recovery: Declare lateness, deduplication and sink commit behavior.
  5. 40–45: defend event_id placement, observations and remaining assumptions.

Go deeper

  • Stateful Stream Processing | Apache Flink · Primary document · nightlies.apache.org. Declare lateness, deduplication and sink commit behavior. Verified 2026-10-26.
  • Windows | Apache Flink · Primary document · nightlies.apache.org. Declare lateness, deduplication and sink commit behavior. Verified 2026-10-26.
  • INCR | Docs · Primary document · redis.io. Declare lateness, deduplication and sink commit behavior. Verified 2026-10-26.

Decision log

Declare lateness, deduplication and sink commit behavior.

Preserve stream event identity and checkpointed operator state ownership.

Revisit changed workload, observations or recovery objectives.