Video in progress
A pod has HTTP requests, a Kafka consumer and @Scheduled jobs. How do you design graceful shutdown from start to finish?
spec:
terminationGracePeriodSeconds: 30
containers:
- name: app
lifecycle:
preStop:
exec: { command: ["sh", "-c", "sleep 5"] }
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=30s
The order: first leave the traffic (the preStop wait), then stop accepting new work, finish the current work, commit offsets, and close resources last. It all has to fit inside terminationGracePeriodSeconds, and every step must be idempotent.
📖 Answer
The first mistake in this configuration: preStop 5 + Spring 30 = 35 seconds, but the grace period is 30. The kubelet sends SIGKILL at the 30th second, the Kafka consumer does not get to commit its offset, and messages are read again. The grace period must be well above the total time, for example 60.
The full chain:
- The preStop sleep, until removal from the endpoints has propagated (5-10 s).
- SIGTERM → Spring's
ContextClosedEvent, readinessREFUSING_TRAFFIC. - Web server graceful: no new connections, current requests finish.
- The Kafka listener containers stop through
SmartLifecycle:pollstops, the current batch is processed, the offset is committed. If processing a batch takes 40 seconds, reducemax.poll.records. - Scheduler:
spring.task.scheduling.shutdown.await-termination=trueandawait-termination-period, otherwise a half-run job is cut off. - Async executors: the same, with
spring.task.execution.shutdown.*. - Connection pools and clients are closed last, since beans are destroyed in reverse order.
Accept that everything can still be cut off anyway: a node dies, an OOMKill happens. That is why the main protection is idempotency. The consumer must survive a Kafka message arriving twice, and if a scheduled job stops halfway, it must be able to continue next time.
Testing: run kubectl delete pod under load, then count the "cut-off" requests and re-read offsets in the log.
Sign up to mark studied questions and save your progress.