Python / Uvicorn Fundamentals Interview Questions
What is the ASGI lifespan protocol and how does Uvicorn support it?
The ASGI lifespan protocol provides startup and shutdown events for an ASGI application, allowing it to initialise resources (database connections, caches, background tasks) before serving requests and clean them up on shutdown.
# FastAPI lifespan example (modern approach) from contextlib import asynccontextmanager from fastapi import FastAPI @asynccontextmanager async def lifespan(app: FastAPI): # Startup: runs before the server begins accepting requests print("Starting up...") app.state.db = await connect_to_database() yield # server is running here # Shutdown: runs after the server stops accepting requests print("Shutting down...") await app.state.db.close() app = FastAPI(lifespan=lifespan) # Pure ASGI lifespan implementation async def app(scope, receive, send): if scope["type"] == "lifespan": while True: message = await receive() if message["type"] == "lifespan.startup": # do startup work await send({"type": "lifespan.startup.complete"}) elif message["type"] == "lifespan.shutdown": # do cleanup await send({"type": "lifespan.shutdown.complete"}) return # ... HTTP handling
| --lifespan value | Behaviour |
|---|---|
| auto (default) | Enable lifespan if the application supports it; ignore if not |
| on | Always enable lifespan - fails at startup if the app does not support it |
| off | Never run lifespan events - useful for testing or apps that don't need it |
The lifespan protocol is especially important for managing async resources like database connection pools (asyncpg, motor), which must be created inside an async context and properly closed to avoid connection leaks.
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...
