Jump to solution
Verify

The Fix

Upgrade to version 0.22.0 or later.

Based on closed Kludex/uvicorn issue #451 · PR/commit linked

Production note: Most teams hit this during upgrades or environment changes. Roll out with a canary and smoke critical endpoints (health, OpenAPI/docs) before 100%.

Jump to Verify Open PR/Commit
@@ -104,6 +104,9 @@ Options: is received within this timeout. [default: 5] + --timeout-graceful-shutdown INTEGER + Maximum number of seconds to wait for + graceful shutdown.
repro.py
import asyncio from datetime import datetime import uvicorn class App: def __call__(self, scope): if scope['type'] == 'lifespan': return self.lifespan elif scope['type'] == 'http': return self.http async def lifespan(self, receive, send): """Handle lifespan messages""" message = await receive() assert message["type"] == "lifespan.startup" print('startup') await send({"type": "lifespan.startup.complete"}) message = await receive() assert message["type"] == "lifespan.shutdown" print('shutdown') await send({"type": "lifespan.shutdown.complete"}) async def http(self, receive, send): """Handle http messages""" message = await receive() assert message['type'] == 'http.request' while message['more_body']: message = await receive() await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ (b'cache-control', b'no-cache'), (b'content-type', b'text/event-stream'), (b'connection', b'keep-alive') ] }) while True: await send({ 'type': 'http.response.body', 'body': f'data: {datetime.now().isoformat()}\n\n'.encode('utf-8'), 'more_body': True }) try: # Check the receive, timing out after a second to send more data receive_task = asyncio.create_task(receive()) await asyncio.wait_for(receive_task, 1) message = receive_task.result() if message['type'] == 'http.disconnect': print('disconnect') break except asyncio.TimeoutError: print('timeout') receive_task.cancel() if __name__ == '__main__': uvicorn.run(App(), port=9009)
verify
Re-run the minimal reproduction on your broken version, then apply the fix and re-run.
fix.md
Option A — Upgrade to fixed release\nUpgrade to version 0.22.0 or later.\nWhen NOT to use: Do not use this fix if the application requires immediate shutdown without waiting for ongoing requests.\n\n

Why This Fix Works in Production

  • Trigger: assert message["type"] == "lifespan.startup"
  • Mechanism: The server does not handle graceful shutdown properly when streaming responses are active
  • Why the fix works: Added a `--timeout-graceful-shutdown` parameter to manage graceful shutdowns, addressing issue #451. (first fixed release: 0.22.0).
Production impact:
  • If left unfixed, the same config can fail only in production (env differences), causing startup failures or partial feature outages.

Why This Breaks in Prod

  • The server does not handle graceful shutdown properly when streaming responses are active
  • Production symptom (often without a traceback): assert message["type"] == "lifespan.startup"

Proof / Evidence

  • GitHub issue: #451
  • Fix PR: https://github.com/kludex/uvicorn/pull/1950
  • First fixed release: 0.22.0
  • Reproduced locally: No (not executed)
  • Last verified: 2026-02-09
  • Confidence: 0.85
  • Did this fix it?: Yes (upstream fix exists)
  • Own content ratio: 0.41

Discussion

High-signal excerpts from the issue thread (symptoms, repros, edge-cases).

“This is the output I'm getting when I make the http request: Without making the http request I get:”
@rob-blackbourn · 2019-10-16 · source
“Ok sorry then so it's a little bit different in your case, you loop indefinitely a few lines above me and never reach lifespan shutdown…”
@euri10 · 2019-10-16 · source
“PR welcome to add a --graceful-timeout. The default value would be None, which means that we don't timeout. The flag will cancel the background tasks,…”
@Kludex · 2022-12-30 · source
“I didn't try your app, will definitely do as I'm also having issues on shutdown on one of my app and I failed at finding…”
@euri10 · 2019-10-16 · source

Failure Signature (Search String)

  • assert message["type"] == "lifespan.startup"
  • assert message["type"] == "lifespan.shutdown"
Copy-friendly signature
signature.txt
Failure Signature ----------------- assert message["type"] == "lifespan.startup" assert message["type"] == "lifespan.shutdown"

Error Message

Signature-only (no traceback captured)
error.txt
Error Message ------------- assert message["type"] == "lifespan.startup" assert message["type"] == "lifespan.shutdown"

Minimal Reproduction

repro.py
import asyncio from datetime import datetime import uvicorn class App: def __call__(self, scope): if scope['type'] == 'lifespan': return self.lifespan elif scope['type'] == 'http': return self.http async def lifespan(self, receive, send): """Handle lifespan messages""" message = await receive() assert message["type"] == "lifespan.startup" print('startup') await send({"type": "lifespan.startup.complete"}) message = await receive() assert message["type"] == "lifespan.shutdown" print('shutdown') await send({"type": "lifespan.shutdown.complete"}) async def http(self, receive, send): """Handle http messages""" message = await receive() assert message['type'] == 'http.request' while message['more_body']: message = await receive() await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ (b'cache-control', b'no-cache'), (b'content-type', b'text/event-stream'), (b'connection', b'keep-alive') ] }) while True: await send({ 'type': 'http.response.body', 'body': f'data: {datetime.now().isoformat()}\n\n'.encode('utf-8'), 'more_body': True }) try: # Check the receive, timing out after a second to send more data receive_task = asyncio.create_task(receive()) await asyncio.wait_for(receive_task, 1) message = receive_task.result() if message['type'] == 'http.disconnect': print('disconnect') break except asyncio.TimeoutError: print('timeout') receive_task.cancel() if __name__ == '__main__': uvicorn.run(App(), port=9009)

What Broke

Shutdown events are not called, leading to potential resource leaks and unresponsive server behavior.

Why It Broke

The server does not handle graceful shutdown properly when streaming responses are active

Fix Options (Details)

Option A — Upgrade to fixed release Safe default (recommended)

Upgrade to version 0.22.0 or later.

When NOT to use: Do not use this fix if the application requires immediate shutdown without waiting for ongoing requests.

Use when you can deploy the upstream fix. It is usually lower-risk than long-lived workarounds.

Option D — Guard side-effects with OnceOnly Guardrail for side-effects

Mitigate duplicate external side-effects under retries/timeouts/agent loops by gating the operation before calling external systems.

  • Place OnceOnly between your code/agent and real side-effects (Stripe, emails, CRM, APIs).
  • Use a stable key per side-effect (e.g., customer_id + action + idempotency_key).
  • Fail-safe: configure fail-open vs fail-closed based on blast radius and spend risk.
Show example snippet (optional)
onceonly.py
from onceonly import OnceOnly import os once = OnceOnly(api_key=os.environ["ONCEONLY_API_KEY"], fail_open=True) # Stable idempotency key per real side-effect. # Use a request id / job id / webhook delivery id / Stripe event id, etc. event_id = "evt_..." # replace key = f"stripe:webhook:{event_id}" res = once.check_lock(key=key, ttl=3600) if res.duplicate: return {"status": "already_processed"} # Safe to execute the side-effect exactly once. handle_event(event_id)

See OnceOnly SDK

When NOT to use: Do not use this to hide logic bugs or data corruption. Use it to block duplicate external side-effects and enforce tool permissions/spend caps.

Fix reference: https://github.com/kludex/uvicorn/pull/1950

First fixed release: 0.22.0

Last verified: 2026-02-09. Validate in your environment.

Get updates

We publish verified fixes weekly. No spam.

Subscribe

When NOT to Use This Fix

  • Do not use this fix if the application requires immediate shutdown without waiting for ongoing requests.
  • Do not use this to hide logic bugs or data corruption. Use it to block duplicate external side-effects and enforce tool permissions/spend caps.

Verify Fix

verify
Re-run the minimal reproduction on your broken version, then apply the fix and re-run.

Did This Fix Work in Your Case?

Quick signal helps us prioritize which fixes to verify and improve.

Prevention

  • Make timeouts explicit and test them (unit + integration) to avoid silent behavior changes.
  • Instrument retries (attempt count + reason) and alert on spikes to catch dependency slowdowns.

Version Compatibility Table

VersionStatus
0.22.0 Fixed

Related Issues

No related fixes found.

Sources

We don’t republish the full GitHub discussion text. Use the links above for context.