Skip to main content

Streams processed continuously,
consistent even when failures occur.

Flink processes bounded and unbounded streams in parallel across the cluster, keeps application state in checkpoints, and computes results by the time each event happened. Follow a job from submission to result and see how a checkpoint protects the state when something fails.

A stream is a sequence of events, with or without a defined end. Apache Flink processes streams with state in TDP Datacenter, on top of YARN.

Stateful

The job remembers what it has already seen

Counts, windows and patterns depend on previous events. Flink keeps this state alongside the tasks, in memory or on disk, and accesses it locally.

Event time

The time it happened

Results can be computed by event time rather than by the time the data arrived, with watermarks marking the progress of that time.

Consistency

Failure without losing the state

Periodic checkpoints save the state to durable storage. On a failure, the job returns to the last completed checkpoint and the streams are re-read from that point.

On this page

Watch a job process a stream​

A job reads events from a Kafka topic, groups them by key and writes the results. Press Play or step through. The underlined names lead to the Glossary.

ClientWho submits
ClientPrepares and submits the dataflow
JobManagerWho coordinates
DispatcherReceives the job through the REST interface
JobMasterDrives the execution of the job
ResourceManagerManages the task slots
TaskManagersWho processes
TaskManagerTasks in its slots
TaskManagerTasks in its slots
DataWhere it comes from, where it goes
Kafka topicThe input events
DestinationThe results
Step 1 of 6

1 The client submits the dataflow

The program describes a dataflow: sources that read the events, transformations and sinks that write the results. The client prepares this dataflow and sends it to the JobManager through the Dispatcher's REST interface.

  1. The client submits the dataflow. The program describes a dataflow: sources that read the events, transformations and sinks that write the results. The client prepares this dataflow and sends it to the JobManager through the Dispatcher's REST interface.
  2. One JobMaster per job. The Dispatcher starts a JobMaster for the job it received. Each job has its own JobMaster, which drives its execution, and several jobs can run at the same time in the same cluster.
  3. Slots in YARN containers. Flink's ResourceManager manages the task slots, the unit of resource scheduling in the cluster. On YARN, the TaskManagers run in containers that the YARN ResourceManager allocates, and Flink allocates and releases TaskManagers according to the slots the jobs need.
  4. Tasks go to the slots. The JobManager decides when to schedule each task. For distributed execution, Flink chains operator subtasks into tasks, and each task runs in a thread, in a slot of a TaskManager.
  5. Events flow. The sources read the events from the Kafka topic. The TaskManagers run the tasks, keep the state locally and exchange streams with each other when they need to be redistributed, as in keyBy, which re-partitions the events by key.
  6. Results go out, and the job keeps running. The sinks write the results to the destination. An unbounded stream has a start but no defined end, so it is processed continuously. The client can disconnect or stay connected to receive the job's progress.
Figure 1 - A Flink job. The client sends the dataflow to the JobManager. The TaskManagers, in YARN containers, run the tasks as events arrive.

Architecture​

A JobManager and one or more TaskManagers form the Flink runtime. The client stays outside: it only prepares and submits the dataflow.

Flink architecture: client, JobManager and TaskManagers in YARN containers and checkpoints on HDFSThe client prepares the dataflow and submits it to the JobManager's Dispatcher. The JobManager has three parts: the Dispatcher, which receives jobs through the REST interface and serves the Web UI; the JobMaster, which drives the execution of one job; and the ResourceManager, which allocates and releases task slots. The JobManager and the TaskManagers run in YARN containers; each TaskManager offers slots, and each slot runs one task. Events enter through a Kafka topic, flow through the tasks and leave for the destination. Task state is saved in checkpoints and savepoints on HDFS.YARN containersClientPrepares and submitsthe dataflowJobManagerDispatcherREST and Web UIReceives jobsJobMasterDrives the executionof a jobResourceManagerAllocates and releasestask slotsHDFSCheckpointsSavepointsKafkaTopicInput eventsDestinationResultsTaskManagerSlotTaskSource → mapSlotTaskkeyBy → windowSlotTaskSinkTaskManagerSlotTaskSource → mapSlotTaskkeyBy → windowSlotTaskSinkJob submissionTasks and checkpoint acknowledgementsState snapshotsEvent flow
Figure 2 - Flink architecture: the client, the JobManager with the Dispatcher, the JobMaster and the ResourceManager, the TaskManagers with their slots in YARN containers, and HDFS with the checkpoints and savepoints. The underlined terms lead to the Glossary.

What the figure shows:

  1. The client prepares the dataflow and submits it to the JobManager's Dispatcher.
  2. The JobManager coordinates the execution: it decides when to schedule tasks, reacts to completed tasks and to failures, and coordinates checkpoints and recovery. It has three parts: the Dispatcher, the JobMaster, and the ResourceManager.
  3. The Dispatcher receives jobs through the REST interface and serves the Web UI.
  4. The JobMaster, one per job, drives the execution of the job and exchanges tasks and checkpoint acknowledgments with the TaskManagers.
  5. The ResourceManager allocates and releases the task slots.
  6. HDFS, a distributed file system, stores the state saved in checkpoints and savepoints. The tasks send it the state snapshots.
  7. The Kafka topic is where the input events come in.
  8. The YARN containers: on YARN, both types of process, the JobManager and the TaskManagers, run in containers.
  9. The TaskManagers run the tasks and buffer and exchange the data streams.
  10. The slots of each TaskManager each run one task.
  11. The destination receives the results.
  12. The flow of events goes from the Kafka topic, through the tasks, to the destination.

From the cluster to the subtask​

Where each piece of the job runs: five levels, each inside the other.

Level 1 of 5

Flink cluster

A JobManager and one or more TaskManagers. Several jobs can run at the same time in the cluster, each with its own JobMaster.

  • JobManagerCoordinates the execution, the checkpoints and the recovery from failures. There is always at least one.
  1. Flink cluster. A JobManager and one or more TaskManagers. Several jobs can run at the same time in the cluster, each with its own JobMaster.
    • JobManager. Coordinates the execution, the checkpoints and the recovery from failures. There is always at least one.
  2. TaskManager. The worker process, in a JVM: it runs the tasks of the dataflow and buffers and exchanges the data streams. There is always at least one.
  3. Slot. A fixed subset of the TaskManager's resources and its smallest unit of scheduling. The number of slots indicates how many tasks the TaskManager processes at the same time. Slots separate the managed memory of tasks, without isolating the CPU.
    • Slot sharing. Subtasks of different tasks, from the same job, can share a slot, and one slot can hold an entire pipeline of the job. That is why the cluster needs as many slots as the highest parallelism used in the job.
  4. Task. Chained operator subtasks executed by a single thread. Chaining reduces thread-to-thread handover and buffering.
  5. Subtask. A parallel instance of an operator. During execution, a stream has one or more partitions, and each operator has one or more subtasks. The number of subtasks is the parallelism of the operator.
    • Keyed state. It lives in an embedded key/value store, partitioned like the streams. Key groups are the unit by which Flink redistributes this state.
Figure 3 - Each level contains the next: the cluster has TaskManagers, the TaskManager offers slots, the slot runs tasks, and the task chains operator subtasks.

A checkpoint, step by step​

How Flink takes a snapshot of the state of a running job, and what it does with that snapshot when a TaskManager fails.

KafkaWhere the events come from
Topic partitionEvents with offsets
DataflowSource, operator and sink
SourceReads the partition
Stateful operatorCounts the events per key
SinkWrites the results
JobManagerWho coordinates
JobManagerCoordinates the checkpoints
StorageWhere the state lives
HDFSState snapshots
Step 1 of 6

1 A barrier enters the stream

At checkpoint n, a barrier is injected into the stream at the sources. The position where it enters, Sn, marks how far the snapshot covers the data. In Kafka, it is the offset of the last event read from the partition. This position is reported to the JobManager, the checkpoint coordinator.

  1. A barrier enters the stream. At checkpoint n, a barrier is injected into the stream at the sources. The position where it enters, Sn, marks how far the snapshot covers the data. In Kafka, it is the offset of the last event read from the partition. This position is reported to the JobManager, the checkpoint coordinator.
  2. The barrier travels with the events. The barrier travels along with the events and never overtakes them. It separates the events that go into snapshot n from those that go into the next snapshot.
  3. The operator saves the state. An operator with several inputs waits for the barrier from all of them: this is alignment. When it has received them, it writes a snapshot of its state to the state backend, which stores it in a reliable distributed storage, such as HDFS, and forwards the barrier downstream.
  4. The sink acknowledges, the checkpoint closes. When the sink receives barrier n from all its inputs, it acknowledges snapshot n to the coordinator. Once all sinks have acknowledged, the checkpoint is complete: it holds the position of each source in the stream and, for each operator, where its state was stored.
  5. A failure. A TaskManager fails during processing. Flink selects the last completed checkpoint, k, and redeploys the entire distributed dataflow.
  6. The state is restored and the stream is re-read. Each operator receives the state it saved in checkpoint k, and the sources resume reading the stream from position Sk: in Kafka, the consumer starts fetching events from offset Sk. Processing continues with a consistent state.
Figure 4 - A Flink checkpoint. The barrier crosses the dataflow and each operator saves its state. On a failure, the job returns to the last completed checkpoint.

Alignment is what gives the state its exactly-once guarantee.

Without it, in at-least-once mode, the operator keeps processing the inputs that have already delivered the barrier, and on recovery those events appear in duplicate.

There is also the unaligned checkpoint: the barrier overtakes the in-flight data, which becomes part of the operator state, to reach the sinks as fast as possible. Savepoints are always aligned.

Where the idea comes from

Flink's snapshot mechanism is inspired by the Chandy-Lamport algorithm for distributed snapshots, adapted to Flink's execution model. Everything involved in checkpointing can be done asynchronously.

Checkpoint or savepoint​

Both store the state of a job. What changes is who creates them, what for, and what happens to them afterwards.

Who creates and deletes

The checkpoint is created, owned and released by Flink itself, without user interaction. The savepoint is created, owned and deleted solely by the user, and does not expire when newer checkpoints complete.

What for

The checkpoint is the recovery mechanism for unexpected job failures. The savepoint serves planned operations: stopping and resuming, forking or updating a job, resuming it with a different parallelism, and updating the cluster without losing the state.

Format

The checkpoint uses the native format of the state backend and, in general, cannot be moved to another location. The savepoint uses a canonical format, independent of the state backend.

When the job is cancelled

Without retention, checkpoints serve only to resume the job after failures and are deleted on cancellation. When retained with RETAIN_ON_CANCELLATION, they remain after cancellation and are cleaned up manually. With DELETE_ON_CANCELLATION, they are available only if the job fails.

Where they are stored

Checkpoints, in the directory set by state.checkpoints.dir. Savepoints, in the directory given when triggering them or in the savepoint directory set by state.savepoints.dir.

The time of events​

In a stream, events can arrive out of order. Flink distinguishes the time an event happened from the time it is processed.

Processing time

The machine's clock

Processing time is the system time of the machine that executes the operation.

Event time

The time recorded in the event

Event time is the time at which each event occurred, on the device that produced it.

Watermark

Event time moves forward

A watermark travels in the stream with a timestamp t and declares that event time has reached t: no more events with a timestamp up to t should arrive.

In an operator with several inputs, the current event time is the minimum of the event times of its inputs.

Events that arrive after the watermark has already passed their timestamp are late events, and a program can expect some of them to arrive.

Because a stream has no end, counts and sums are computed over windows, defined by time or by number of events: tumbling windows, without overlap; sliding windows, with overlap; and session windows, separated by a gap of inactivity.

The jobs of a Flink application run in a cluster dedicated to it or in a shared session cluster. What changes is the lifecycle of the cluster and the isolation of resources.

Application Cluster

A cluster dedicated to the jobs of a single application, with main() running on the cluster rather than on the client. The cluster lives as long as the application lives. On YARN, main() runs on the JobManager, and the cluster shuts down when the application finishes.

Session Cluster

A long-running cluster that accepts several jobs and stays up until the session is stopped. Slots are allocated when the job arrives and released when it finishes, which saves the time of requesting resources and starting TaskManagers. In return, if a TaskManager goes down, all jobs with tasks on it fail.

Job Cluster

A cluster for each job, created by the cluster manager and torn down when the job finishes. This mode exists only on YARN and is deprecated.

About YARN

Flink services are submitted to the YARN ResourceManager, which spawns containers on the machines of the NodeManagers. The JobManager and the TaskManagers run in them. YARN replaces containers that fail, including the JobManager's, and unused TaskManagers are freed after a timeout.

JobManager high availability

A leading JobManager and others on standby, ready to take over. The high availability services with ZooKeeper serve any Flink deployment form and require a running ZooKeeper quorum.

The chosen form is the job's deployment mode. In all of them, the job's path is the one in Figure 1, and the state is protected by the checkpoints in Figure 4.

Any stream

Unbounded or bounded

The same framework processes continuous streams, which start and have no defined end, and bounded streams, processed in batch.

State

Part of the engine itself

Application state is handled by Flink and accessed locally, which favors high throughput and low latency.

Consistency

Exactly-once for the state

The checkpointing and recovery algorithms guarantee the consistency of the application state when a failure occurs.

Event time

Accurate and consistent results

With event time, the results are the same over recorded or real-time events.

Layered APIs

From SQL to fine-grained control

SQL and the Table API, unified for batch and stream; the DataStream API, with functions such as map(), reduce() and aggregate(); and ProcessFunctions, with control over time and state. The CEP library detects patterns of events.

Scale

In memory, spilled to disk

Applications are split into many parallel tasks. The state stays in memory, or in on-disk structures when it exceeds memory, and asynchronous checkpoints have minimal impact on latency.

In the TDP editions​

Available in the TDP editions
EditionVersionDocumentation
TDP Datacenter1.17.2TDP Datacenter components

In TDP Datacenter​

In TDP Datacenter, Flink is a service of the stack, installed and managed by Ambari.

Service components

FLINK_CLIENT (client, one or more), FLINK_JOBHISTORYSERVER (master, one or more) and FLINK_RESTSERVER (master, one instance). The FLINK_CLIENT requires HDFS_CLIENT (HDFS), MAPREDUCE2_CLIENT (MapReduce) and YARN_CLIENT (YARN). The FLINK_JOBHISTORYSERVER requires HDFS_CLIENT (HDFS), MAPREDUCE2_CLIENT (MapReduce) and YARN_CLIENT (YARN). The FLINK_RESTSERVER requires HDFS_CLIENT (HDFS), MAPREDUCE2_CLIENT (MapReduce) and YARN_CLIENT (YARN). Component category.

Execution and parallelism

The deployment target of jobs is set in execution.target, and the file system for paths without a scheme in fs.default-scheme. The parallelism of programs that do not define it is set in parallelism.default, and the slots of each TaskManager in taskmanager.numberOfTaskSlots.

Process memory

Configurable in jobmanager.memory.process.size and taskmanager.memory.process.size.

Checkpoints

Can be enabled in Ambari with execution.checkpointing.interval, with the exactly-once or at-least-once mode in execution.checkpointing.mode, the maximum time, the minimum pause and the number of concurrent checkpoints in execution.checkpointing.timeout, execution.checkpointing.min-pause and execution.checkpointing.max-concurrent-checkpoints, and the retention in execution.checkpointing.externalized-checkpoint-retention.

State and directories

The state backend is set in state.backend, with incremental checkpoints in state.backend.incremental. The checkpoint and savepoint directories are set in state.checkpoints.dir and state.savepoints.dir.

High availability

Can be enabled in Ambari in high-availability, with ZooKeeper, whose quorum is set in high-availability.zookeeper.quorum, and the metadata in a durable file system, in high-availability.storageDir.

Job history

The JobManager archives completed jobs in jobmanager.archive.fs.dir, and the History Server queries the directories in historyserver.archive.fs.dir, at every interval of historyserver.archive.fs.refresh-interval.

Web interface and REST

The address of the REST server is set in rest.address and rest.bind-address. Submitting and cancelling jobs through the web interface can be enabled in web.submit.enable and web.cancel.enable. SSL can be enabled in security.ssl.rest.enabled and, for the History Server, in security.ssl.historyserver.enabled.

Who uses Flink

JupyterLab, which points to the Flink client in FLINK_HOME, in the jupyterlab-env configuration (see JupyterLab); Zeppelin, with the flink and flink-cmd interpreters (see Apache Zeppelin); and OpenMetadata, which catalogs Flink with flink.enabled, in openmetadata_integration (see OpenMetadata).

Authentication

Kerberos, which can be enabled in Ambari, with the delegation tokens system for external services in security.delegation.tokens.enabled. See Security in TDP Datacenter.

Dependencies

Ambari requires in the cluster HDFS and YARN.

Scenario: deciding while the event happens​

Situation: an operation generates events all the time, such as transactions, sensor readings, or passages through checkpoints, and maintains reference data with limits and restriction lists. Today, irregularities are found afterwards, by sampling and manual cross-checks.

What TDP does: a Flink job, in TDP Datacenter, consumes the events from Kafka and keeps state per key, such as a customer, an order, or a piece of equipment:

  1. Cross-checking: each event is checked against the reference data, which also arrives through Kafka topics, and against the state accumulated for that key.
  2. Rules over time: using event time, the job compares the observed sequence with the expected one and applies deadline windows. The CEP library detects patterns in that sequence of events.
  3. Decisions: each triggered rule becomes an event in a decisions topic, with the alert or the action, which the organization's systems consume.

Checkpoints ensure that, after a failure, the state is recovered without counting an event twice.

Effect: the irregularity is flagged at the moment of the event, with the rule that triggered it, and the history of the events and decisions is stored for later analysis.

Reference architecture

The complete design, with the role of each component: Reference architectures › Real-time decisions on events.

Next steps​

Sources​

Apache Flink - Architecture

Apache Flink - Applications

Apache Flink 1.17 - Flink Architecture

Apache Flink 1.17 - Learn Flink

Apache Flink 1.17 - Stateful Stream Processing

Apache Flink 1.17 - Timely Stream Processing

Apache Flink 1.17 - Checkpoints

Apache Flink 1.17 - Savepoints

Apache Flink 1.17 - Checkpoints vs. Savepoints

Apache Flink 1.17 - Apache Hadoop YARN

Apache Flink 1.17 - High Availability

Apache Flink 1.17 - History Server

Apache Flink 1.17 - Configuration