Django under uvicorn: an atexit flush that runs on Ctrl+C but not on SIGTERM

2026-12-06来源 dev.toEnglish

I kept per-customer request counts in memory in a Django app and wrote them out with an atexit hook. Under uvicorn, stopping the server with Ctrl+C (SIGINT) wrote all 21 requests: 20 for key_a and one without a key. Stopping it with SIGTERM, the default stop signal for docker stop, wrote nothing. With a lifespan wrapper in asgi.py, both signals wrote all 21.

A Django forum post on API keys, rate limits and per-customer quotas in one middleware describes the same loss: under uvicorn, Django doesn't handle the ASGI lifespan shutdown, so counts that hadn't been sent were lost on every restart. The post adds that gunicorn doesn't need the fix. I wanted to see why Ctrl+C and SIGTERM behave differently under uvicorn.

The test app

One file, Django 6.1.4, Python 3.15. A middleware counts requests per X-API-Key in a dict, and flush() appends what it has to a log file with the process ID and the reason:

_counts, _lock = {}, threading.Lock() def flush(reason): with _lock: pending = dict(_counts) _counts.clear() with open(LOG, "a") as f: f.write(json.dumps({"pid": os.getpid(), "reason": reason, "counts": pending}) + "\n") if os.environ.get("FLUSH_ATEXIT"): atexit.register(flush, "atexit") class CountUsage: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) key = request.headers.get("X-API-Key", "") with _lock: _counts[key] = _counts.get(key, 0) + 1 return response 

In a real app, flush() would send the totals to your billing or metering service. Each run sends one request without a key while waiting for the server to start, then 20 with X-API-Key: key_a, then stops the server.

Results

uvicorn 0.55.0 and gunicorn 27.0.1, on macOS:

Server Flush hook Stopped with Written
uvicorn, 1 process atexit SIGINT (Ctrl+C) 21
uvicorn, 1 process atexit SIGTERM nothing
uvicorn, --workers 2 atexit SIGTERM nothing
uvicorn, 1 process lifespan wrapper SIGINT (Ctrl+C) 21
uvicorn, 1 process lifespan wrapper SIGTERM 21
uvicorn, --workers 2 lifespan wrapper SIGTERM 21, one line per worker
gunicorn sync, -w 2 (WSGI) atexit SIGTERM 21, one line per worker

With the plain Django ASGI app, uvicorn logs this at startup:

INFO: ASGI 'lifespan' protocol appears unsupported. 

On SIGTERM, it logs Shutting down and Finished server process, and the flush log stays empty.

Why atexit doesn't run

uvicorn installs its own signal handlers, shuts down gracefully, then puts the original handlers back and sends the same signal to itself again (signal.raise_signal in capture_signals() in uvicorn/server.py). The idea is that the process should end the way the signal would normally end it.

For SIGINT, Python's default handler raises KeyboardInterrupt. The uvicorn command catches it and exits, so atexit runs. For SIGTERM, the default action terminates the process. The shell reported exit code 143 (128 + 15), and the atexit hook never ran.

With --workers 2, each worker is a separate uvicorn server started with multiprocessing's spawn method. The parent passes SIGTERM on to the workers, each one stops the same way, and neither writes anything.

gunicorn's sync workers stop by exiting normally, so atexit ran in both of them.

The lifespan wrapper

Django's ASGI handler doesn't take part in lifespan, so the shutdown message has to be handled before Django sees the scope:

# asgi.py from django.core.asgi import get_asgi_application django_app = get_asgi_application() from myproject.usage import flush # import after Django is set up async def application(scope, receive, send): if scope["type"] == "lifespan": while True: message = await receive() if message["type"] == "lifespan.startup": await send({"type": "lifespan.startup.complete"}) elif message["type"] == "lifespan.shutdown": flush("lifespan") await send({"type": "lifespan.shutdown.complete"}) return else: await django_app(scope, receive, send) 

With the wrapper, the "appears unsupported" line at startup went away. On SIGTERM, uvicorn stopped taking new requests, logged Waiting for application shutdown., sent lifespan.shutdown to the wrapper, and only then sent the signal to itself again. In the two-worker run, each worker flushed its own counts.

Before you rely on it

Ctrl+C sends SIGINT, so testing in a terminal hides the problem. I reproduced the empty log with kill -TERM <pid>. If you deploy in Docker, check the stop signal your image sets, run docker stop on your own container, and look for the flush in the log.

The wrapper calls flush() on the event loop, so a slow network call there holds up the shutdown. Give it a short timeout. With the default timeout for Linux containers, docker stop sends SIGKILL if the container is still running after 10 seconds.

SIGKILL skips both hooks, and so does an out-of-memory kill. Flushing on a timer as well, say once a minute, keeps the backlog small, but anything counted since the last successful flush can still be lost.

Each worker and each container flushes its own totals. Add them up on the receiving side.

原文:https://www.a8q9.cn/en/article/django-under-uvicorn-an-atexit-flush-that-runs-on-ctrl-c-but-not-on-sigterm-0d5d34.html

相关文章