Home / Data Platform / Streaming & CDC

Data PlatformRunbookAdvanced

Flink job restarting in a loop - read the exception history, fix the root cause and set a restart strategy that stops hiding it

A Flink job keeps cycling RESTARTING to RUNNING. Find the first exception, classify it (poison record, lost TaskManager, checkpoint failures, broken restore), fix it, and tune restart strategies.

Deepak Bhardwaj7 min read

Applies toApache Flink 1.17 to 2.x (standalone, YARN, Kubernetes operator); defaults changed in 1.19, noted inline

Symptom

The job never shows FAILED. It shows RUNNING, but the restart count climbs, Kafka consumer lag grows, and output is late or duplicated. In the web UI the job flips between RESTARTING and RUNNING every few seconds or minutes.

That is the restart strategy doing its job, but on a failure that a restart will never fix. Since Flink 1.19 the default strategy with checkpointing enabled is exponential-delay, and its attempt limit defaults to unlimited. A broken job can loop for days without anyone getting paged.

Step 1: confirm the loop and how fast it is

# Running jobs and their IDs
flink list -r

# Job status and restart count via REST
JM=http://flink-jobmanager:8081
JOB=$(curl -s $JM/jobs/overview | jq -r '.jobs[] | select(.state=="RUNNING" or .state=="RESTARTING") | .jid' | head -1)
curl -s $JM/jobs/$JOB | jq '{name, state, duration}'
curl -s "$JM/jobs/$JOB/metrics?get=numRestarts" | jq .

numRestarts is the job-level metric to chart and alert on. Older dashboards may use the deprecated fullRestarts, which does not count region restarts.

Step 2: read the first exception, not the last

Every restart adds an entry to the exception history. The newest entries are often side effects ("Job is being restarted", cancelled tasks, network errors from peers going down). The useful one is the earliest entry in the current loop.

curl -s $JM/jobs/$JOB/exceptions | jq -r '
  .exceptionHistory.entries[]
  | "\(.timestamp | ./1000 | todate)  \(.taskName // "-")  \(.exceptionName)"' | tail -20

# Full stack trace of the oldest retained entry
curl -s $JM/jobs/$JOB/exceptions | jq -r '.exceptionHistory.entries[-1].stacktrace' | head -60

The history holds a limited number of entries (web.exception-history-size, default 16). If the loop is fast, the original cause may already be gone. Check the JobManager log for the first switched from RUNNING to FAILED line for a task:

kubectl logs deploy/flink-jobmanager -c flink-main-container --since=6h \
  | grep -m5 -B2 -A30 "switched from RUNNING to FAILED"

Step 3: classify the cause

First exception looks like Likely cause Restart will fix it?
Deserialization error, JsonParseException, Avro SerializationException, NullPointerException in a map function Poison record or unexpected data No, the same record is replayed after every restore
TaskManager ... lost, heartbeat of TaskManager ... timed out, container exit code 137 TaskManager killed (OOM, node loss, preemption) Sometimes; not if it is memory sizing
Exceeded checkpoint tolerable failure threshold Checkpoints failing; job fails after the tolerated count No, until checkpoint failures are fixed
StateMigrationException, Failed to rollback to checkpoint/savepoint, serializer incompatible Code change broke state compatibility No
ClassNotFoundException, NoSuchMethodError Dependency or JAR conflict after a deploy No
Sink errors: connection refused, TimeoutException, auth failures Downstream system unavailable Yes, once the dependency is back

Only the last row is the kind of failure restart strategies are for. For the rest, stop the loop and fix the cause.

Step 4: stop the loop safely

If the job is producing wrong or duplicate output, stop it. Take a savepoint if the job can reach a checkpointable state. In a fast restart loop it often cannot, so fall back to the last completed checkpoint.

# Try a savepoint first (stop drains sources and commits sinks)
flink stop --savepointPath s3://flink-savepoints/orders-enrich $JOB

# If stop hangs or fails because tasks never reach RUNNING
flink cancel $JOB

# Find the last completed checkpoint to restore from later
curl -s $JM/jobs/$JOB/checkpoints | jq '.latest.completed | {id, external_path, latest_ack_timestamp}'

Caution

Retained checkpoints survive a cancel only if externalized checkpoint retention is set to RETAIN_ON_CANCELLATION (execution.checkpointing.externalized-checkpoint-retention in 1.x; the key was renamed in Flink 2.x, so check your version's docs). With DELETE_ON_CANCELLATION, cancelling deletes the checkpoint you need to resume. Note the external_path before you cancel.

On the Kubernetes operator, set spec.job.state: suspended with upgradeMode: savepoint or last-state instead of calling the CLI. The operator handles the savepoint and keeps the restore path in the resource status.

Step 5: fix by cause

Poison record

Find the offset. Most deserialization errors include the topic, partition and offset, or you can log them in your deserializer. Then do one of these:

  • Catch the error in the deserializer and send the raw bytes to a side output or a dead-letter topic instead of throwing.
  • As a one-off, restore from the checkpoint with a code change that skips the bad record. Do not move the Kafka offsets outside Flink. Flink restores offsets from its own state, not from the consumer group.
// KafkaRecordDeserializationSchema that never throws on bad payloads
@Override
public void deserialize(ConsumerRecord<byte[], byte[]> rec, Collector<Order> out) {
    try {
        out.collect(mapper.readValue(rec.value(), Order.class));
    } catch (Exception e) {
        LOG.warn("Bad record topic={} partition={} offset={}", rec.topic(), rec.partition(), rec.offset(), e);
        badRecords.inc();   // a Counter registered in open()
    }
}

TaskManager lost

Check the pod or container for OOMKilled / exit code 137 and the TaskManager log for OutOfMemoryError. Fix the memory pool that ran out. Raising the container size alone often does not help, because Flink splits memory into fixed pools. Long GC pauses can also trip heartbeat.timeout (default 50 s); fix the GC pressure before you raise the timeout.

Checkpoint failures

execution.checkpointing.tolerable-failed-checkpoints is unset by default, which means no checkpoint failure is tolerated, so one failed checkpoint fails the job. Fix the cause (backpressure, slow state upload, a sink that blocks during snapshot) first. Raising the threshold to a small number such as 3 is reasonable so a single slow checkpoint does not cause a restart.

Broken restore after a deploy

Roll back to the previous JAR, restore from the same savepoint, and confirm it runs. Then fix operator UIDs or serializers in the new version before you redeploy.

Step 6: set a restart strategy that surfaces real failures

The goal: ride out short dependency outages, then fail visibly instead of looping.

# config.yaml (Flink 1.19+), or spec.flinkConfiguration on the Kubernetes operator
restart-strategy.type: exponential-delay
restart-strategy.exponential-delay.initial-backoff: 1 s
restart-strategy.exponential-delay.max-backoff: 2 min
restart-strategy.exponential-delay.backoff-multiplier: 2.0
restart-strategy.exponential-delay.reset-backoff-threshold: 30 min
restart-strategy.exponential-delay.jitter-factor: 0.1
restart-strategy.exponential-delay.attempts-before-reset-backoff: 10

jobmanager.execution.failover-strategy: region

With these settings the job retries with growing delays, up to 10 times. If it then stays healthy for 30 minutes, the backoff and the attempt count reset. If it keeps failing, it goes to FAILED, and an alert on job state catches it.

Alternatives:

# Fail if more than 5 failures in 10 minutes
restart-strategy.type: failure-rate
restart-strategy.failure-rate.max-failures-per-interval: 5
restart-strategy.failure-rate.failure-rate-interval: 10 min
restart-strategy.failure-rate.delay: 10 s

# Or a fixed number of attempts
restart-strategy.type: fixed-delay
restart-strategy.fixed-delay.attempts: 5
restart-strategy.fixed-delay.delay: 15 s

Warning

A strategy set in the job code (env.setRestartStrategy(...) or the job's Configuration) overrides the cluster config. Check the job's actual config in the UI (Job → Configuration) before you assume the cluster setting applies. Option names and defaults changed in 1.19 and again in 2.0; check your version's configuration page.

region failover restarts only the pipelined region that contains the failed task. For jobs with all-to-all shuffles (keyBy everywhere) the region is usually the whole job, so expect full restarts anyway.

Step 7: restart from the right state

# Resume from the savepoint or retained checkpoint
flink run -d -s s3://flink-savepoints/orders-enrich/savepoint-4f2a1c-8b7e2d9a1f00 \
  -c com.example.OrdersEnrich orders-enrich-1.4.2.jar

Watch numRestarts stay flat and the Kafka source lag (records-lag-max or pendingRecords, depending on connector version) fall before you close the incident.

Prevent it next time

  • Alert on increase(numRestarts[10m]) > 3, not only on job state FAILED.
  • Set attempts-before-reset-backoff (or use failure-rate) so unfixable failures end in FAILED.
  • Make deserializers and parsing functions tolerant, with a dead-letter output and a bad-record counter.
  • Retain checkpoints on cancellation, and keep savepoints for every deploy.
  • Pin operator UIDs and test restoring from a production savepoint in staging before each release.