FastAPI interview question · Most asked

How do you run startup and shutdown logic in FastAPI?

Summary

Use the lifespan parameter with an async context manager: code before yield runs at startup (create DB pools, HTTP clients, load ML models) and code after runs at shutdown.

Longer Answer

The older @app.on_event("startup") handlers are deprecated. Lifespan can yield a state dict, available as request.state (Starlette 0.26+), or store objects on app.state. With multiple Uvicorn workers, lifespan runs once per worker process.

Code Example

from contextlib import asynccontextmanager
import httpx

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.http = httpx.AsyncClient(timeout=10)
    app.state.model = load_model("model.bin")
    yield
    await app.state.http.aclose()

app = FastAPI(lifespan=lifespan)

Key Points

  • lifespan= async context manager
  • Replaces deprecated on_event
  • Runs per worker process
  • Good place for shared clients/pools

More most-asked FastAPI questions

← All FastAPI questions