Full answer
Replace the deprecated @app.on_event("startup") handlers with lifespan:
class State(TypedDict):
http: httpx.AsyncClient
tasks: set[asyncio.Task]
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[State]:
async with httpx.AsyncClient(timeout=5) as client:
tasks: set[asyncio.Task] = set()
yield {"http": client, "tasks": tasks}
await asyncio.gather(*tasks, return_exceptions=True) # drain background work- Everything before
yieldis startup; everything after is shutdown. Because of theasync with, the client is closed even when startup later fails or the server is interrupted. - The yielded dict becomes
request.statefor every request (request.state.http), and alsoscope["state"]. Type hints: annotate withRequestand a typed accessor, or a small dependencydef get_http(request: Request) -> httpx.AsyncClient: return request.state.http. This avoids module-level globals that complicate testing and multi-app processes. - Tests:
with TestClient(app) as client:runs lifespan; without the context manager lifespan does not run. Override the dependency to inject fakes. - With multiple workers each process runs its own lifespan, so each opens its own pool: size pools per process.
Graceful shutdown sequence (Uvicorn/Gunicorn):
- SIGTERM received: the server stops accepting new connections.
- In-flight requests continue until they finish or
--timeout-graceful-shutdownexpires (Uvicorn) orgraceful_timeout(Gunicorn). - The lifespan shutdown phase runs: cancel or await tracked background tasks, flush buffers (metrics, logs), close pools and clients.
- The process exits; the orchestrator's termination grace period must be longer than all of these timers, or it sends SIGKILL and cuts them short.
Also: keep shutdown work bounded (use asyncio.wait_for), mark the readiness probe unhealthy first, do not start new long tasks during shutdown, and handle CancelledError in long-running tasks so they clean up. Exceptions in startup abort the app start, which is what you want when the database is unreachable.
import asyncio
from contextlib import asynccontextmanager
from typing import AsyncIterator, TypedDict
import httpx
from fastapi import Depends, FastAPI, Request
from fastapi.testclient import TestClient
log = []
class State(TypedDict):
http: httpx.AsyncClient
tasks: set[asyncio.Task]
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[State]:
log.append("startup: open client")
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda r: httpx.Response(200, json={"ok": True}))) as client:
tasks: set[asyncio.Task] = set()
yield {"http": client, "tasks": tasks}
log.append(f"shutdown: draining {len(tasks)} task(s)")
await asyncio.gather(*tasks, return_exceptions=True)
log.append("shutdown: tasks drained")
log.append(f"shutdown: client closed={client.is_closed}")
app = FastAPI(lifespan=lifespan)
def get_http(request: Request) -> httpx.AsyncClient:
return request.state.http # one place that knows where the resource lives
async def flush_metrics():
await asyncio.sleep(0.01)
log.append("background flush finished")
@app.get("/ping")
async def ping(request: Request, http: httpx.AsyncClient = Depends(get_http)):
reply = await http.get("https://upstream.example/health")
task = asyncio.create_task(flush_metrics())
request.state.tasks.add(task)
task.add_done_callback(request.state.tasks.discard)
return reply.json()
with TestClient(app) as client: # the with-block runs lifespan
print(client.get("/ping").json())
print("\n".join(log))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install httpx`; a mock transport replaces the real network. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'ok': True} startup: open client shutdown: draining 1 task(s) background flush finished shutdown: tasks drained shutdown: client closed=True
Key points
- lifespan replaces on_event; before yield is startup, after is shutdown
- The yielded state dict is available as request.state
- Expose resources through dependencies, not globals, for testability
- Graceful shutdown: stop accepting, drain, cleanup, exit
- Termination grace period must exceed server and lifespan timeouts
Common mistakes
- Using deprecated on_event handlers in new code
- Module-level globals for clients and pools
- Forgetting the with-block in TestClient so lifespan never runs
- Untracked background tasks that get killed at shutdown
- Pool sizes not adjusted per worker process
Follow-ups
- How do Uvicorn and Gunicorn graceful timeouts differ?
- How would you share state between multiple lifespans?
- How does the readiness probe fit in?
Tips
- Show the lifespan code
- List shutdown steps
- Mention TestClient context manager