Apache Flink
hard 28 minApache 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
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
January 2015
The Apache Software Foundation announces Flink as a top-level project.
March 2016
Flink 1.0.0 is released, with stability promises for its public interfaces.
2017
The paper "State Management in Apache Flink" appears in the VLDB proceedings and describes the snapshot algorithm.
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.
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.
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
| API | You write | Good for |
|---|---|---|
| SQL | A query | Analysts, ETL, quick prototypes |
| Table API | A query in Java or Python | The same, inside a program |
| DataStream | map, filter, keyBy, window, join | Most custom pipelines |
| ProcessFunction | Code per event, with state and timers | Patterns that no window fits |
Architecture
Who does what in a cluster
A Flink cluster
- 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
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
Ingest
Each source task reads its own partitions, assigns event timestamps and emits watermarks.
- 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
Checkpoint
The JobManager triggers a snapshot. Operators copy state to durable storage in the background.
- 6
Write
Sink tasks write results. A transactional sink commits only after the checkpoint succeeded.
The processes
| Part | Job | If it dies |
|---|---|---|
| JobManager: Dispatcher | Accepts submissions, starts a JobMaster | One instance by default: no new jobs |
| JobManager: ResourceManager | Hands out task slots | The same process, so the same fate |
| JobManager: JobMaster | Runs one job, triggers checkpoints | With high availability, a new leader resumes |
| TaskManager | Runs tasks in slots | Affected tasks restart from the checkpoint |
| ZooKeeper or Kubernetes | Leader election and pointers to job metadata | Needed only for high availability |
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
State backends
| Backend | State lives in | Strength | Cost |
|---|---|---|---|
| HashMap (default) | Java heap objects | Fastest access | Limited by memory, garbage collection |
| EmbeddedRocksDB | Serialized bytes on local disk | Very large state, incremental checkpoints | Every access serializes, about ten times slower on average |
| ForSt (experimental) | Remote storage, local disk as a cache | State beyond local disk, light recovery | Not recommended for production yet |
Which backend?
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
Alignment, step by step
- 1
Barrier on input A
An operator with two inputs stops reading A, so no later record slips into the snapshot.
- 2
Keep reading B
Records on B before its barrier still belong to the snapshot.
- 3
Barrier on input B
Now both inputs are at the cut. The operator snapshots and forwards one barrier.
- 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?
| Checkpoint | Savepoint | |
|---|---|---|
| Made by | Flink, on an interval | You, when you ask |
| Used for | Recovery from failure | Upgrades, moving, planned rescaling |
| Deleted by | Flink, unless you retain it | Only you |
| Format | Native to the backend, may be incremental | Canonical by default, portable across backends |
Failure
What happens when a worker dies
- 1
Detect
Heartbeats stop or a task throws an error.
- 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
Restore
State comes back from the last completed checkpoint and sources rewind to the positions saved in it.
- 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?
Time
Event time, watermarks and windows
| Kind of time | Meaning | Use it when |
|---|---|---|
| Event time | When it happened, stamped in the event | Almost all business logic |
| Processing time | The clock of the machine handling it | You only care about now, and replays may differ |
The usual watermark
An event meets a window
Windows
| Window | Shape | Example |
|---|---|---|
| Tumbling | Fixed, no overlap | Sales per 5 minutes |
| Sliding | Fixed, overlapping | Last 5 minutes, every minute |
| Session | Ends after a gap | A visit ends after 30 quiet minutes |
| Global | Everything for a key | Needs a custom trigger, for example every 100 events |
| Count | A number of events | Average of the last 50 readings |
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
Can the sink upsert by key?
Then at-least-once plus upserts is simplest. See idempotency.
- 2
Does it support transactions?
Use the two-phase commit sink and accept delay of one checkpoint interval.
- 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
Red flags
| You see | Cause | Remedy |
|---|---|---|
| Event-time windows never fire | No watermark, or an idle partition | Set a watermark strategy and idleness |
| One subtask at 100% busy | Hot key | Pre-aggregate, or salt the key and merge |
| Checkpoints time out | Backpressure or huge state | Fix the bottleneck, incremental or unaligned |
| Out of memory | Large state on the heap | RocksDB, TTL |
| Slow sink | One request per record | Batch, async I/O, more partitions |
Operations
Running it
# 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# 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/haBefore production
- 1
Give every stateful operator a uid
Without stable ids a savepoint cannot match state to the changed job.
- 2
Match parallelism to the source
More source tasks than Kafka partitions leaves some tasks idle.
- 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
Watch four things
Source lag, checkpoint duration and size, backpressure, restarts.
- 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
| Tool | Shared with Flink | Different | Best for |
|---|---|---|---|
| Spark Structured Streaming | SQL, Kafka, exactly-once, event time | Micro-batch by default, bigger batch and ML ecosystem | Teams already on Spark |
| Kafka Streams | RocksDB state, event time, exactly-once | A library in your app, not a cluster. Kafka in and out | Kafka-only microservices |
| Apache Beam | Batch and stream model | An API that runs on Flink, Spark or Dataflow | Portability |
| Apache Storm | Record at a time, low latency | At-least-once at its core, lower-level spouts and bolts | Existing systems only |
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.