Video in progress
When you deploy a service with a Kafka consumer and producer, how do you configure graceful shutdown so messages aren't lost and duplicates are minimal?
When the pod gets SIGTERM, the listener containers must finish the current batch, commit the offset and stop, and the producer must manage to send what's in its buffer. For that, the Kubernetes grace period has to be longer than the timeouts inside the application, and the processing code must stop through the Spring lifecycle, not in @PreDestroy.
📖 Answer
When the Spring context closes, the listener containers stop through the lifecycle. By default (immediate-stop: false) the container finishes the records from the current poll, commits the offsets and leaves the group. Then the KafkaTemplate producers are closed, and close() flushes the messages in the buffer.
The problem is a collision of timings. A typical failure case:
terminationGracePeriodSeconds: 30 (Kubernetes default)
batch: 500 record × 100 ms = 50 s
At 30 seconds SIGKILL arrives, in the middle of the batch: nothing is committed, and the 300 records already processed get processed again on the next pod. Or the messages in the producer buffer are lost entirely, if they haven't been sent yet and aren't stored anywhere else.
Here's how I usually configure it:
spring:
lifecycle:
timeout-per-shutdown-phase: 45s
kafka:
consumer:
max-poll-records: 50 # so one batch finishes quickly
# Kubernetes
terminationGracePeriodSeconds: 60
The container also has its own shutdownTimeout (10 s by default); if a batch takes longer than that, you need to raise it too.
Extras:
- a cooperative assignor or static membership to reduce the number of rebalances, so in a rolling deploy each pod doesn't trigger two rebalances;
- sending important events through an outbox: even if the producer buffer dies with the pod, the event stays in the DB;
- keep the consumer idempotent anyway: graceful shutdown reduces duplicates, but it doesn't help on an OOMKill or when a node goes down.
It's easy to verify: in staging, run kubectl delete pod on a pod under load and count the "dublikat o'tkazib yuborildi" log lines from the dedup table.
Sign up to mark studied questions and save your progress.