AlgoViz

Apache Flink

hard 28 min

Apache Flink runs programs that never end: they read events one at a time, remember things per key, and survive crashes by taking consistent snapshots while the data keeps moving.

Video lesson · Chapter 1 of 5

Count clicks while they are arriving

0:00 / 4:00

Flink checkpoints in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Apache Flink is a distributed engine for stateful computation over streams. A stream can be unbounded, such as clicks that never stop, or bounded, such as a file. One runtime handles both.

You write a program as a chain of operators: read, transform, group by key, aggregate, write. Flink runs many copies of each operator on a cluster, keeps the state of each copy close to the code, and takes care of time, failures and scaling.

Records are handled as they arrive instead of being collected into small batches first. That is why results can appear within milliseconds to seconds, depending on windows, sinks and configuration.

Why it exists

Counting events is easy until a machine dies. If the counter was in memory it is gone, and if you read the input again you count twice. Flink ties the input position and the state together in one snapshot, so after a crash both return to the same moment.

Events also arrive late and out of order. A phone in a tunnel sends its clicks ten minutes later. Flink separates when something happened from when you saw it, so a replay of old data can give the same answer.

The general ideas (windows, time, delivery guarantees) belong to stream processing. This page is about the product.

A short history

  1. January 2015

    The Apache Software Foundation announces Flink as a top-level project.

  2. March 2016

    Flink 1.0.0 is released, with stability promises for its public interfaces.

  3. 2017

    The paper "State Management in Apache Flink" appears in the VLDB proceedings and describes the snapshot algorithm.

  4. March 2025

    Flink 2.0.0 removes old interfaces and introduces disaggregated state, where state can live in remote storage.

Words to know

JobManager
The process that schedules tasks, triggers checkpoints and handles recovery.
TaskManager
A worker process. It offers task slots and runs the operators.
Keyed state
Memory that belongs to one key, such as one user. It is available after keyBy.
Checkpoint
An automatic consistent snapshot of state and input positions, used after a failure.
Savepoint
A snapshot you ask for and own, used for upgrades and planned moves.
Watermark
A marker in the stream that says event time has probably reached this point.
Backpressure
A slow operator slowing down everything upstream of it.

How it works

Step through the idea, or press Play.

Step 1 of 3

Read and group. Sources read partitions in parallel, keyBy sends each key to one task

Understand it

Start here

The potters and the yellow marker

Imagine potters along a moving belt. Each one counts something, and nobody may stop the belt to take notes. So they send a yellow marker down the belt. Whoever sees the marker copies their slate into a notebook. When everybody has copied, the page shows one moment that everyone agrees on.

The marker on the belt
Notebookred2blue1Count the pots as they pass

Nothing is counted twice, because the counts and the place on the belt go back together.

What you get

Why teams choose it

  • One record at a time

    No micro-batch to wait for. Useful for fraud checks, alerts and live dashboards.

  • Exactly-once state

    Distributed snapshots mean a failure neither loses nor repeats a state update.

  • Event time

    Out-of-order and late events land in the right window. A replay can give the same result.

  • Rich state

    Value, list, map, reducing and aggregating state per key, plus broadcast state for rules that every task needs.

  • Batch and stream

    Batch is a stream with an end. The same APIs and runtime serve both.

  • SQL and Table API

    Write a pipeline as a query. The optimizer plans joins and aggregations.

Pick the API by how much control you need

APIYou writeGood for
SQLA queryAnalysts, ETL, quick prototypes
Table APIA query in Java or PythonThe same, inside a program
DataStreammap, filter, keyBy, window, joinMost custom pipelines
ProcessFunctionCode per event, with state and timersPatterns that no window fits
Flink also ships a complex event processing library (CEP) for patterns such as "three failed logins, then a payment".

Architecture

Who does what in a cluster

A Flink cluster

A client submits a job to the JobManager inside the Flink cluster. The JobManager deploys tasks to two TaskManagers. Kafka feeds both TaskManagers, results go to a sink, and both TaskManagers write checkpoints to object storage.
The thick boxes are processes you run. Kafka, storage and the sink are separate systems.
  1. 1

    Submit

    The program becomes a job graph, a logical chain of operators. The JobManager turns it into an execution graph with a parallelism for every operator.

  2. 2

    Deploy

    The ResourceManager part hands out slots. Tasks are threads inside TaskManager JVMs. Neighbouring operators are often chained into one thread, and a slot can hold a whole slice of the pipeline.

  3. 3

    Ingest

    Each source task reads its own partitions, assigns event timestamps and emits watermarks.

  4. 4

    Process

    keyBy hashes the key and sends the record over the network to the task that owns it. That task updates local state.

  5. 5

    Checkpoint

    The JobManager triggers a snapshot. Operators copy state to durable storage in the background.

  6. 6

    Write

    Sink tasks write results. A transactional sink commits only after the checkpoint succeeded.

The processes

PartJobIf it dies
JobManager: DispatcherAccepts submissions, starts a JobMasterOne instance by default: no new jobs
JobManager: ResourceManagerHands out task slotsThe same process, so the same fate
JobManager: JobMasterRuns one job, triggers checkpointsWith high availability, a new leader resumes
TaskManagerRuns tasks in slotsAffected tasks restart from the checkpoint
ZooKeeper or KubernetesLeader election and pointers to job metadataNeeded only for high availability
By default there is a single JobManager. High availability needs several, with ZooKeeper or Kubernetes services for leader election, and durable storage.

State

Keyed state and where it lives

After keyBy(user), every user has a private drawer. Only one task owns a key, so it can read and change the drawer without locks or a network call. State types are ValueState, ListState, MapState, ReducingState and AggregatingState.

From key to task

Keys are packed into key groups. When parallelism changes, whole groups move to other tasks.

State backends

BackendState lives inStrengthCost
HashMap (default)Java heap objectsFastest accessLimited by memory, garbage collection
EmbeddedRocksDBSerialized bytes on local diskVery large state, incremental checkpointsEvery access serializes, about ten times slower on average
ForSt (experimental)Remote storage, local disk as a cacheState beyond local disk, light recoveryNot recommended for production yet
RocksDB is an LSM tree. Set state.backend.type to hashmap, rocksdb or forst. Incremental checkpoints are off by default.

Which backend?

Measure. There is no fixed size in megabytes where the answer flips.

Snapshots

How a checkpoint works

Flink uses a variant of the Chandy-Lamport algorithm. A barrier travels in the stream like a record. Everything before it belongs to the snapshot, everything after it does not.

One checkpoint with a transactional sink

State is copied asynchronously, so records keep flowing while the upload runs.

Alignment, step by step

  1. 1

    Barrier on input A

    An operator with two inputs stops reading A, so no later record slips into the snapshot.

  2. 2

    Keep reading B

    Records on B before its barrier still belong to the snapshot.

  3. 3

    Barrier on input B

    Now both inputs are at the cut. The operator snapshots and forwards one barrier.

  4. 4

    Go on

    Input A is released again.

Aligned (default)

  • Small snapshots: state only
  • Simple meaning: a clean cut
  • Slow when inputs are backed up

Unaligned

  • Barriers overtake waiting records
  • Finishes under backpressure
  • Stores in-flight records, so snapshots and storage traffic grow

A middle way is the aligned checkpoint timeout: start aligned, and switch to unaligned when the alignment takes too long.

Checkpoint or savepoint?

CheckpointSavepoint
Made byFlink, on an intervalYou, when you ask
Used forRecovery from failureUpgrades, moving, planned rescaling
Deleted byFlink, unless you retain itOnly you
FormatNative to the backend, may be incrementalCanonical by default, portable across backends

Failure

What happens when a worker dies

  1. 1

    Detect

    Heartbeats stop or a task throws an error.

  2. 2

    Choose what restarts

    Flink restarts the smallest set of connected tasks. In a streaming job with a keyBy, the tasks are usually all connected, so the whole job restarts.

  3. 3

    Restore

    State comes back from the last completed checkpoint and sources rewind to the positions saved in it.

  4. 4

    Replay

    Records after the checkpoint are processed again. Their earlier effects on state were discarded, so state counts each once.

How long until the job has caught up?

Tcatch up=r×(tsince+trestart)c−r10,000×(60+30)40,000−10,000=30 sT_{\text{catch up}} = \frac{r \times (t_{\text{since}} + t_{\text{restart}})}{c - r} \qquad \frac{10{,}000 \times (60 + 30)}{40{,}000 - 10{,}000} = 30\ \text{s}
rr is the input rate, cc the most the job can process, tsincet_{since} the age of the checkpoint. With no spare capacity (cc equal to rr) the job never catches up.

Time

Event time, watermarks and windows

Kind of timeMeaningUse it when
Event timeWhen it happened, stamped in the eventAlmost all business logic
Processing timeThe clock of the machine handling itYou only care about now, and replays may differ

The usual watermark

W=max⁡(tevent)−B−1 msW = \max(t_{\text{event}}) - B - 1\,\text{ms}
BB is the bounded out-of-orderness you allow. It is not the same setting as allowed lateness, which keeps a window alive after it fired.

An event meets a window

Allowed lateness is zero by default, so a late event is dropped unless you ask for a side output.

Windows

WindowShapeExample
TumblingFixed, no overlapSales per 5 minutes
SlidingFixed, overlappingLast 5 minutes, every minute
SessionEnds after a gapA visit ends after 30 quiet minutes
GlobalEverything for a keyNeeds a custom trigger, for example every 100 events
CountA number of eventsAverage of the last 50 readings
A task with several inputs uses the smallest watermark of them. One silent partition can hold back every window, so configure idleness.

Output

Exactly-once, all the way out

The checkpoint protects state inside Flink. Outside, a restart replays records and a simple sink writes them again. You need one of two remedies.

Transactional sink

  • Write into an open transaction
  • Prepare when the barrier arrives
  • Commit after the checkpoint completes
  • Readers must ignore uncommitted data

Idempotent sink

  • Write by a stable key (upsert)
  • A repeat overwrites the same row
  • Simple and fast
  • Results may briefly step back during replay

Idempotent or transactional?

  1. 1

    Can the sink upsert by key?

    Then at-least-once plus upserts is simplest. See idempotency.

  2. 2

    Does it support transactions?

    Use the two-phase commit sink and accept delay of one checkpoint interval.

  3. 3

    Neither?

    Say at-least-once out loud and deduplicate later.

Speed

Backpressure and skew

Flink moves data between tasks with credits: a receiver tells the sender how many buffers are free. When a task is slow, credits run out, the sender waits, and the wait travels back to the source. That protects memory. It is a symptom to fix only when it lasts.

Find the slow operator

Each subtask reports busy, idle and backpressured time, which together make about 1,000 ms per second.

Red flags

You seeCauseRemedy
Event-time windows never fireNo watermark, or an idle partitionSet a watermark strategy and idleness
One subtask at 100% busyHot keyPre-aggregate, or salt the key and merge
Checkpoints time outBackpressure or huge stateFix the bottleneck, incremental or unaligned
Out of memoryLarge state on the heapRocksDB, TTL
Slow sinkOne request per recordBatch, async I/O, more partitions

Operations

Running it

Shell
# run a job detached, from a jar./bin/flink run --detached app.jar./bin/flink list --running# snapshot a running job, and keep it running./bin/flink savepoint $JOB_ID s3://bucket/savepoints# planned stop: take a savepoint, then finish./bin/flink stop --savepointPath s3://bucket/savepoints $JOB_ID# start the new version from that savepoint./bin/flink run --detached --fromSavepoint s3://bucket/savepoints/savepoint-abc app.jar
Prefer stop with a savepoint over cancel: it ends the job gracefully, from source to sink.
YAML
# config.yaml (Flink 2.x)state.backend.type: rocksdbexecution.checkpointing.interval: 60 sexecution.checkpointing.mode: EXACTLY_ONCEexecution.checkpointing.min-pause: 30 sexecution.checkpointing.timeout: 10 minexecution.checkpointing.incremental: trueexecution.checkpointing.dir: s3://bucket/checkpointsexecution.checkpointing.externalized-checkpoint-retention: RETAIN_ON_CANCELLATIONrestart-strategy.type: exponential-delayhigh-availability.type: kuberneteshigh-availability.storageDir: s3://bucket/ha
Flink 2.0 removed setters such as setStateBackend and RestartStrategies from the Java API. Use these options.

Before production

  1. 1

    Give every stateful operator a uid

    Without stable ids a savepoint cannot match state to the changed job.

  2. 2

    Match parallelism to the source

    More source tasks than Kafka partitions leaves some tasks idle.

  3. 3

    Choose application mode

    One cluster per application isolates jobs. A session cluster shares workers, so one crash can hit many jobs. Per-job mode was removed in 2.0.

  4. 4

    Watch four things

    Source lag, checkpoint duration and size, backpressure, restarts.

  5. 5

    Practise recovery

    Kill a TaskManager in staging and time the catch-up.

Choose

When Flink, and when not

Choose Flink

  • State and sub-second to second latency
  • Exactly-once state updates
  • Out-of-order events and event-time windows
  • Event patterns (CEP)
  • Streaming ETL into a lake such as Apache Hudi
  • Live features for machine learning
  • One code path for live data and replays
  • Streaming analytics in SQL

Choose something else

  • Plain batch: Spark is simpler for many teams
  • Ad-hoc queries on stored data: Trino or Presto
  • A small stream: a plain consumer will do
  • No streaming experience and no time to learn
  • Only moving messages: Kafka is enough
  • A one-time migration: a batch tool

The alternatives

ToolShared with FlinkDifferentBest for
Spark Structured StreamingSQL, Kafka, exactly-once, event timeMicro-batch by default, bigger batch and ML ecosystemTeams already on Spark
Kafka StreamsRocksDB state, event time, exactly-onceA library in your app, not a cluster. Kafka in and outKafka-only microservices
Apache BeamBatch and stream modelAn API that runs on Flink, Spark or DataflowPortability
Apache StormRecord at a time, low latencyAt-least-once at its core, lower-level spouts and boltsExisting systems only
Kafka Streams has event time but no watermark records: it tracks stream time from the records themselves.

Strengths

  • Record-at-a-time with low latency
  • Consistent state through snapshots
  • Correct results with late data
  • Large state on disk, incremental checkpoints
  • One API family for batch and stream
  • SQL, CEP and many connectors

Costs

  • A cluster to run, or the Kubernetes operator
  • Event time, watermarks and state take time to learn
  • JVM memory tuning
  • Large state makes slow checkpoints if untuned
  • Distributed state is hard to inspect
  • Smaller batch and ML ecosystem than Spark

Summary

The whole topic in one minute.

Flink processes events one by one and keeps state per key. Barriers flow through the stream with the data and mark a consistent cut, so a checkpoint holds both the state and the input position that match it. After a failure the job restores that checkpoint and reads the rest again.

Event time and watermarks make windows correct when data is late. End-to-end exactly-once needs a replayable source and a sink that commits together with the checkpoint, or one that is idempotent. Flink earns its operational cost when you need state, event time and low latency. Without those, choose something simpler.

  • Records flow one at a time through parallel operators. keyBy gives each key one owner.
  • A checkpoint stores state and input positions that match, marked by barriers.
  • Watermarks move event time forward. The smallest input wins.
  • End-to-end exactly-once needs a replayable source and a transactional or idempotent sink.
  • HashMap is the default backend. RocksDB is for large state.
  • Checkpointing is off until you set an interval.

Sources