Graceful shutdown in Python without orphaned resources
SIGTERM is the polite knock at the door: a process manager asks a service to stop, then gives it time to finish. Python’s normal finally blocks and context managers cannot help when the default signal action terminates the interpreter outright. I wanted a reusable answer for that gap.
My first attempt registered a handler that deleted a temporary directory immediately. It worked in a demo, then raced with a worker still writing an export. That failure pushed me toward a design with explicit ownership, one shutdown path, and cleanup that can be tested without endangering the test runner.
The finished module tracks temporary paths and child processes, coordinates a single stop request, and removes only what it created. It is deliberately small, dependency-free, and usable inside command-line tools as well as long-running services.
Why normal cleanup misses termination
Unix signals do not follow Python’s normal exception flow. Unless SIGTERM is intercepted, the operating system ends the process, so finally clauses may never run. A handler that raises an exception can work, but it changes the exit status and may interrupt cleanup code already in progress.
SIGTERM also differs from SIGKILL, which cannot be caught. The module therefore treats termination as a grace period: stop new work, release resources, and exit with a deliberate status. If cleanup stalls, an outer supervisor can still enforce a hard deadline.
Building a registry with explicit ownership
I began with a registry object. Each temporary file, directory, lock, or subprocess is registered with the object that created it and, where practical, entered through a context manager. The registry remembers ownership, dependencies, and the safe order in which entries must be released.
That small-tool approach matches the Python utilities I maintain here, including the Kodos project page for its regular-expression debugger. A narrow module with ordinary Python types is easier to audit than a framework, and it can be copied into projects that do not want another package in production.
Waking the process without unsafe cleanup
A signal handler should do as little as possible. Python runs handlers on the main thread, between bytecodes, so deleting files inside the handler can re-enter application logic or deadlock on a lock. The handler in my module records the signal number and writes one byte to a self-pipe.
def _on_sigterm(self, signum, frame):
self._requested = signum
os.write(self._wake_write_fd, b"\x00")
A supervisor thread waits on the pipe, converts that byte into a shutdown event, and lets the coordinator move the application into a stopping state. The self-pipe matters when the main thread is waiting for I/O: it provides a reliable wake-up without doing expensive work in the signal path.
Deadlines use time.monotonic() rather than wall-clock time. That distinction matters on Australian servers: daylight-saving changes in Sydney and Melbourne alter UTC offsets, while a monotonic clock keeps the allowed cleanup interval steady. Local time is useful in logs, not in timeout arithmetic.
Removing temporary resources in safe order
Temporary resources are created with tempfile, but stored in the registry instead of relying only on TemporaryDirectory. Each entry records whether it is active and whether removal has already succeeded. Cleanup runs once, in reverse dependency order, so a child path disappears before the directory that contains it.
The remover checks ownership before calling unlink or rmtree. It refuses suspicious symlinks and paths outside the temporary root it created. This avoids the common bug where a stale path is replaced by a link and cleanup follows it somewhere unexpected. Failed removals are logged and retried only when safe.
Subprocesses receive termination first and are given a short chance to exit before their parent is released. Files are opened with exclusive creation where possible, and temporary directories use restrictive permissions. The result is predictable even when a deployment is interrupted halfway through.
Testing termination in a separate process
Signal tests belong in a child process. A test spawns a small Python program with a temporary root, waits until it reports that its resource is ready, and sends SIGTERM. The parent then checks the exit code, logs, absence of the temporary directory, and any intentionally preserved diagnostic file.
I also inject failures into unlink and subprocess termination because happy-path tests miss lock contention and partially written state. Each test has its own temporary root and timeout, so one failed cleanup cannot damage the working tree. On Linux CI, the subprocess can be isolated with ordinary user permissions.
Packaging the module for dependable use
Packaging exposed several design questions: minimum Python version, public versus private methods, and whether the module should own a signal handler at all. I kept the handler optional, documented the previous handler restoration behaviour, and published type hints without adding runtime dependencies.
The release and deployment notes for FoldYourSO were a useful model for producing source archives, checksums, a change log, and a systemd example. A dependency-free module is particularly practical for Australian teams running self-hosted Linux VPS instances and maintaining their own deployment scripts.
The documentation uses Australian English, including licence as a noun and behaviour in technical descriptions. It also explains that the package is source-first: maintainers can read it, patch it, and use it under the published licence rather than depending on a hosted service.
A practical shutdown checklist
Before deploying the module, I check that every resource has an owner and that cleanup cannot remove something supplied from outside the registry. The shutdown sequence then becomes a fixed routine rather than a collection of ad hoc signal handlers.
The checklist below is what I now use for command-line tools and services:
- Register each temporary path and subprocess immediately after creation.
- Install the handler before allocating resources that need graceful release.
- Keep the handler lightweight and perform destructive work in the coordinator.
- Send SIGTERM in an integration test and verify both cleanup and exit status.
With that discipline, SIGTERM becomes an orderly request instead of an ambush. The module exits without orphaned directories, stale locks, or orphaned children, leaving the machine clean as a whistle.
