Skip to content
Kafka Is Fun

Production Patterns · Intermediate · Topic 4 of 5

Batch Listener Pattern

A batch listener receives all the records one poll() returned, in one call. With the BATCH ack mode the offsets are committed once the whole batch has been processed. RECORD ack mode is not supported for batch listeners, and neither are non-blocking retries.

BatchOrderConsumer.javajava
@Service
@Slf4j
public class BatchOrderConsumer {

    // Receives every record from one poll(); ackMode MANUAL lets us acknowledge when the batch is done
    @KafkaListener(
        topics = "orders.order.created",
        groupId = "batch-processor",
        containerFactory = "batchListenerFactory",
        ackMode = "MANUAL"
    )
    public void onOrdersBatch(List<ConsumerRecord<String, OrderEvent>> records, Acknowledgment ack) {
        log.info("Processing batch of {} orders", records.size());

        List<Order> orders = records.stream()
            .map(r -> orderMapper.toOrder(r.value()))
            .collect(Collectors.toList());

        orderRepository.saveAll(orders);   // one bulk insert for the whole batch

        ack.acknowledge();                 // commit after the entire batch is processed
    }

    // Value-only batch: with the factory's BATCH ack mode the offsets are committed
    // after the method returns normally
    @KafkaListener(topics = "analytics.events", containerFactory = "batchListenerFactory")
    public void onEventsBatch(List<AnalyticsEvent> events) {
        analyticsService.bulkProcess(events);
    }
}

// Config
@Bean
public ConcurrentKafkaListenerContainerFactory<String, Object> batchListenerFactory(
    ConsumerFactory<String, Object> cf
) {
    var factory = new ConcurrentKafkaListenerContainerFactory<String, Object>();
    factory.setConsumerFactory(cf);
    factory.setBatchListener(true); // enables batch mode
    factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.BATCH);
    factory.getContainerProperties().setPollTimeout(3000);   // the default is 5000 ms
    return factory;
}

Sources

Checked against Spring for Apache Kafka 4.1.1, Spring Boot 4.1.1 and Kafka 4.2 documentation on 11 October 2026. Draft: not yet reviewed by a Kafka specialist, and releases move on, so confirm against the current documentation before you act on it.