0
0
FastAPIframework~8 mins

Global dependencies in FastAPI - Performance & Optimization

Choose your learning style9 modes available
Performance: Global dependencies
MEDIUM IMPACT
Global dependencies affect the server response time and resource usage by running shared logic once per request or application lifecycle.
Sharing common logic or resources across multiple routes
FastAPI
from fastapi import Depends, FastAPI

async def get_db():
    db = create_db_connection()
    try:
        yield db
    finally:
        db.close()

app = FastAPI(dependencies=[Depends(get_db)])

@app.get("/items/")
async def read_items(db=Depends()):
    return "Use shared db connection"

@app.get("/users/")
async def read_users(db=Depends()):
    return "Use shared db connection"
The database connection is created once per request globally and reused in all routes, reducing overhead.
📈 Performance Gainsingle resource initialization per request, lowering latency
Sharing common logic or resources across multiple routes
FastAPI
from fastapi import Depends, FastAPI

def get_db():
    db = create_db_connection()
    try:
        yield db
    finally:
        db.close()

app = FastAPI()

@app.get("/items/")
async def read_items(db=Depends(get_db)):
    return db.query_items()

@app.get("/users/")
async def read_users(db=Depends(get_db)):
    return db.query_users()
The database connection is created and closed separately for each route call, causing repeated overhead.
📉 Performance Costtriggers multiple resource initializations per request, increasing latency
Performance Comparison
PatternResource InitializationRequest LatencyReusabilityVerdict
Per-route dependencyMultiple times per requestHigher latencyLow[X] Bad
Global dependencyOnce per requestLower latencyHigh[OK] Good
Rendering Pipeline
Global dependencies run before route handlers, preparing shared resources once per request, reducing repeated setup work.
Request Handling
Dependency Injection
⚠️ BottleneckRepeated resource initialization in each route handler
Optimization Tips
1Declare shared dependencies globally on the FastAPI app to reduce repeated setup.
2Avoid creating expensive resources separately in each route handler.
3Use global dependencies to improve request handling speed and resource reuse.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using global dependencies in FastAPI?
AThey increase bundle size but improve caching
BThey reduce client-side rendering time
CShared setup runs once per request, reducing repeated overhead
DThey eliminate the need for database connections
DevTools: Network
How to check: Open DevTools, go to Network tab, make repeated requests to different routes, and compare response times.
What to look for: Look for consistent and lower response times when using global dependencies versus per-route dependencies.