How to Systematically Debug an Apache Flink Job
Kafka lag is climbing. An operator looks fully busy. A TaskManager is consuming almost all its available CPU. Where do you start?
The tempting answer is to add CPU or increase parallelism. Sometimes that helps, but it does not explain which task is slow, what it is doing, or whether the change actually fixes the problem.
A better approach follows a chain of evidence:
Symptom > operator > subtask > worker > execution path > verified cause > measured fix.
This guide turns lessons from a stateful aggregation investigation into a reusable debugging playbook. Environment identifiers and application-specific details are omitted. The original raw thread dumps were not available in the source analysis, so the stack examples below are illustrations, not recovered production evidence.
1. Start with the Failure Mode, Not a Favorite Theory
First decide whether the job is failing, waiting for resources, or running too slowly.
%%{init: {"flowchart": {"useMaxWidth": false}}}%%
flowchart TB
START["Confirm job, version, and UTC time window"] --> STATUS{"What is the symptom?"}
STATUS -->|"Failing or restarting"| FAIL["Correlate exceptions, worker events,<br/>and checkpoint failures"]
STATUS -->|"Not reaching RUNNING"| SCHEDULE["Inspect available slots,<br/>resource requirements, and deployment events"]
STATUS -->|"Running but slow"| FLOW["Trace throughput and backpressure<br/>downstream; compare individual subtasks"]
FLOW --> HOT["Map the suspect subtask<br/>to its current TaskManager"]
HOT --> EVIDENCE["Correlate CPU, throttling, GC,<br/>I/O, checkpoints, and thread stacks"]
FAIL --> THEORY["Write a testable hypothesis"]
SCHEDULE --> THEORY
EVIDENCE --> THEORY
THEORY --> TEST["Profile or run a bounded experiment"]
TEST --> VERIFY["Verify performance, correctness,<br/>and recovery; document remaining uncertainty"]
classDef start fill:#0f172a,stroke:#0f172a,color:#ffffff
classDef step fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
classDef decision fill:#fef3c7,stroke:#d97706,color:#78350f
classDef result fill:#dcfce7,stroke:#16a34a,color:#14532d
class START start
class FAIL,SCHEDULE,FLOW,HOT,EVIDENCE,THEORY,TEST step
class STATUS decision
class VERIFY result
Follow the branch that matches the symptom. On smaller screens, the diagram scrolls horizontally.
| Symptom | First evidence to collect |
|---|---|
| Repeated failures or restarts | Earliest relevant exception, JobManager and TaskManager logs, container termination reason, and checkpoint history. |
| Tasks cannot be scheduled | Available suitable slots, resource requirements, worker registration, and platform deployment events. |
| Increasing source backlog | Partition-level lag, input/output rates, busy/backpressured/idle time, and downstream health. |
| Slow or failing checkpoints | Per-subtask checkpoint timing, alignment/start delay where exposed, state size, storage errors, and concurrent backpressure. |
| High CPU or memory | Actual worker/container scope, CPU limits and throttling, JVM/GC metrics, task placement, and bounded profiling. |
For a restart, do not stop at the final cancellation message. It may be a consequence of an earlier task failure. Establish the timeline before assigning cause.
For checkpoint-driven restarts, see Flink Checkpoint Failures and Job Restarts.
2. Freeze the Identity and Observation Window
Before comparing charts, record:
- Native Flink job ID, job name, and current execution attempt.
- Cluster, namespace, and deployment identity, where applicable.
- Flink/JVM versions and deployed application artifact or commit.
- Job start time, operator parallelism, and recent deployment/configuration changes.
- The incident interval in UTC, including the metrics sampling window.
A platform deployment ID is not necessarily the native Flink job ID. Likewise, a Kubernetes pod name is not the Flink TaskManager resource ID used by the REST API.
Choose one interval in which the symptom is demonstrably present. Comparing yesterday’s CPU peak with today’s task placement can create a convincing but incorrect story.
Keep a simple evidence ledger:
| UTC window | Job/attempt | Operator/subtask/worker | Observation | Evidence location | Interpretation |
|---|---|---|---|---|---|
| Fill in | Fill in | Fill in | Exact metric or raw stack | Approved artifact location | Hypothesis and limitations |
Preserve successful raw responses and logs using approved storage. An HTTP 404 is a failed retrieval, not evidence that a metric is zero. A null or missing metric means unknown, not healthy.
3. Trace Backpressure in the Correct Direction
Records flow downstream. Backpressure propagates upstream.
Record flow: Source ---> Deduplicate ---> Aggregate ---> Sink
Backpressure: <-------------
when Aggregate cannot keep up
Suppose deduplication is backpressured, aggregation is very busy, and the sink is not backpressured. That makes aggregation a candidate bottleneck. It does not prove aggregation is CPU-bound, and it does not establish the sink’s health.
Start at the backpressured task and inspect its downstream consumers. Look for where output blocking gives way to sustained work, an external wait, or another constrained resource. In a branched job, follow every affected downstream path.
Read the three task-time metrics together
Flink exposes these metrics for task subtasks:
| Metric | Interpretation |
|---|---|
busyTimeMsPerSecond | Time accounted as busy by Flink’s task instrumentation. |
backPressuredTimeMsPerSecond | Time blocked by unavailable output buffers. |
idleTimeMsPerSecond | Time waiting for input to process. |
For supported tasks, these add up approximately to 1,000 milliseconds per second. They describe a recent averaging window, not an instantaneous state.
Busy time is not CPU utilization. Synchronous I/O inside an operator can occupy its execution thread without consuming much CPU. Async/background work and chained operators also complicate attribution; inspect the metric scope and implementation.
The Flink job graph can display the maximum busy/backpressure value across subtasks. Neither that maximum nor a dashboard average describes every subtask. Always open the subtask-level view.
4. Compare Subtasks Before Scaling the Job
For the suspect vertex, compare:
| Evidence | What it can reveal |
|---|---|
| Records in/out per second | Uneven traffic, processing rate, or downstream blocking. |
| Busy/backpressured/idle time | Whether most subtasks are constrained or only a few. |
| State size and key distribution, where observable | Expensive keys or large per-key state. |
| Hosting TaskManager | Whether hot tasks share a worker. |
| Checkpoint timing | Whether the same subtasks also delay checkpoints. |
Different patterns suggest different hypotheses:
- Most subtasks are busy: widespread per-record cost or insufficient overall capacity.
- Only a few are busy: skewed traffic, expensive keys, uneven state sizes, or worker contention.
- Hot tasks cluster on one worker: placement and shared worker resources deserve attention.
These are leads, not diagnoses. A worker can be hot because it hosts expensive tasks; co-location alone does not prove that placement caused the problem.
More parallelism does not necessarily split one hot key across subtasks. A keyed stream routes a key to one keyed operator instance at a time. Salting or changing the aggregation strategy can distribute work, but changes the algorithm and may require a second aggregation stage.
For the relationship between workers, slots, and tasks, see the visual guide to TaskManagers and parallelism.
5. Map the Hot Subtask to Its Current TaskManager
In the native Flink UI:
- Open the suspect task vertex and its subtask details.
- Record the subtask index, attempt, host, and TaskManager identity.
- Open that TaskManager’s metrics, logs, and thread-dump view.
- Match the execution thread to the operator or full chain name.
Repeat the mapping after a restart or rescale: execution attempts and placement can change. Chained operators share an execution task, so a thread may represent more than one logical operator.
The following read-only routes are documented in Flink 2.3:
| GET route | Purpose |
|---|---|
/jobs/:jobid | Job details and execution vertices. |
/jobs/:jobid/vertices/:vertexid | Task-vertex details and subtask summaries. |
/jobs/:jobid/exceptions | Recent handled job exceptions. |
/jobs/:jobid/checkpoints | Checkpoint statistics. |
/taskmanagers/:taskmanagerid/thread-dump | Worker thread dump. |
Replace placeholders with native Flink IDs and verify routes against your deployed version. Managed platforms may add a proxy path or require authenticated access. Do not append these paths to an unrelated Grafana URL.
Use approved access mechanisms. Do not copy tokens, cookies, authorization headers, or sensitive record contents into evidence files or a public incident report.
6. Distinguish CPU Saturation from Other Resource Problems
Compare CPU usage with the correct resource scope.
Usage, requests, and limits are different
- CPU usage: measured CPU time per wall-clock second; approximately 7.8 means 7.8 cores of consumption.
- CPU request: Kubernetes scheduling reservation; not a hard maximum.
- CPU limit: configured ceiling that can cause throttling, subject to platform enforcement.
Compare the main TaskManager container’s usage with that same container’s requests and limits. A pod-wide sum includes sidecars and is not a like-for-like comparison.
These example PromQL queries require common cAdvisor and kube-state-metrics exports. Replace the generic labels with your environment’s labels and check scrape duplication before using the results.
# CPU usage in cores for the selected TaskManager container.
sum by (namespace, pod, container) (
rate(container_cpu_usage_seconds_total{
namespace="example",
pod=~"example-job-.*",
container="taskmanager"
}[5m])
)
# Configured CPU limit; a missing series is not a zero-core limit.
max by (namespace, pod, container) (
kube_pod_container_resource_limits{
namespace="example",
pod=~"example-job-.*",
container="taskmanager",
resource="cpu",
unit="core"
}
)
Add an exact cluster filter if your monitoring system spans multiple clusters. The first query sums usage series; verify they represent disjoint CPU usage rather than duplicate scrapes. The second uses max to avoid summing duplicate reports of the same limit.
Check throttling separately, for example through container_cpu_cfs_throttled_periods_total relative to container_cpu_cfs_periods_total where available. That ratio measures the fraction of periods with throttling, not the percentage of CPU capacity lost.
Check more than heap and average GC time
Correlate worker CPU with:
- JVM heap, GC time/count, allocation activity, and pause distribution.
- Process/container memory, native memory, RocksDB/cache usage, and OOM events.
- Storage latency, compaction activity, network throughput, and sink retries.
- Other tasks and background threads sharing the worker.
Low reported GC elapsed time does not establish low GC-thread CPU, and it does not rule out allocation pressure. A healthy heap chart does not rule out an off-heap container OOM.
7. Use Thread Dumps to Generate Hypotheses
A thread dump is a snapshot, not a CPU profile.
During a verified high-load interval, a bounded starting point is three to five dumps, several seconds apart, if permitted. Record timestamps and preserve complete thread blocks: headers, states, stack frames, and lock/wait information.
Illustrative state-read stack
at ExampleHashMap.rehash(...)
at ExampleStateValue.fromMessage(...)
at ExampleStateSerializer.deserialize(...)
at RocksDBValueState.value(...)
at ExampleAggregator.processElement(...)
Read from the bottom up:
Process event
-> Read keyed state
-> Deserialize the value
-> Reconstruct application objects
-> Grow a map
This suggests investigating deserialization and map sizing. It does not measure rehashing’s share of total CPU.
Illustrative state-write stack
at AbstractMessageLite.toByteArray(...)
at ExampleStateSerializer.serialize(...)
at RocksDBValueState.update(...)
at ExampleAggregator.processElement(...)
This suggests state serialization on an update path. Source inspection must establish how often the path runs and how much data it rewrites.
Interpret thread state and stack together
| Stack pattern | Follow-up question |
|---|---|
| Application conversion, serialization, map growth | Does profiling attribute substantial CPU or allocations here? |
| Socket, queue, future, or monitor wait | Is there I/O waiting, lock contention, or downstream dependency? |
| RocksDB/native work | Is storage or native processing expensive? |
| GC/background threads | Does worker CPU come from outside the task’s main execution thread? |
RUNNABLE alone does not prove CPU consumption. Repeated stack appearances strengthen a lead but are not an accurate CPU percentage.
To navigate approved, locally saved dumps with PowerShell:
$dump = 'C:\ApprovedEvidence\thread-dump-01.txt'
Select-String -LiteralPath $dump `
-Pattern 'ExampleAggregator|ExampleStateSerializer|rehash|RocksDBValueState' `
-Context 8,20
Replace the path and application names. Search context is only a navigation aid; inspect the full original thread block before drawing conclusions.
8. Inspect the Source That Actually Ran
Use the deployed artifact’s matching source, not whichever branch is currently open.
For a stateful aggregation operator, trace:
Event -> state read -> object conversion -> business update -> state write
Answer these questions with source locations and representative state sizes:
- Does each event read and write one large nested value?
- Does serialization traverse every nested entry?
- Does deserialization reconstruct collections with undersized initial capacities?
- Can entry counts grow beyond the intended bound?
- Which branches read without a subsequent write, return early, or fail?
- What TTL refresh/cleanup semantics apply in this backend and version?
- Do expensive keys have larger state even when their event rate is ordinary?
A state access is not necessarily cheap just because the application updates one field. Updating a large serialized ValueState value may require converting and rewriting the whole value.
Possible optimizations need different safeguards:
| Candidate | Required verification |
|---|---|
| Pre-size collections | Real entry distribution, allocation/CPU benefit, and memory overhead. |
| Reduce intermediate objects or repeated conversion | CPU/allocation profile and serializer compatibility. |
| Change state granularity | Backend access costs, migration plan, checkpoint/savepoint recovery, and correctness. |
| Change TTL refresh policy | Every read/write branch, intended expiration behavior, and backend/version semantics. |
For example, switching TTL from OnReadAndWrite to OnCreateAndWrite can change when read-only keys expire. It is not a safe performance tweak based solely on one observed update path.
9. Check Competing Explanations
Before settling on serialization, deliberately look for evidence that could contradict it.
| Alternative | Evidence to inspect |
|---|---|
| Hot-key or state-size skew | Per-subtask load, bounded key-distribution samples, and state cardinality. |
| Slow external service or sink | Latency, retries, errors, outstanding requests, and output rate. |
| Checkpoint/storage pressure | Checkpoint timelines, upload latency, alignment/start delay, and storage failures. |
| CPU quota contention | Container limits, throttling, worker placement, and node contention. |
| GC/allocation pressure | Allocation profiles, pauses, and GC-thread activity. |
| Source/input constraint | Partition count, source rate, idle time, and upstream availability. |
A sink with low backpressure is not automatically healthy. It may simply receive less traffic because an upstream operator is slow. It can also be the constrained consumer that is backpressuring upstream tasks while reporting little backpressure of its own.
Likewise, long checkpoints can be a symptom of slow processing or storage pressure. Correlate their timing with the slowdown instead of assuming direction of causality.
10. Profile and Test One Hypothesis at a Time
Write the hypothesis before changing anything:
Deserializing large per-key values repeatedly rebuilds maps. If this is a significant CPU cost, profiling should show recurring CPU/allocation samples in that path, and pre-sizing should reduce cost at representative state sizes.
Use an approved, bounded profiling method supported by the deployed JVM and platform, such as JFR or async-profiler. Choose CPU sampling, wall-clock sampling, or allocation recording to match the question; they measure different things.
Before attaching, confirm permissions, overhead, duration, supported configuration, and secure artifact handling. Do not install tools, expose management ports, or restart production merely to obtain a profile without approval.
For an experiment, record:
| Hold stable where possible | Measure |
|---|---|
| Input rate and key/state distribution | Throughput and partition-level backlog trend. |
| Artifact/configuration except the tested change | CPU per processed record and allocations per record. |
| Parallelism and worker resource scope | Worker CPU, throttling, memory, and placement. |
| Comparable checkpoint conditions | Checkpoint duration/failures and recovery behavior. |
Worker CPU divided by record rate is only a rough cost proxy unless the same worker/task scope is isolated; other tasks and background work contribute CPU.
If increasing CPU also restarts the job, placement, caches, and workload timing may change. Better throughput supports a capacity-related hypothesis, but it does not isolate CPU allocation as the sole cause.
Validate output semantics, TTL behavior, and recovery compatibility before accepting a state-handling optimization. Keep a rollback path.
11. Measure Backlog Correctly
Worst-partition lag is not total backlog. Dividing the largest partition’s lag by job-wide throughput gives a misleading catch-up estimate.
For a single partition with comparable offset-lag and rate units, an approximate estimate is:
Drain rate = partition consumption rate - partition arrival rate
Catch-up time ~= partition backlog / drain rate
This only predicts catch-up when the drain rate is positive and reasonably stable. Kafka offsets do not always map one-to-one to application records, so validate the units and transaction/connector behavior.
For a whole topic, inspect every relevant partition. A healthy aggregate consumption rate can hide one partition whose lag is still rising. Job output rate may also differ from source consumption because operators filter, deduplicate, or aggregate records.
12. Close the Investigation with Evidence, Not Confidence
Separate the final report into four statements:
Observed:
Timestamped metrics, complete raw stacks, and matching source behavior.
Inferred:
A bottleneck hypothesis connecting those observations.
Unproven:
Missing CPU attribution, competing explanations, or uncontrolled changes.
Validated:
A measured improvement with correctness and recovery preserved.
A useful conclusion is:
Aggregation subtasks were busy while upstream tasks were backpressured. Their hosting workers showed high CPU. Repeated stacks suggested state conversion as a candidate cost; profiling and a controlled benchmark are needed to quantify it.
An unjustified conclusion is:
A serializer appeared in one dump, therefore serialization caused the incident.
The goal is not merely to make the chart green. It is to understand the failure mode well enough that the fix is explainable, repeatable, and safe.
References
- Flink 2.3: Monitoring Back Pressure
- Flink 2.3: Metrics
- Flink 2.3: REST API
- Flink 2.3: Working with State
- Flink 2.3: Task Failure Recovery
The examples use a running streaming job. Metric names, REST responses, and available profiling features can differ by Flink version, connector, and hosting platform; verify them against the deployed system.