Video in progress

Strong Middle 🧩 Microservices

Why do clients get errors by sending requests to an instance that's been shut down during a deploy?

The list of instances in the client or load balancer is updated with a delay: the pod is already stopping, but requests are still being sent to it. It's solved with graceful shutdown, a preStop wait, and a retry to another instance on a connection error on the client side.

📖 Answer

This is especially visible with Eureka: the registry doesn't remove the instance immediately, clients refresh the list every 30 seconds, and Spring Cloud LoadBalancer has its own cache too. As a result a removed instance stays in the list for several tens of seconds, and requests sent to it get Connection refused.

Kubernetes has a similar race. When a pod is deleted, two things run in parallel:

  • the kubelet sends SIGTERM to the container;
  • the endpoint controller removes the pod from the Service, and that change spreads to the kube-proxies on every node and to the ingress.

The second can be slower. If the application stops immediately on SIGTERM, requests are still arriving at it.

lifecycle:
  preStop:
    exec:
      command: ["sh", "-c", "sleep 10"]
terminationGracePeriodSeconds: 40
server:
  shutdown: graceful
spring:
  lifecycle:
    timeout-per-shutdown-phase: 25s

The sleep in preStop gives traffic time to stop, then Spring stops accepting new requests and finishes the ones in progress. Kafka consumers also hand over their partitions cleanly.

If you use Eureka, the instance should additionally deregister from the registry before shutting down, and the client cache should be made smaller. Either way, putting one retry to a different instance on the client side for Connection refused is a good safety net: this error means the request never reached the server, so repeating it is safe.