Sub topic 16
Graceful shutdown on signals
This chapter assumes you know asyncio.TaskGroup, Task.cancel(), and try/finally cleanup from the earlier chapters. It also assumes Python 3.11 or newer on Linux or macOS.
Why shutdown needs a plan
A service stops because it receives a signal. SIGINT comes from Ctrl+C, and SIGTERM comes from a process manager such as systemd, Docker, or Kubernetes. Python's default handling kills the program at an arbitrary point. Open connections are dropped and buffered data is lost.
Graceful shutdown turns the signal into ordinary cancellation. The signal sets a flag, the main task cancels the workers, and each worker's finally block releases its resources.
Turning a signal into an event
loop.add_signal_handler(sig, callback) runs a plain callback inside the event loop. The callback should do almost nothing, so have it set an asyncio.Event. The main coroutine waits on that event.
import asyncio
import os
import signal
async def worker(name):
try:
while True:
print(f"{name}: working")
await asyncio.sleep(0.5)
finally:
print(f"{name}: releasing resources")
async def main():
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, stop.set)
# Demo only: send ourselves SIGTERM after 1.2 seconds.
loop.call_later(1.2, os.kill, os.getpid(), signal.SIGTERM)
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(worker(n)) for n in ("a", "b")]
await stop.wait()
print("signal received, shutting down")
for t in tasks:
t.cancel()
print("all workers stopped")
asyncio.run(main())Cancelling the child tasks does not make the group fail. The group ignores CancelledError from its children, waits for each finally block to finish, and then lets main continue. The last line prints only after every worker has cleaned up.
Bounding the shutdown time
A worker can hang during cleanup, and a process manager will eventually send SIGKILL. Put a deadline on the cancel-and-wait step so you decide what happens first. Replace the cancel loop with this:
async with asyncio.timeout(5):
for t in tasks:
t.cancel()
await asyncio.gather(*tasks, return_exceptions=True)If cleanup takes longer than five seconds, TimeoutError is raised. Catch it outside the group, log which resources leaked, and exit with a non-zero status.
What to watch for
add_signal_handleris not available on Windows. There,signal.signalis the fallback, but it needsloop.call_soon_threadsafeto touch asyncio objects.- Never put
awaitcalls or long work in the signal callback. Set an event or calltask.cancel()and return. - If a worker catches
CancelledError, it must re-raise it. Otherwise the shutdown stalls. - Since 3.11,
asyncio.runalready turns the first Ctrl+C into cancellation of the main task. A customSIGINThandler replaces that behavior, so test both signals.
Exercise
In the example, why does "all workers stopped" print only after both "releasing resources" lines, even though main calls cancel() on the tasks and keeps going?
Show answer
Leaving the async with asyncio.TaskGroup() block waits for every child task to finish. Cancelled workers still run their finally blocks before they finish, so the group does not exit, and the final print does not run, until both have cleaned up.