Concept Flow - Connection lifecycle management
Start Request
Open Connection
Process Request
Close Connection
End Request
This flow shows how FastAPI opens a connection at the start of a request, processes it, then closes the connection at the end.
from fastapi import FastAPI, Depends from sqlalchemy.orm import Session app = FastAPI() def get_db(): db = Session() try: yield db finally: db.close()
| Step | Action | Connection State | Yielded Value | Notes |
|---|---|---|---|---|
| 1 | Request received | No connection | None | Start handling request |
| 2 | Call get_db() | Open connection | db session object | Connection opened and yielded |
| 3 | Process endpoint using db | Connection open | db session object | Use connection for queries |
| 4 | Request processing done | Connection open | db session object | Ready to close connection |
| 5 | Exit get_db() generator | Connection closed | None | Connection closed in finally block |
| 6 | Response sent | No connection | None | Request fully handled |
| Variable | Start | After Step 2 | After Step 5 | Final |
|---|---|---|---|---|
| db | None | Session object (open) | None (closed) | None (closed) |
FastAPI connection lifecycle: - Open connection before request (yield in dependency) - Use connection during request - Close connection after request (finally block) - Ensures resources free even on errors - Use generator dependencies for clean lifecycle
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