Tiếng Việt · English
Shutting down gracefully
Every deploy of a new version means shutting down the old one. At dine, that happens while orders are still running. This article is about what happens when you shut down carelessly, what "shutting down gracefully" means, when it helps and when it does not.
What happens if you shut down carelessly
Picture the service being stopped instantly, like pulling the plug, right while it is busy:
- Requests in progress are cut off. A guest who just pressed Book a table gets an error back, even though the order may already have been written to the database.
- Messages being processed are dropped halfway. Next time they are redelivered and have to be processed from the start.
- Locks being held are left hanging until they expire by themselves. Meanwhile other orders that need that item have to wait.
- A service goes silent because it died before it could reply, so the order is cancelled after 5 seconds even though nothing was really wrong.
- Logs still in memory are lost, exactly the lines you need most to find out what just happened.
None of these leaves the system permanently wrong (the end of the article explains why), but each one is extra cleanup, and guests can see it. The more often you deploy, the more often this happens.
Two ways to stop a program
On Linux, you stop a program by sending it a signal. Two signals matter:
SIGTERM: a warning, "get ready to shut down". The program hears it, and decides for itself how to clean up.docker stop,killand deployment tools all send this signal.SIGKILL: pulling the plug. The program hears nothing; the operating system stops it immediately.
The two usually come together: docker stop sends SIGTERM, waits 10 seconds, and if the program
has not exited by then, sends SIGKILL. So shutting down gracefully really means finishing the cleanup within the time you are given.
What shutting down gracefully means
On receiving SIGTERM, the service does three things in order:
- Stop taking new work: no new requests, no new messages fetched.
- Finish the work in progress: complete the requests that are running, finish processing the messages it is holding.
- Close connections, then exit: flush the remaining logs, close the connections to the database and Kafka.
When it helps, and when it does not
A graceful shutdown is just a chance, given in advance, to clean up. Sometimes you get that chance, sometimes you do not.
| It helps | It does not help |
|---|---|
| Deploying a new version | kill -9 (SIGKILL) |
| A planned restart, machine maintenance | Out of memory, the operating system kills the process itself |
| Scaling down the number of running instances | Power loss, the server dies, the machine's network is cut off completely |
| Pressing Ctrl+C during a test run | The program is hung and no longer reacts to signals |
The left column is the times you choose to shut down, which is also most of the shutdowns in practice. The right column is incidents: no warning, no line of code gets to run.
Done, but still not effective
This is the part that is often missed: you wrote graceful shutdown code, but it still does not do its job, for these reasons.
- Cleanup takes longer than the time you are given. Docker gives 10 seconds. If the service needs 15 seconds to finish its work,
it gets
SIGKILLat second 10, as if it had done nothing. Your own cleanup deadline has to be shorter than the outside one. - Connections that never finish by themselves. The dine home page receives data over a connection that stays open forever (a live stream). If you only "wait for running requests to finish", you wait until the deadline runs out. Connections like these must be told to close as soon as shutdown begins. The browser will reconnect by itself.
- Work in progress that is too long. A task that runs for several minutes cannot be "finished" in a few seconds. Long work has to be split into smaller pieces, or made safe to rerun from the start.
- New requests keep pouring in. The service has stopped accepting, but whatever sits in front of it (Nginx, a load balancer) keeps forwarding requests, so those requests are refused. At dine each service currently runs only one instance, so during the few seconds of a restart, new requests still fail. Avoiding that entirely requires running two instances and switching gradually; see the article Zero-downtime deploys.
- Using shutdown time for business work. For example "on shutdown, send all remaining messages". The next
SIGKILLwill skip that part. Whatever must happen should be guaranteed by the database and the outbox, not left for shutdown to carry.
In Go: context
Go already ships almost everything you need, so there is not much to write:
contextis the main tool. When the shutdown signal arrives, a sharedcontextswitches to "cancelled". Every background loop watches it: after finishing the current round it checks, and if it is cancelled, it stops. Thesignal.NotifyContextfunction creates acontextthat cancels itself onSIGTERMor Ctrl+C.http.Server.Shutdownhandles the API side: it stops accepting new connections and waits for running requests to finish within a given deadline. dine allows at most 1 second.sync.WaitGrouplets the main program wait until every background job reports that it has stopped, and only then flush the logs and exit.
When you don't get to shut down gracefully
For the "does not help" column above, there is no way around it. So dine is designed to still be correct in that case, and almost every mechanism from the earlier articles plays a part:
| Dying suddenly while… | What saves it |
|---|---|
| Writing an order to the database, not yet committed | The database rolls back the unfinished transaction itself, as if nothing happened |
| Claiming a message in the outbox to send | After 30 seconds the stuck message is handed back to another worker (Transactional outbox) |
| Having processed a message, before telling Kafka | Kafka redelivers that message, and the receiver filters the duplicate (Idempotency) |
| Holding a lock on a stock item | The lock expires by itself after 5 seconds (Two orders fighting over the last ingredients) |
| A service dies mid-processing and never replies | After 5 seconds order cancels and undoes
(Why 5 seconds cancels an order) |
So what is a graceful shutdown for, if the system is correct without it? To need rescuing less often: fewer messages to redeliver, fewer locks to wait out, fewer orders cancelled for nothing. And it works exactly when shutdowns happen most: during deploys.
In short: design for the worst case (the plug is pulled), optimize for the common case (you get a warning). A graceful shutdown makes the shutdowns you choose go smoothly, but the system's correctness must not depend on it.
See it for yourself
- Home page Orders running live over the stream. When the server is replaced, the stream closes and reconnects by itself a moment later.
- One service goes silent The case where a service dies midway without replying: the timeout saves the order.
Spotted a mistake, or have a question? Write to [email protected].
dine is a personal project about distributed systems, written in Go: orchestrated sagas, transactional outbox, Kafka. More articles.