Graceful shutdown

Why you need it

A rolling deploy stops old copies one by one. If a copy is stopped while it is still answering someone, that answer is cut off halfway: a payment that may or may not have gone through, and an error on the visitor's screen.

Think of it like this

A shop at closing time. First the door is locked so nobody new comes in. The customers already inside still pay at the till. Only then are the lights turned off.

Where you’ll find it

  • Kubernetes: On pod termination it stops sending visitors, sends the program a stop signal, and waits up to 30 seconds by default.
  • AWS: Load balancers have a deregistration delay: a server being removed gets no new visitors but may finish what it has.
  • Go: Server.Shutdown stops taking new requests and waits for the open ones to finish.

What to know first

Replacing copies. A deploy stops old copies and starts new ones. See Rolling deploys.

Request in progress. Work a copy has started for a visitor but not finished yet, like charging a card.

Stop signal. A message the system sends a program before it ends it, often called SIGTERM. The program can use it to tidy up.

How it works

  1. Stopping at once cuts work off. A visitor is paying when the deploy stops that copy. The payment is cut off halfway and the visitor sees an error. This is the first picture in the animation.
  2. First, no new visitors. The copy is taken out of the load balancer before anything else. New visitors go to the other copies. This is the arrow pulling back in the animation.
  3. Then finish what it has. The copy keeps working on the requests it already has, until each one is answered. The payment completes and the visitor sees "Paid".
  4. Only then stop. With nothing left to answer, the copy stops, and a new one takes its place. That order is a graceful shutdown.
  5. Set a time limit. A request that never ends must not block the deploy forever. So there is a limit, say 30 seconds, after which the copy is stopped anyway. Keep it longer than your slowest normal request.

An example

A payment takes about 3 seconds. The shop handles 20 payments a second, spread over 4 copies.

Stop a copy at once: about 15 payments (5 a second for 3 seconds) are cut off halfway.

Graceful: new visitors stop going to it, it finishes those 15 within 3 seconds, then stops. Nobody is cut off.

Further reading