0
0
FastAPIframework~8 mins

Async database with databases library in FastAPI - Performance & Optimization

Choose your learning style9 modes available
Performance: Async database with databases library
HIGH IMPACT
This affects how quickly the server can handle database queries without blocking other requests, improving responsiveness and throughput.
Handling database queries in a FastAPI app
FastAPI
import databases
import sqlalchemy
from fastapi import FastAPI

db = databases.Database('sqlite:///test.db')

app = FastAPI()

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

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

@app.get('/items')
async def read_items():
    query = 'SELECT * FROM items'
    results = await db.fetch_all(query)
    return results
Async calls free the event loop during database operations, allowing other requests to be processed concurrently.
📈 Performance GainNon-blocking queries improve throughput and reduce request latency
Handling database queries in a FastAPI app
FastAPI
import databases
import sqlalchemy
from fastapi import FastAPI

db = databases.Database('sqlite:///test.db')

app = FastAPI()

@app.get('/items')
def read_items():
    query = 'SELECT * FROM items'
    results = db.fetch_all(query)
    return results
Using synchronous database calls blocks the async event loop, causing delays in handling other requests.
📉 Performance CostBlocks event loop during query, increasing response time and reducing concurrency
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous DB calls in FastAPIN/AN/AN/A[X] Bad
Async DB calls with databases libraryN/AN/AN/A[OK] Good
Rendering Pipeline
Async database calls do not directly affect browser rendering but improve server response time, which reduces time to first byte and interaction delays.
Server Processing
Network Response
⚠️ BottleneckServer Processing when synchronous blocking occurs
Core Web Vital Affected
INP
This affects how quickly the server can handle database queries without blocking other requests, improving responsiveness and throughput.
Optimization Tips
1Always use async database calls in async frameworks to avoid blocking.
2Connect and disconnect the database asynchronously during app startup and shutdown.
3Avoid mixing synchronous DB calls inside async endpoints to keep event loop free.
Performance Quiz - 3 Questions
Test your performance knowledge
Why is using async database calls important in a FastAPI app?
AIt automatically caches all queries.
BIt reduces the size of the database.
CIt prevents blocking the event loop, improving concurrency and responsiveness.
DIt makes the database run faster internally.
DevTools: Network
How to check: Open DevTools, go to Network tab, make a request to the API endpoint, and observe the response time.
What to look for: Look for lower response times and no long blocking periods indicating server-side delays.