Spring-Kafka
Consumer Application
Graceful Shutdown
Application Maintenance
Java Programming

How to gracefully shut down a Spring Kafka consumer application

Codemia Knowledge Hub ·

A graceful shutdown means the consumer stops fetching new records and finishes processing the ones it already has, so no messages are lost. In Spring Kafka you get there by controlling listener containers through KafkaListenerEndpointRegistry, tying them into the context lifecycle with SmartLifecycle, and closing the application context when a termination signal arrives.

How the consumer loop affects shutdown

Kafka consumers poll the broker in a loop to fetch records. Timing is governed by properties such as max.poll.interval.ms and session.timeout.ms in ConsumerConfig. After a record is processed, the consumer commits its offset to tell Kafka the message is done. A shutdown that interrupts processing before the commit is what causes reprocessing or loss.

Configuring the consumer for a clean stop

  1. Set max.poll.interval.ms high enough: this is the maximum delay between poll() calls before the consumer is considered dead. Make it large enough for your expected processing time.
  2. Implement ConsumerAwareListenerErrorHandler: handle exceptions during consumption so errors do not break the shutdown path.
  3. Use KafkaListenerEndpointRegistry: Spring provides it to manage listener lifecycles, including pausing and resuming:
java
1   @Autowired
2   private KafkaListenerEndpointRegistry registry;
3
4   public void pauseConsumers() {
5       registry.getListenerContainers().forEach(MessageListenerContainer::pause);
6   }
7
8   public void resumeConsumers() {
9       registry.getListenerContainers().forEach(MessageListenerContainer::resume);
10   }
  1. Implement SmartLifecycle: this gives you control over the order in which Kafka listeners start and stop with the application context:
java
1   @Component
2   public class KafkaConsumerLifecycleManager implements SmartLifecycle {
3       @Autowired
4       private KafkaListenerEndpointRegistry registry;
5
6       private boolean isRunning = false;
7
8       @Override
9       public void start() {
10           // Initiate processes or resources here
11           isRunning = true;
12       }
13
14       @Override
15       public void stop() {
16           // Clean up processes or resources here
17           registry.getListenerContainers().forEach(MessageListenerContainer::pause); // Ensure all consumers are paused
18           isRunning = false;
19       }
20
21       @Override
22       public boolean isRunning() {
23           return this.isRunning;
24       }
25   }

Triggering the shutdown

  • Close the application context: calling ApplicationContext.close() starts the shutdown and invokes the stop methods of all SmartLifecycle beans.
  • Handle termination signals: catch signals such as SIGTERM on UNIX and shut down cleanly. Spring Boot's ShutdownEndpoint or the @PreDestroy annotation can hold custom cleanup logic.

Quick reference

Key AspectDescription
max.poll.interval.msAdjust to allow ample time for message processing before rebalancing
Error HandlingImplementing ConsumerAwareListenerErrorHandler for proper error management
KafkaListenerEndpointRegistryUtilize for pausing and resuming consumers as part of the lifecycle
SmartLifecycleImplement for precise control over Kafka consumers startup and shutdown processes
Signal HandlingProperly handle shutdown signals for graceful cleanup

Logging and transactions

  • Logging and monitoring: log around message processing and the shutdown sequence so you can confirm everything completed.
  • Kafka transactions: use them to make read-process-write sequences exact.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design