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
- How does dependency injection with `Depends` work in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- When should an endpoint be `async def` versus plain `def` in FastAPI?