0
0
FastAPIframework~8 mins

Async database queries in FastAPI - Performance & Optimization

Choose your learning style9 modes available
Performance: Async database queries
HIGH IMPACT
This concept affects how quickly the server can respond to requests by not blocking while waiting for database results.
Fetching data from a database in a web API endpoint
FastAPI
from fastapi import FastAPI
from databases import Database

app = FastAPI()
database = Database('sqlite:///test.db')

@app.on_event('startup')
async def startup():
    await database.connect()

@app.on_event('shutdown')
async def shutdown():
    await database.disconnect()

@app.get('/items')
async def read_items():
    query = 'SELECT * FROM items'
    items = await database.fetch_all(query)  # async non-blocking call
    return items
The async call does not block the event loop, allowing the server to handle other requests while waiting for the database.
📈 Performance GainNon-blocking query improves concurrency and reduces request latency under load
Fetching data from a database in a web API endpoint
FastAPI
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()  # synchronous blocking call
    return items
The synchronous database call blocks the server thread until the query finishes, reducing concurrency and increasing response time under load.
📉 Performance CostBlocks event loop during query, increasing response latency and reducing throughput
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous DB queryN/A (server-side)N/AN/A[X] Bad
Async DB queryN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Async database queries affect the server-side response time, which impacts how quickly the browser receives data to render. The browser rendering pipeline starts only after the server sends the response.
Server Processing
Network Transfer
Browser Rendering
⚠️ BottleneckServer Processing (waiting for database response)
Core Web Vital Affected
INP
This concept affects how quickly the server can respond to requests by not blocking while waiting for database results.
Optimization Tips
1Always use async database drivers and queries in async FastAPI endpoints.
2Avoid blocking calls inside async functions to keep the event loop free.
3Monitor server response times in DevTools Network tab to detect blocking.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using async database queries in FastAPI?
AThey prevent blocking the server event loop, improving concurrency.
BThey reduce the size of the database.
CThey automatically cache query results in the browser.
DThey increase the number of database connections.
DevTools: Network
How to check: Open DevTools, go to the Network tab, reload the page, and inspect the timing of the API request to see server response time.
What to look for: Look for long waiting (TTFB) times indicating slow server response due to blocking database calls.