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:

  1. The preStop sleep, until removal from the endpoints has propagated (5-10 s).
  2. SIGTERM → Spring's ContextClosedEvent, readiness REFUSING_TRAFFIC.
  3. Web server graceful: no new connections, current requests finish.
  4. The Kafka listener containers stop through SmartLifecycle: poll stops, the current batch is processed, the offset is committed. If processing a batch takes 40 seconds, reduce max.poll.records.
  5. Scheduler: spring.task.scheduling.shutdown.await-termination=true and await-termination-period, otherwise a half-run job is cut off.
  6. Async executors: the same, with spring.task.execution.shutdown.*.
  7. 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.