Sub topic 9
Offset commits and acknowledgment modes
This chapter assumes you can run a Spring Boot application with a @KafkaListener, and that you know the topic, partition, offset and consumer group model from the earlier chapters. It covers what a committed offset is, when Spring commits it, and how to take control of that timing.
What a committed offset is
A consumer group tracks its progress per partition. That progress is stored in Kafka itself, in an internal topic called __consumer_offsets. Each entry is keyed by group, topic and partition, and its value is a single number: the offset of the next record the group should read.
If the last record you processed on partition 0 had offset 41, the committed offset is 42. When a consumer restarts, or when a rebalance moves the partition to another consumer, reading resumes at the committed offset.
Two points follow from this:
- Kafka does not track individual records as "done". It stores one position per partition. Committing offset 42 means everything before 42 is treated as finished.
- Committing is separate from reading. A consumer can read many records past its committed offset. The committed offset only matters after a restart or rebalance.
If a group has no committed offset for a partition, the auto-offset-reset property decides where to start. earliest starts at the oldest record. latest starts at the end. It has no effect once an offset is committed.
Why the commit moment decides your delivery guarantee
The time between processing a record and committing its offset is a window for failure.
- Commit before processing. If the consumer crashes after committing but before finishing, the record is skipped. This is at-most-once delivery.
- Commit after processing. If the consumer crashes after finishing but before committing, the record is delivered again after restart. This is at-least-once delivery.
Spring Kafka commits after your listener returns, so the default is at-least-once. Your listener can therefore see the same record twice.
Auto-commit versus container-managed commits
The plain Kafka client has enable.auto.commit. When it is true, the client commits the offsets returned by the last poll() on a timer, every auto.commit.interval.ms (5 seconds by default). The timer has no knowledge of whether your code finished with those records. A slow handler can have its records committed before it completes them.
Spring for Apache Kafka sets enable.auto.commit to false unless you set it yourself. The listener container then commits offsets according to its ack mode. Leave client auto-commit off in a Spring application. Mixing it with container commits makes it hard to say when a record counts as done.
Ack modes
The ack mode is a property of the listener container. In Spring Boot you set it with spring.kafka.listener.ack-mode.
| Ack mode | When the offset is committed |
|---|---|
| `BATCH` (default) | After all records from one `poll()` have been processed |
| `RECORD` | After each record's listener call returns |
| `TIME` | After a batch is processed, once `ack-time` has elapsed since the last commit |
| `COUNT` | After a batch is processed, once `ack-count` records have been seen since the last commit |
| `COUNT_TIME` | When either the `TIME` or the `COUNT` condition is met |
| `MANUAL` | After your code calls `acknowledge()`, queued and committed after the current batch is processed |
| `MANUAL_IMMEDIATE` | Immediately when your code calls `acknowledge()` |
The modes trade throughput against the amount of work repeated after a failure.
BATCHmakes one commit per poll. This is cheap, but a crash in the middle of a batch redelivers the whole batch. The batch size is capped bymax.poll.records(500 by default).RECORDmakes one commit per record. A crash redelivers at most the record in flight. It costs one broker round trip per record, which reduces throughput.TIME,COUNTandCOUNT_TIMEreduce commit frequency further. They widen the redelivery window.
All of these still give at-least-once delivery. The choice only changes how many records can be repeated.
Configuring the ack mode
This extends the application.yml from the setup chapter. Only the listener section is new.
spring:
kafka:
bootstrap-servers: localhost:9092
consumer:
group-id: order-service
auto-offset-reset: earliest
enable-auto-commit: false
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
properties:
spring.json.trusted.packages: com.example.orders
spring.json.value.default.type: com.example.orders.OrderEvent
listener:
ack-mode: recordWith ack-mode: record, the offset moves forward after every successful call to your listener method. No listener code changes.
Manual acknowledgment
Sometimes the container cannot know when a record is truly done. For example, your listener may hand work to another thread, or you may want to commit only after a database write succeeds. Set the mode to manual or manual_immediate, and add an Acknowledgment parameter to the listener.
spring:
kafka:
listener:
ack-mode: manual_immediatepackage com.example.orders;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;
@Component
public class ManualAckOrderListener {
private static final Logger log = LoggerFactory.getLogger(ManualAckOrderListener.class);
private final Set<String> processedOrderIds = ConcurrentHashMap.newKeySet();
@KafkaListener(topics = "orders", groupId = "order-service")
public void onOrder(OrderEvent event, Acknowledgment ack) {
if (!processedOrderIds.add(event.orderId())) {
log.info("Skipping duplicate order {}", event.orderId());
ack.acknowledge();
return;
}
log.info("Processing order {} for {} cents", event.orderId(), event.amountCents());
ack.acknowledge();
}
}The in-memory set stands in for a durable store, such as a unique key in a database. It shows the pattern: because delivery is at-least-once, the handler must tolerate duplicates.
The difference between the two manual modes:
MANUALrecords the acknowledgment and commits it once the container has finished processing the current batch of records. Severalacknowledge()calls merge into one commit.MANUAL_IMMEDIATEcommits at the moment you callacknowledge(). This gives the smallest redelivery window, at the cost of more commits.
If the listener method returns without calling acknowledge(), the offset is not committed. The container keeps reading later records, so a later acknowledgment on the same partition also covers the skipped one.
Acknowledging out of order
Because a committed offset is a position, acknowledging offset 45 implies offsets 42 to 44 are done too. In Spring Kafka, acknowledging out of order is not supported when you process on your own threads. If you hand records to a thread pool and acknowledge them as they finish, a fast record 45 can cause the commit to pass a still-running record 43. A crash then loses 43.
Either process each record in the listener thread, or hold acknowledgment until all earlier records on that partition are finished.
Not acknowledging: nack
When processing fails and you want the record redelivered, you have two options. Throw an exception and let the error handler decide, as covered in the error handling chapter. Or call ack.nack(Duration) in manual modes:
@KafkaListener(topics = "orders", groupId = "order-service")
public void onOrder(OrderEvent event, Acknowledgment ack) {
try {
handle(event);
ack.acknowledge();
} catch (TemporaryFailureException e) {
ack.nack(java.time.Duration.ofSeconds(2));
}
}nack makes the container pause, seek back to the failed record, and redeliver it after the given sleep. It must be called from the listener thread. The records after the failed one in the same poll are also redelivered, to keep partition order.
Interaction with rebalances
A rebalance can occur while records are being processed. When a partition is taken away, the container commits offsets for records already processed in the current batch, according to the ack mode. Records read but not processed are redelivered to the new owner.
Two settings affect this:
max.poll.interval.ms(5 minutes by default) is the longest allowed gap betweenpoll()calls. A listener that runs longer than this gets the consumer removed from the group, its commit fails, and the records are redelivered to someone else. Reducemax.poll.recordsor speed up the handler.- Larger batches mean more work is repeated after a rebalance.
Common mistakes
- Acknowledging before the work is durable. If you call
acknowledge()and then write to the database, a crash between the two loses the record. - Forgetting that
Acknowledgmentonly works in a manual ack mode. WithBATCHorRECORD, the container does not provide it, and the listener method fails to bind. - Assuming exactly-once delivery from
RECORDmode. It reduces repeats, but does not remove them. - Setting
auto-offset-reset: earliestand expecting it to replay records for a group that already has committed offsets. It does not. Change the group ID or reset the offsets with thekafka-consumer-groupstool.
Exercise
A listener uses ack mode BATCH with max.poll.records at 500. The consumer processes 300 records of a poll, then the JVM is killed. What happens to those 300 records after restart, and which delivery guarantee does this show?
Show answer
None of the 300 records were committed, because BATCH commits only after the whole poll has been processed. After restart, the group resumes from the last committed offset, so all 300 records are delivered again. This is at-least-once delivery. The listener must handle duplicates.
Exercise
You use MANUAL_IMMEDIATE and call ack.acknowledge() as the first line of your listener, before saving the order to the database. The save then throws an exception. Is the record redelivered? How should you change the code?
Show answer
No. The offset was already committed, so the record is skipped and lost. This is at-most-once behavior. Move acknowledge() to after the database save succeeds, and make the save safe to repeat, for example with a unique constraint on the order ID.