Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Flink Execution Flow Deep Dive: From Source Code to Runtime
Big Data 87 min read

Flink Execution Flow Deep Dive: From Source Code to Runtime

This article provides a comprehensive source-code analysis of Apache Flink's core execution flow, covering StreamGraph/JobGraph/ExecutionGraph generation, task scheduling, checkpointing for exactly-once semantics, state backends, data transfer mechanisms, credit-based flow control, and FLIP-6 deployment model evolution.

1. Starting from WordCount

The article uses Flink's official SocketTextStreamWordCount example to illustrate the entire execution flow. The program obtains a StreamExecutionEnvironment, reads from a socket, splits lines via flatMap, keys by word, sums counts, and prints results.

1.1 Execution Environment

StreamExecutionEnvironment.getExecutionEnvironment()

returns a LocalStreamEnvironment for local runs. The environment holds configuration (parallelism, etc.) and provides the execute() entry point.

1.2 Operator Registration

Each transformation (e.g., flatMap) calls transform(), which infers output types via reflection and creates a StreamFlatMap operator. Operators are registered in the environment for later graph generation. Flink's core concept: data flows through a chain of operators (source → transforms → sink), with operator chaining for efficiency (similar to chain-of-responsibility pattern).

1.3 Program Execution

env.execute()

triggers: (1) StreamGraph generation, (2) JobGraph generation, (3) configuration assembly, (4) submission to cluster (local or remote), (5) cluster startup (metrics, web, JobManager, ResourceManager, TaskManagers), (6) task launch with a user-classloader for dynamic loading.

Remote mode uses StandaloneClusterClient and JobClientActor (Akka) for async communication with JobManager. The client blocks on awaitJobResult until completion.

2. Flink's Three-Layer Graph Structure

Flink transforms user logic through three graph layers:

StreamGraph : Direct mapping of user code (operators, edges). Generated by StreamGraphGenerator from registered transformations. Built recursively from sinks backward.

JobGraph : Optimized for execution; chains operators into JobVertex units. Generated by StreamingJobGraphGenerator. Chaining conditions: same parallelism, downstream indegree=1, same slot group, chaining strategies ALWAYS/HEAD, forward partitioning, no user disable.

ExecutionGraph : Parallelized, schedulable graph created on JobManager. Expands JobVertex into ExecutionJobVertex and ExecutionVertex per parallel subtask. Adds IntermediateResult and IntermediateResultPartition for data exchange.

Each layer serves a purpose: StreamGraph mirrors user logic; JobGraph optimizes via chaining; ExecutionGraph enables parallel scheduling.

2.2 StreamGraph Generation Details

StreamGraphGenerator.generateInternal()

iterates transformations, dispatching by type ( OneInputTransformation, SourceTransformation, etc.). For each, it sets slot-sharing group, adds operator to graph, configures key selectors (for keyed streams), parallelism, max parallelism, and adds edges. Logical nodes (union, split, partition) are merged into edges during addEdgeInternal.

2.3 JobGraph Generation & Chaining

setChaining()

traverses StreamNodes; chain heads become JobVertex, chained operators are embedded. setPhysicalEdges() creates JobEdge (communication pipes) between vertices. configureCheckpointing() propagates checkpoint config.

2.4 ExecutionGraph Construction

Built on JobManager via ExecutionGraphBuilder. For each topologically sorted JobVertex, creates ExecutionJobVertex, IntermediateResult per output, and ExecutionVertex per parallel subtask. Connects predecessors via IntermediateResult.

3. Task Scheduling & Execution

3.1 Resource Scheduling: Task Slots

A TaskManager's resources are divided into slots. One slot per TaskManager ⇒ each task in separate JVM; multiple slots ⇒ tasks share JVM (shared TCP, heartbeat, data structures). Slots can hold operator chains or SlotSharingGroup (non-chained operators sharing a slot). Example: source + flatMap in one slot, keyed aggregation + sink in another, reducing total slots needed to max parallelism.

3.2 JobManager Components & Startup

JobManager (Akka actor) includes BlobServer (jar storage), InstanceManager (TaskManager heartbeats), CompletedCheckpointStore, MemoryArchivist (job metadata). Startup: configure Akka, start ActorSystem, HA services, metrics, start JobManager actors (web, ResourceManager), await termination, leader election via LeaderService.

3.3 TaskManager Execution

TaskManager runs submitTask(TaskDeploymentDescriptor): deserializes operators, creates Task object with ResultPartition writers and InputGate readers, starts task thread. Task.run() transitions state (CREATED→DEPLOYING), loads user code, registers with network, restores state if recovered, then calls invokable.invoke() (e.g., StreamTask.invoke()).

3.4 StreamTask & StreamOperator

StreamTask.run()

loops calling inputProcessor.processInput(). StreamInputProcessor fetches buffers via barrierHandler.getNextNonBlocked(), deserializes records, handles watermarks/stream status/latency markers, then invokes streamOperator.processElement(record). Operators are chained via OperatorChain; head operator receives input, passes output to next.

4. StreamOperator Abstractions

4.1 StreamSource & Time Model

StreamSource

runs user SourceFunction (e.g., SocketTextStreamFunction) within a SourceContext that handles watermark emission, latency markers, and checkpoint locking. Time characteristic (EventTime/ProcessingTime/IngestionTime) determines watermark behavior.

4.2 OneInputStreamOperator & AbstractUdfStreamOperator

OneInputStreamOperator

defines processElement, processWatermark, processLatencyMarker. StreamFlatMap simply delegates to user FlatMapFunction. AbstractUdfStreamOperator provides open() / close() for rich functions.

4.3 StreamSink

Sink's processElement invokes user SinkFunction. reportOrForwardLatencyMarker reports latency (sinks don't forward).

5. Fault Tolerance: Exactly-Once via Distributed Snapshots

5.1 Evolution: Storm → Spark → Dataflow → Flink

Storm's acking gives at-least-once with idempotency burden. Spark's micro-batch trades latency for throughput, struggles with cross-batch ops and backpressure. Dataflow's transactional logging inspires Flink's lightweight asynchronous snapshots using barriers .

5.2 Checkpoint Lifecycle

Trigger : CheckpointCoordinator schedules periodic triggers via ScheduledTrigger. On trigger, creates PendingCheckpoint, sends triggerCheckpoint to each Execution → TaskManagerGateway.triggerCheckpoint.

Task Preparation : Task creates CheckpointMetaData, runs async invokable.triggerCheckpoint. StreamTask.performCheckpoint broadcasts barrier via operatorChain.broadcastCheckpointBarrier, then snapshots operator state.

Operator State & Barrier Propagation : Each operator snapshots state to StateBackend (deep copy, async write to stream). Barriers flow downstream; an operator with multiple inputs aligns barriers (buffers early arrivals) before triggering its own checkpoint. Kafka source snapshots partition offsets.

Completion Reporting : Async AsyncCheckpointRunnable reports to RpcCheckpointResponder → JobMaster → CheckpointCoordinator.receiveAcknowledgeMessage. When all acks received, PendingCheckpoint becomes CompletedCheckpoint, stored, and notifyCheckpointComplete sent to all tasks.

5.3 State & StateBackend

State types: KeyedState (ValueState, ListState, MapState, etc.) and OperatorState. Managed vs raw. Backends: MemoryStateBackend, FsStateBackend, RocksDBStateBackend.

6. Data Flow: Memory & Network Stack

6.1 Data Abstractions

MemorySegment (32KB default): unified abstraction over heap byte[] or direct ByteBuffer. HybridMemorySegment supports both; single implementation avoids virtual-call overhead.

NetworkBuffer & NetworkBufferPool : NetworkBuffer wraps MemorySegment with reference counting. NetworkBufferPool (per TaskManager) allocates all segments upfront (direct memory) to reduce GC. LocalBufferPool per task gets segments via dynamic redistribution: minimum guaranteed, excess distributed proportionally to (max−min).

RecordWriter & StreamRecord : StreamRecord wraps user object + timestamp. StreamWriter.sendToTarget serializes via RecordSerializer into buffers, flushes periodically (default) or per record ( flushAlways).

6.2 Cross-Task Data Transfer

Operator → RecordWriter → ChannelSelector picks downstream channel.

Per-channel serializer → ByteBuffer.

Write to ResultSubpartition (direct memory).

Flusher thread pushes via Netty NIO.

Remote Netty client decodes, copies to buffer, notifies InputChannel.

Downstream StreamInputProcessor reads buffer, deserializes to StreamRecord, processes.

6.3 Credit-Based Flow Control (Backpressure)

Receiver allocates credit (buffer capacity) per virtual channel. Sender transmits only up to credit balance: Crd_Bal = Buf_Alloc - (Tx_Cnt - Fwd_Cnt). Receiver sends credit updates; sender throttles. Per-virtual-channel design lets receiver balance multiple upstreams. Flink's test shows producer rate syncs with consumer slowdown/recovery.

7. Core Concepts

7.1 EventTime & Watermarks

Three time notions: EventTime (data creation), IngestionTime (source entry), ProcessingTime (operator wall-clock). Watermarks mark event-time progress; operators use min watermark across inputs. Late elements handled by delaying watermark insertion.

7.2 FLIP-6: Deployment & Processing Model Evolution

Pre-1.5 issues: static resources, poor YARN/K8s integration, no JobManager scheduling, session/per-job confusion. FLIP-6 introduces: Single Job JobManager (one JM per job), ResourceManager (slot lifecycle, TM caching), TaskManager (interacts with both), JobManager Slot Pool , Dispatcher (unified submission). Cluster managers (YARN, Mesos, Standalone, K8s) adapt: YARN per-job containers, Mesos with Marathon for Dispatcher HA, K8s with job-specific pods. Failure handling detailed for TM, RM, JM, and combinations.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Distributed SystemsFlinkStream ProcessingSource Code AnalysisState BackendExactly-OnceBackpressureCheckpointingDataflow GraphFLIP-6

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion