Application lifespan and startup/shutdown events

Difficulty: Intermediate

Question

How do you run code on application startup and shutdown in FastAPI?

Answer

FastAPI uses a `lifespan` context manager (recommended since FastAPI 0.93+) to run code at startup and shutdown. The older `@app.on_event('startup')` / `@app.on_event('shutdown')` decorators are deprecated.

Use lifespan for: - Initializing DB connections or connection pools - Loading ML models into memory - Creating background worker threads - Connecting to external services (Redis, Kafka)

Code before `yield` runs on startup; code after `yield` runs on shutdown.

Code examples

Lifespan context manager

from contextlib import asynccontextmanager
from fastapi import FastAPI
import asyncpg

db_pool = None

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    global db_pool
    db_pool = await asyncpg.create_pool("postgresql://localhost/mydb")
    print("Database pool created")
    
    yield  # App runs here
    
    # Shutdown
    await db_pool.close()
    print("Database pool closed")

app = FastAPI(lifespan=lifespan)

@app.get("/health")
async def health():
    return {"status": "ok", "db_pool": db_pool is not None}

Key points

Concepts covered

lifespan, startup, shutdown, context manager, app state