Performance: Connection lifecycle management
This concept affects how efficiently the server handles client connections, impacting request latency and server resource usage.
from fastapi import FastAPI from fastapi import Depends app = FastAPI() async def get_db(): db = open_db_connection() try: yield db finally: db.close() @app.get("/") async def read_root(db=Depends(get_db)): data = db.query("SELECT * FROM table") return data
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): # Opening a new database connection per request without closing db = open_db_connection() data = db.query("SELECT * FROM table") return data
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Opening new DB connection per request without closing | N/A | N/A | N/A | [X] Bad |
| Using dependency injection with connection close in finally block | N/A | N/A | N/A | [OK] Good |
| WebSocket without disconnect handling | N/A | N/A | N/A | [X] Bad |
| WebSocket with disconnect exception handling | N/A | N/A | N/A | [OK] Good |
yield in FastAPI dependencies for connection lifecycle management?yield in dependenciesyield is used in dependencies to create a setup before the request and a cleanup after the request finishes.yield?yield to provide the connection and then closes it after the request.async def get_db():
db = await connect_db()
try:
yield db
finally:
await db.disconnect()
What happens when a request finishes using this dependency?yield pauses the function to provide db during the request, then finally runs cleanup after the request.await db.disconnect() runs after the request finishes, closing the connection asynchronously.@app.on_event("startup")
@asynccontextmanager
async def startup():
await connect_to_service()
yield
await disconnect_from_service()@app.on_event("startup") expects a normal async function, not an async context manager.@asynccontextmanager with @app.on_event on the same function is invalid because FastAPI expects a coroutine, not a context manager.@app.on_event("startup") and @app.on_event("shutdown") to open and close the pool directly is the simplest and recommended way.@asynccontextmanager to create a context manager function and call it in @app.on_event("startup") and @app.on_event("shutdown") misuses @asynccontextmanager with events. Use a dependency with yield to open and close the pool per request opens/closes per request, which is inefficient. Open the pool globally outside FastAPI and never close it never closes, risking resource leaks.Pass the test and this pattern moves unknown