00:00

Kafka Delivery Semantics

Last updated:

Kafka delivery semantics describe what can happen to a message between the producer and the consumer’s finished processing: can it be lost, can it be processed twice, or neither? Kafka supports all three classic guarantees, at-most-once, at-least-once and exactly-once, and which one you get is decided by a handful of producer, broker and consumer settings plus the point at which your consumer commits its offset.

This article explains each guarantee, how messages get lost or duplicated at each hop, how a consumer confirms that a message was processed, and the settings that prevent message loss. Examples use the Kafka 4.4 Java client.

1. What Are Delivery Semantics?

A message passes two hops: producer → broker (the write) and broker → consumer (the read and processing). Failures can happen on either hop, for example a lost network response, a crashed broker or a consumer killed mid-batch. Delivery semantics state what the system promises despite those failures:

  • Is every message processed at least once (no loss)?
  • Is every message processed at most once (no duplicates)?
  • Or both, which is exactly once?

The guarantee of the whole pipeline is only as strong as its weakest hop. An idempotent producer combined with a consumer that commits before processing is still at-most-once end to end.

2. At-Most-Once, At-Least-Once and Exactly-Once

On the consumer side, the guarantee follows directly from when the offset is committed relative to processing:

How commit timing decides Kafka delivery semanticsAt-most-once: the consumer polls, commits the offset, then processes; a crash during processing loses the record. At-least-once: the consumer polls, processes, then commits; a crash before the commit means the record is processed again. Exactly-once: the consumer polls, then writes its output records and the consumer offsets in one Kafka transaction; a crash aborts the transaction and the retry leaves no visible duplicate. At-most-once poll commit offset process ✕ crash hererecord lost At-least-once poll process commit offset ✕ crash hereprocessed again(duplicate) Exactly-once poll one Kafka transaction:output records + consumer offsets commit together crash → transaction aborted → retried as a wholeno visible duplicate
Commit before processing risks loss; commit after processing risks duplicates; committing output and offsets atomically in a transaction gives exactly-once inside Kafka.
GuaranteeLoss possible?Duplicates possible?How you get itTypical use
At-most-onceYesNoCommit before processing; producer without retriesMetrics, logs where gaps are acceptable
At-least-onceNoYesProcess, then commit; acks=all with retriesMost business events, with idempotent consumers
Exactly-onceNoNo (inside Kafka)Idempotent producer, transactions, read_committed consumersKafka-to-Kafka processing: stream jobs, aggregations

3. How a Consumer Confirms Processing

Kafka has no per-message acknowledgement like JMS or RabbitMQ. A consumer confirms progress by committing an offset for each partition: the offset of the next record it wants to read. The group coordinator stores this in the internal __consumer_offsets topic. Committing offset 43 confirms everything up to and including offset 42 in that partition.

This has two consequences. First, a consumer cannot acknowledge record 45 while record 44 is still in progress; commits are cumulative. Second, after a crash or a rebalance, the new owner of a partition starts at the last committed offset, so anything processed after that commit is processed again. Commit APIs (commitSync, commitAsync, auto-commit, Spring ack modes) are covered in Kafka Offset Management.

4. The Producer Side: Loss and Duplicates on Write

The producer decides whether a message is safely stored before the application moves on:

FailureEffectPrevented by
The leader acknowledged with acks=1 and then crashed before followers copied the recordLoss of an acknowledged recordacks=all with min.insync.replicas=2
The write succeeded but the acknowledgement was lost; the producer retriedDuplicate in the logIdempotent producer (default since Kafka 3.0)
Retries ran out (delivery.timeout.ms) and the error was only loggedLossHandle the callback error: alert, or use an outbox
The application crashed with records still in the producer bufferLossflush()/close() on shutdown; outbox for critical events

The Producer Acknowledgment tutorial explains acks=0, 1 and all in detail, and Idempotent Producer explains how retries stay duplicate-free.

5. The Consumer Side: Commit Timing in Code

The same consumer becomes at-most-once or at-least-once depending on one line. At-least-once: process the batch, then commit.

AtLeastOnceConsumer.java
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "invoice-service");
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);          // we decide when to commit
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
    consumer.subscribe(List.of("orders"));
    while (running) {
        ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));
        for (ConsumerRecord<String, String> record : records) {
            invoiceService.createInvoice(record.key(), record.value());   // 1. process
        }
        if (!records.isEmpty()) {
            consumer.commitSync();                                       // 2. then commit
        }
    }
}

Moving commitSync() above the processing loop turns this into at-most-once: a crash after the commit skips the uncommitted work forever. Kafka’s auto-commit commits during a later poll(), so it behaves as at-least-once only while all processing happens synchronously in the poll loop; handing records to another thread and returning makes it at-most-once by accident.

6. How Exactly-Once Works in Kafka

Exactly-once in Kafka is built from three features working together:

  1. Idempotent producer: producer retries never duplicate a record in a partition.
  2. Transactions: a producer with a transactional.id writes output records to several partitions and commits the consumer’s offsets with sendOffsetsToTransaction(), all in one atomic transaction.
  3. isolation.level=read_committed: downstream consumers only see records from committed transactions.

If anything fails, the transaction aborts: its output is never shown to read_committed consumers and its offsets are not committed, so the input is processed again from the old position. Kafka Streams wraps all of this behind processing.guarantee=exactly_once_v2, and Spring for Apache Kafka enables it when spring.kafka.producer.transaction-id-prefix is set. The internals are covered in How Kafka Transactions Work Internally.

The boundary: exactly-once covers reading from Kafka and writing to Kafka. A database insert, an email or a REST call made during processing is outside the transaction and can still happen twice. For those, use an idempotent consumer.

7. How Kafka Prevents Message Loss

No single setting prevents loss; every hop has to be configured for it:

LayerSetting or practiceWhy
Produceracks=all, idempotence on, sensible delivery.timeout.msA send counts as successful only when all in-sync replicas have it
Producer codeCheck the send result; never ignore callback errorsA failed send after retries is otherwise silent
TopicReplication factor 3, min.insync.replicas=2One broker can fail without losing acknowledged data or blocking writes
Brokerunclean.leader.election.enable=false (default)An out-of-sync replica never becomes leader and silently drops records
ConsumerCommit after processing; auto-commit only with synchronous processingA crash leads to reprocessing, not skipping
OperationsRetention longer than the worst consumer outage; alert on lagUnread records deleted by retention are gone for that consumer

Broker-side durability is explained further in Kafka Fault Tolerance and Kafka Broker Failure and Recovery.

8. How Kafka Handles Duplicate Messages

Kafka removes some duplicates itself; the rest are the application’s job. Knowing which is which avoids false confidence:

Source of the duplicateRemoved by
Producer-internal retry after a lost acknowledgementKafka: idempotent producer
Partial failure in a consume–transform–produce stepKafka: transactions with read_committed
Application resends the same event (new send() call)Application: stable event ID + idempotent consumer
Consumer crash or rebalance before the offset commitApplication: idempotent consumer, or offsets stored with the data
Outbox relay republishes after a crashApplication: idempotent consumer

9. Choosing a Guarantee

  • Default choice for business events: at-least-once delivery plus idempotent consumers. It is simple, fast and safe.
  • Kafka-to-Kafka pipelines (enrichment, aggregation, Kafka Streams): exactly-once with transactions.
  • High-volume, loss-tolerant data (telemetry sampling, debug logs): at-most-once can be acceptable if it measurably saves resources.

10. Common Mistakes

  • Calling exactly-once “end to end” when the consumer writes to a database.
  • Processing asynchronously with auto-commit enabled, which commits records that have not been processed yet.
  • Using acks=all with min.insync.replicas=1, which still acknowledges after a single copy when followers fall behind.
  • Ignoring the producer callback, so records that failed after all retries disappear silently.
  • Reading transactional topics with the default read_uncommitted, which exposes records from aborted transactions.

11. Summary

Kafka offers at-most-once, at-least-once and exactly-once semantics. On the write path, acks=all, idempotence and replicated topics prevent loss and producer duplicates. On the read path, committing offsets after processing gives at-least-once, and transactions with read_committed give exactly-once for Kafka-to-Kafka processing. Duplicates caused by resends, rebalances and side effects outside Kafka are handled by idempotent consumers, so at-least-once plus idempotent consumers is the most common production design.

13. References