Özer Cem KELAHMETKELAHMET
Articles · Stream processing

Kafka exactly-once explained: idempotent producers, transactions and read_committed

Exactly-once in Kafka is three mechanisms stacked together: an idempotent producer, transactions that commit output and input offsets atomically, and consumers that read only committed data. A runnable crash simulation shows what each layer removes and what it costs.

Download Markdown
At a glance
Reading time
18 min
Sections
11
Code examples
3
Tables
4
Sources
9
Published
25 Nov 2026
In 30 seconds
What changed
Kafka 4.4.0 adds transactional state stores to Kafka Streams
Why it matters
Exactly-once is a property of the whole pipeline.
What to do
Check producer settings

Every streaming pipeline eventually crashes mid-batch. If the job had written its output but not yet recorded how far it had read, it rereads and writes those records twice. If it recorded its position first and crashed before writing, those records are gone. Kafka's exactly-once semantics remove both outcomes for pipelines that read from and write to Kafka.

The guarantee is three stacked mechanisms: an idempotent producer, transactions that commit output and consumer offsets atomically, and consumers that read only committed data. Each removes one failure and costs some latency or care. The transaction protocol itself was hardened in Kafka 4.0, and Kafka 4.4, released on 22 October 2026, extends exactly-once to Kafka Streams state stores.

This article walks through each layer with a crash simulation in plain Python and the real defaults from the Kafka 4.4 documentation. For Kafka basics, see the Apache Kafka tool page.

What happened

Kafka 4.4.0 adds transactional state stores to Kafka Streams (22 October 2026)

Apache Kafka 4.4.0 includes 25 KIPs. Two touch exactly-once directly. KIP-892 adds transactional state stores to Kafka Streams, off by default behind enable.transactional.statestores. Under exactly-once, stores are no longer wiped and rebuilt after an error; only writes since the last commit are replayed. The release also adds statestore.uncommitted.max.bytes and a setting for the isolation level of interactive queries. KIP-1319 introduces version 6 of the TxnOffsetCommit request, which uses topic IDs and returns specific errors instead of folding them into ILLEGAL_GENERATION.

The stronger transaction protocol is the default since Kafka 4.0 (18 March 2025)

KIP-890, "Transactions Server Side Defense", is enabled automatically on servers since Kafka 4.0 through the transaction.version feature flag. With it, and with producers on version 4.0 or later, the producer epoch is bumped on every transaction. According to the Kafka documentation, this ensures each transaction includes only its intended messages and stops a late duplicate from landing in the next transaction. It also cuts one round trip: the broker makes a single add-partitions call instead of a client call plus a server verification call.

Layer 1: the idempotent producer

Start with the smallest failure. The broker appends a batch, but the acknowledgement is lost, so the producer retries and, without protection, the batch is appended twice.

Kafka's design documentation describes the fix in one line: the broker assigns each producer an ID and deduplicates messages using a sequence number. Every batch carries the producer ID and a sequence number per partition. If the broker sees a sequence number it has already written for that producer, it acknowledges without appending again. Think of a cloakroom ticket: if you hand in the same ticket twice, the attendant knows it is the same coat.

In current Kafka clients this is on by default. The 4.4 producer configuration lists:

Table 1. Layer 1: the idempotent producer
Setting Default Why it matters for idempotence
enable.idempotence true Turns on producer IDs and sequence numbers
acks all Required to be all when idempotence is on
retries 2147483647 Must be greater than 0
max.in.flight.requests.per.connection 5 Must be 5 or less, because the broker keeps at most 5 batches per producer
delivery.timeout.ms 120000 Upper bound for a send, including retries

Idempotence has a hard limit. The producer ID belongs to one producer session. If your application crashes and restarts, it gets a new identity, and the broker cannot know that a record from the new session is a replay of one from the old session. Idempotence fixes retry duplicates inside a session. It does nothing about the application reprocessing input after a crash.

Layer 2: transactions that include the offsets

The crash problem needs a different tool. A read-process-write job does two things for each batch: it writes output records, and it commits the consumer offset that says "I have processed up to here". If those two writes are separate, a crash between them causes either duplicates (output written, offset not committed) or loss (offset committed, output not written).

Kafka's answer is to make the offset commit part of the same transaction as the output. The consumer position is itself stored as a message in an internal topic, so the producer can write it inside a transaction. Either all output records and the offset commit become visible, or none do. It is like a bank transfer: the debit and the credit are booked together or not at all.

The moving parts:

  • transactional.id. A stable name for the producer, set by you. It survives restarts, unlike the producer ID. Setting it implies idempotence. When a new instance starts with the same transactional.id, any in-flight transaction from the old instance is aborted, and the old instance is fenced out by the higher epoch.
  • The transaction coordinator. A broker that records transaction state in the internal transaction log. Broker defaults are transaction.state.log.replication.factor 3 and transaction.state.log.min.isr 2, which is why the documentation says transactions need at least three brokers by default.
  • Markers. When a transaction commits or aborts, the coordinator writes a commit or abort marker into every partition the transaction touched. Consumers use these markers to decide what to show.
  • Timeouts. The producer's transaction.timeout.ms defaults to 60000 (1 minute). If a transaction stays open longer, the coordinator aborts it. The value cannot exceed the broker's transaction.max.timeout.ms, which defaults to 900000 (15 minutes). Idle transactional.id entries expire after transactional.id.expiration.ms, 7 days by default.

A transactional loop in Python with the confluent-kafka client looks like this. It is written against that client's API and needs a running broker, so treat it as a template rather than something we executed here:

from confluent_kafka import Consumer, Producer, KafkaException

consumer = Consumer({
    "bootstrap.servers": "localhost:9092",
    "group.id": "orders-enricher",
    "isolation.level": "read_committed",
    "enable.auto.commit": False,
    "auto.offset.reset": "earliest",
})
producer = Producer({
    "bootstrap.servers": "localhost:9092",
    "transactional.id": "orders-enricher-0",   # stable across restarts
})
consumer.subscribe(["orders"])
producer.init_transactions()                    # fences older instances

while True:
    msgs = consumer.consume(num_messages=500, timeout=1.0)
    if not msgs:
        continue
    producer.begin_transaction()
    try:
        for m in msgs:
            if m.error():
                continue
            producer.produce("orders_enriched", key=m.key(), value=m.value().upper())
        producer.send_offsets_to_transaction(
            consumer.position(consumer.assignment()),
            consumer.consumer_group_metadata())
        producer.commit_transaction()           # output and offsets, atomically
    except KafkaException:
        producer.abort_transaction()            # in production: rewind or restart
        raise

Two settings on the consumer side are not optional. The Kafka design documentation states that the consumer configuration must include isolation.level=read_committed and enable.auto.commit=false. Auto-commit would commit offsets outside the transaction and quietly reintroduce the loss case.

Layer 3: read_committed consumers and the last stable offset

Transactional records reach the log before they commit, and aborted records stay there, only marked as aborted. So the reader decides what it sees.

The consumer setting isolation.level defaults to read_uncommitted, which returns everything, including records from aborted transactions. With read_committed, poll() returns only committed transactional records, plus all non-transactional ones.

There is a subtle consequence. Records arrive in offset order, so a read_committed consumer cannot skip past an open transaction. The Kafka documentation defines the last stable offset (LSO) as one less than the offset of the first open transaction, and a read_committed consumer reads only up to it. Records written after an open transaction wait until it finishes, even if they are not part of it. A slow or stuck producer therefore delays every read_committed reader of that partition, up to the transaction timeout. It is like a single-lane road: one car waiting to turn holds up everyone behind it.

A runnable crash simulation

To see what each layer removes, the simulation below models a read-process-write job over 10,000 input records. It commits every 100 records. At each record there is a 0.2% chance the application crashes, and each produce request has a 1% chance of timing out after the broker already appended it, which triggers a retry. After a crash the job restarts from the last committed offset with a new producer session. Four modes are compared: at-most-once (commit offset first, no retries), at-least-once (write, then commit), idempotent (at-least-once plus broker deduplication) and transactional (output and offsets in one transaction, read with read_committed).

import random
from collections import Counter

def run(mode, n=10_000, crash_p=0.002, retry_p=0.01, batch=100, seed=7):
    rng = random.Random(seed)
    log, aborted, seen_seq = [], set(), set()
    committed, pid, txn = 0, 0, 0
    pos = committed
    while pos < n:
        txn += 1; start = pos; crashed = False
        if mode == "at_most_once":
            committed = min(pos + batch, n)            # commit before processing
        for off in range(start, min(start + batch, n)):
            if rng.random() < crash_p:
                crashed = True; break
            sends = 2 if (mode != "at_most_once" and rng.random() < retry_p) else 1
            for _ in range(sends):
                if mode in ("idempotent", "transactional") and (pid, off) in seen_seq:
                    continue                           # broker drops the retry
                seen_seq.add((pid, off))
                log.append((off, txn if mode == "transactional" else None))
        if crashed:
            if mode == "transactional":
                aborted.add(txn)                       # coordinator aborts open txn
            pid += 1                                   # restart: new producer session
            pos = committed
            continue
        if mode != "at_most_once":
            committed = min(start + batch, n)          # commit after writing
        pos = committed
    seen = [v for v, t in log if not (mode == "transactional" and t in aborted)]
    c = Counter(seen)
    return len(log), sum(k - 1 for k in c.values()), n - len(c)

for m in ["at_most_once", "at_least_once", "idempotent", "transactional"]:
    print(m, run(m))

The results (records in the output log, duplicates a consumer sees, records lost):

Table 2. A runnable crash simulation
Mode Output log size Duplicates seen Lost Duplicates seen with read_uncommitted
At-most-once 9,002 0 998 0
At-least-once 11,233 1,233 0 1,233
Idempotent producer 11,115 1,115 0 1,115
Transactional + read_committed 11,115 0 0 1,115

Read the table one row at a time. At-most-once never duplicates but loses about 10% of records, because every crash discards the rest of a batch whose offset was already committed. At-least-once loses nothing but shows 1,233 duplicates. Idempotence removes 118 of them, the retry duplicates (11,233 − 11,115 = 118), but the 1,115 duplicates caused by replay after crashes remain, because each restart is a new producer session. Transactions remove those too: the replayed records were first written inside a transaction that was aborted. The last column is the trap. The aborted records are still in the log, so a consumer left on the default read_uncommitted sees exactly the same 1,115 duplicates as the idempotent mode.

Duplicates and losses per 10,000 records by delivery mode
duplicates seenrecords lost
02505007501,0001,250at-most-onceat-least-onceidempotenttransactional duplicates seen · at-most-once: 00duplicates seen · at-least-once: 1,2331,233duplicates seen · idempotent: 1,1151,115duplicates seen · transactional + read_committed: 00records lost · at-most-once: 998998records lost · at-least-once: 00records lost · idempotent: 00records lost · transactional + read_committed: 00delivery moderecords
Figure 1. Computed in this article's Python simulation: 0.2% crash chance per record, 1% produce retry chance, commit every 100 records

Transaction size is a trade-off

The simulation also shows why transaction size matters. Under exactly-once, a crash does not create visible duplicates, but it does waste work: everything written in the aborted transaction must be written again. Varying the records per commit gave these counts of aborted records written (the same records a read_uncommitted reader would see as duplicates):

Table 3. Transaction size is a trade-off
Records per commit At-least-once duplicates Transactional: aborted records written Transactional: duplicates seen
10 215 111 0
50 600 491 0
100 1,233 1,115 0
500 8,539 8,345 0
1,000 24,493 24,133 0
Wasted writes grow with transaction size
aborted records written (transactional)duplicates seen (at-least-once)
05,00010k15k20k25k10501005001000aborted records written (transactional) · 10: 111aborted records written (transactional) · 50: 491aborted records written (transactional) · 100: 1,115aborted records written (transactional) · 500: 8,345aborted records written (transactional) · 1000: 24.1kduplicates seen (at-least-once) · 10: 215duplicates seen (at-least-once) · 50: 600duplicates seen (at-least-once) · 100: 1,233duplicates seen (at-least-once) · 500: 8,539duplicates seen (at-least-once) · 1000: 24.5krecords per commitrecords
Figure 2. Computed in this article's Python simulation with 10,000 input records and a 0.2% crash chance per record

The growth is not linear, and simple probability explains it. With a 0.2% crash chance per record, a batch of b records completes without a crash with probability 0.998^b. For b = 100 that is about 0.819, so a batch needs on average 1 / 0.819 = 1.22 attempts. For b = 1,000 it is about 0.135, so a batch needs 1 / 0.135 = 7.4 attempts, and most of them write hundreds of records before failing. Real crash rates are far lower than 0.2% per record, but the shape holds: transactions should be short relative to how often things fail.

Small transactions have their own cost. Each commit writes a marker to every partition it touched and adds coordinator round trips. A job writing to 20 partitions and committing every 100 ms writes up to 10 × 20 = 200 markers per second. That is why Kafka Streams and Flink use time-based commit intervals rather than committing every record.

Kafka Streams. Set processing.guarantee to exactly_once_v2 (the default is at_least_once). It requires brokers on version 2.5 or later and, for production, at least three brokers. Under exactly-once, the default commit.interval.ms drops from 30000 to 100 milliseconds, so output becomes visible to read_committed readers within roughly a tenth of a second. Kafka 4.4 adds enable.transactional.statestores, off by default: state store writes are buffered and committed together with the changelog transaction, so an error replays only writes since the last commit instead of rebuilding the store from the changelog.

Flink. The KafkaSink offers three guarantees. NONE, the default, can lose or duplicate. AT_LEAST_ONCE waits for outstanding records to be acknowledged on each checkpoint. EXACTLY_ONCE writes records in Kafka transactions that commit when a checkpoint completes, and requires a transactional ID prefix that is unique per application on the cluster. Both stronger modes need checkpointing enabled.

Flink's design ties visibility to checkpoints. A read_committed consumer sees a record only after the checkpoint that contains it completes. With a 60-second checkpoint interval, a record written at a uniformly random moment waits on average about 30 seconds plus the checkpoint's own duration before it becomes visible. The Flink documentation also warns that the producer's transaction.timeout.ms must be at least the maximum checkpoint duration plus the maximum restart time, or Kafka may expire uncommitted transactions and data can be lost. Because the broker caps transactions at transaction.max.timeout.ms, 15 minutes by default, long checkpoints or slow restarts may require raising that broker limit.

Table 4. Exactly-once in Kafka Streams and Flink
Engine Setting Visibility delay driver Main operational risk
Hand-written client transactional.id, read_committed Your commit interval Getting abort and rewind logic right
Kafka Streams processing.guarantee=exactly_once_v2 commit.interval.ms (100 ms default under EOS) State store restores, now reduced by KIP-892
Flink KafkaSink DeliveryGuarantee.EXACTLY_ONCE + ID prefix Checkpoint interval and duration Transaction timeout shorter than checkpoint plus restart

Where exactly-once stops

The guarantee covers Kafka-to-Kafka pipelines. Kafka's design documentation says that for other destinations, exactly-once requires cooperation from the external system. If your job writes to a database, a warehouse or an HTTP API, a crash can still apply a write twice unless the sink is idempotent or transactional itself. The usual patterns are an upsert keyed on a business key, a MERGE that ignores rows already applied, or storing the Kafka offset in the same database transaction as the data. The same idea is used when applying change data capture streams, as shown in CDC with Debezium and Kafka Connect. Side effects such as sending an email are never covered by Kafka transactions.

Exactly-once also says nothing about event time. Late events, windows and watermarks are a separate problem, covered in Spark Structured Streaming watermarks and windows and the streaming windows and watermarks simulation.

Use cases and examples

Payment event enrichment. A fintech enriches card authorisations with merchant data and writes them to a topic feeding fraud scoring and ledger reconciliation, where duplicates would double-count spend. It uses Kafka Streams with exactly_once_v2, so output is visible about 100 ms after each commit, and code review enforces read_committed on every downstream consumer, the simulation's last column.

Clickstream aggregation in Flink. A media company aggregates page views per article per minute in Flink and writes results to Kafka with EXACTLY_ONCE. Checkpoints run every 60 seconds and take about 10 seconds. Using the rule from the Flink documentation, they set transaction.timeout.ms above the worst checkpoint duration plus the worst restart time and keep it within the broker's 15-minute cap. Dashboards accept the average delay of roughly 30 seconds plus checkpoint time that this design implies.

Order events into a warehouse. A retailer streams orders into a warehouse with a sink connector. Kafka transactions cannot reach inside the warehouse, so rows carry the order ID and a version and the load uses MERGE, making a replayed batch a no-op. This is the usual pattern with Kafka Connect.

A stuck producer stalls readers. read_committed consumers on one partition stop advancing while read_uncommitted tools show new data. A producer opened a transaction and hung, and the LSO cannot pass it until the coordinator aborts it at transaction.timeout.ms. The team lowers that timeout and alerts on lag against the LSO.

What it means in practice

Exactly-once is a property of the whole pipeline. Producers need idempotence, which clients give by default. Jobs need transactions that include input offsets, which Kafka Streams and Flink handle. Every reader needs read_committed, which nothing sets for you; miss it and the guarantee disappears silently.

The price is latency and care. Output appears at transaction boundaries, open transactions can block readers through the LSO, and timeouts must fit checkpoint and restart times. Kafka 4.0 and 4.4 smooth the rough edges but do not remove the boundary with external systems. For a broader map of streaming tools see the streaming topic page and Spark Streaming.

What to do now

  1. Check producer settings. Confirm enable.idempotence is not disabled by a conflicting setting such as acks=1 or more than 5 in-flight requests.
  2. Audit every consumer. List consumers of transactional topics and confirm isolation.level=read_committed; the default is read_uncommitted.
  3. Disable auto-commit in transactional jobs. Offsets must be committed inside the transaction, never by the background auto-commit.
  4. Use stable transactional IDs. One per producer instance or partition set, stable across restarts, and a unique Flink prefix per application.
  5. Size timeouts. Keep transaction.timeout.ms above checkpoint plus restart time and below the broker's transaction.max.timeout.ms.
  6. Run three brokers. Transactions default to a replication factor of 3 and a minimum ISR of 2 for the transaction log.
  7. Make sinks idempotent. For databases and warehouses, use keyed upserts or MERGE so replays are harmless.
  8. Monitor lag against the LSO. A stuck transaction shows up as lag for read_committed readers only.
  9. Test crashes. Kill the job mid-batch in staging and count duplicates downstream, as the simulation does.
  10. Evaluate KIP-892 on 4.4. For Kafka Streams apps with large state, test enable.transactional.statestores to shorten recovery after errors.

Risks and open questions

Silent misconfiguration is the main risk. One consumer on read_uncommitted sees aborted records, and nothing warns you.

External systems break the chain. Kafka transactions do not cover databases, object stores or APIs. Without an idempotent or transactional sink, end-to-end exactly-once is not achieved.

Latency is the price. Data becomes visible only at commit or checkpoint boundaries, which may be too slow for some alerting use cases.

Long transactions block readers. The LSO holds back all read_committed readers of a partition until the oldest open transaction finishes or times out.

New features are opt-in. Transactional state stores ship disabled by default in Kafka 4.4, so real-world experience with them is still limited.

Watch next: adoption of KIP-892 transactional state stores in production Kafka Streams apps, client support for the new TxnOffsetCommit version from KIP-1319, and progress on proposals for Kafka to take part in external two-phase commits.

Frequently asked questions

Is the idempotent producer enough for exactly-once?

No. It removes duplicates caused by producer retries within one session. After an application crash and restart, the producer has a new identity, so replayed records are not recognised as duplicates; that needs transactions.

Why do I still see duplicates with transactions enabled?

Most often a consumer is using the default isolation.level=read_uncommitted. Aborted records stay in the log and are only hidden from read_committed readers. Check every consumer, including tools and connectors.

Does exactly-once cover writes to my database?

Not by itself. Kafka's documentation says exactly-once for other destinations needs cooperation from the external system. Use idempotent upserts, MERGE on a business key, or store offsets in the same database transaction as the data.

What is the last stable offset?

It is one less than the offset of the first open transaction in a partition. A read_committed consumer reads only up to it, so a long open transaction delays all such readers of that partition.

What changed in Kafka 4.4 for exactly-once?

KIP-892 adds optional transactional state stores to Kafka Streams, so errors under exactly-once replay only uncommitted writes instead of rebuilding stores. KIP-1319 adds a new version of the transactional offset commit request with topic IDs and clearer errors.

Summary

Kafka exactly-once is three layers. Idempotent producers deduplicate retries using producer IDs and sequence numbers. Transactions write output and consumer offsets atomically, so a crash aborts partial work. Consumers set to read_committed read only committed data, up to the last stable offset. Our 10,000-record crash simulation showed at-least-once producing 1,233 duplicates, idempotence alone leaving 1,115 and transactions with read_committed leaving none, while a read_uncommitted reader still saw all 1,115. Kafka Streams (exactly_once_v2) and Flink (EXACTLY_ONCE) wrap the mechanism, trading latency at commit or checkpoint boundaries. Kafka 4.0 hardened the protocol, Kafka 4.4 added transactional state stores, and sinks outside Kafka still need to be idempotent.

Sources

Cite this article

Kelahmet, Ö. C. (2026, November 25). Kafka exactly-once explained: idempotent producers, transactions and read_committed. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/kafka-exactly-once-idempotence-transactions

BibTeX
@online{kelahmet2026kafka,
  author = {Kelahmet, {\"O}zer Cem},
  title  = {{Kafka exactly-once explained: idempotent producers, transactions and read_committed}},
  year   = {2026},
  month  = {nov},
  url    = {https://www.ozercemkelahmet.com/articles/kafka-exactly-once-idempotence-transactions}
}
Version historyfirst version
  1. Published

Factual corrections are listed here with what changed. Wording and formatting edits are not listed.

Last updated Nov 25, 2026
Type to search.
    ↑↓ navigate↵ open