Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 25 min · revision 3

Health, Readiness and Graceful Shutdown

Separate liveness from readiness so a database outage does not become a restart storm, let Uvicorn drain in-flight requests on SIGTERM, and use a preStop delay and a sized grace period so rolling updates drop as few requests as possible.

Contentsand lesson path

What you will learn

  • Implement liveness and readiness checks that reflect real dependencies, and shut down gracefully on SIGTERM by draining in-flight requests and jobs.

Prerequisites: Database Schema Migrations

01. Health probes: the difference between liveness and readiness

Orchestrators such as Kubernetes call health endpoints on every container and act on the answers. A common mistake is to expose one generic /health endpoint and use it for two different questions: is the process alive, and should it get traffic?

1. Liveness (/livez): "Is this process stuck?" The liveness probe checks that the process itself still responds: the event loop is not blocked, the worker threads are not deadlocked.

  • On failure: after failureThreshold failed probes in a row, Kubernetes kills the container (SIGTERM, then SIGKILL after the grace period) and starts it again.
  • What to check: only local state. Keep it cheap and fast, well inside the probe timeout, and never call shared dependencies.

2. Readiness (/readyz): "Should this replica get traffic now?" The readiness probe decides whether load balancers send this replica new requests.

  • On failure: Kubernetes marks the Pod not ready and removes it from the endpoints of its Services, so load balancers stop sending it new requests. The container is not restarted; it gets traffic again once the probe passes.
  • What to check: that start-up work is finished (connection pools open, models loaded) and that the dependencies this replica cannot work without answer a shallow check within a short timeout.

3. Startup (/startupz): protection during slow starts. For services that need a long warm-up, such as loading large model weights, a startup probe holds off the liveness and readiness probes until start-up has succeeded, so a slow start is not mistaken for a hang.

02. Graceful shutdown: handling SIGTERM and draining connections

During a rolling update Kubernetes starts new Pods, waits for them to become ready, and then deletes old ones. Deleting a Pod starts two things at the same time:

  • On the node: the kubelet runs the container's preStop hook, if there is one, and then sends SIGTERM to process 1 in the container.
  • In the control plane: the Pod's entries in the Service EndpointSlices are marked terminating and not ready. kube-proxy on every node, ingress controllers and any external load balancer then have to notice the change and stop sending new connections to the Pod.

The second path takes time, and how long is not fixed: it depends on cluster size, on your ingress controller and on how quickly an external load balancer deregisters targets. If the application closes its listening socket the moment SIGTERM arrives, clients that still route to it get connection errors, which a proxy turns into 502s.

A shutdown that drops as few requests as possible looks like this:

  1. Wait before stopping the listener. A preStop hook of a few seconds delays SIGTERM while the endpoint removal spreads. Put the delay here, not in the application: Uvicorn closes its listener as soon as it receives SIGTERM.
  2. Stop accepting, finish what is in flight. On SIGTERM, Uvicorn stops accepting connections, closes idle keep-alive connections, and waits for running requests, up to --timeout-graceful-shutdown seconds; whatever is still running then is cancelled.
  3. Release resources. Uvicorn then runs the shutdown half of the ASGI lifespan, where you close pools and flush buffers.
  4. Exit before SIGKILL. terminationGracePeriodSeconds (default 30) covers the preStop hook and the drain. When it runs out, the kubelet sends SIGKILL, which cannot be caught.

This makes dropped requests rare, not impossible. A load balancer may take longer to deregister than your delay, a client may reuse a keep-alive connection just as it closes, a request may outlast the drain timeout, and a Pod can disappear without any SIGTERM when its node fails or it is killed for using too much memory. Clients should therefore still retry idempotent requests.

03. Worked example: probes and a drain you can watch

The application below separates the two probes and leaves signal handling to Uvicorn. Do not install your own handler with loop.add_signal_handler(signal.SIGTERM, ...) inside the lifespan: Uvicorn registers its own handlers before the lifespan starts, so your handler replaces them. A service that does this logs the signal, flips a flag and then keeps serving; it never runs the lifespan shutdown and has to be killed with SIGKILL. The example uses /slow to stand for a request that is in flight when SIGTERM arrives, and was tested with Python 3.13, FastAPI 0.163.1 and Uvicorn 0.54.0.

Python · app.py
import asyncio
from contextlib import asynccontextmanager

from fastapi import FastAPI, Response, status

STATE = {"started": False}


async def ping_database() -> None:
    await asyncio.sleep(0.01)  # stand-in for "SELECT 1" on the pool


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: Uvicorn waits for this before it accepts traffic.
    print("startup: opening database pool", flush=True)
    await asyncio.sleep(0.1)  # stand-in for creating the pool
    STATE["started"] = True
    yield
    # Shutdown: Uvicorn runs this after SIGTERM, once it has stopped
    # accepting connections and in-flight requests have finished
    # (or --timeout-graceful-shutdown has expired).
    STATE["started"] = False
    print("shutdown: closing database pool", flush=True)


app = FastAPI(lifespan=lifespan)


@app.get("/livez")
async def livez():
    # Process only: never call shared dependencies here.
    return {"status": "alive"}


@app.get("/readyz")
async def readyz(response: Response):
    try:
        if not STATE["started"]:
            raise RuntimeError("starting")
        await asyncio.wait_for(ping_database(), timeout=1.0)
    except (RuntimeError, OSError, asyncio.TimeoutError):
        response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
        return {"status": "not_ready"}
    return {"status": "ready"}


@app.get("/slow")
async def slow():
    await asyncio.sleep(3)  # a request that is in flight during SIGTERM
    return {"done": True}

Install the packages in a virtual environment (python -m pip install fastapi==0.163.1 uvicorn==0.54.0), save the script below next to app.py and run it with bash drain_test.sh. It starts the server, starts a three-second request, sends SIGTERM half a second later, and then tries a new request. This is the test the skill project asks for: proof that SIGTERM drains an in-flight request.

Bash · drain_test.sh
#!/usr/bin/env bash
# Start the app, begin a 3 s request, then send SIGTERM half a second later.
uvicorn app:app --port 8000 --timeout-graceful-shutdown 25 &
SERVER=$!
until curl -fs localhost:8000/livez >/dev/null; do sleep 0.2; done
curl -s localhost:8000/readyz; echo
curl -s localhost:8000/slow > slow.out &
CLIENT=$!
sleep 0.5
kill -TERM "$SERVER"
sleep 0.5
curl -s -o /dev/null -w 'new request: %{http_code}\n' localhost:8000/livez
wait "$CLIENT"; echo "in-flight request got: $(cat slow.out)"
wait "$SERVER"; echo "uvicorn exit status: $?"
Illustrative output (from a real run: PIDs and client ports differ, and client and server lines may interleave)
INFO:     Started server process [717913]
INFO:     Waiting for application startup.
startup: opening database pool
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     127.0.0.1:41742 - "GET /livez HTTP/1.1" 200 OK
INFO:     127.0.0.1:41756 - "GET /readyz HTTP/1.1" 200 OK
{"status":"ready"}
INFO:     Shutting down
INFO:     Waiting for connections to close. (CTRL+C to force quit)
new request: 000
INFO:     127.0.0.1:41772 - "GET /slow HTTP/1.1" 200 OK
in-flight request got: {"done":true}
INFO:     Waiting for application shutdown.
shutdown: closing database pool
INFO:     Application shutdown complete.
INFO:     Finished server process [717913]
uvicorn exit status: 143

Read the output in order. The in-flight /slow request still returns 200 after SIGTERM, and the lifespan shutdown runs only after it has finished. The new request gets 000, which is curl's way of saying the connection was refused: the listener closed immediately. That refusal is exactly what clients would see if Kubernetes delivered SIGTERM before routing had caught up, and it is why the delay belongs in preStop. Exit status 143 means "ended by signal 15": after a clean shutdown, Uvicorn re-raises the signal it received, so do not expect status 0. If you rerun the script with --timeout-graceful-shutdown 1, the slow request is cancelled and returns 500 with Cancel 1 running task(s), timeout graceful shutdown exceeded in the log: the drain timeout must be longer than your slowest normal request.

In Kubernetes, the pieces fit together like this. The preStop sleep action is run by the kubelet, so the image needs no sleep binary; it is enabled by default from Kubernetes 1.30 (on older clusters use exec with ["sleep", "5"]). The grace period of 40 seconds covers the 5-second delay, the 25-second drain and a margin for the lifespan shutdown. Readiness fails fast (failureThreshold: 2 every 5 seconds) while liveness is more patient.

You do not need to fail /readyz yourself during shutdown for Kubernetes Services: a terminating Pod is already marked not ready in its EndpointSlices. It still helps with load balancers that health-check Pods directly; if you need that, let the preStop hook call a local endpoint that flips readiness, and keep that endpoint unreachable from outside the Pod.

YAML · deployment.yaml (probes, preStop delay and grace period)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 3
  selector:
    matchLabels: {app: api}
  template:
    metadata:
      labels: {app: api}
    spec:
      terminationGracePeriodSeconds: 40   # > preStop 5 s + drain 25 s + margin
      containers:
        - name: api
          image: registry.example.com/api:1.4.2
          # uvicorn runs as PID 1, so it receives SIGTERM itself
          command: ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000",
                    "--timeout-graceful-shutdown", "25"]
          ports:
            - containerPort: 8000
          readinessProbe:
            httpGet: {path: /readyz, port: 8000}
            periodSeconds: 5
            timeoutSeconds: 2
            failureThreshold: 2
          livenessProbe:
            httpGet: {path: /livez, port: 8000}
            periodSeconds: 10
            timeoutSeconds: 2
            failureThreshold: 3
          lifecycle:
            preStop:
              sleep:
                seconds: 5   # kubelet waits; needs no sleep binary in the image

04. Check your understanding

Practice check · 3 questions

Signal handling, preStop delays and grace periods

Three scenario questions on Uvicorn signal handling, the preStop delay and sizing the grace period.

Q1. Inside a FastAPI lifespan, a developer calls `loop.add_signal_handler(signal.SIGTERM, mark_not_ready)`. The app runs under Uvicorn. What happens when the Pod is deleted?
Q2. In a local test, new connections are refused immediately after SIGTERM while an in-flight request still completes. In Kubernetes, what stops clients that have not yet seen the endpoint change from hitting that closed port?
Q3. A Pod has a preStop sleep of 5 seconds and runs Uvicorn with `--timeout-graceful-shutdown 25`. Which `terminationGracePeriodSeconds` lets a full drain finish before SIGKILL?
Practice only: not graded, not saved, not evidence.

05. Apply it

For your own service:

  • Separate /livez and /readyz: keep /livez free of dependencies; in /readyz, check start-up state and the dependencies this replica needs, each with a short timeout (about one second).
  • Prove the drain with a test: adapt drain_test.sh (or a pytest that starts Uvicorn in a subprocess) to show that a request in flight during SIGTERM still succeeds.
  • Set probe thresholds on purpose: readiness should react within seconds; liveness should tolerate short pauses such as a garbage-collection spike.
  • Add the preStop delay and size the grace period: at least preStop plus --timeout-graceful-shutdown plus a margin, and longer than your slowest normal request.
  • Measure, then tune: during a rolling update under load, count errors at the client or ingress; if any appear, lengthen the delay to match your slowest load balancer.

In the next lesson, we will explore configuration management, Twelve-Factor environment variable injection, and fail-fast validation.

06. Review prompt

Without looking back, explain the difference between a liveness and a readiness probe and what happens during a database outage when liveness queries the database. Then walk through a Pod deletion during a rolling update: what the kubelet and the control plane each do, what Uvicorn does on SIGTERM, where the routing delay should live, how to size terminationGracePeriodSeconds, and why this minimises dropped requests during a rollout without guaranteeing zero.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check