Sub topic 3
Reliable Delivery in Spring Boot with Kafka
This chapter assumes Java, Spring Boot beans, application.yml, and basic Kafka concepts such as topics, partitions, and consumer groups.
Reliable producer delivery
A producer's acks setting controls how much broker confirmation it requires. With acks: all, Kafka waits for all in-sync replicas before confirming the send. enable.idempotence: true prevents producer retries from creating duplicate records. Idempotence is safe when the producer uses compatible settings, including acks: all.
spring:
kafka:
producer:
acks: all
retries: 10
properties:
enable.idempotence: trueKafkaTemplate.send is asynchronous. Inspect its CompletableFuture to record success or failure. A successful future means Kafka accepted the record according to the configured acknowledgment level. It does not mean that a consumer completed its business action.
Listener retries and back-off
A listener error handler decides what happens when a @KafkaListener method throws an exception. A back-off is the delay between attempts. This handler retries a record three times, waiting one second between attempts:
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
var recoverer = new DeadLetterPublishingRecoverer(template);
var backOff = new FixedBackOff(1000L, 3L);
return new DefaultErrorHandler(recoverer, backOff);
}After the retries are exhausted, the recoverer publishes the record to a dead-letter topic. By default, Spring Kafka commonly uses a name such as orders.DLT. Configure the destination explicitly when your operations or security rules require a different name. A dead-letter consumer should preserve the original record details and alert an operator rather than silently discarding the message.
Transactions with Spring
Use Kafka transactions when several Kafka sends must commit or roll back together. Configure a transaction ID prefix:
spring:
kafka:
producer:
transaction-id-prefix: orders-tx-Then use Spring's Kafka transaction manager with @Transactional. A transaction can atomically publish multiple records. It does not automatically include an arbitrary database transaction. Coordinating Kafka and a database requires careful design, such as an outbox pattern.
Testing Kafka code
Use Testcontainers for tests that need a real Kafka broker and realistic serialization, partitions, and offsets. An embedded broker can make focused tests faster. Test that a producer sends the expected key and payload, and that a listener processes a record. Also test failure behavior: verify retry attempts and the final DLT record.
Exercise
Why can a listener process the same Kafka record more than once?
Show answer
The listener can fail before its offset is committed, so Kafka delivers the record again after a retry or restart.