Sub topic 16
Graceful shutdown on signals
A long-running asyncio program, such as a queue consumer or an API server, usually ends because the operating system sends it a signal. A graceful shutdown stops taking new work, lets in-flight work finish within a deadline, and releases resources. This chapter combines signal handling with the tools from earlier chapters: TaskGroup, asyncio.timeout, and CancelledError cleanup.
It assumes you know TaskGroup, asyncio.timeout, and why CancelledError must be re-raised after cleanup. It also assumes you are on Python 3.11 or newer.
What happens without any handling
The two signals you will meet most often behave differently by default.
| Signal | Sent by | Default behaviour |
|---|---|---|
| `SIGINT` | Ctrl+C in a terminal | `asyncio.run` cancels the main task, waits for it to finish, then raises `KeyboardInterrupt` (3.11+) |
| `SIGTERM` | `kill`, Docker stop, Kubernetes, systemd | The process ends immediately. No `finally` block runs |
The SIGTERM row is the one that matters in production. Container platforms send SIGTERM, wait a grace period (often 10 to 30 seconds), and then send SIGKILL, which cannot be caught. If you do not handle SIGTERM, your cleanup code never runs.
Why add_signal_handler
Python's signal.signal runs your function between bytecode instructions in the main thread. At that point the event loop may be in the middle of an operation, so most asyncio calls are not safe there.
loop.add_signal_handler(sig, callback, *args) is the asyncio-aware alternative. The loop notices the signal and then calls your callback as an ordinary loop callback. Inside it you can safely call Event.set() or Task.cancel().
add_signal_handler is Unix-only. On Windows it raises NotImplementedError. The fallback is signal.signal with loop.call_soon_threadsafe to hop back into the loop safely.
Two ways to react
You can turn a signal into a shutdown request in two ways.
- Set a stop event. Workers check the event and return normally. This is cooperative: each worker finishes its current job and exits its loop.
- Cancel the main task. The
CancelledErrorpropagates into theTaskGroup, which cancels every child. This is abrupt: jobs are interrupted wherever they are awaiting.
The event approach suits workers that have natural job boundaries. Cancellation suits work that can be interrupted safely. A common design uses both. It asks workers to stop with an event and falls back to cancellation if they take too long.
A complete shutdown pattern
This program starts three workers inside a TaskGroup, waits for a signal, and then gives the workers a fixed time to drain. Run it and press Ctrl+C, or send kill -TERM <pid> from another terminal.
import asyncio
import signal
DRAIN_TIMEOUT = 3.0
async def worker(name: str, stop: asyncio.Event) -> None:
try:
while not stop.is_set():
print(f"{name}: starting job")
await asyncio.sleep(1) # stands in for real work
print(f"{name}: job done")
finally:
print(f"{name}: released resources")
async def run_workers(stop: asyncio.Event) -> None:
async with asyncio.TaskGroup() as tg:
for i in range(3):
tg.create_task(worker(f"w{i}", stop))
def install_stop_handlers(loop: asyncio.AbstractEventLoop, stop: asyncio.Event) -> None:
for sig in (signal.SIGINT, signal.SIGTERM):
try:
loop.add_signal_handler(sig, stop.set)
except NotImplementedError: # Windows event loops
signal.signal(sig, lambda *_: loop.call_soon_threadsafe(stop.set))
async def main() -> None:
loop = asyncio.get_running_loop()
stop = asyncio.Event()
install_stop_handlers(loop, stop)
runner = asyncio.create_task(run_workers(stop))
runner.add_done_callback(lambda _: stop.set()) # wake main if workers fail
await stop.wait()
print("shutdown requested, draining")
try:
async with asyncio.timeout(DRAIN_TIMEOUT):
await runner
except TimeoutError:
print("drain deadline hit, workers were cancelled")
print("exit")
asyncio.run(main())Each part of the program has a job:
stopis the shutdown request. Handlers only set it, which is fast and cannot fail.runnerholds theTaskGroup. Because the group is the only thing that owns the workers, no worker can outlive it.- The done callback sets
stopifrunnerends for any reason. Without it, a crash in the workers would leavemainwaiting onstop.wait()forever. asyncio.timeout(DRAIN_TIMEOUT)bounds the drain. If it expires, the timeout cancels the awaiting main task. Cancellation propagates torunner, and theTaskGroupcancels each worker.await runnerraises only after that cancellation has finished, so thefinallyblocks have already run whenTimeoutErrorappears.- If the workers raised errors,
await runnerraises theExceptionGroup, which you can catch withexcept*as in earlier chapters.
The sequence for a normal shutdown looks like this:
Cancelling the main task instead
When your code is already cancellation-safe, you can skip the event and cancel the main task directly:
import asyncio
import signal
async def main() -> None:
loop = asyncio.get_running_loop()
loop.add_signal_handler(signal.SIGTERM, asyncio.current_task().cancel)
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(asyncio.sleep(3600))
except asyncio.CancelledError:
print("main: cancelled, cleanup done")
raise
try:
asyncio.run(main())
except asyncio.CancelledError:
print("terminated by SIGTERM")Here main re-raises CancelledError, as the cleanup rules from earlier chapters require. asyncio.run then raises CancelledError to its caller, which you can catch at the top level to choose an exit code.
Edge cases and gotchas
- Handlers must be quick. Do not run cleanup inside the callback. Set an event or cancel a task, and let normal async code do the work.
- Repeated signals. Operators often press Ctrl+C twice. A second signal while
stopis already set is a good moment to give up on a clean exit and callsys.exit(1). - Blocking calls delay shutdown. The loop can only run your handler when it regains control. A blocking call such as
time.sleep(30)delays the whole shutdown by that long. - Workers that only sleep. In the example, a worker notices
stoponly after its currentsleepends. For long waits, wait on the event with a deadline usingasyncio.timeoutaroundstop.wait(). Use that instead of sleeping. - Shield cleanup that must finish. If your
finallyblock awaits something slow, such as flushing a buffer, a second cancellation can interrupt it. Wrap that await inasyncio.shieldonly when finishing it matters more than meeting the deadline. - Pick the drain timeout from the platform. If Kubernetes allows 30 seconds, a 25-second drain leaves room for the final cleanup. A drain longer than the grace period ends in
SIGKILL. - Handler registration needs a running loop. Call
add_signal_handlerinside a coroutine, as in the examples. Calling it beforeasyncio.runfails because no loop is running yet.
Exercise
A worker catches CancelledError with except asyncio.CancelledError: print("stopping") and does not re-raise. The program receives SIGTERM, and main cancels the TaskGroup. What goes wrong?
Show answer
The worker swallows the cancellation, so it appears to finish normally and the task is not marked as cancelled. Code that depends on cancellation (the TaskGroup, an asyncio.timeout block, or the caller awaiting the task) no longer sees it. The worker may also continue past the point where it should have stopped. The fix is to do the cleanup and then re-raise CancelledError, or use try/finally and let it propagate.
Exercise
Why does the full example set the stop event from a done callback on the runner task, and what happens in the example if you remove that line and one worker raises an exception?
Show answer
The callback makes main wake up whenever the runner finishes for any reason. Without it, if a worker raises, the TaskGroup cancels the other workers and the runner ends with an ExceptionGroup. Main is still blocked on stop.wait(), and no signal arrives, so the program hangs and the error is never reported.