Kafka Producers, Consumers and Delivery Guarantees

Producing and consuming safely: batching and partitioning, idempotent producers, at-most-once vs at-least-once vs exactly-once, Kafka transactions and read_committed, offset management, rebalancing, retries, dead-letter topics and backpressure, with Spring for Apache Kafka examples.

On this page

Simple definition#

A producer writes records to topic partitions. A consumer reads them and records its progress as offsets. Delivery guarantees describe what happens to a record when something fails in between: it can be lost, duplicated or processed exactly once.

The problem#

Networks drop acknowledgements, brokers fail over and consumers crash after doing work but before committing their offset. Without care you will lose events (a missed payment notification) or duplicate them (a double debit). You need to know which guarantee each flow needs and how to get it.

The three delivery semantics#

Semantics How it happens Risk Use for
At most once Commit the offset before processing; no producer retries Loss Metrics where gaps do not matter
At least once Process, then commit; producer retries Duplicates The default for most business events, with idempotent consumers
Exactly once Idempotent producer + transactions + read_committed Complexity; Kafka-to-Kafka only Stream processing pipelines inside Kafka

The producer#

Producer internals
flowchart LR
    APP["send(record)"] --> SER["Serialize<br/>key + value"] --> PART["Partitioner<br/>hash(key)"] --> ACC["Record accumulator<br/>batches per partition"] --> SENDER["Sender thread<br/>compress, send"] --> B["Leader broker"]
    B -->|"ack / error"| SENDER

Important producer settings:

Setting Recommendation Why
acks all Durable against a leader failure
enable.idempotence true (default since 3.0) The broker de-duplicates retries using producer ID + sequence number
retries / delivery.timeout.ms High retries, bounded total timeout (for example 120 s) Retry transient errors without hanging forever
max.in.flight.requests.per.connection ≤ 5 with idempotence Keeps ordering while pipelining
linger.ms / batch.size 5–20 ms, 64–256 KB Bigger batches mean higher throughput
compression.type zstd or lz4 Less network and disk use

Transactions and exactly-once#

A transactional producer (transactional.id) writes to several partitions and commits consumer offsets atomically. Downstream consumers with isolation.level=read_committed see only committed data.

Exactly-once consume, process, produce in Kafka · drawn with Archify · zoom, guided views, search and SVG/PNG export. © 2026 Samir Kumar Sahoo, all rights reserved. Open full screen ↗
  • Zombie fencing: a stable transactional.id plus an epoch means a restarted instance fences off an old “zombie” instance, which can no longer commit.
  • Transactions version 2 (KIP-890, in the Kafka 4.x line) hardens the protocol against hanging transactions with server-side defences.
  • Cost: a little extra latency (commit markers) and throughput overhead. Kafka Streams and Flink use this under the hood when you configure processing.guarantee=exactly_once_v2 or the exactly-once sink mode.

The consumer#

Consumer loop (at-least-once)
flowchart LR
    POLL["poll()"] --> PROC["process records<br/>(idempotently)"] --> COMMIT["commit offsets<br/>after success"] --> POLL
    PROC -->|"transient error"| RETRY["retry with backoff"]
    RETRY -->|"still failing"| DLT["dead-letter topic"]
  • Offsets: turn off auto-commit for business processing (enable.auto.commit=false) and commit after the work succeeds.
  • max.poll.interval.ms: if processing a batch takes longer than this, the consumer is evicted and its partitions rebalance. Keep batches small, or hand slow work to a share group or a worker pool.
  • Rebalancing: prefer the new consumer protocol (group.protocol=consumer, KIP-848) for incremental, broker-coordinated assignment. With the classic protocol, use the cooperative-sticky assignor.
  • Static membership (group.instance.id) avoids rebalances during rolling restarts.
  • Lag (log-end offset minus committed offset) is the main health signal. Alert on lag growth and on time-based lag.

Retries, dead letters and poison messages#

Error type Handling
Transient (timeout, 503) Retry with exponential backoff and jitter; then a retry topic for longer delays
Permanent (validation, deserialisation) Send straight to a dead-letter topic (DLT) with error headers; alert; fix and replay
Ordering-sensitive key Blocking retry, or park all later events for that key; do not skip ahead

Share groups (Kafka 4.2) add broker-side delivery counts. A record that keeps failing can be REJECTed or sent to a dead-letter queue after N attempts, without custom retry topics.

Example: Spring for Apache Kafka#

@Configuration
class KafkaConfig {
  @Bean
  DefaultErrorHandler errorHandler(KafkaTemplate<String, Object> template) {
    var recoverer = new DeadLetterPublishingRecoverer(template);            // -> payments.authorised.v1-dlt
    var backoff = new ExponentialBackOffWithMaxRetries(5);
    backoff.setInitialInterval(500); backoff.setMultiplier(2.0);
    var handler = new DefaultErrorHandler(recoverer, backoff);
    handler.addNotRetryableExceptions(ValidationException.class);           // permanent: straight to DLT
    return handler;
  }
}

@Component
class PaymentListener {
  private final ProcessedEventRepository processed;   // idempotency store
  private final LedgerService ledger;

  @KafkaListener(topics = "payments.authorised.v1", groupId = "ledger-posting")
  @Transactional
  public void on(PaymentAuthorised event) {
    if (!processed.markIfNew(event.eventId())) return;  // duplicate: already handled
    ledger.post(event);                                  // same DB transaction as the marker
  }
}

The listener is at-least-once plus idempotent. The processed-event marker and the business update commit in one database transaction, so a redelivery after a crash is harmless.

Backpressure and flow control#

Kafka consumers pull, so backpressure is natural: a slow consumer simply lags. Protect downstream systems by:

  • capping concurrency (concurrency in Spring, the number of consumer instances)
  • pausing partitions when a downstream circuit breaker opens (consumer.pause())
  • using quotas on brokers for noisy clients.

Common mistakes#

Quick check#

What does the idempotent producer prevent? Duplicate records caused by producer retries. The broker de-duplicates using the producer ID and sequence numbers.

What do Kafka transactions make atomic? Writes to several partitions plus the consumer offset commit, so a consume-process-produce step either fully happens or not at all.

Why is exactly-once not enough when writing to a database? The database is outside the Kafka transaction. You need at-least-once delivery with an idempotent consumer, or the outbox pattern.

When should offsets be committed for at-least-once? After processing succeeds, never before.

What is a dead-letter topic? A topic for records that cannot be processed (permanent errors). It has error metadata, so the main flow continues and the bad records can be fixed and replayed.

What does isolation.level=read_committed do? The consumer skips records from aborted transactions and does not read past open transactions.

Summary#

  • Pick a delivery guarantee per flow. At-least-once plus idempotent consumers is the workhorse.
  • Producers: acks=all, idempotence on, bounded retries, sensible batching and compression.
  • Transactions give exactly-once for Kafka-to-Kafka processing. Side effects need idempotency.
  • Consumers: commit after success, watch lag, use the new rebalance protocol, and route poison messages to dead-letter topics.

References#