Home / Data Platform / Streaming & CDC

Data PlatformTroubleshootingAdvanced

Flink exactly-once Kafka sink: transaction timeouts, lost commits and stuck read_committed consumers

Diagnose Flink KafkaSink exactly-once failures - rejected timeouts, transactions aborted before commit, prefix clashes and open transactions that hold back downstream consumers.

Deepak Bhardwaj7 min read

Applies toApache Flink 1.17 to 2.x with KafkaSink / SQL Kafka connector, Apache Kafka 3.x and 4.x brokers

Symptom

A Flink job writes to Kafka with DeliveryGuarantee.EXACTLY_ONCE and one of these happens:

  • The job fails at startup because the transaction timeout is larger than the broker allows.
  • The job recovers from an outage and looks healthy, but a block of records is missing from the output topic.
  • The committer logs that it cannot commit a transaction because it is fenced or in an invalid state.
  • read_committed consumers stop, although the Flink job is running and the topic is growing.
  • Two jobs keep failing each other with ProducerFencedException.

Most of these come from one fact: a Flink checkpoint and a Kafka transaction have separate lifetimes, and Kafka can abort a transaction that Flink still intends to commit.

How the sink commits

  1. Between checkpoints, each sink subtask writes into its own open Kafka transaction.
  2. At the checkpoint barrier, it flushes and stores the transaction's identity in Flink state as a committable. The transaction is pre-committed: still open in Kafka.
  3. When the checkpoint completes, the committer commits it.
  4. If the job dies between steps 2 and 3, the restored job resumes the transaction and commits it.

The window between steps 2 and 4 is the risk. Once the checkpoint is complete, the source offsets have moved past those records. If Kafka aborts the transaction before step 4, replay will not produce them again. That is data loss under an exactly-once setting.

Symptom Likely cause Fix
Startup error about transaction timeout Producer transaction.timeout.ms exceeds broker transaction.max.timeout.ms Raise the broker limit or lower the sink value
Missing records after a long outage Transaction timed out before the job restored Longer timeout, replay the range
Missing records after restoring an old savepoint Committables reference expired or aborted transactions Replay; stop jobs cleanly with a savepoint
Fencing that follows a second deployment Shared transactional ID prefix One prefix per sink, per job
Consumers hold at an offset Open transaction pins the last stable offset Recover the job, or abort the transaction
Latency equal to the checkpoint interval Expected behaviour Shorten the interval or use at-least-once

Checks

1. Compare the three timeouts

Check the broker cap. Kafka's default is 15 minutes, whereas the DataStream KafkaSink has traditionally defaulted to 1 hour, so untouched defaults conflict.

BS=broker1:9092
kafka-configs.sh --bootstrap-server $BS --describe --all \
  --entity-type brokers --entity-name 1 \
  | grep -E 'transaction.max.timeout.ms|transactional.id.expiration.ms'

Then read the checkpoint interval and timeout from Flink:

FLINK=http://jobmanager:8081
JOB=<job-id>
curl -s $FLINK/jobs/$JOB/checkpoints/config | jq '{mode, interval, timeout}'

2. Search for failed commits

The committer can treat a fenced or invalid transaction as a known failure: it logs the error and carries on, because retrying cannot succeed. The job stays RUNNING.

kubectl logs <taskmanager-pod> --since=24h \
  | grep -E 'Unable to commit transaction|ProducerFencedException|InvalidTxnStateException|InvalidPidMappingException'

Also graph the sink committer metrics, especially failedCommittables, retriedCommittables and pendingCommittables (names vary by version; check your build's output). Any increase in failedCommittables needs a reconciliation.

3. Find open transactions

kafka-transactions.sh --bootstrap-server $BS list
kafka-transactions.sh --bootstrap-server $BS describe \
  --transactional-id <transactional-id>
kafka-transactions.sh --bootstrap-server $BS describe-producers \
  --topic orders-enriched --partition 0

In describe-producers, a value in the current transaction start offset column that never advances identifies the producer holding the partition. On brokers, kafka.cluster:type=Partition,name=LastStableOffsetLag shows the same problem per partition.

4. Confirm it is only a read_committed stall

kafka-console-consumer.sh --bootstrap-server $BS --topic orders-enriched \
  --partition 0 --offset <stuck-offset> --max-messages 5 \
  --isolation-level read_uncommitted

If read_uncommitted returns records and read_committed does not, an open transaction is the cause. Records from later, already committed transactions are also invisible behind it.

Fix

Set a timeout from your recovery time

Use a value greater than maximum checkpoint duration plus maximum restart and outage time. An overnight outage with nobody on call needs hours, not minutes.

On self-managed brokers, set transaction.max.timeout.ms in server.properties and apply it with a rolling restart if your version does not support changing it dynamically. Managed services may cap it; check the current limits. Then set the sink explicitly:

KafkaSink<String> sink = KafkaSink.<String>builder()
    .setBootstrapServers("broker1:9092")
    .setRecordSerializer(
        KafkaRecordSerializationSchema.builder()
            .setTopic("orders-enriched")
            .setValueSerializationSchema(new SimpleStringSchema())
            .build())
    .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
    .setTransactionalIdPrefix("prod-orders-enricher-main")
    .setProperty("transaction.timeout.ms", "7200000")
    .build();

The SQL equivalent, where properties.* passes through to the client:

CREATE TABLE orders_enriched (
  order_id STRING,
  amount   DECIMAL(12, 2)
) WITH (
  'connector' = 'kafka',
  'topic' = 'orders-enriched',
  'properties.bootstrap.servers' = 'broker1:9092',
  'properties.transaction.timeout.ms' = '7200000',
  'format' = 'json',
  'sink.delivery-guarantee' = 'exactly-once',
  'sink.transactional-id-prefix' = 'prod-orders-enricher-main'
);

Warning

A longer timeout protects against loss but extends the worst-case stall. If the job is gone for good, read_committed consumers can wait the full timeout.

Make prefixes unique and stable

Encode environment, job and sink in the prefix. Two sinks in one job need two prefixes. Keep it stable across restarts: the sink uses it to find and abort its own leftover transactions. Changing it can leave the old ones open until they time out.

A cloned job, such as a blue/green deployment or a test started from a production savepoint, must not reuse the prefix while the original runs.

Release a stuck partition

Try these in order:

  1. Restore the original job from its latest checkpoint. It commits what it owns and aborts the rest.
  2. If it is retired, wait for the timeout if consumers can tolerate it.
  3. Abort the specific transaction:
kafka-transactions.sh --bootstrap-server $BS abort \
  --topic orders-enriched --partition 0 --start-offset <txn-start-offset>

Caution

Aborting a pre-committed transaction permanently discards records that a completed checkpoint says were written. Do this only when the job will not be restored, or when you have already planned a replay.

Repair a lost range

Compare source and sink counts for the outage window. Replay from the source with a separate job and a separate prefix, into a repair topic or a keyed sink that can absorb duplicates. Rewinding the main job replays everything after the rewind point, including records already committed.

Consider transaction ID pooling

Incrementing transactional IDs create new IDs over time, which adds coordinator state and can make recovery slow. FLIP-511 added a pooling strategy (TransactionNamingStrategy.POOLING, set on the builder or through sink.transaction-naming-strategy), which reuses IDs and lists open transactions on recovery.

Before enabling it, check that your connector release includes it, confirm that the broker version and ACLs allow listing transactions, and test the state upgrade. A safe order is to upgrade the connector first with the old strategy, complete a checkpoint, then switch.

Prevent it next time

  • Alert on failed committables and on LastStableOffsetLag, not only job status.
  • Alert when a job has been down for half of transaction.timeout.ms.
  • Stop jobs with flink stop --savepointPath <path> <job-id> so transactions are committed.
  • Don't restore old savepoints from exactly-once jobs without a replay plan.
  • Set isolation.level=read_committed on every consumer that relies on the guarantee.
  • If the sink is keyed and idempotent, use AT_LEAST_ONCE: lower latency and none of these failure modes.