# Graceful shutdown

## What it is

Graceful shutdown is a planned sequence for ending a running process while
accounting for work it has already started. The process receives a stop request,
stops taking new work and gives active operations a bounded chance to finish or
reach a recoverable state. At the end it closes its resources and exits. The
sequence makes an ordinary restart or deployment predictable for the service and
its callers.

The steps depend on what the process does. An HTTP server can stop accepting
connections and wait for active requests. A queue worker can stop pulling jobs
and record a safe point for the ones it already owns. A process that maintains
an upgraded connection such as a WebSocket can need its own policy for telling
clients to reconnect. State the expected behaviour of each kind of work. A
single process can serve several kinds at once.

The platform usually gives the process a deadline. In Kubernetes, the Pod's
termination grace period is part of that lifecycle. In a supervised service, a
stop timeout can determine how long the supervisor waits before forcing the
process to exit. The application should use its deadline to bound its own work
and leave enough time to release or preserve the resources whose state a later
attempt needs.

## Why it matters

A process can be replaced during a normal release while a user is uploading a
form or waiting for an answer. If the application stops abruptly, the client may
have no evidence about whether the work was saved. It may try again, and a
second request can produce another effect. A graceful sequence can help a
started operation finish cleanly or return it to a state a retry can handle.
Where uncertainty remains, stable identities and durable state give the product
a way to describe it.

Queued work has similar consequences. A job may have downloaded data, generated
a file or sent a message before a worker stops. The queue can deliver it again
if completion was never recorded. Design the job's durable steps and
deduplication policy so that a retry can establish the correct outcome. Waiting
for a short task to finish is useful. A documented retry path is useful when a
task is longer than the time available.

Shutdown also influences how a rollout uses capacity. A process that remains
eligible for requests while it tries to drain can receive new work until the
deadline. Coordinate traffic admission with the application and the platform.
Observe when old connections stop carrying work and how replacement instances
become ready. In a busy service those timings make the difference between a
quiet release and a wave of client retries.

## What it looks like in practice

Imagine an application with a download endpoint and a worker that builds
requested reports. First signal that the application is leaving service. Stop
accepting new report requests in that instance and stop reserving jobs in the
worker. Let active connections and jobs continue until their respective
deadlines. A report whose output is completely written can be published with its
stable identifier. A job that needs more time should remain eligible for a
deliberate retry, and its unfinished output should be easy to distinguish from a
complete file.

Test three cases. Shut down with no active work, with a simple request that
finishes within the grace period and with a job that is intentionally held
longer. Record which operations finished, what a new worker can see and how a
client learns the final status. The third case proves how the system behaves
when its graceful interval is exhausted. Check the result at the normal
application entry point and with the queue's own records.

Engineer's
[durable River job-queue case study](/portfolio/moved-slow-work-onto-a-river-job-queue/)
explains why work such as generating a document or rebuilding an index belongs
in a persistent queue. Its PostgreSQL-backed jobs support retries and a visible
history. The shutdown example uses that same separation between accepting work
and finishing it. The service can preserve a task across replacement and still
have measurable outcomes for operations that were already active.

## Where it goes wrong

A shutdown handler can wait on a resource after another handler has already
closed it. Write the order in terms of where each operation still needs access.
A worker finishing a transaction may need its database connection until its
outcome is durable. The process can close the connection pool once the relevant
work has completed or reached a known stopping point. Keep cleanup bounded and
test a failure during the drain itself.

Application and platform timeouts can also conflict. If the application expects
a minute to finish a job and the platform forcibly stops it after a shorter
interval, the application's best-case path may never run in a release. Observe
actual signals and deadlines in an environment representative of production.
Include time consumed by any hook and inspect what happens when the process
exits unusually fast or fails to exit.

Finally, verify repeatability. Send a second stop request while a drain is
underway, and restart the service after it reaches the hard deadline. Check for
surviving temporary output, stuck job ownership and operations whose clients
were disconnected. Look at the user's outcome as well as a clean process exit.
The aim is a transition whose remaining work, finished results and recovery
obligations are visible to the next instance and the people operating it.

## Further reading

- [The Kubernetes Pod termination lifecycle](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-termination).
  Describes termination, endpoint state and grace-period behaviour.
- [Go HTTP Server.Shutdown](https://pkg.go.dev/net/http#Server.Shutdown).
  Documents how a Go server closes listeners and waits for connections.
- [systemd service stop timeouts](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#TimeoutStopSec=).
  Explains how a supervisor limits the time spent stopping a service.

<https://engineer.company/glossary/graceful-shutdown/>
