Apache Kafka — Event Streaming from Basics to a Platform Service›10 · Delivery guarantees and exactly-once

Lesson 10 of 17 · How Kafka works

Delivery guarantees and exactly-once

What delivery guarantees really mean and where they break: at-most-once, at-least-once and exactly-once; the idempotent producer; Kafka transactions and read_committed consumers for exactly-once inside Kafka; why writing to a database and Kafka together loses or duplicates data, and how the outbox pattern fixes it; designing idempotent consumers; and handling poison messages with retry and dead-letter topics.

Advanced
Key wordsdelivery semanticsat-most-onceat-least-onceexactly-onceEOSidempotent producertransactionstransactional.idread_committedisolation.levelconsume-transform-producedual writeoutbox patternidempotent consumerdeduplicationdead-letter topicDLQpoison messageretry topic

Three guarantees

Guarantee Means How you get it Risk
At-most-once Each record processed 0 or 1 times Commit offsets before processing Loss on crash
At-least-once 1 or more times Commit after processing; producer retries Duplicates on crash or retry
Exactly-once Effect happens once Transactions within Kafka, or at-least-once + idempotent processing Complexity

Most systems choose at-least-once delivery and make processing idempotent, so a duplicate has no extra effect. That gives "effectively once" end to end.

You post an important letter. At-most-once: you post it once and hope; it might get lost. At-least-once: you keep posting a copy every day until the reply comes, so it arrives, but maybe twice. Exactly-once: the receiver keeps a list of letter numbers they've already opened, so when a second copy of letter 42 arrives, they bin it without reading.

Where duplicates come from

  1. Producer retries: fixed by the idempotent producer (lesson 6), on by default.
  2. Consumer crashes after processing but before committing: the records are processed again after restart or rebalance.
  3. Application re-sends: your service restarts and publishes the same business event again.

Only the first is solved inside the client. The others need design.

Exactly-once inside Kafka: transactions

A common pattern is consume → transform → produce: read from topic A, write results to topic B. Kafka transactions make the output records and the consumed offsets commit atomically:

producer.initTransactions()                # uses a stable transactional.id
loop:
    records = consumer.poll()
    producer.beginTransaction()
    for r in records: producer.send(topicB, transform(r))
    producer.sendOffsetsToTransaction(offsets, consumer.groupMetadata())
    producer.commitTransaction()           # all or nothing
  • A transaction coordinator on the brokers tracks it, using the internal __transaction_state topic.
  • If the producer crashes, the transaction is aborted; a restarted instance with the same transactional.id fences the old one so a "zombie" cannot commit.
  • Downstream consumers must use isolation.level=read_committed to skip aborted and in-progress records.
  • Kafka Streams does all of this with one setting: processing.guarantee=exactly_once_v2.

Transactions stop at Kafka's edge

Exactly-once covers reading from and writing to Kafka. The moment you call an external API, send an email or write to a database, that side effect is outside the transaction. For those, use idempotent operations or the outbox pattern.

The dual-write problem and the outbox pattern

A service often must change its database and publish an event:

BEGIN; INSERT INTO orders …; COMMIT;     ✔
producer.send("orders", OrderPlaced)      ✘ crash here → order saved, event never sent

Swapping the order is no better (event sent, database write fails). Two systems cannot be updated atomically by your code.

The outbox pattern: write the event into an outbox table in the same database transaction as the business change. A separate process reads the outbox and publishes to Kafka:

BEGIN;
  INSERT INTO orders (...) VALUES (...);
  INSERT INTO outbox (id, topic, key, payload) VALUES (uuid, 'orders', 'order-123', '{...}');
COMMIT;                                          ← both or neither

outbox relay ──► Kafka                         (CDC with Debezium, or a polling publisher)

The relay is at-least-once, so the event may be published twice; consumers deduplicate with the event's unique id. Lesson 12 shows Debezium, which reads the outbox from the database's change log.

Designing idempotent consumers

Make the effect of processing a record the same whether it runs once or three times:

Technique Example
Natural idempotence SET status = 'paid' rather than balance = balance - 10
Upsert by key INSERT … ON CONFLICT (order_id) DO UPDATE
Deduplication table Store each processed event ID; skip IDs already seen, in the same database transaction as the change
Version checks Apply an update only if its version is newer than the stored one
Idempotency keys for APIs Send the event ID as the idempotency key to payment providers

Every event should therefore carry a unique ID (and usually a version or timestamp).

Poison messages, retries and dead-letter topics

A poison message fails every time (bad data, a bug). Because a partition is processed in order, retrying it forever blocks everything behind it and lag grows.

orders ──► consumer ──fails──► retry (with backoff, a few times)
                    └─still failing──► orders.dlq  (+ headers: error, stack, original topic/partition/offset)
                    └─ commit and continue
  • Retry in place a few times for transient errors (timeouts).
  • For longer waits, publish to a retry topic consumed later, so the main partition keeps moving (note: this gives up strict ordering for that key).
  • After the limit, send the record to a dead-letter topic (DLQ) with error details in headers, alert, and continue.
  • Provide a replay tool to move fixed records from the DLQ back to the main topic.

Try it: see transactions and duplicates

  1. On the lab cluster, start a console consumer with --isolation-level read_committed and another without it, on the same topic.
  2. Write a short program (any client library) that begins a transaction, sends three records, and aborts. Which consumer shows them?
  3. Simulate at-least-once: process records with a script that writes to a file, kill it before committing, restart, and count duplicates.
  4. Add deduplication by record ID and repeat. Are there still duplicate effects?

Going deeper

  • Transactions add latency (a commit per batch) and coordinator load; use them where the guarantee matters, not everywhere.
  • Each producer instance needs its own stable transactional.id (for example derived from the pod name in a StatefulSet).
  • Ordering and DLQs conflict: if per-key order is critical, a failing record may need to pause that key rather than skip it.

Recap

  • At-least-once + idempotent consumers is the usual, robust choice.
  • Transactions + read_committed give exactly-once for consume-transform-produce inside Kafka.
  • Writing to a database and Kafka together needs the outbox pattern.
  • Give every event a unique ID; design consumers so duplicates have no extra effect.
  • Handle poison messages with bounded retries and a dead-letter topic.

This site is a public version of my personal engineering knowledge hub. It intentionally excludes confidential company information and internal operational details.