Setup
xml
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka-test</artifactId>
<scope>test</scope>
</dependency>
yaml
# application.yml
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
acks: all
properties:
enable.idempotence: true
linger.ms: 10
spring.json.add.type.headers: false
consumer:
group-id: email-service
auto-offset-reset: earliest
enable-auto-commit: false
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
properties:
spring.deserializer.value.delegate.class: org.springframework.kafka.support.serializer.JsonDeserializer
spring.json.value.default.type: com.example.shop.OrderCreated
spring.json.trusted.packages: com.example.shop
listener:
ack-mode: record
concurrency: 3
| Setting | Why |
ErrorHandlingDeserializer | Wraps the real deserializer so a bad message does not crash the consumer in an endless loop |
spring.json.trusted.packages | Security: only allow listed packages when deserializing JSON types |
listener.concurrency | Number of consumer threads in this app instance (up to the partition count) |
enable-auto-commit: false | Spring commits offsets after the listener returns (by ack-mode) |
Producing Messages
java
public record OrderCreated(String orderId, String customerId, double total) {}
@Service
public class OrderEventPublisher {
private final KafkaTemplate<String, OrderCreated> kafkaTemplate;
public OrderEventPublisher(KafkaTemplate<String, OrderCreated> kafkaTemplate) { this.kafkaTemplate = kafkaTemplate; }
public void publish(OrderCreated event) {
kafkaTemplate.send("shop.orders.created.v1", event.orderId(), event) // key = orderId keeps order per order
.whenComplete((result, ex) -> {
if (ex != null) {
log.error("Send failed for {}", event.orderId(), ex); // retry, store for later, or alert
} else {
RecordMetadata md = result.getRecordMetadata();
log.info("Sent to {}-{} offset {}", md.topic(), md.partition(), md.offset());
}
});
}
}
java
@Bean
NewTopic ordersTopic() { // Spring creates the topic at startup if missing (uses AdminClient)
return TopicBuilder.name("shop.orders.created.v1").partitions(6).replicas(3)
.config("min.insync.replicas", "2").build();
}
Consuming Messages
java
@Component
public class EmailListener {
@KafkaListener(topics = "shop.orders.created.v1", groupId = "email-service")
public void onOrder(@Payload OrderCreated event,
@Header(KafkaHeaders.RECEIVED_PARTITION) int partition,
@Header(KafkaHeaders.OFFSET) long offset) {
log.info("Order {} from partition {} offset {}", event.orderId(), partition, offset);
emailService.sendConfirmation(event); // must be idempotent (at-least-once delivery)
}
}
Receive the full record with ConsumerRecord<String, OrderCreated> record as the parameter to read key, headers and timestamp. Return normally to acknowledge. Throw an exception to trigger the error handler.
Batch Listener
java
@KafkaListener(topics = "shop.orders.created.v1", groupId = "warehouse-sync", batch = "true")
public void onBatch(List<ConsumerRecord<String, OrderCreated>> records) {
warehouseRepository.saveAll(records.stream().map(r -> toEntity(r.value())).toList()); // one DB round trip per poll
}
Manual Acknowledgement
java
// application.yml: spring.kafka.listener.ack-mode: manual
@KafkaListener(topics = "shop.orders.created.v1", groupId = "billing")
public void onOrder(OrderCreated event, Acknowledgment ack) {
billingService.charge(event);
ack.acknowledge(); // commit only after the work succeeded
}
| Ack mode | Commit happens |
record | After each record is processed |
batch (default) | After all records from one poll are processed |
manual / manual_immediate | When your code calls acknowledge() |
time / count | After a time or record-count threshold |
Error Handling: Retry then Dead Letter Topic
java
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
DeadLetterPublishingRecoverer recoverer = new DeadLetterPublishingRecoverer(template,
(record, ex) -> new TopicPartition(record.topic() + ".DLT", record.partition()));
ExponentialBackOffWithMaxRetries backOff = new ExponentialBackOffWithMaxRetries(4); // 4 retries
backOff.setInitialInterval(1000); backOff.setMultiplier(2.0); backOff.setMaxInterval(10000);
DefaultErrorHandler handler = new DefaultErrorHandler(recoverer, backOff);
handler.addNotRetryableExceptions(IllegalArgumentException.class, JsonProcessingException.class); // bad data will never succeed
return handler;
}
- The failing record is retried in place with backoff (blocking that partition)
- After the last retry it is published to
<topic>.DLT with headers describing the exception
- Create the DLT topic with at least as many partitions as the original, or use a function that always returns partition 0 or -1
Non-Blocking Retries with @RetryableTopic
java
@RetryableTopic(attempts = "4",
backoff = @Backoff(delay = 5000, multiplier = 3.0, maxDelay = 120000),
dltStrategy = DltStrategy.FAIL_ON_ERROR,
include = { TransientDownstreamException.class })
@KafkaListener(topics = "shop.orders.created.v1", groupId = "email-service")
public void onOrder(OrderCreated event) { emailService.sendConfirmation(event); }
@DltHandler
public void onDead(OrderCreated event, @Header(KafkaHeaders.EXCEPTION_MESSAGE) String reason) {
log.error("Order {} went to DLT: {}", event.orderId(), reason);
alertService.notifyOps(event, reason);
}
Spring creates topics such as shop.orders.created.v1-retry-0, -retry-1 and -dlt. Failed records move to the next retry topic, so the main topic keeps flowing. The trade-off is that ordering is not preserved for failed records.
Transactions (Read-Process-Write)
yaml
spring:
kafka:
producer:
transaction-id-prefix: order-processor-tx-
consumer:
isolation-level: read_committed
enable-auto-commit: false
java
@Transactional("kafkaTransactionManager")
@KafkaListener(topics = "orders", groupId = "order-processor")
public void process(Order order) {
kafkaTemplate.send("orders.validated", order.id(), validate(order)); // output and consumed offset commit atomically
}
Testing
java
@SpringBootTest
@EmbeddedKafka(partitions = 1, topics = "shop.orders.created.v1", bootstrapServersProperty = "spring.kafka.bootstrap-servers")
class OrderFlowTest {
@Autowired OrderEventPublisher publisher;
@MockBean EmailService emailService;
@Test
void listenerSendsEmail() {
publisher.publish(new OrderCreated("o-1", "c-7", 59.9));
verify(emailService, timeout(5000)).sendConfirmation(argThat(e -> e.orderId().equals("o-1")));
}
}
java
// closer to production: Testcontainers
@Testcontainers
@SpringBootTest
class OrderFlowContainerTest {
@Container static KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("apache/kafka:3.9.0"));
@DynamicPropertySource static void props(DynamicPropertyRegistry r) { r.add("spring.kafka.bootstrap-servers", kafka::getBootstrapServers); }
}
Production Tips
- Expose Micrometer metrics (
spring-boot-starter-actuator) for listener timing, producer errors and consumer lag
- Use
max.poll.records and max.poll.interval.ms to match your processing time
- Keep listeners small: map to a domain service, keep business logic testable
- Use a schema registry or versioned DTO classes, and avoid sharing one huge event class across services
- Always make handlers idempotent (store processed event ids, or use upserts)
Conclusion
With Spring Kafka you configure serializers in application.yml, send with KafkaTemplate, receive with @KafkaListener, protect against poison messages with ErrorHandlingDeserializer, use DefaultErrorHandler plus DLT or @RetryableTopic, and test with EmbeddedKafka or Testcontainers.
Quick Summary: KafkaTemplate + @KafkaListener; ErrorHandlingDeserializer; DefaultErrorHandler + DLT; @RetryableTopic; EmbeddedKafka.