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

  • Store shared resources on `app.state` to make them accessible in routes
  • The old `@app.on_event` API still works but is deprecated
  • Lifespan is also supported by TestClient for integration tests

Common follow-up questions

  • How do you access app state from inside a dependency?
  • What happens if lifespan startup code raises an exception?

Interview tips

  • Use the lifespan pattern when asked about initialization - it's the modern FastAPI way

Concepts covered

lifespan, startup, shutdown, context manager, app state

More FastAPI Interview questions