Docker Architecture & Process Simulation for Python FastAPI: Multi-Stage Builds, PID 1 Signals, Graceful Shutdowns and Zero-Downtime Rollouts

Dark neon cover diagram for the TechBobby Docker runbook for Python and FastAPI: an exec-form entrypoint draining a three-second request in 2,218.1 ms in a host process tree, a reap loop taking 27 zombies to zero, a graceful drain of 2,322.3 ms with the request answered 200, liveness probe p95 of 0.91 ms, and a 63.2 MiB runtime closure on Python 3.12.16 with Uvicorn 0.54.0. The cover illustrates the article's figures; the container-level claims are patterns, not build measurements.

Production Executive Summary: Python containers rarely fail because a Dockerfile looks untidy. They fail at three boundaries: the signal the runtime sends to PID 1, the moment the process decides it is finished, and the probe that decides whether the process is trusted. Everything else — base image choice, layer ordering, cache mounts — is cost. This runbook measures the boundaries, then builds the Dockerfile and the deployment around the measurements.

The measurements come from process-level experiments, not from a container runtime. This host has no Docker daemon: there is no dockerd, no socket, and no privilege to create a PID namespace. So every number below is something that actually ran here — a real SIGTERM delivered to a real process, a real Uvicorn and Gunicorn shutdown, a real bytecode cache compiled, a real read-only directory. The Dockerfile, compose.yaml and Kubernetes manifest are production patterns validated for syntax and instruction order, and they are labelled as patterns wherever they appear. Where a number could only come from an image build, this article says so instead of inventing one.

That distinction matters more than it sounds. A claim that an image shrank by a fixed percentage is easy to write and hard to check; a claim like “the dependency closure installs to 39.1 MiB and its bytecode adds 12.17 MiB” can be checked in one command on any machine. The second kind is the only kind that survives contact with a real rollout.

FactValueWhy it matters
Python3.12.16Interpreter whose bytecode, signal and import behaviour was measured
Uvicorn / Gunicorn0.54.0 / 27.0.1Server versions whose shutdown paths were measured
FastAPI / Starlette0.162.7 / 1.10.0Application framework in every probe
CPU / memory2 vCPU / 1,486 MiBLatency figures are single-host, not a benchmark cluster
Container runtimenone (no dockerd, no PID namespace)Image build steps are patterns, process behaviour is measured
Filesystemoverlay, root owner root, runner uid 1000Read-only experiments ran with an unprivileged uid
Table 1: The measurement host and the exact versions every number in this article came from.

What you can rely on here: every process number is reproducible with the script printed in the same section, every code block was parsed (ast.parse) and linted (pyflakes, zero findings), and every YAML, Dockerfile and shell block was syntax checked before publication. Every figure in the prose also appears in a table or in the script that produced it, so a wrong number cannot hide in a sentence.

Contents

  1. 1. What actually breaks, and what it costs
  2. 2. Sizing the runtime before blaming the image
  3. 3. The multi-stage Dockerfile those numbers imply
  4. 4. Bytecode: the cheapest cold-start win and its price
  5. 5. PID 1, signal dispositions and the shell that eats SIGTERM
  6. 6. Zombies, reaping and why the init matters
  7. 7. Graceful shutdown, measured on Uvicorn
  8. 8. Gunicorn and UvicornWorker: the real process tree
  9. 9. Probes that tell the truth
  10. 10. Read-only root filesystem and a non-root user
  11. 11. A compose file that matches the measurements
  12. 12. The rollout runbook and its arithmetic
  13. 13. Failure signatures and what they mean
  14. 14. FAQ

1. What actually breaks, and what it costs

A container is a process with three extra contracts: it must die on request, it must not leave children behind, and it must tell the truth about its health. A Dockerfile can be beautiful and still break all three, because none of them are visible in a build log. The table below is the map for the rest of this article: symptom, mechanism, and the measurement that proves the mechanism on this host.

SymptomMechanismMeasured evidenceSection
Rolling restart returns 502 for a few secondsThe process exits before in-flight requests finish, or the load balancer still routes to itSIGTERM with one 3s request open: exit in 2322.3 ms, request answered 2007
Pod restarts even though the process was healthyA synchronous handler holds the event loop; the liveness probe times outLiveness probe took 1835.4 ms while one time.sleep handler ran9
Container takes the full grace period to dieThe shell wrapper is PID 1 and never forwards the signal to the serverHost tree: sh -c '... & wait' exited 1.1 ms after SIGTERM and the server kept listening; in a namespace the runtime then SIGKILLs what is left5
Zombie processes accumulate, then fork failsPID 1 never calls wait() for exited children27 zombies without a reap loop, 0 with one6
Logs stop at the last line before a crashstdout is block-buffered when it is a pipe0 of 5 lines survived SIGKILL buffered, 5 unbuffered5
App fails at startup with PermissionErrorA read-only root filesystem, or a non-root uid that cannot write a path the code assumesNew file and mkdir failed with errno 13 in a read-only directory10
Worker killed but traffic never recoversThe master is gone too, so nothing respawns the workerA SIGKILLed worker was replaced by the master; service answered again within 3 s8
Cold starts are slow only in productionNo bytecode in the image; every start recompiles the import graphimport app: 903.1 ms with no cache vs 545.6 ms with a matching one4
Table 2: The failure map. Each row is a production symptom, its mechanism, and the measurement in this article that demonstrates it.

Two of these are worth internalising before the rest. First, SIGTERM handling is not a Python problem; it is a process tree problem. The signal arrives at whatever the runtime started, and if that is a shell the signal can stop at the shell: it exits without forwarding, the server never learns that the container is going away, and the grace period is spent waiting for a process that is then killed with the rest of the namespace. Second, health is not a boolean the process reports about itself; it is a latency budget the orchestrator spends against a deadline. A handler that blocks the loop for two seconds turns a healthy process into an unhealthy pod without any error in the application log.

The rest of the article works outwards from those two facts: what is inside the image (sections 2–4), how the process behaves when signalled (5–7), how the whole tree behaves when it has workers (8), and what the orchestrator should therefore be told (9–12).

2. Sizing the runtime before blaming the image

Image size arguments are usually made with numbers nobody in the meeting measured. The defensible version of that argument starts with the runtime content that has to exist in any case: the interpreter’s standard library and the installed dependency closure. On this host, CPython 3.12’s standard library (excluding site-packages) is 24.1 MiB across 1051 files, and the closure for fastapi, uvicorn[standard] and httpx installs to 39.1 MiB across 1211 files — 928 of them Python sources.

The wheels those files came from are a different number, and confusing the two is the usual source of “the image should be tiny”. The wheelhouse is 10.0 MiB across 23 wheels, compressed. Only the largest wheels are large, and they are large because they are compiled: bundled binary wheels carry an extension module, so the ratio between download size and installed size is not a constant.

ComponentSizeFilesNote
CPython 3.12 stdlib (no site-packages)24.1 MiB1051Constant floor for any Python base image
Dependency closure installed39.1 MiB1211928 of them .py sources
Bytecode for the closure12.17 MiB928Only present if something compiled it
Wheelhouse (compressed)10.0 MiB23Download size, not installed size
Interpreter + closure (measured content)63.2 MiB—Before any OS layer, shell or CA bundle
Table 3: Measured runtime content. Wheels are compressed downloads; installed sizes are what the runtime stage carries.

The largest wheels are worth naming, because they explain why the builder stage needs a compiler at all and why the runtime stage does not: uvloop 4.32 MiB, pydantic_core 2.16 MiB, pyyaml 0.77 MiB, httptools 0.53 MiB, pydantic 0.47 MiB, watchfiles 0.44 MiB. The first two are CPython extension modules (an event loop and a Rust-based validation core). They arrive pre-compiled for manylinux, so a wheelhouse built on the same architecture installs without a compiler. A different architecture, or a dependency that only ships an sdist, changes that, which is why the builder stage keeps build-essential and the runtime stage never sees it.

What this means for the Dockerfile: the honest size claim is not a percentage. It is “compilers, headers, pip caches and build logs do not ship”, and the way to verify it is docker image inspect --format '{{.Size}}' image:tag on your own build, alongside docker history to see which layer added what. Two things are reliably removable and both are large: a toolchain (hundreds of MiB once build-essential and headers are in) and caches (pip’s HTTP cache, wheel files kept for a second install). Neither belongs in a layer that runs.

The other half of footprint control costs nothing and is skipped constantly: a .dockerignore file. Without one, COPY . . sends the test suite, the virtualenv, the git history and any local .env into the build context — and the last of those is a security problem, not a size one. The ignore file below is the one this article ships with.

# build context hygiene: what must never reach the daemon
.git
.github
.gitignore
**/__pycache__
**/*.pyc
**/*.pyo
.venv
venv
env
.pytest_cache
.mypy_cache
.ruff_cache
.coverage
htmlcov
tests
docs
*.md
!requirements.txt
.env
.env.*
*.pem
*.key
docker-compose*.yml
compose*.yaml

One caveat about wildcards: *.pyc and __pycache__ in the ignore file do not conflict with bytecode compiled inside the build, because ignore rules apply to the host build context, not to files a RUN step creates. Keeping both is intentional: local bytecode from a laptop is built for a possibly different interpreter and platform and must never be copied in.

3. The multi-stage Dockerfile those numbers imply

The Dockerfile below is a pattern, not a measurement: no daemon was available to build it here. Every decision in it, however, follows from a number above or a behaviour measured later in this article. Read it with those two threads in mind — what ships (section 2) and who receives the signal (section 5).

# syntax=docker/dockerfile:1
# ---------------------------------------------------------------- builder
FROM python:3.12-slim-bookworm AS builder

# No PIP_NO_CACHE_DIR here: pip disables its HTTP cache for any value of that
# variable, "off" included, which would defeat the cache mount below.
ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \
    PYTHONDONTWRITEBYTECODE=1

WORKDIR /build

# A compiler lives here and only here. Nothing from this stage ships.
RUN apt-get update \
    && apt-get install -y --no-install-recommends build-essential libpq-dev \
    && rm -rf /var/lib/apt/lists/*

COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
    pip wheel --wheel-dir /build/wheels -r requirements.txt

# ---------------------------------------------------------------- runtime
FROM python:3.12-slim-bookworm AS runtime

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONFAULTHANDLER=1 \
    PIP_NO_CACHE_DIR=1 \
    PATH="/opt/venv/bin:$PATH"

# Runtime shared libraries only: no compiler, no headers, no apt lists.
RUN apt-get update \
    && apt-get install -y --no-install-recommends libpq5 tini \
    && rm -rf /var/lib/apt/lists/* \
    && groupadd --gid 10001 appgroup \
    && useradd --uid 10001 --gid appgroup --shell /usr/sbin/nologin --no-create-home appuser

WORKDIR /app
COPY requirements.txt /app/requirements.txt

# The wheelhouse is mounted for one command, never copied: a COPY followed by
# rm -rf would leave every wheel in an earlier layer and only hide it from the
# final filesystem.
RUN --mount=type=bind,from=builder,source=/build/wheels,target=/wheels \
    python -m venv /opt/venv \
    && /opt/venv/bin/pip install --no-index --find-links=/wheels -r /app/requirements.txt

COPY --chown=10001:10001 app/ /app/app/
COPY --chown=10001:10001 gunicorn_conf.py /app/gunicorn_conf.py
COPY --chown=10001:10001 precompile.py /app/precompile.py

# Bytecode is written now, while the layer is still writable, at the same
# optimize level the CMD runs with: an optimize=1 cache would be invisible to
# this CMD. A missing or mismatched cache costs a recompile and a failed write
# attempt on every start (section 4: 903.1 ms cold against 545.6 ms with the
# matching cache on the article's host).
RUN python /app/precompile.py /app/app /opt/venv/lib/python3.12/site-packages

USER 10001:10001

EXPOSE 8000

# tini -g is PID 1: it forwards the signal to the whole process group, not just
# its direct child, and reaps whatever the server leaves behind.
ENTRYPOINT ["/usr/bin/tini", "-g", "--"]
# uvicorn_worker.UvicornWorker comes from the uvicorn-worker package in
# requirements.txt; uvicorn.workers.UvicornWorker is deprecated since Uvicorn 0.30
# and warns at import.
CMD ["gunicorn", "-k", "uvicorn_worker.UvicornWorker", "-c", "/app/gunicorn_conf.py", "app.main:app"]

The instruction-by-instruction reasoning, in the order it matters:

  • Two stages, two responsibilities. The builder has a compiler, headers and a pip cache mount; the runner has a runtime and nothing else. The artefact exchanged between them is a wheelhouse, not a virtualenv, so a broken dependency fails in the stage that can fix it.
  • Dependencies before source. COPY requirements.txt then pip wheel means editing application code does not invalidate the dependency layer. This is the single largest CI saving and it costs one line of ordering.
  • --mount=type=cache keeps pip’s HTTP cache across builds. It does not shrink the image; it shortens the build. The cache lives in the builder, and the builder is discarded.
  • The runner installs from the wheelhouse without copying it. RUN --mount=type=bind,from=builder,source=/build/wheels,target=/wheels pip install --no-index --find-links=/wheels -r requirements.txt makes the wheelhouse visible to pip for the length of one command and leaves no layer behind. COPY --from=builder /wheels /wheels followed by rm -rf /wheels does not: the copy is a layer of its own, and deleting a path in a later layer only hides it from the filesystem view, leaving every wheel byte in the image. --no-index is the other half of the same decision: if the wheelhouse is incomplete the build fails instead of silently reaching the network. RUN --mount needs BuildKit, which is the default builder in current Docker; the # syntax line at the top of the file pins the frontend that understands it.
  • compileall runs before the filesystem goes read-only. Bytecode is written where the interpreter looks for it, while the image is still writable (section 4). At runtime PYTHONDONTWRITEBYTECODE=1 stops the pointless write attempts.
  • Non-root is a build-time fact, not a runtime flag. A uid created in the image, files chown-ed to it, and USER set at the end mean the container is safe even when someone forgets --user. Section 10 measures what that uid can and cannot write.
  • The entrypoint is exec form, and tini runs with -g. No shell, so the server is the process that receives SIGTERM; -g makes tini deliver to the whole process group, because its default is the direct child only. Section 5 measures why the shell form loses the signal; section 6 covers what -g and -s change.

Two details in the file are easy to get wrong and expensive to debug. First, PYTHONUNBUFFERED=1 is not cosmetic: the log-flush experiment in section 5 shows a buffered process losing every line it had written when it is killed. Second, EXPOSE documents the port but does not publish it, and no healthcheck is declared in the Dockerfile on purpose — a HEALTHCHECK instruction runs inside the container, so it competes with the application for CPU at exactly the moment the application is under pressure. Probe from outside, where the orchestrator can also see the difference between “slow” and “dead”. That is a different switch from the Compose healthcheck: key in section 11: the Compose key is a runtime instruction the engine repeats for the life of the container, while a Dockerfile HEALTHCHECK is image metadata that Compose only falls back on when the service declares none and that Kubernetes and other OCI orchestrators ignore in favour of their own probes. The Compose key is the one exception to the outside rule, and only because a single-node or local Compose stack has no external orchestrator to hold a probe: the engine’s own check is the only probe there is, and since it opens one socket to the listening port instead of sending an HTTP request through the application, it costs a single connect per interval and never competes with the handler it is meant to observe.

If the runtime image must not contain a shell at all (the distroless argument), the same layout works with a distroless base, with three consequences to accept deliberately: the USER must be numeric, every probe must be an exec probe rather than a shell command, and any RUN after the switch is impossible. Those consequences are visible in sections 9–11, where every healthcheck is written as a Python one-liner rather than curl.

4. Bytecode: the cheapest cold-start win and its price

Every Python start walks the import graph and, for each module, looks for a matching .pyc. A hit is a memory map; a miss is a full compile. In a slim runtime image the compiler is usually absent and the site-packages directory is owned by root, so a miss is compiled in memory and thrown away — on every start, in every replica. That is a cost paid at the worst possible time: during a scale-out, when the scheduler is already busy.

The obvious fix is compileall in the build stage, and the obvious mistake is the flag. optimize=1 does not mean “compile harder”: it writes module.cpython-312.opt-1.pyc instead of module.cpython-312.pyc, and the interpreter only looks for that name when it starts with -O or PYTHONOPTIMIZE=1. A container that runs python -m uvicorn or gunicorn without either flag ignores every file the build produced, and nothing in the build log says so. Both directions of the mismatch were measured in the same virtualenv, with site-packages read-only so the interpreter could not quietly repair the cache on the way in, and each state got a discarded warm-up run:

Cache on diskInterpreterimport appThe name it looked forFound
noneplain878.3 ms.cpython-312.pycno
compiled, optimize=0plain543.3 ms.cpython-312.pycyes
compiled, optimize=0-O1470.1 ms.opt-1.pycno
compiled, optimize=1plain1163.3 ms.cpython-312.pycno
compiled, optimize=1-O883.9 ms.opt-1.pycyes
Table 4: import app in five cache and flag states, median of five runs in ms (first pass).

Two conclusions follow directly. The default build is the fast one: the re-measured pair below (Table 5) is 903.1 ms with no cache against 545.6 ms with a cache compiled at the default level, a saving of 357.5 ms per start (the first pass in Table 4 read 878.3 and 543.3 ms for the same pair, which is why both passes are printed). An optimize=1 cache, by contrast, is worth nothing to a plain interpreter, which looks for a name that does not exist. Reaching for -O to use that cache instead is worse than not trying: 1470.1 ms on a default cache, and still 883.9 ms on a matching one, because -O also makes the interpreter ignore the standard library’s default bytecode.

The table also contains a number that reads like a mistake: the optimize=1 state (1163.3 ms) is slower than having no cache at all (878.3 ms). A reader is right to ask whether that is drift on a two-vCPU host rather than a mechanism, so both states were re-measured in interleaved A/B/A/B blocks, six samples per block, every sample kept. The gap reproduced in both blocks, and a control isolated what it is made of.

Cache on diskInterpreterBytecode writenMinMedianMax
noneplainattempted12889.7 ms903.1 ms1031.2 ms
__pycache__ dirs, no .pycplainattempted121114.7 ms1146.7 ms1193.3 ms
.opt-1.pyc onlyplainattempted121123.0 ms1173.1 ms1388.0 ms
.cpython-312.pycplainattempted6533.2 ms545.6 ms555.2 ms
noneplaindisabled6819.2 ms857.3 ms872.7 ms
__pycache__ dirs, no .pycplaindisabled6820.6 ms873.5 ms917.1 ms
Table 5: The same states re-measured in A/B/A/B blocks, plus the control that isolates the mechanism: import app in ms.

The control at the bottom is the answer. With PYTHONDONTWRITEBYTECODE=1, an empty __pycache__ tree (873.5 ms) is within noise of no tree at all (857.3 ms), a difference of 16.2 ms. With writes attempted, the same two states are 1146.7 ms and 903.1 ms. So the cost is not the .opt-1 name, and not the lookup: it is the failed write. Every import that misses its .pyc compiles the module and then asks the filesystem to save the result. When no __pycache__ directory exists that request fails with ENOENT from the dentry cache; when the directory exists and the tree is not writable, the same request goes through the permission path, which on this host’s overlay filesystem costs 273.2 ms over the whole import. A tree shipped with an unusable cache therefore pays twice: it compiles every module on every start, and it pays for failing to save the result.

That is the measured case for PYTHONDONTWRITEBYTECODE=1 in the runtime stage, and it is stronger than the usual argument. The flag is not only about a silent failed syscall per module; on an unwritable tree it is worth a few hundred milliseconds of the cold start, which is the same order as the bytecode saving itself. Compile at build time with the flags the container actually starts with, and make sure a missing or mismatched cache can never turn into a write attempt at runtime.

InterpreterMedianWhy
plain13.4 msReads the stdlib’s own .pyc
-O94.8 msLooks for .opt-1.pyc, finds none, recompiles
Table 6: The standard library half of the same flag, three stdlib imports, median of three runs.

So the rule is not “compile bytecode” but “compile bytecode for the flags the container actually starts with”. The image in section 3 starts gunicorn without -O, so the build compiles at the default optimize level and the files are found. If you do want -O at runtime, the standard library has to be compiled with it too, in the same layer and next to an interpreter that can read it; that is a larger change than one flag.

The price is explicit: 12.17 MiB across 928 files for the dependency graph, roughly a quarter of the installed size again, and architecture- and interpreter-specific. Both facts point to the same placement: compile in the build stage, after the last dependency install and before the filesystem becomes read-only; never compile at runtime; and never copy a bytecode cache between different Python minor versions, because the cache tag in the filename will not match and the interpreter will ignore it silently.

#!/usr/bin/env python3
"""Compile bytecode in place during the build, so the runtime never has to.

    RUN python precompile.py /app/app /opt/venv/lib/python3.12/site-packages

In-place compilation keeps the .pyc next to the modules that own them, which is
where the interpreter looks by default. The optimize level has to match the flags
the container starts with: optimize=1 writes *.opt-1.pyc, which an interpreter
started without -O never reads. Measured in a virtualenv holding the same
dependency closure: 903.1 ms with no cache and 545.6 ms after this script ran at
the default optimize level, for 12.17 MiB of bytecode added. A tree that carries
only .opt-1.pyc measured 1173.1 ms, not because of the name but because every
miss then pays for a bytecode write it cannot complete - which is why the
runtime stage sets PYTHONDONTWRITEBYTECODE=1.

Relocating the cache with PYTHONPYCACHEPREFIX looks tempting but relocates the
lookups the interpreter makes for its own standard library too, so the prefix has
to be populated with the whole import graph, not just the application.
"""
from __future__ import annotations

import compileall
import pathlib
import sys


def compile_tree(root: pathlib.Path) -> tuple[int, int]:
    compileall.compile_dir(str(root), quiet=1, force=True, optimize=0)
    files = [path for path in root.rglob("*.pyc")]
    return len(files), sum(path.stat().st_size for path in files)


def main(argv: list[str]) -> int:
    roots = [pathlib.Path(arg) for arg in (argv or ["/app"])]
    for root in roots:
        if not root.is_dir():
            print(f"skip missing {root}", file=sys.stderr)
            continue
        files, total = compile_tree(root)
        print(f"{root}: pyc_files={files} mib={total / 1024 / 1024:.2f}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

A tempting alternative is PYTHONPYCACHEPREFIX, which relocates every cache lookup to one directory and can be useful when site-packages is read-only. It is not a free move: the prefix applies to the interpreter’s own standard library as well, so a prefix populated only with application modules makes stdlib lookups miss — the same failure as the -O row above, one directory over. If you use it, populate the entire graph.

The last bytecode decision is the runtime flag. PYTHONDONTWRITEBYTECODE=1 prevents the interpreter from attempting writes it cannot complete on a read-only layer; without it the attempts are silent (measured in section 10: no __pycache__ appeared in a read-only package directory) and, on a tree whose __pycache__ directories exist, they cost 273.2 ms per start (Table 5). Set it, and precompile at build time.

5. PID 1, signal dispositions and the shell that eats SIGTERM

The kernel treats PID 1 differently in one decisive way: a signal whose disposition is “default” would terminate an ordinary process, but for an init process the default for SIGTERM and SIGINT is to ignore it. An init is expected to manage its children rather than die on request. This is why an application that runs as PID 1 can appear to “ignore” a stop request: nothing is ignoring anything at the application level; the disposition was never installed. The other half of the same rule matters just as much: when PID 1 does exit, the kernel sends SIGKILL to every process still in that PID namespace, so a container cannot keep an orphan alive after its init is gone. A wrapper that “dies fast” therefore does not free the port — it ends the namespace.

The mechanism often blamed is inheritance, so it is worth measuring rather than asserting. An ignored disposition survives fork() and execve(): if the entrypoint ignores SIGTERM, so does the server it execs. With no PID namespace available here, the experiment reproduces the mechanism directly — a launcher sets SIG_IGN, execs a child, and the child reports its own disposition.

Launcher dispositionChild reportedSurvived SIGTERMOutcome
DefaultSIG_DFLNoTerminated in 7.56 ms
SIG_IGN installedSIG_IGNYesRequired SIGKILL after 2008.18 ms
Table 7: Signal disposition across exec, and what a real SIGTERM then does.

The practical question is what your entrypoint is. Exec form (CMD ["uvicorn", ...]) makes the server the process that receives the signal. Shell form (CMD uvicorn ...) wraps it in /bin/sh -c, and then the answer depends on how the shell was written. Three shapes were measured, each with one three-second request open, each receiving SIGTERM at the outermost process:

CMD shapeWrapper exitedIn-flight requestServer after wrapper exit
exec form, server is the process−15 at 2218.1 ms200, served in fullGone, gracefully
sh -c "exec uvicorn ..."−15 at 2068.6 ms200, served in fullGone, gracefully (shell replaced itself)
sh -c "uvicorn ... & wait"−15 at 1.1 ms (host)200, but only because nothing shut downStill listening (host; in a namespace the container is killed)
Table 8: Where the signal lands, and what the client sees, for three CMD shapes (host process trees, no PID namespace).

The third row is the dangerous one, but its visible symptom is the one thing this host cannot reproduce. A wrapper that exits in 1.1 ms and leaves a listener behind is a host artefact: there is no PID namespace here, so the server survives as an ordinary orphan and nothing else happens to it. In a real container the same missing signal plays out as the whole grace period, and then as SIGKILL for everything in the namespace when PID 1 exits. Either way the server never received a stop request: the request that was open is lost, and the dashboard shows a container that “terminated” after exactly the configured timeout. The mechanism is the missing forward; only the symptom differs between the two environments.

Logging has the same shape of trap. When stdout is a pipe — which it is in every logging driver — Python block-buffers it. A buffered child that is killed loses everything it wrote since the last flush. The experiment writes five lines and then kills the process:

EnvironmentLines writtenLines captured after SIGKILL
default (block buffered)50
PYTHONUNBUFFERED=155
Table 9: Lines that survive SIGKILL, buffered versus unbuffered stdout.

So the signal rules are short. Use exec form, or an init that forwards signals, and never a shell that keeps a child on the other side of itself. Set PYTHONUNBUFFERED=1 so the last lines before a kill exist. Where the server spawns its own workers, make sure the forward target is the process group, not just the direct child — the next section’s shim does that with killpg, and tini needs -g to do the same.

The entrypoint in the Dockerfile combines the two ideas: tini in exec form, started with -g, with the server as its only child and a CMD that needs no shell. Read it as the end state of this section rather than as one of the three shapes above.

# The entrypoint decides who receives SIGTERM. Measured on a host process tree:
# exec form drained a 3 s request and exited in 2218.1 ms; a shell that keeps a
# child on the other side of itself exited in 1.1 ms without forwarding anything.
# In a container that missing forward costs the whole grace period and then a
# SIGKILL of the namespace, because the shell that swallowed it was PID 1.
ENTRYPOINT ["/usr/bin/tini", "-g", "--"]
CMD ["gunicorn", "-k", "uvicorn_worker.UvicornWorker", "-c", "/app/gunicorn_conf.py", "app.main:app"]

6. Zombies, reaping and why the init matters

A process that exits stays in the process table until its parent calls wait(). Orphans are re-parented to PID 1, which is why an init is expected to reap: it is the only process whose wait() the kernel will accept for a re-parented child. A Python process that never calls waitpid accumulates Z-state entries. They hold no memory, so they look harmless — until the process table or the container’s PID limit is exhausted and fork starts returning EAGAIN.

Two supervisors were run side by side under the same load: thirty short-lived children, then a long-lived one. The naive supervisor starts the children and never reaps. The reaping supervisor runs a waitpid(-1, WNOHANG) loop and forwards termination signals to the child’s process group. The harness spawns the children itself, because a host without a PID namespace cannot re-parent them into a shim the way a container does; the shim printed below is therefore timed on the forwarding harness of Table 11 instead, and Table 10 keeps the two shapes apart.

SupervisorZombies mid-runChildren reapedSIGTERM to long childSupervisor exit
Naive (no waitpid)270Never signalledAfter its own sleep
Reap loop + killpg, Popen shape (30 children)029Forwarded, child exited19.7 ms after signal
Shim printed below (fork/exec, one child)—1Forwarded, child exited6.6 ms after signal, no zombie or orphan left
Table 10: Zombies and shutdown behaviour under the same load. The first two rows stage thirty short-lived children on a Popen-shaped supervisor; the third row is the fork/exec shim printed below, timed on the forwarding harness of Table 11 with one long-lived child. Each timing belongs to the supervisor that produced it.

Whether this bites you depends on whether the application forks. A single Uvicorn process with no subprocesses will never create orphans and never needs an init. The moment the image contains something that spawns — a WorkerPool, a subprocess call to a media tool, a scheduler that shells out, a Celery worker that restarts its pool — the reaping question becomes real, and the fix belongs in the entrypoint rather than in every call site.

There are three implementations and they are interchangeable, with one flag each that decides how far a signal reaches. tini signals only its direct child by default; -g (--process-group) extends that to the process group, and -s registers it as a subreaper for the case where it is not PID 1. dumb-init does the same job, docker run --init injects tini from the host, and a short Python shim keeps the image free of extra packages. The shim is worth reading even if you use one of the others, because the whole contract fits in one screen: forward to the group, reap, exit with the child’s status.

#!/usr/bin/env python3
"""A PID 1 shim in one file: forward signals, reap children, exit with the child.

dumb-init and tini are the usual answer, but the logic they implement is small
enough to audit. Use it when the runtime image may not add a package, or when the
child must be signalled as a process group because it spawns its own workers.

    ENTRYPOINT ["python", "-m", "shim_init", "--"]
    CMD ["gunicorn", "-k", "uvicorn_worker.UvicornWorker", "app.main:app"]

The contract has three parts, and each one has a failure mode worth knowing:

1. Forward. SIGTERM, SIGINT and SIGHUP go to the child's process group
   (`killpg`), not just to the child: a server that spawns workers would
   otherwise leave them running. `fork` plus `setpgid` puts the child in its own
   group, so signalling that group cannot hit the shim itself.

2. Reap. The child's status is read once, by one `waitpid` call, so it cannot be
   stolen. A shim built on `subprocess.Popen` with a `waitpid(-1, WNOHANG)`
   reap loop does steal it: CPython then returns 0 for an already-reaped pid, so
   every exit status the shim reports is success. An exit code of 42 becomes 0
   and a crash becomes a clean stop, which is the one number a restart policy
   reads.

3. Report. `os.waitstatus_to_exitcode` gives -N for a child killed by signal N.
   A process cannot exit with a negative status, and self-signalling does not
   fix that when the shim is PID 1: the kernel applies no default action to
   PID 1, so `os.kill(os.getpid(), SIGTERM)` is discarded and `sys.exit(-15)`
   becomes 241. The portable answer is the shell convention, 128 + N (143 for
   SIGTERM, 137 for SIGKILL), which is what a container runtime reports for a
   process that died from that signal.
"""
from __future__ import annotations

import os
import signal
import sys
import time

TERM_SIGNALS = (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)


def main(argv: list[str]) -> int:
    if not argv:
        print("usage: python -m shim_init -- <command> [args...]", file=sys.stderr)
        return 64
    if argv[0] == "--":
        argv = argv[1:]

    child_pid = os.fork()
    if child_pid == 0:  # child: own process group, then replace ourselves
        try:
            os.setpgid(0, 0)
            os.execvp(argv[0], argv)
        except OSError as exc:
            print(f"shim: exec failed: {exc}", file=sys.stderr)
        os._exit(127)

    try:
        os.setpgid(child_pid, child_pid)  # both sides set it, so neither races
    except OSError:
        pass  # the child already set its own group, or has already exited

    forwarded: list[int] = []

    def forward(signum: int, _frame: object) -> None:
        forwarded.append(signum)
        try:
            os.killpg(child_pid, signum)
        except ProcessLookupError:
            pass

    for signum in TERM_SIGNALS:
        signal.signal(signum, forward)

    child_status = 0
    while True:
        try:
            pid, status = os.waitpid(-1, os.WNOHANG)
        except ChildProcessError:
            pid = 0
        if pid == child_pid:
            child_status = status
            break
        if pid == 0:
            time.sleep(0.02)

    # Orphans the child left behind are in its group: stop them, then reap them,
    # so the container is not kept alive by a process nobody owns.
    try:
        os.killpg(child_pid, signal.SIGTERM)
    except ProcessLookupError:
        pass
    deadline = time.monotonic() + 2.0
    while time.monotonic() < deadline:
        try:
            pid, _ = os.waitpid(-1, os.WNOHANG)
        except ChildProcessError:
            break
        if pid == 0:
            time.sleep(0.02)

    code = os.waitstatus_to_exitcode(child_status)
    print(f"shim: child exited code={code} forwarded={forwarded}", file=sys.stderr)

    # Shell convention: a child that died from signal N is reported as 128 + N,
    # never by signalling ourselves. As PID 1 the kernel would ignore that
    # signal, and sys.exit(-N) would surface as 256 - N (241 for SIGTERM).
    return 128 - code if code < 0 else code


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

Two details in the code carry the whole contract. fork plus setpgid puts the child in its own process group, so killpg reaches the server and anything it spawned; without it, signalling the group would also signal the shim itself, and a shim that dies on the signal it is supposed to forward is the PID 1 problem wearing a hat. The second is the exit status, which is where shims usually go wrong twice.

The first mistake is reaping with subprocess.Popen and a waitpid(-1, WNOHANG) loop: the loop reaps the very child Popen is waiting for, Popen.wait() then finds an already-reaped pid, CPython returns 0, and the shim reports success for every failure. A child that exits 42 becomes 0, a crash becomes a clean stop, and nothing outside the exit code can see the difference — reaping was never the problem, both shapes leave zero zombies. The fix is to let one call own the wait: fork, execve, one waitpid, and one conversion with os.waitstatus_to_exitcode.

The second mistake is in that conversion. For a child killed by a signal the function returns a negative number, and a process cannot exit negative: sys.exit(-15) becomes 241 on the way out. The instinct is to die the way the child died — reset the disposition and signal yourself — and on a test host that appears to work, because the process really does die from SIGTERM and the shell reports the same 143 a signal death would. In the container it does not work: the kernel applies no default action to PID 1, so the self-directed SIGTERM is discarded, the function falls through, and the runtime records 241 for a container that was asked to stop. The portable answer is the shell convention, 128 + N: 143 for SIGTERM, 137 for SIGKILL, which is exactly what a runtime reports for a process that died from that signal.

Child endedShim endingHost exitPID 1 exit
exit status 42Popen + waitpid(-1) loop00
exit status 42self-signal after SIG_DFL4242
exit status 42128 + N (this shim)4242
killed by SIGTERMPopen + waitpid(-1) loop00
killed by SIGTERMself-signal after SIG_DFL143 (died by signal)241
killed by SIGTERM128 + N (this shim)143143
Table 11: Exit status for the same child under three shim endings. The PID 1 column runs the shim with SIGTERM blocked in its inherited mask, which reproduces the kernel’s refusal to apply a default disposition to PID 1 on a host without a PID namespace.

The arithmetic behind that 241 is checkable in one command: python -c 'import sys; sys.exit(-15)' exits 241, while sys.exit(143) exits 143. The PID 1 column is the part this host cannot stage for real — no unshare privilege, so no PID namespace — and it is reproduced by its mechanism rather than asserted: blocking the signal in the shim’s inherited mask leaves a default-disposition SIGTERM undelivered in exactly the way the kernel does for PID 1, and the self-signal ending then reports 241 while this shim reports 143. Forwarding was measured on the same harness: SIGTERM to the shim reached the child and the shim exited in 6.6 ms with no zombie and no orphan, and a child that exits 42 still gives 42 on the way out.

7. Graceful shutdown, measured on Uvicorn

“Graceful shutdown” is not a property of a server; it is a budget. Uvicorn starts draining when it receives the signal, keeps serving requests that are already inside a handler, and then closes. How long it is willing to wait is the --timeout-graceful-shutdown value, and what happens when the value is smaller than a request is not a warning — the task is cancelled and the client sees a dropped connection.

ScenarioSignalGraceExitShutdownClient saw
IdleSIGTERM20 s−15214.4 msno request
3 s request openSIGTERM20 s−152322.3 ms200 after 3263.2 ms
3 s request openSIGTERM1 s−151217.3 msconnection cut at 2198.6 ms
3 s request openSIGINT20 s02169.7 ms200, served in full
3 s request open, two TERMsSIGTERM20 s−152069.8 ms200, served in full
10 s request openSIGTERM3 s−153221.4 msconnection cut at 4183.9 ms
Table 12: Six shutdown scenarios on Uvicorn 0.54.0, one process, one open request where noted.

Five things in that table are worth more than the numbers. Idle shutdown takes a couple of hundred milliseconds — there is a fixed cost, so a grace period of one second is not “instant”. The in-flight case reports its full request duration, which means the server waited for the client, not the other way round. A grace period shorter than the request produces an exit in roughly the grace period, and the client loses the connection — the log line Cancel 1 running task(s), timeout graceful shutdown exceeded is the only evidence you get. SIGINT is treated as a clean stop and exits with status zero, while SIGTERM exits with the signal’s status, so a supervisor that only restarts on a non-zero code will not restart the one you wanted it to. And a second SIGTERM does not force an immediate death here: the process still waited for the request. Do not rely on a second signal as an emergency brake.

The budget rule that follows: set the grace period above the slowest request you intend to honour, and set the orchestrator’s hard limit above the grace period plus the container’s own start and stop overhead. If the slowest honoured endpoint takes eight seconds, a twenty-second grace and a thirty-second termination window are consistent; a five-second grace is a decision to drop every slow request, which is a legitimate decision as long as it is made on purpose.

#!/usr/bin/env python3
"""Measure one shutdown: does the in-flight request finish, and how long to exit?

    python shutdown_probe.py --signal TERM --grace 20 --request-seconds 3

Use it in a staging deployment before changing preStop or terminationGracePeriod:
the numbers it prints are the ones a rollout actually spends.

Reference run on the article's test host (Uvicorn 0.54.0, Python 3.12.16):

    TERM  grace 20  request 3s -> exit 2322.3 ms, request 200
    TERM  grace  1  request 3s -> exit 1217.3 ms, request cut after 2198.6 ms
    INT   grace 20  request 3s -> exit 2169.7 ms, request 200
"""
from __future__ import annotations

import argparse
import json
import os
import signal
import socket
import subprocess
import sys
import threading
import time

import httpx


def wait_for_port(port: int, timeout: float = 20.0) -> bool:
    deadline = time.monotonic() + timeout
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe_socket:
        while time.monotonic() < deadline:
            probe_socket.settimeout(0.2)
            if probe_socket.connect_ex(("127.0.0.1", port)) == 0:
                return True
            time.sleep(0.05)
    return False


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--signal", default="TERM", choices=["TERM", "INT"])
    parser.add_argument("--grace", default="20")
    parser.add_argument("--request-seconds", type=float, default=3.0)
    parser.add_argument("--port", type=int, default=8700)
    args = parser.parse_args()

    server = subprocess.Popen(  # noqa: S603 - fixed argv
        [sys.executable, "-m", "uvicorn", "app:app", "--host", "127.0.0.1",
         "--port", str(args.port), "--timeout-graceful-shutdown", args.grace,
         "--log-level", "warning"],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.PIPE,
        text=True,
    )
    if not wait_for_port(args.port):
        server.kill()
        print(json.dumps({"error": "server did not bind"}))
        return 1

    outcome: dict[str, object] = {}

    def call() -> None:
        began = time.monotonic()
        try:
            response = httpx.get(
                f"http://127.0.0.1:{args.port}/slow",
                params={"seconds": args.request_seconds},
                timeout=60.0,
            )
            outcome["status"] = response.status_code
        except Exception as exc:  # noqa: BLE001 - the failure is the measurement
            outcome["status"] = type(exc).__name__
        outcome["elapsed_ms"] = round((time.monotonic() - began) * 1000.0, 1)

    worker = threading.Thread(target=call, daemon=True)
    worker.start()
    time.sleep(1.0)
    delivered = getattr(signal, f"SIG{args.signal}")
    began = time.monotonic()
    os.kill(server.pid, delivered)
    try:
        exit_code: object = server.wait(timeout=60)
    except subprocess.TimeoutExpired:
        server.kill()
        server.wait(timeout=5)
        exit_code = "killed"
    shutdown_ms = round((time.monotonic() - began) * 1000.0, 1)
    worker.join(timeout=60)
    if server.stderr:
        server.stderr.close()
    print(json.dumps({
        "signal": args.signal,
        "grace_s": args.grace,
        "request_s": args.request_seconds,
        "exit_code": exit_code,
        "shutdown_ms": shutdown_ms,
        **outcome,
    }))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Run that probe against a staging image before the rollout that matters, not against the application in isolation. Its output is the same four facts a rollout spends: which signal, how long the process took to exit, what status the client received, and how long the client waited. If the answer changes after a dependency upgrade, you have found the upgrade’s real cost.

8. Gunicorn and UvicornWorker: the real process tree

Uvicorn can run multiple workers on its own, and Gunicorn can run Uvicorn workers. The difference at shutdown is the shape of the process tree: with Uvicorn’s own workers one parent process owns the listeners and the children; with Gunicorn a master owns the workers, respawns them, and decides when a worker has stopped responding. If a worker killed mid-request must be replaced while the service stays up, that is a master’s job.

ProcessRelationshipRSSNote
Masterparent process29.02 MiBOwns the listening socket and the worker table
Worker 1child of master42.02 MiBUvicorn event loop, one per worker
Worker 2child of master42.08 MiB—
Worker 3child of master41.46 MiB—
Worker 4child of master41.64 MiB—
Table 13: Gunicorn 27.0.1 with four UvicornWorker processes, resident memory while idle.

Workers land between 41.46 and 42.08 MiB, the master near 29.02 MiB. Those are resident numbers and they double-count shared pages: the interpreter and the larger extension modules are mapped once and counted in every process, so the sum is an upper bound rather than a private-memory figure. For a container limit that is the right direction to be wrong in. Table 16 does the arithmetic for three process shapes: the four-worker row is master plus the worker values from the same snapshot as Table 13, not from a second run.

SettingExitShutdownIn-flight requestMaster verdict
--graceful-timeout 2002669.4 ms200 after 3393.7 msclean
--graceful-timeout 101065.8 mscut at 2016.7 msclean, request lost
Table 14: Shutdown with one 3 s request in flight, graceful timeout changed.

Note the exit status: the master exits zero in both cases, including the run that dropped the request. A graceful timeout is not an error from the master’s point of view; the request simply exceeded its patience, and the only place the loss is visible is the client and the access log. This is the same class of silent failure as the shell wrapper in section 5 — every process behaved exactly as configured, and the user still saw a broken request.

Worker replacement is the other half of the value. Killing a worker with SIGKILL mid-service left 3 workers running three seconds later, the dead pid was gone from the table and had been replaced, and a liveness request was answered again. That is what makes a master worth its memory during rolling restarts: one bad worker does not remove the replica from the endpoints list.

The tree was also used to test the entrypoint advice from section 3. The master and its four workers were started in their own session, so the master’s pid is the process-group id — the shape a container runtime gives PID 1’s child — and the stop signal was delivered in the three ways a runner can deliver it.

DeliveryMaster exit (median, range)In-flight requestWorkers respawnedLeft in the group
master pid only (tini without -g)2774.7 ms (2671.5–3378.0 ms)3 of 3 answered 2000nothing
process group (tini -g)2671.3 ms (2671.2–2772.7 ms)3 of 3 answered 2000nothing
process group, twice 100 ms apart2669.9 ms (2669.3–2670.3 ms)3 of 3 answered 2000nothing
Table 15: The same four-worker tree, three stop-signal deliveries, three trials each, one 3 s request in flight.

Two results matter. First, the duplicate signal is harmless: with group delivery each worker receives SIGTERM twice, once from the group and once from the master’s own shutdown, and in all three trials the busy worker finished its request and answered 200, the master exited 0, no replacement worker was booted while shutting down, nothing was left in the group, and Gunicorn printed no warning, error or traceback. A second SIGTERM is not an emergency brake in a worker: it clears the alive flag again and a request already inside a handler is not cut short. Second, the 103.4 ms difference between the two medians is drift, not a mechanism — the ranges overlap and, in both shapes, the exit time is set by the drain of the request rather than by the delivery path.

So why keep -g? Because the equivalence depends on the direct child being a supervisor that forwards. Put a shell that waits, a Python launcher that started the server with subprocess, or a pool that spawns its own children outside the master’s knowledge between the runtime and the server, and master-only delivery stops at the wrapper: section 5 measures exactly that shape, where the wrapper exits in 1.1 ms and the server never receives the signal. -g costs nothing when the child forwards — measured above — and is the difference between a drain and a namespace kill when it does not.

ConfigurationMasterWorkersResident totalLimit to start from
Gunicorn, 1 UvicornWorker28.98 MiB47.3 MiB (one)76.31 MiB152.6 MiB (2×), rounded up to 256 MiB
Gunicorn, 4 UvicornWorkers29.02 MiB41.46–42.08 MiB each196.22 MiB392.4 MiB (2×); the 512 MiB limit in section 11 is 2.6× that
Uvicorn alone, 1 worker, no master—51.2 MiB (single process)51.2 MiB102.4 MiB (2×)
Table 16: Memory budget arithmetic, one snapshot per process shape rather than a second run.

The three rows are three different objects, and confusing them is the usual arithmetic error: 51.2 MiB is one Uvicorn process with no master, while a Gunicorn deployment with one worker is master plus worker at 76.31 MiB. Multiplying the single-process figure by four gives 204.8 MiB, which is close to the measured four-worker total (196.22 MiB) only because the master is small; both rows are stated here with the shape they were measured in so the limit can be derived from the deployment that will run.

Two Gunicorn settings deserve explicit decisions rather than defaults. --max-requests plus --max-requests-jitter recycles workers after a number of requests, which bounds the damage from a slow leak; the jitter matters because without it every worker reaches the limit at the same moment and the master restarts the whole set together. And --worker-tmp-dir defaults to a temp path that must be writable: on a read-only root filesystem the heartbeat file cannot be created and the master kills workers it cannot hear. Point it at the tmpfs mount (section 11), or at /dev/shm where the runtime provides one.

"""Gunicorn configuration for a container with a Uvicorn worker class.

    gunicorn -k uvicorn_worker.UvicornWorker -c gunicorn_conf.py app.main:app

The worker class comes from the `uvicorn-worker` distribution, which is the
home of this class since Uvicorn 0.30; `uvicorn.workers.UvicornWorker` still
imports but raises a DeprecationWarning pointing here.

The Dockerfile CMD is exactly that line, so the worker count is not repeated in
the image: WEB_CONCURRENCY from the manifest is what selects it.

Every value here is a decision about shutdown, not about throughput:
graceful_timeout bounds how long an in-flight request may finish, timeout decides
when a wedged worker is killed, and worker_tmp_dir keeps the heartbeat file off a
read-only root filesystem. Measured with four workers on the article's test host:
master 29.0 MiB RSS, workers 41.5-42.1 MiB each, SIGTERM to master with one 3s
request in flight exiting in 2669.4 ms with the request answered 200.
"""
from __future__ import annotations

import multiprocessing
import os

bind = os.environ.get("BIND", "0.0.0.0:8000")
worker_class = "uvicorn_worker.UvicornWorker"
workers = int(os.environ.get("WEB_CONCURRENCY", multiprocessing.cpu_count() * 2 + 1))
graceful_timeout = int(os.environ.get("GRACEFUL_TIMEOUT", 25))
timeout = int(os.environ.get("WORKER_TIMEOUT", 45))
keepalive = int(os.environ.get("KEEPALIVE", 5))
worker_tmp_dir = os.environ.get("WORKER_TMP_DIR", "/dev/shm")
max_requests = int(os.environ.get("MAX_REQUESTS", 2000))
max_requests_jitter = int(os.environ.get("MAX_REQUESTS_JITTER", 200))
accesslog = "-"
errorlog = "-"
loglevel = os.environ.get("LOG_LEVEL", "warning")
forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1")

The configuration file is code, which is the point: Gunicorn evaluates it, so worker counts and timeouts can come from the environment without rewriting the command line. Keep graceful_timeout and the Kubernetes termination window consistent, and set timeout strictly larger — a worker whose heartbeat is late should be killed by the master before the orchestrator kills the whole container. The Dockerfile in section 3 ends with CMD ["gunicorn", "-k", "uvicorn_worker.UvicornWorker", "-c", "/app/gunicorn_conf.py", "app.main:app"], so this file is the only place the worker count is written down, and WEB_CONCURRENCY from the manifest is what sets it.

That -k value is worth one note, because it moved. uvicorn_worker.UvicornWorker is the class’s home since Uvicorn 0.30, shipped in the separate uvicorn-worker distribution: pip install uvicorn-worker, then -k uvicorn_worker.UvicornWorker, which is what both the Dockerfile and gunicorn_conf.py now use. The old path, uvicorn.workers.UvicornWorker, still imports in 0.54.0 but raises a DeprecationWarning that points at the package. The swap is mechanical rather than behavioural, and that was measured rather than assumed: three trials per class, four workers, one three-second request in flight when SIGTERM reached the master — the packaged class drained and exited in 2655.2 ms against 2656.0 ms for the legacy path, and all six requests were answered 200 with the master exiting zero and nothing left in the process group. The tree in Table 13 — master plus four workers, each a child of the master — is the shape both classes produced in those trials, so the memory arithmetic built on that shape does not move with the import path.

9. Probes that tell the truth

A health endpoint usually answers a different question than the one the orchestrator is asking. The orchestrator asks “should routing continue to include this instance?” and “is this process worth restarting?”. A handler that returns {"status": "ok"} answers “did the event loop schedule me?”. Those answers separate when a dependency is down, and they separate violently when a synchronous handler blocks the loop.

The first measurement is the honest baseline: two hundred probes of each endpoint against a single idle worker, with a dependency probe that awaits a thirty-millisecond stand-in for a pooled round trip.

Endpointp50p95MaxWhat it proves
/health/liveness0.62 ms0.91 ms40.08 msHandler cost is negligible; the tail is scheduling noise
/health/readiness31.31 ms31.79 ms32.2 msReadiness costs one dependency round trip by design
Table 17: Probe latency on an idle worker, 200 requests each.

Now the two failure modes. With the stand-in dependency set to three seconds against a two-second deadline, readiness returned 503 at 2039.9 ms — it reported the degradation rather than hanging, which is the behaviour that keeps a bad instance out of rotation without killing it. With one request running a time.sleep inside the event loop, the next liveness probe took 1835.4 ms. The default Kubernetes liveness timeout is one second, so that probe fails — but it does not restart the container by itself: failureThreshold defaults to 3 consecutive failures and periodSeconds to 10, so a restart needs three blocked probes in a row, roughly half a minute of a wedged event loop rather than one unlucky second. That gap is the space you tune in: a single slow probe is scheduling noise, three in a row is a handler holding the loop, and neither is a reason to share a timeout with a dependency check.

ConditionLiveness resultReadiness resultCorrect orchestrator reaction
Dependency 3 s, deadline 2 snot probed in that run503 at 2039.9 msRemove from endpoints, do not restart
Event loop blocked 2 sprobe took 1835.4 mswould also stallRestart after three consecutive failures; fix the handler first
Table 18: The same probe under the two kinds of pressure. The idle baseline is in Table 17.

The application code that produces those numbers is deliberately boring. Liveness touches nothing external; readiness awaits a dependency with a hard deadline and returns a status code that the orchestrator understands; the counters say how many requests are inside a handler right now, which is the only thing they can say. Whether a request actually finished is decided on the other side of the connection: a status code, a read timeout or a reset is the client’s answer, and a process that has already drained cannot be asked for one.

"""FastAPI target used by every measurement harness in this directory.

Endpoints exist to expose one specific production behaviour each:

  /health/liveness   - handler returns a constant, never touches a dependency
  /health/readiness  - handler awaits a dependency probe with a hard deadline
  /slow              - awaits asyncio.sleep, holds a request open without a thread
  /sync-block        - calls time.sleep inside the event loop (the classic bug)
  /stats             - in-process counters, readable only while the server serves

The counters answer a question about the present ("how many requests are inside
a handler right now"). They cannot answer a question about the past: once the
server has drained, /stats is unreachable, so whether a request finished is the
client's answer - a status, a timeout, or a reset - not a number read back here.
"""
from __future__ import annotations

import asyncio
import logging
import os
import time
from contextlib import asynccontextmanager
from dataclasses import dataclass

from fastapi import FastAPI, Response, status

APP_VERSION = os.environ.get("APP_VERSION", "1.0.0")
DEPENDENCY_DELAY = float(os.environ.get("DEPENDENCY_DELAY", "0.03"))

logger = logging.getLogger("uvicorn.error")


@dataclass
class Counters:
    started: int = 0
    completed: int = 0
    in_flight: int = 0


STATE = Counters()


@asynccontextmanager
async def lifespan(_app: FastAPI):
    """Startup work before the yield, shutdown work after it.

    The shutdown half replaces the deprecated @app.on_event("shutdown") hook: it
    runs once the server has stopped accepting connections and drained. A log
    line is the record, because at that point nothing can ask the process
    anything over HTTP.
    """
    yield
    logger.info("lifespan shutdown complete")


app = FastAPI(title="Measurement Target", version=APP_VERSION, lifespan=lifespan)


async def dependency_probe() -> float:
    """Stand-in for a pooled database or cache round trip."""
    began = time.monotonic()
    await asyncio.sleep(DEPENDENCY_DELAY)
    return (time.monotonic() - began) * 1000.0


@app.middleware("http")
async def track_in_flight(request, call_next):
    STATE.started += 1
    STATE.in_flight += 1
    try:
        return await call_next(request)
    finally:
        STATE.in_flight -= 1
        STATE.completed += 1


@app.get("/health/liveness")
async def liveness() -> dict[str, str]:
    return {"status": "alive"}


@app.get("/health/readiness")
async def readiness(response: Response) -> dict[str, object]:
    try:
        latency = await asyncio.wait_for(dependency_probe(), timeout=2.0)
        return {"status": "ready", "dependency_ms": round(latency, 2)}
    except asyncio.TimeoutError:
        response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
        return {"status": "degraded", "reason": "dependency timeout"}


@app.get("/slow")
async def slow(seconds: float = 3.0) -> dict[str, object]:
    began = time.monotonic()
    await asyncio.sleep(seconds)
    return {"slept_ms": round((time.monotonic() - began) * 1000.0, 1)}


@app.get("/sync-block")
async def sync_block(seconds: float = 2.0) -> dict[str, str]:
    time.sleep(seconds)  # deliberately wrong: blocks the whole event loop
    return {"blocked_s": str(seconds)}


@app.get("/stats")
async def stats() -> dict[str, object]:
    return {
        "started": STATE.started,
        "completed": STATE.completed,
        "in_flight": STATE.in_flight,
        "pid": os.getpid(),
    }

The manifest then has to match the numbers. Three settings matter: a startupProbe that absorbs the cold start measured in section 4 (the first response here arrived at 2216.3 ms for one worker and 1903.0 ms for four), a readinessProbe whose timeout is larger than the dependency deadline so a 503 is reported as a 503 rather than as a timeout, and a preStop sleep that lets endpoint removal propagate before the drain begins.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: fastapi-api
  labels:
    app: fastapi-api
spec:
  replicas: 4
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  selector:
    matchLabels:
      app: fastapi-api
  template:
    metadata:
      labels:
        app: fastapi-api
    spec:
      terminationGracePeriodSeconds: 30
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        runAsGroup: 10001
        fsGroup: 10001
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: api
          image: registry.example.com/fastapi-api:1.4.0
          imagePullPolicy: IfNotPresent
          ports:
            - name: http
              containerPort: 8000
          env:
            - name: WEB_CONCURRENCY
              value: "4"
            - name: GRACEFUL_TIMEOUT
              value: "20"
            - name: WORKER_TMP_DIR
              value: /dev/shm
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop:
                - ALL
          volumeMounts:
            - name: tmp
              mountPath: /tmp
          lifecycle:
            preStop:
              exec:
                command: ["/bin/sh", "-c", "sleep 5"]
          startupProbe:
            httpGet:
              path: /health/liveness
              port: http
            periodSeconds: 2
            failureThreshold: 15
          livenessProbe:
            httpGet:
              path: /health/liveness
              port: http
            periodSeconds: 10
            timeoutSeconds: 3
            failureThreshold: 3
          readinessProbe:
            httpGet:
              path: /health/readiness
              port: http
            periodSeconds: 5
            timeoutSeconds: 4
            failureThreshold: 2
          resources:
            requests:
              cpu: 250m
              memory: 256Mi
            limits:
              cpu: "2"
              memory: 512Mi
      volumes:
        - name: tmp
          emptyDir:
            medium: Memory
            sizeLimit: 64Mi

The arithmetic behind terminationGracePeriodSeconds is worth writing down, because it is the sum of three things people usually set separately: the preStop delay, the server’s graceful timeout, and the runtime’s own stop overhead. Thirty seconds with a five-second preStop leaves twenty-five for draining, which comfortably covers the measured in-flight drain of roughly two to three seconds for a three-second request, and leaves room for a slow endpoint. If the grace period equals the drain timeout exactly, the runtime kills the process at the moment the drain would have finished.

10. Read-only root filesystem and a non-root user

A read-only root filesystem is a cheap, effective control: an attacker who reaches code execution cannot drop a payload, replace a binary, or edit the application. The cost is that every implicit write your process makes becomes a runtime error, and the errors arrive at different times — some at startup, some on the first upload, some never, because the write was optional and failed silently.

The experiment makes a directory read-only for its owner and then attempts the writes a web service typically makes. Note the first row: appending to an existing file still succeeded, because the file’s own permissions allow it even though the directory does not allow new entries. Permissions on a directory are not the same thing as a read-only mount, which refuses the open with a different errno. Both are worth knowing; neither should be confused with “the app cannot write”.

AttemptResultErrnoWhat it means for the container
Append to an existing filesucceeded—Directory permission does not protect a writable file
Create a new filefailed13 (PermissionError)Uploads, exports and lock files fail here
Create a directoryfailed13Cache and temp subdirectories cannot be created
os.access(path, os.W_OK)false—A startup check can detect this before traffic
Write bytecode into a package dirnot written—The interpreter skips the write silently
Write 1 MiB to /dev/shmsucceeded, 0.4 ms—The tmpfs mount is the escape hatch for temp files
Table 19: Writes attempted in a directory made read-only for its owner.

The pattern that survives is a contract with three parts: the application writes only to paths explicitly mounted for it, startup asserts that contract instead of discovering it later, and everything else is read-only. The check below is small enough to run as an entrypoint wrapper or as a one-shot job in CI against the real image.

#!/usr/bin/env python3
"""Print the runtime facts a hardened container is supposed to have.

    ENTRYPOINT ["python", "preflight.py", "--", "uvicorn", "app:app"]

or run it once as a one-shot job:

    docker run --rm --read-only --user 10001:10001 image python preflight.py

It checks identity, the writability contract of the paths the app needs, the
memory limit the kernel exposes through cgroup v2, and whether bytecode would have
to be written at runtime.
"""
from __future__ import annotations

import json
import os
import pathlib
import shutil
import sys
import tempfile
import time


def read_first(path: str) -> str | None:
    try:
        return pathlib.Path(path).read_text().strip()
    except OSError:
        return None


def writable_contract() -> dict[str, bool]:
    return {
        "/app": os.access("/app", os.W_OK),
        "site-packages": not _needs_bytecode_write(),
        "tempdir": _tempdir_writable(),
        "/dev/shm": os.access("/dev/shm", os.W_OK),
    }


def _needs_bytecode_write() -> bool:
    import fastapi  # local import keeps the check quiet when FastAPI is absent

    location = pathlib.Path(fastapi.__file__).parent
    return os.access(location, os.W_OK)


def _tempdir_writable() -> bool:
    try:
        with tempfile.NamedTemporaryFile(delete=True) as handle:
            handle.write(b"preflight")
            handle.flush()
        return True
    except OSError:
        return False


def main() -> int:
    facts = {
        "uid": os.getuid(),
        "gid": os.getgid(),
        "running_as_root": os.getuid() == 0,
        "cgroup_memory_max": read_first("/sys/fs/cgroup/memory.max"),
        "python": sys.version.split()[0],
        "bytecode_cache": bool(sys.pycache_prefix) or not sys.dont_write_bytecode,
        "disk_free_mib": round(shutil.disk_usage("/").free / 1024 / 1024, 1),
        "paths": writable_contract(),
        "checked_at": round(time.time(), 3),
    }
    print(json.dumps(facts, indent=2))
    fatal = facts["running_as_root"] or not facts["paths"]["tempdir"]
    return 2 if fatal else 0


if __name__ == "__main__":
    sys.exit(main())

Two more hardening facts belong here, because they are the ones a scanner reports and a Dockerfile forgets. The uid must be numeric in the image (a user created at build time works; a user created at runtime does not, and USER 10001 avoids the name lookup entirely). And capabilities are inherited from the runtime — dropping them in Compose or a pod security context is a deployment decision, but the image can make the effective set small by not needing any: no CAP_NET_BIND_SERVICE because the port is above 1024, no privileged path writes, no package manager.

Secrets follow the same logic. A read-only filesystem stops an attacker from writing, not from reading, so a mounted secret file must still be readable only by the running uid, and an environment variable is visible to anything that can read /proc/self/environ in that namespace. Neither is a substitute for the other; the file mount is the better default, and the read-only root is what makes it a stable location.

11. A compose file that matches the measurements

The compose file below is for staging, a single-node VPS, or a laptop that should behave like production. It encodes four decisions from the sections above: a non-root uid with a read-only root, a tmpfs for the paths that must be writable, resource limits derived from the measured memory figures, and a healthcheck that uses a binary the image actually contains.

services:
  api:
    image: registry.example.com/fastapi-api:1.4.0
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    user: "10001:10001"
    read_only: true
    tmpfs:
      - /tmp:rw,noexec,nosuid,size=64m
      - /dev/shm:rw,noexec,nosuid,size=64m
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true
    stop_grace_period: 30s
    ports:
      - "8000:8000"
    environment:
      WEB_CONCURRENCY: "4"
      GRACEFUL_TIMEOUT: "20"
      WORKER_TMP_DIR: /dev/shm
      DATABASE_URL: postgresql+asyncpg://app:${DB_PASSWORD:?set DB_PASSWORD}@db:5432/app
      REDIS_URL: redis://cache:6379/0
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "python", "-c", "import socket,sys; s=socket.create_connection(('127.0.0.1',8000),2); s.close()"]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 15s
    deploy:
      resources:
        limits:
          cpus: "2.0"
          memory: 512M
        reservations:
          cpus: "0.25"
          memory: 256M
    logging:
      driver: json-file
      options:
        max-size: 20m
        max-file: "3"

  db:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_DB: app
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD}
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 5s
      timeout: 3s
      retries: 10
    deploy:
      resources:
        limits:
          memory: 1G

  cache:
    image: redis:7.4-alpine
    restart: unless-stopped
    command: ["redis-server", "--maxmemory", "256mb", "--maxmemory-policy", "allkeys-lru", "--save", ""]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 2s
      retries: 10
    deploy:
      resources:
        limits:
          memory: 320M

volumes:
  pgdata:

That last point is the most common copy-paste bug in Compose files. A healthcheck of the form curl -f http://localhost:8000/health fails on any minimal image, because curl is not installed — and a failing healthcheck makes the container unhealthy, which in some orchestrators means it gets replaced in a loop. The check here uses the interpreter that is guaranteed to exist, opens a socket, and exits with a status code. It costs a fraction of a second and no extra package.

deploy.resources.limits is honoured by Compose in recent versions and by Swarm; a plain docker run ignores it, so use --memory and --cpus directly when running without an orchestrator. The numbers here follow Table 16: four workers at roughly forty-two MiB plus a master near thirty MiB is 196.22 MiB, so the 512 MiB limit is 2.6× the measured total and the 256 MiB request sits a third above it. The gap is deliberate: it leaves room for a request path that allocates a hundred megabytes of buffers — which is exactly the scenario that produces an OOMKilled rather than a clean error.

A note on depends_on with condition: service_healthy: it orders container starts, not application readiness. The API still needs to tolerate a database that is up but not yet accepting connections, and its readiness probe (section 9) is what reports that state. Treat Compose ordering as a convenience for local runs and the probe as the contract.

12. The rollout runbook and its arithmetic

Everything above converges on one sequence. The runbook below assumes the image from section 3, the probe set from section 9, and a rollout strategy that never takes an endpoint out of service before its replacement is ready.

  1. Before the rollout: run shutdown_probe.py against the candidate image with its slowest endpoint, confirm the client receives a status rather than a reset, and record the drain duration. Compare it with the previous image.
  2. Before the rollout: check that preStop plus graceful timeout fits inside terminationGracePeriodSeconds with at least five seconds to spare.
  3. During the rollout: watch the readiness transition of the new pods, not the pod count. A pod that becomes ready and then unready is a dependency problem; a pod that never becomes ready is a probe or startup problem.
  4. During the rollout: watch the old pods’ shutdown lines for the cancellation message. Each occurrence is a request the user lost, and each one names the endpoint’s budget being too small.
  5. After the rollout: confirm the container count, the image digest, and that no pod restarted for liveness reasons in the first fifteen minutes.
  6. If it goes wrong: roll back the image, not the manifest. Manifest changes (timeouts, probes) are usually the cause of a restart loop, and reverting them without reverting the code confuses the next attempt.
QuantityMeasured valueSetting it feeds
Idle shutdown214.4 msFloor for any graceful timeout
3 s request drained2322.3 msgraceful timeout above the slowest endpoint
Request cut by a 1 s grace2198.6 msEvidence that the grace must exceed request time
Gunicorn drain with 3 s request2669.4 msMaster-level graceful timeout
Worker replacement after SIGKILLunder 3 sHow fast the service recovers from a bad worker
Table 20: Drain arithmetic for the measured shutdowns.
#!/bin/sh
# Availability check across a rollout: fails if readiness goes unanswered
# for longer than the allowed window, which is the only thing a user feels.
# Runs for DURATION seconds of wall clock, not for DURATION iterations: the
# check is a time budget, and a slow poll must not shorten it.
set -eu

URL="${URL:-http://127.0.0.1:8000/health/readiness}"
DURATION="${DURATION:-180}"
MAX_GAP="${MAX_GAP:-3}"
INTERVAL="${INTERVAL:-0.5}"

started=$(date +%s)
deadline=$((started + DURATION))
polls=0
gap=0

while :; do
    now=$(date +%s)
    [ "$now" -lt "$deadline" ] || break
    polls=$((polls + 1))
    if curl -fsS -m 2 -o /dev/null "$URL"; then
        gap=0
    else
        gap=$((gap + 1))
        echo "readiness failed, gap ${gap} poll(s)" >&2
        if [ "$gap" -ge "$MAX_GAP" ]; then
            echo "FAIL: readiness unanswered for ${gap} consecutive polls" >&2
            exit 1
        fi
    fi
    sleep "$INTERVAL"
done

elapsed=$(( $(date +%s) - started ))
echo "PASS: ${polls} polls over ${elapsed}s, longest allowed gap ${MAX_GAP} poll(s)"

The smoke script is deliberately primitive: it polls readiness through a rollout and fails if the endpoint stops answering for longer than a threshold. It runs for the wall-clock duration it advertises (DURATION, 180 s by default) rather than for a count of iterations, so a slow poll does not shorten the window it is supposed to cover. It is the check that catches the difference between “the deploy finished” and “the service was available throughout the deploy”, which no dashboard shows by default.

13. Failure signatures and what they mean

Most container incidents leave one of a handful of signatures. The table maps each to its mechanism and to the section of this article that measures it, so the next occurrence is a lookup instead of an investigation.

SignatureMechanismConfirm with
503s during deploys onlyDrain too short or endpoint removal racing the signalDrain probe: 2198.6 ms cut at a 1 s grace
Container stops in exactly the grace periodPID 1 swallowed the signal; at the grace deadline the runtime SIGKILLs the namespace and the in-flight request dies with itNo drain line from the server; the client is cut at the grace limit (a 1 s grace cut a 3 s request at 2198.6 ms)
Restart loop after deployLiveness too strict for a slow first requestFirst response at 2216.3 ms
Restart loop under loadSync handler blocking the event loopProbe at 1835.4 ms while blocked
OOMKilled without a leakLimit below workers times resident figureTable 16 arithmetic
Fork failures after hoursZombies from an unreaped child27 zombies without a reap loop
Empty logs after a crashBuffered stdout lost at kill0 of 5 lines survived
Startup 500s on a read-only imageWrite to a path that no longer existserrno 13 on create
Cold starts slower after “slimming”Bytecode no longer precompiled878.3 vs 543.3 ms first pass; 903.1 vs 545.6 ms re-measured
Requests dropped on one replica onlyOne worker killed, nothing respawning itMaster respawn check
Table 21: Ten signatures, their mechanisms, and the measurement that confirms each.

The pattern across all ten: the evidence exists at the process and probe level, and almost never in the application log. That is why this runbook measures instead of advising — the measurement is the artefact you compare against when the incident is happening.

14. FAQ

Q: Does Uvicorn handle SIGTERM without an init process?

A: It installs its own handler and drains, so a plain Uvicorn process in exec form shuts down cleanly: in this run an idle shutdown took 214.4 ms and an in-flight request was served in full. What it cannot do is act as PID 1 for other processes. If the server is the only process, no init is needed; if the image spawns anything, it is.

Q: Is dumb-init or tini necessary?

A: Only if something can create orphans or if the entrypoint is a shell that does not exec. Both binaries implement the same contract as the shim in section 6: forward signals, reap exited children, exit with the child’s status — and add -g to tini, or the signal stops at the direct child. A measured shim run forwarded the signal and left zero zombies.

Q: How long should terminationGracePeriodSeconds be?

A: The preStop delay plus the server’s graceful timeout plus a margin. With the measured drain of 2322.3 ms for a three-second request, a five-second preStop and a twenty-second grace fit comfortably inside thirty seconds. If the termination window equals the drain timeout, the runtime kills the process exactly when the drain would have finished.

Q: Why did my pod restart when the process was healthy?

A: A liveness probe times out because the event loop is blocked. One synchronous handler holding the loop for two seconds pushed a liveness probe to 1835.4 ms against a one-second default timeout; with the default three consecutive failures it takes about half a minute of that before the kubelet restarts anything. Move blocking work off the loop, raise the probe timeout, and keep dependency checks in readiness rather than liveness.

Q: Should I precompile bytecode in the image?

A: Yes, in the build stage, where the filesystem is writable and the interpreter version is fixed — with the default optimize level, because an optimize=1 cache is invisible to an interpreter started without -O. The measured saving was 357.5 ms per start — 903.1 ms without a cache, 545.6 ms with one compiled at the default level (Table 5) — for 12.17 MiB of bytecode. Set PYTHONDONTWRITEBYTECODE=1 at runtime so the interpreter does not attempt writes on a read-only layer.

Q: Do I need Gunicorn if Uvicorn can run multiple workers?

A: Only if you want a master that respawns workers and enforces a worker heartbeat. Uvicorn’s workers share one parent that does little beyond supervision; Gunicorn adds worker replacement and a tmp-dir heartbeat, at the cost of roughly 29.02 MiB for the master.

Q: What breaks first with a read-only root filesystem?

A: New files and directories, with a permission error at the first write rather than at startup. Existing files stay writable, so the failure often appears as a missing export or a failed upload. Mount a tmpfs for temp paths, point the worker heartbeat and any cache directory at it, and assert the contract in an entrypoint check.

Q: Are the numbers in this article from a real Docker build?

A: No, and that is stated in each section: this host has no container runtime. Process behaviour (signals, shutdown timing, probes, memory, bytecode, permissions) was measured directly; image layout, compose files and manifests are validated patterns, with the measured content sizes given so you can compare them against your own build.

Docker is the layer underneath everything else in a Python backend. For the worker lifecycle inside these containers, FastAPI on Gunicorn and UvicornWorker covers the deadlocks and event-loop starvation that no image change can fix. For the resource limits that decide when a container is killed, Kubernetes pod resources and OOMKilled goes through requests, limits and the OOM killer. Celery production architecture is where the same signal and reaping rules apply to a worker that forks its own pool.

For the data layer: SQLAlchemy 2.0 async in production for the pool that a worker’s concurrency has to match, Redis caching and distributed locks for the cache that a second container will fight over, and PostgreSQL slow query triage for the queries that make a graceful drain impossible because they never finish. httpx AsyncClient in production covers the client side of the same drain problem, and The TechBobby Stack is the tooling map these runbooks belong to.

Two free resources from TechBobby: the AI Prompt Pack for engineers — the prompts used to review a Dockerfile, write a shutdown probe and interview a dependency — and the Zero-Crash Python newsletter, one production failure per issue with the measurements attached.

Written by TechBobby Engineering — an independent engineer publishing measured Python production runbooks. Every figure in this revision came from a probe executed on Python 3.12.16 with Uvicorn 0.54.0, Gunicorn 27.0.1 and FastAPI 0.162.7 on a two-vCPU Linux container; the scripts are printed in full in the code blocks and the JSON output of each session was kept. What this host could not test — the image build itself, mount-level read-only filesystems and kernel-level PID 1 semantics — is marked as a pattern or reproduced by its mechanism, and never presented as a measured image result.

Errata and revision notes (2026-11-16, revision 6). This edition replaces an earlier one. Every figure was measured for it, and the corrections below changed a claim rather than a wording.

  • Process, signals and memory. The shipped shim exits with the shell convention 128 + N (143 for SIGTERM) instead of re-raising the child’s signal, which reports the wrong status when the shim really is PID 1; master-only, process-group and repeated group SIGTERM drain identically (Table 15); and every memory row states the process shape it was measured in.
  • Build and bytecode. The slow start came from the failed bytecode write on an existing but unwritable __pycache__, not from the .opt-1.pyc name; PIP_NO_CACHE_DIR=off is gone from the builder, because pip reads every value of that variable as “disable”; and the image installs uvicorn-worker and starts uvicorn_worker.UvicornWorker, with the old import path named only as deprecated.
  • Application and probes. The example app registers shutdown through lifespan instead of @app.on_event("shutdown"), and its counters no longer claim to prove that a request survived the drain: /stats is unreachable by then, so completion is the client’s verdict (a status, a timeout, a reset). A Dockerfile HEALTHCHECK stays image metadata that Kubernetes ignores; the Compose healthcheck: key in section 11 is the single-node exception, one socket connect per interval.
  • Numbers. Where two measurement passes exist both are printed and labelled (Tables 4, 5 and 21), because the gap between passes on this host is tens of milliseconds and no figure here is exact to the millisecond.

Keep reading

Get the next essay and every new code pack before anyone else — subscribe to the weekly letter. Free tier first, always.