Chapter 30: Application Startup, Lifespan, and Hosting
ASP.NET Core has host startup, dependency registration, and app lifetime events. FastAPI uses lifespan events for startup and shutdown.
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.settings = Settings()
app.state.http_client = httpx.AsyncClient(timeout=5)
yield
await app.state.http_client.aclose()
app = FastAPI(lifespan=lifespan)
Use lifespan for:
- Creating shared clients.
- Verifying critical configuration.
- Connecting to telemetry.
- Warming caches when necessary.
- Closing resources cleanly.
Do not do slow, fragile work in startup unless the app truly cannot serve without it. For migrations, prefer deployment steps over app startup migrations in most production systems.