0
0
FastAPIframework~8 mins

Database session management in FastAPI - Performance & Optimization

Choose your learning style9 modes available
Performance: Database session management
HIGH IMPACT
This affects backend response time and frontend loading speed by controlling how database connections are opened, reused, and closed during API requests.
Managing database connections per API request
FastAPI
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()
Using connection pooling inside SessionLocal reuses existing connections, reducing overhead per request.
📈 Performance Gainreduces latency by 30-40ms per request, improving LCP
Managing database connections per API request
FastAPI
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()
Creating and closing a new database session for every single request causes overhead and delays, especially under high load.
📉 Performance Costadds 10-50ms latency per request due to connection setup and teardown
Performance Comparison
PatternDB ConnectionsLatency ImpactConcurrencyVerdict
New session per request without poolingCreates new connection each timeHigh latency (10-50ms extra)Poor concurrency due to overhead[X] Bad
Global session reused across requestsSingle connection reusedLow latency but risk of stale dataBlocks concurrent requests[X] Bad
Scoped session with connection poolingReuses pooled connectionsLow latency (~5-10ms overhead)Good concurrency and fresh data[OK] Good
Rendering Pipeline
Database session management impacts the backend response time, which affects when the browser receives data to render the page.
Backend Processing
Network Transfer
Browser Rendering
⚠️ BottleneckBackend Processing (database query latency)
Core Web Vital Affected
LCP
This affects backend response time and frontend loading speed by controlling how database connections are opened, reused, and closed during API requests.
Optimization Tips
1Always use connection pooling to reuse database connections.
2Create and close database sessions scoped to each request.
3Avoid global or long-lived database sessions to prevent blocking.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using connection pooling in FastAPI database sessions?
AIt caches query results on the client side.
BIt reduces the number of new database connections created per request.
CIt eliminates the need for database sessions entirely.
DIt delays closing database connections until server shutdown.
DevTools: Network
How to check: Open DevTools > Network tab, reload the page, and check the Time and Waiting (TTFB) columns for API calls.
What to look for: Look for long server response times indicating slow database queries or connection overhead.