Performance: Database session management
This affects backend response time and frontend loading speed by controlling how database connections are opened, reused, and closed during API requests.
Jump into concepts and practice - no test required
from fastapi import Depends from sqlalchemy.orm import Session # Use connection pooling configured in SessionLocal def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get("/items/") def read_items(db: Session = Depends(get_db)): return db.query(Item).all()
def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get("/items/") def read_items(db: Session = Depends(get_db)): return db.query(Item).all()
| Pattern | DB Connections | Latency Impact | Concurrency | Verdict |
|---|---|---|---|---|
| New session per request without pooling | Creates new connection each time | High latency (10-50ms extra) | Poor concurrency due to overhead | [X] Bad |
| Global session reused across requests | Single connection reused | Low latency but risk of stale data | Blocks concurrent requests | [X] Bad |
| Scoped session with connection pooling | Reuses pooled connections | Low latency (~5-10ms overhead) | Good concurrency and fresh data | [OK] Good |
get_db function in FastAPI when working with databases?get_dbget_db function is designed to open a database session when a request starts and close it when the request ends.Depends?Depends to inject dependencies like database sessions into route functions.Session and assign it Depends(get_db) to call the dependency function.from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
app = FastAPI()
def get_db():
db = Session()
try:
yield db
finally:
db.close()
@app.get('/items')
def read_items(db: Session = Depends(get_db)):
items = db.query(Item).all()
return itemsget_db function creates a session, yields it for use, then closes it safely after the request.Item records and returns them as a list.def get_db():
db = Session()
yield db
db.close()
@app.post('/add')
def add_item(item: Item, db: Session = Depends(get_db)):
db.add(item)
db.commit()db.close() is called after yield without a try-finally block, so if an exception happens, the session may never close.get_db implementations best achieves this?