This page is meant as a template for writing a FLIP. To create a FLIP choose Tools->Copy on this page and modify with your content and replace the heading with the next FLIP number and a description of your issue. Replace anything in italics with your own description.

Document the state by adding a label to the FLIP page with one of "discussion", "accepted", "released", "rejected".

Discussion threadhttps://lists.apache.org/thread/zgj32q8b6mo6tp47hlf4kgmwmnqr38j4
Vote thread
JIRA
Release<Flink Version>

Please keep the discussion on the mailing list rather than commenting on the wiki (wiki discussions get unwieldy fast).

Motivation

Streaming jobs frequently need to (re)process a large backlog of historical data before they catch up with fresh, real-time data. This happens whenever:

  • a new stateful query is started against sources with long (or infinite) data retention,

  • an existing query is modified in a way that is not state compatible and must be resubmitted from scratch.

Processing this backlog in STREAMING execution mode can be slow. The dominant costs are the ones the STREAMING mode pays for low-latency, incremental processing of unbounded data: a disk-based state backend (e.g. RocksDB) with random access across the whole key space, and checkpointing while reprocessing. For large, complex stateful queries the catch-up phase can take many hours.

Flink already has an execution mode that is designed for exactly this kind of workload: the BATCH execution mode (FLIP-134/FLIP-140). Given a bounded input, the same job graph can be executed stage by stage with blocking, key-sorted shuffles and the purely in-memory BatchExecutionKeyedStateBackend, which holds state for only a single key at a time. In our benchmarks of stateful SQL queries this is 1.3x-15x faster than STREAMING execution — the more complex and stateful the query, the bigger the difference. Please see the benchmark results below.

What is missing is a bridge between the two modes: today the state built up during a BATCH execution is simply discarded at the end of the job. There is no way to run the backlog through the batch engine and then continue the same query in STREAMING mode from where the batch execution left off.

This FLIP proposes such a bridge, called state catch-up:

  1. Execute the (unchanged) streaming pipeline in BATCH execution mode over the bounded backlog.

  2. At the end of input, produce a regular savepoint in canonical format containing the state of all operators, plus source positions describing where the bounded input ended.

  3. Start the same pipeline in STREAMING execution mode from that savepoint; sources resume exactly where the batch phase stopped.

Crucially, this works because BATCH and STREAMING execution modes run the same job graph with the same operators, state descriptors and serializers. They just run that same job graph in a different manner. There is no state translation step — the savepoint written by the batch phase is directly and trivially restorable by the streaming job.

A note on scope for SQL: This proposal is not about migrating from Flink Batch SQL to Streaming SQL. Batch SQL and Streaming SQL use different planners, produce differently shaped plans and use incompatible operator implementations (see Rejected Alternatives). Instead, for Table API/SQL the streaming planner and streaming physical operators (StreamExecNodes) are used in both phases; only the runtime execution mode differs.

A note on scope for the DataStream API: the job graph is already identical across modes, so nothing special is needed on the API side. With this FLIP user will be able to use BATCH execution mode to catch up the state of his DataStream API jobs.

Proposed Changes

Two-phase workflow

State catch-up consists of two separately submitted jobs running the same pipeline:

  1. Batch phase (producer): the pipeline is submitted with execution.runtime-mode: BATCH and execution.state-catch-up.mode: BATCH, with bounded sources (e.g. Kafka sources with stopping offsets). The job processes the whole backlog and, as part of successful completion, writes a canonical-format savepoint to the configured savepoint directory.

  2. Streaming phase (consumer): the pipeline is submitted with execution.runtime-mode: STREAMING and execution.state-catch-up.mode: BATCH, restoring from the savepoint produced in phase 1. Sources convert their bounded end positions into streaming start positions and the job continues processing fresh data with exactly-once semantics.

Orchestration of the two phases (submit batch job, wait for completion, locate the savepoint, submit the streaming job) is left to the user or an external driver/control plane. Automatic, in-JobManager switching between the modes is a possible future extension (see Rejected Alternatives).

Running the streaming plan on the batch engine

For Table API/SQL, DefaultPlannerFactory will return the StreamPlanner — instead of the BatchPlanner — when the runtime mode is BATCH and state catch-up is enabled. The resulting plan consists of streaming physical operators (including streaming-only ones such as ChangelogNormalize and SinkUpsertMaterializer), so all state that the streaming phase will need is populated, and every operator's state layout matches 1:1.

The batch phase then executes this plan with the standard batch runtime stack:

  • Scheduler: AdaptiveBatchScheduler — stage-by-stage execution, dynamic parallelism derived from actual data volumes.

  • Shuffles: blocking, persisted partitions (SortMergeResultPartition / BoundedBlockingResultPartition).

  • Sorted keyed input: SortingDataInput / MultiInputSortingDataInput sort each keyed operator's input by key, so that all records for one key arrive consecutively.

  • State backend: BatchExecutionKeyedStateBackend, keeping only the current key's state in memory and dropping (in this FLIP: snapshotting, see below) it on key change.

Stable sorting

Streaming operators emit and consume changelogs. Retractions (-U/-D) must never overtake the insertions they retract, otherwise downstream state gets corrupted. The blocking shuffle implementations already preserve a stable order, but the record sorters do not guarantee stability for equal keys. SortingDataInput and MultiInputSortingDataInput will therefore tag each record with a monotonically increasing sequence number that is used as the final tie-breaker in the sort key, making the sort stable.

Producing a savepoint from a batch job

This is the core runtime change: a batch job must be able to complete with a savepoint. Today the CheckpointCoordinator is never started for batch jobs, and several of its assumptions do not hold there. The savepoint is written in canonical format, i.e. state-backend agnostic, so the streaming phase can restore it into any backend (typically RocksDB).

The mechanics of how the keyed state is serialized into canonical form inside BatchExecutionKeyedStateBackend (incremental snapshotting on every key change, sort/spill/merge of the resulting entries) are deliberately out of scope of this FLIP and will be covered by a separate, companion FLIP. This FLIP covers the job-level orchestration of the savepoint.

One progressive savepoint spanning the whole execution

A batch job cannot use the normal checkpoint-barrier flow: stages run one after another, and by the time the last stage runs, upstream tasks are long gone. Also, with the batch scheduler the ExecutionJobVertexes are initialized lazily (their parallelism is only decided right before they run — FLINK-25032), while the CheckpointCoordinator traditionally expects all vertices (and their OperatorCoordinators) to exist up front.

Therefore a single, job-wide savepoint is triggered once, at scheduling start (DefaultExecutionGraph#triggerBatchSavepointIfStateCatchUp), and then accumulates progressively over the whole execution:

  1. A PendingCheckpoint is created when scheduling starts. Checkpointing is enabled for the
    dynamic (batch) execution graph when state catch-up is active.

  2. As the scheduler initializes vertices (possibly several at once, independent DAG branches run
    concurrently), their tasks are added to the pending checkpoint and are immediately sent the snapshot trigger. No checkpoint barriers are used; the trigger information is delivered via RPC.

  3. A task defers the actual snapshot until it reaches end of input; the state accumulated for the final key plus all previously spilled state is then written out and acknowledged. The task's mailbox loop is kept alive until the snapshot's synchronous phase completes.

  4. OperatorCoordinators (e.g. source enumerators) are checkpointed after all tasks of their vertex have acknowledged — the reverse of the streaming order. This is safe because after end of input there are no more events flowing between coordinators and tasks, and it is necessary because coordinator state (e.g. final split positions) is only complete once the tasks have finished.

  5. When all vertices of the DAG have been added and acknowledged, the pending checkpoint completes and the _metadata file is written.

On the coordinator side this is managed by a small state machine (BatchSavepointState): WaitingForSavepointInitialization → RunningSavepoint → SavepointCompleted | SavepointFailed.

The job only transitions to FINISHED once the savepoint future completes successfully; a savepoint failure fails the job immediately (possibly hours before the job would otherwise finish), rather than letting it run on and produce no usable artifact.

Failure semantics: no task restarts

In the batch phase the restart strategy is forced to no-restart (with a WARN log if the user configured something else). The single progressive savepoint is a one-shot artifact: it is triggered once at scheduling start, and after a task failure the savepoint state machine is already in a terminal state, so restarted tasks could never re-contribute to it. Any failure — including a failed savepoint — therefore fails the whole batch job, and the external orchestration decides whether to retry the catch-up from scratch. Support for fine-grained restarts of the batch phase is future work.

Note that this override is required for correctness: enabling checkpointing normally flips the default restart strategy to exponential-delay with unbounded attempts, which for a state-catch-up job would lead to a restart loop that can never produce a savepoint.

Exactly-once sinks

Savepoints do not trigger notifyCheckpointComplete, and the batch phase does not commit sink transactions. Pending committables are persisted in the savepoint like on any savepoint, and are committed by the streaming phase after restore, following the standard two-phase-commit protocol. This keeps end-to-end exactly-once semantics across the batch→streaming handoff without any sink-specific changes.

Watermarks, timers and end of input

Stock BATCH execution mode ends a job by draining it: it emits MAX_WATERMARK, which fires all registered event-time timers, and calls endInput() on all operators. For state catch-up this would produce incorrect results — the query is not finished, only the backlog is. Windows would fire as if the input had ended, and results emitted that way could never be retracted by the streaming phase.

The batch catch-up phase therefore behaves differently:

  • No watermarks are emitted. As a consequence, no event-time timers fire during the batch phase.

  • Unfired timers are retained and persisted. Instead of firing the outgoing key's timers on every key change, the batch timer service drains them into the savepoint, under the same canonical timer state names used by the streaming timer service. The restored streaming job fires them once its own watermark (or processing-time clock) advances past them.

  • End of input does not drain the pipeline. Tasks finish with StopMode.NO_DRAIN, so endInput() is not called on operators; the input sorters still flush their buffered records on the stop signal.

Deriving correct watermarks from the actual input — so that windows can already fire and be pruned during the batch phase — is a future improvement (see Limitations).

Source handoff: from bounded end positions to streaming start positions

The batch phase runs with bounded sources; the savepoint captures each split with the position range it covered. On restore in the streaming phase, the source converts that bounded state into resumable streaming state — typically, each bounded split's end position becomes the start position of an unbounded split.

Sources without support for such automatic conversion can still be handed off manually: if the batch phase ran with a bounded source with an explicit stopping offset, the user can replace it in the streaming submission with an unbounded source that starts from that same offset.

The concrete implementation of the automatic conversion for the Kafka connector will be proposed in a separate FLIP for the flink-connector-kafka repository.

Limitations (v1) and future work

  • No watermarks during the batch phase. Since the batch phase emits no watermarks, no windows fire and no timer state is pruned until the streaming phase's watermark catches up: all pending windows and timers of the whole backlog are carried through the savepoint. For long backlogs with fine-grained windows this inflates the savepoint and defers a large burst of timer firings to the streaming phase. Deriving correct watermarks from the actual input — firing and pruning windows as the backlog is processed — is a future improvement. Note that state catch-up benefits are largest for non-windowed stateful queries (regular joins, group aggregations, deduplication, changelog normalization, sink materialization) in the first place.

  • No restarts within the batch phase. A failure requires redoing the whole catch-up (see above).

  • Changelog squashing. Streaming operators executed in batch mode still emit the full intermediate changelog (+I/-U/+U chains per key). Squashing it to the final value per key would reduce shuffle volume and downstream work, and is a possible future optimization.

  • Automatic mode selection. Deciding automatically whether a given job would benefit from state catch-up (e.g. based on the size of the backlog) is out of scope; the mode is selected explicitly via configuration (see Rejected Alternatives).

  • Dynamic switching between STREAMING and BATCH. In the future, a job could switch back and forth between the two modes during its lifetime — for example, temporarily switching to BATCH when a sudden load spike causes a backlog to accumulate, or after the job has been down for a longer period of time.

  • Continuous catch-up as a form of micro-batching. Taking dynamic switching to the extreme, some jobs could run permanently in catch-up mode: the job is continuously re-submitted, with each run quickly processing the records that arrived while the previous run was executing. This would offer better performance at the cost of higher end-to-end latency.

Both dynamic switching and continuous micro-batching additionally require BatchExecutionKeyedStateBackend to support recovery from a canonical savepoint (currently it can only write one), which is future work.

Public Interfaces

Configuration

One new user-facing configuration option in ExecutionOptions (marked @Experimental):
 

@Experimental
public static final ConfigOption<StateCatchUpMode> STATE_CATCH_UP_MODE =
        ConfigOptions.key("execution.state-catch-up.mode")
                .enumType(StateCatchUpMode.class)
                .defaultValue(StateCatchUpMode.DISABLED)
                .withDescription(
                        Description.builder()
                                .text(
                                        "Specifies the state catch-up mode, when `%s: %s` is used: ",
                                        code(RUNTIME_MODE.key()),
                                        code(RuntimeExecutionMode.STREAMING.name()))
                                .list(
                                        text(
                                                "%s: no state catch-up will be used.",
                                                code(StateCatchUpMode.DISABLED.name())),
                                        text(
                                                "%s: BATCH execution mode will be used to perform state catch-up of Streaming jobs. "
                                                        + "Once the backlog is processed, savepoint will be created and job can be restarted from that savepoint in the STREAMING mode. "
                                                        + "If using Flink SQL or Table API, Flink Streaming SQL (StreamPlanner and Streaming operators) will be used in BATCH execution mode",
                                                code(StateCatchUpMode.BATCH.name())))
                                .build());

/** State catch-up mode for batch execution. */
@Experimental
public enum StateCatchUpMode {
    /** No state catch-up will be used. */
    DISABLED,

    /** {@link RuntimeExecutionMode#BATCH} will be used to perform state catch-up. */
    BATCH
}


The option is interpreted together with execution.runtime-mode:

execution.runtime-mode

execution.state-catch-up.mode

Meaning

BATCH

BATCH

Batch (producer) phase: run the streaming plan on the batch engine, finish with a canonical savepoint.

STREAMING

BATCH

Streaming (consumer) phase: restore from a catch-up savepoint; source enumerators convert bounded end positions to streaming start positions.

any

DISABLED (default)

State catch-up inactive; behavior unchanged.

Additional options tuning the savepoint generation inside the batch keyed state backend (memory budget for sort buffers, spill-file compression) belong to the companion FLIP covering BatchExecutionKeyedStateBackend snapshot support and are not part of this proposal.

Other public-facing behavior

  • The savepoint produced by the batch phase is a regular canonical-format savepoint: it can be inspected and managed with existing tooling and is restorable by any state backend.

  • Sources opt into the catch-up handoff by converting bounded end positions into streaming start positions on restore; the Kafka connector implementation will be proposed in a separate FLIP.

  • In the batch phase the configured restart strategy is overridden with no-restart

Compatibility, Deprecation, and Migration Plan

There is no impact on existing users. The feature is opt-in behind execution.state-catch-up.mode, whose default value DISABLED preserves the current behavior of both execution modes. All new interfaces are marked @Experimental. Nothing is deprecated and no migration is needed.

Test Plan

  • Unit tests for the progressive savepoint trigger state machine in the CheckpointCoordinator and for the stable-sort changes.

  • Operator-level restore tests verifying batch-populated state restores correctly into streaming operators for all keyed state types (value, list, map, reducing, aggregating) and namespaces.

  • End-to-end integration tests covering: batch phase producing a savepoint, streaming phase restoring from it and continuing with exactly-once results, savepoint failure handling, and the forced no-restart behavior.

  • The feature has been implemented and is being validated at Confluent and IBM; the accepted version will be re-validated there before merging.

Benchmarked queries

Example benchmark results on a couple of queries. Generally speaking, the more complex the query and operators that are being used, the higher the performance improvement.

 
 
 

Query

Batch Execution Mode

Streaming Execution Mode

Improvement

insert into `product-average-price`
select 
  o1.`product_id`,
  o1.`customer_id`,
  avg(o1.`price`)
from
 `orders-bounded` o1,
 `orders-bounded` o2
where
 o1.`order_id` = o2.`order_id`
group by
 o1.`customer_id`,
 o1.`product_id`

This query had a SinkMaterializer with quite large duplication of values

10min 44s

2h 44min

14.9x

insert into `keyvalue`
select 
  2,
  count(*)
from
 `orders-bounded` o1,
 `orders-bounded` o2
where
 o1.`order_id` = o2.`order_id`

7m 31s

29m 58s

4x


insert into `keyvalue` select 2, count(*) from `orders-bounded`

2m 0s

2m 34s

1.3x


The whole TPC-DS suite is faster on average by ~6x when using PoC version of the state catch up mode.

Rejected Alternatives

Bootstrapping with Batch SQL and translating the state

Running the backlog through Flink Batch SQL and converting the result into streaming operator state is not feasible:

  • Batch and Streaming SQL use different planners; the same query can compile to completely different plan shapes (different optimization rules, different operator order).

  • Streaming-only operators such as ChangelogNormalize and SinkUpsertMaterializer have no batch equivalent, yet their state must be bootstrapped for correct results.

  • Even for logically matching operators (e.g. joins), the batch and streaming implementations organize their state completely differently; there is no practical translation between them.

Executing the streaming plan in BATCH execution mode sidesteps all three problems by construction: identical graph, operators and state layout.

Bootstrapping with the State Processor API

The State Processor API requires users to re-implement each operator's state-building logic by hand and to know the internal state layouts of SQL operators — which are internal, version-specific implementation details. This is impractical for SQL pipelines and error-prone for DataStream ones.

In-JobManager mode switching (single job)

Instead of two submitted jobs, the JobManager could run the batch phase and then switch the same job to streaming internally. This would give lower handoff latency and would enable dynamic back-and-forth switching, but it requires invasive changes to the scheduler/ExecutionGraph lifecycle. External orchestration of two jobs is far simpler and sufficient for the target use case; internal switching remains a possible future extension on top of the mechanisms introduced here.

Committing sink transactions at the end of the batch phase

Committing transactions before the savepoint is persisted breaks exactly-once: if a failure occurs between committing and persisting the savepoint (or between commits of multiple committables), there is no persisted state to retry the commits from, especially once TaskManagers and their local shuffle data are gone. Deferring all commits to the streaming phase reuses the standard savepoint semantics (no notifyCheckpointComplete) and the existing two-phase-commit recovery path.

Distributed/streamed savepoint upload via the checkpoint barrier flow

Reusing the normal CheckpointBarrier propagation to snapshot the batch job does not work: stages execute sequentially, so there is no point in time where a barrier could flow through the whole pipeline. The progressive, coordinator-driven savepoint described above is the alternative.