Python / FastAPI 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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
