← Back to FastAPI map
FastAPI · Architecture

Lifecycle

Open shared resources at startup and close them at shutdown.

startup

Overview

Some resources should live as long as the application, not a single request: database pools, Redis clients, HTTP clients, machine-learning models. The lifespan function runs once when the server starts - before any request is accepted - and resumes after the server stops taking requests, so you can open these resources once and close them cleanly.

Key concepts

asynccontextmanager
Everything before yield is startup; everything after yield is shutdown.
app.state
A place to keep shared resources, reachable from any route as request.app.state.
Per worker
Each Uvicorn or Gunicorn worker process runs its own lifespan and holds its own copies of these resources.
on_event
The older @app.on_event("startup") and ("shutdown") decorators, deprecated in favour of lifespan.

Best practices

  • Create expensive clients once in lifespan instead of on every request.
  • Close everything you opened on shutdown, so deploys do not leak connections.
  • Fail fast: if a required resource cannot connect at startup, let the app crash rather than start and serve errors.

Startup and shutdown

lifespan - modern approach

Modern
from contextlib import asynccontextmanager from fastapi import FastAPI, Request @asynccontextmanager async def lifespan(app: FastAPI): # -- STARTUP --------------------- app.state.db_pool = await create_db_pool() app.state.redis = await create_redis() print("Application ready") yield # app runs here # -- SHUTDOWN -------------------- await app.state.db_pool.close() await app.state.redis.close() print("Cleanup complete") app = FastAPI(lifespan=lifespan) # Access in routes via request.app.state @app.get("/items") async def items(request: Request): db = request.app.state.db_pool return await db.fetch_all("SELECT * FROM items")

Watch out: The deprecated @app.on_event("startup") still works, but lifespan is the modern pattern - it also runs correctly under TestClient when used as a context manager.

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...