Kafka Delivery Semantics
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:
| Guarantee | Loss possible? | Duplicates possible? | How you get it | Typical use |
|---|---|---|---|---|
| At-most-once | Yes | No | Commit before processing; producer without retries | Metrics, logs where gaps are acceptable |
| At-least-once | No | Yes | Process, then commit; acks=all with retries | Most business events, with idempotent consumers |
| Exactly-once | No | No (inside Kafka) | Idempotent producer, transactions, read_committed consumers | Kafka-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:
| Failure | Effect | Prevented by |
|---|---|---|
The leader acknowledged with acks=1 and then crashed before followers copied the record | Loss of an acknowledged record | acks=all with min.insync.replicas=2 |
| The write succeeded but the acknowledgement was lost; the producer retried | Duplicate in the log | Idempotent producer (default since Kafka 3.0) |
Retries ran out (delivery.timeout.ms) and the error was only logged | Loss | Handle the callback error: alert, or use an outbox |
| The application crashed with records still in the producer buffer | Loss | flush()/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.
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:
- Idempotent producer: producer retries never duplicate a record in a partition.
- Transactions: a producer with a
transactional.idwrites output records to several partitions and commits the consumer’s offsets withsendOffsetsToTransaction(), all in one atomic transaction. 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.
7. How Kafka Prevents Message Loss
No single setting prevents loss; every hop has to be configured for it:
| Layer | Setting or practice | Why |
|---|---|---|
| Producer | acks=all, idempotence on, sensible delivery.timeout.ms | A send counts as successful only when all in-sync replicas have it |
| Producer code | Check the send result; never ignore callback errors | A failed send after retries is otherwise silent |
| Topic | Replication factor 3, min.insync.replicas=2 | One broker can fail without losing acknowledged data or blocking writes |
| Broker | unclean.leader.election.enable=false (default) | An out-of-sync replica never becomes leader and silently drops records |
| Consumer | Commit after processing; auto-commit only with synchronous processing | A crash leads to reprocessing, not skipping |
| Operations | Retention longer than the worst consumer outage; alert on lag | Unread 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 duplicate | Removed by |
|---|---|
| Producer-internal retry after a lost acknowledgement | Kafka: idempotent producer |
| Partial failure in a consume–transform–produce step | Kafka: 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 commit | Application: idempotent consumer, or offsets stored with the data |
| Outbox relay republishes after a crash | Application: 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=allwithmin.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.
12. Related Reading
- How Kafka Transactions Work Internally
- Idempotent Consumer in Kafka
- Transactional Outbox Pattern with Kafka
- Kafka Broker Failure and Recovery
13. References
- Apache Kafka design: Message delivery semantics
- Apache Kafka 4.4: Producer configs (acks, enable.idempotence, delivery.timeout.ms)
- Apache Kafka 4.4: Consumer configs (enable.auto.commit, isolation.level)
- Apache Kafka 4.4 Javadoc: KafkaConsumer (offsets and consumer position)
- Spring for Apache Kafka: Exactly Once Semantics
Kafka Delivery Semantics Interview Questions and Answers
Common interview questions on Kafka Delivery Semantics, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. How does the moment a consumer commits its offset decide its delivery semantics?
Answer: Committing before processing gives at-most-once: if the consumer crashes after the commit, the unprocessed records are skipped. Committing after processing gives at-least-once: a crash before the commit means the records are delivered and processed again. Committing the offsets inside a Kafka transaction together with the output records, through sendOffsetsToTransaction(), gives exactly-once for Kafka-to-Kafka processing, because output and progress succeed or fail as one unit.
Q. How does a consumer tell Kafka that a message has been received and processed?
Answer: By committing an offset per partition, not by acknowledging individual messages. The committed value is the offset of the next record to read, stored by the group coordinator in __consumer_offsets, and it confirms every earlier record in that partition. Commits happen automatically (enable.auto.commit), manually with commitSync/commitAsync, or through the listener container in Spring. Committing after processing makes the consumer at-least-once.
Intermediate questions
Q. Messages can be lost at the producer, the broker and the consumer. Give one cause and its fix for each.
Answer: Producer: a send fails after its retries and the callback only logs it; handle the error or publish through an outbox. Broker: the leader acknowledged with acks=1 and died before replication, or an out-of-sync replica became leader; use acks=all, replication factor 3, min.insync.replicas=2 and keep unclean leader election off. Consumer: the offset was committed before processing finished, or retention deleted records the consumer had not read yet; commit after processing and keep retention longer than the worst outage.
Q. Which duplicates does Kafka remove by itself, and which must the application handle?
Answer: Kafka removes duplicates caused by producer-internal retries (idempotent producer) and hides partial results of failed consume–transform–produce steps (transactions with read_committed). It cannot detect a second send() of the same event by the application or an outbox relay, or a record reprocessed because the consumer crashed before committing. Those need a stable event ID and an idempotent consumer.
Tricky and scenario questions
Q. Does exactly-once in Kafka mean each record is delivered to the consumer only once?
Answer: No. Records can still be fetched more than once; for example, after an aborted transaction the input is read again. Exactly-once means the effect in Kafka happens once: the output records and offset commits of a processing step become visible exactly once. Effects outside Kafka, such as database writes or HTTP calls made during processing, are not covered and can repeat.
Q. To raise throughput, a consumer commits offsets with commitAsync() right after poll() and processes the records afterwards. Which guarantee does it now provide?
Answer: At-most-once. The commit can succeed before processing finishes, so if the consumer crashes or loses its partitions in a rebalance mid-batch, the new owner starts after the committed position and the unfinished records are never processed. To keep at-least-once without slowing down, commit asynchronously after processing each batch, and do a final commitSync() on shutdown and when partitions are revoked.