Menu

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

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

DEV Community: django·Jack Ma·about 18 hours ago
#deHNEnde
#devtodjango#devto#dev#uvicorn#lifespan
Long article (941 words) — no AI summary yet.
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.