Python / FastAPI Basics Interview Questions
How do you run startup and shutdown logic in FastAPI using lifespan?
FastAPI supports a lifespan context manager (introduced in FastAPI 0.93, replaces the deprecated on_event decorators) for running code at application startup and shutdown — e.g. creating DB connection pools, loading ML models, or connecting to message brokers.
from contextlib import asynccontextmanager from fastapi import FastAPI import asyncpg # Module-level storage for shared resources db_pool: asyncpg.Pool | None = None @asynccontextmanager async def lifespan(app: FastAPI): # --- STARTUP: runs before the app starts serving requests --- global db_pool db_pool = await asyncpg.create_pool( "postgresql://user:pass@localhost/db", min_size=5, max_size=20, ) print("Database pool created") yield # app runs here # --- SHUTDOWN: runs after last request is processed --- await db_pool.close() print("Database pool closed") app = FastAPI(lifespan=lifespan) @app.get("/users") async def list_users(): async with db_pool.acquire() as conn: rows = await conn.fetch("SELECT id, username FROM users") return [dict(r) for r in rows]
Common startup tasks: create DB connection pools, initialise Redis clients, load ML models into memory, connect to message brokers (Kafka, RabbitMQ).
Common shutdown tasks: close DB pools, flush metrics, close broker connections, gracefully drain request queues.
More Related questions...