Sitemap

Member-only story

Python AnyIO + AsyncResource: Cancellation-Safe Startup/Shutdown Hooks for APIs

Build API lifecycle hooks that don’t panic when a deploy rolls through, a client disconnects, or your server sends a cancellation signal. Your startup becomes boring. Your shutdown becomes trustworthy.

5 min readJan 5, 2026

--

Press enter or click to view image in full size

The first time I hit this bug, it didn’t look like a bug.

Requests were fine. Metrics were fine. Then, during a routine redeploy, our API left behind a handful of “zombie” connections and a background consumer that sometimes kept running just long enough to double-process messages. Not always. Just enough to be spooky.

If you’ve ever tried to make startup/shutdown hooks “clean,” you already know the trap: shutdown is where cancellation goes to party.

And cancellation does not care about your finally block.

The real problem: shutdown happens inside a cancellation storm

Modern async runtimes cancel tasks aggressively:

  • A server is stopping and cancels the main task.
  • The framework starts teardown.
  • Your teardown code tries to await (close DB…

--

--

Bytecraft
Bytecraft

Written by Bytecraft

I write about Python, DuckDB, FastAPI, TypeScript & n8n. Deep dives into performance, local analytics, and tiny tools that save hours.