Bird
Raised Fist0
FastAPIframework~8 mins

Async database queries in FastAPI - Performance & Optimization

Choose your learning style10 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.

Practice

(1/5)
1. What is the main benefit of using async database queries in FastAPI?
easy
A. It removes the need for database connections.
B. It makes the database run faster internally.
C. The app can handle other tasks while waiting for the database response.
D. It automatically caches all database results.

Solution

  1. Step 1: Understand async behavior in FastAPI

    Async lets the app continue running other code instead of waiting for slow operations like database queries.
  2. Step 2: Identify the benefit of async database queries

    This means the app stays responsive and can handle more requests while waiting for the database.
  3. Final Answer:

    The app can handle other tasks while waiting for the database response. -> Option C
  4. Quick Check:

    Async = non-blocking tasks [OK]
Hint: Async means do other work while waiting [OK]
Common Mistakes:
  • Thinking async speeds up the database itself
  • Believing async caches results automatically
  • Assuming async removes database connections
2. Which of the following is the correct way to define an async function for a database query in FastAPI?
easy
A. async def get_data(): return await session.execute(query)
B. async def get_data(): return session.execute(query)
C. def get_data(): return await session.execute(query)
D. def get_data(): return session.execute(query)

Solution

  1. Step 1: Recognize async function syntax

    Async functions must be declared with async def to use await inside.
  2. Step 2: Match correct usage of await

    To wait for the database query, await must be used with the async session call.
  3. Final Answer:

    async def get_data(): return await session.execute(query) -> Option A
  4. Quick Check:

    Async function + await = correct syntax [OK]
Hint: Use async def with await inside async functions [OK]
Common Mistakes:
  • Missing async keyword but using await
  • Using await without async function
  • Calling async functions without await
3. Given this async function in FastAPI using SQLAlchemy async session:
async def fetch_users(session):
    result = await session.execute("SELECT name FROM users")
    users = result.scalars().all()
    return users

What will fetch_users return?
medium
A. A coroutine object that needs awaiting
B. A list of user names from the database
C. A SQLAlchemy Result object
D. An error because scalars() is not async

Solution

  1. Step 1: Understand await on session.execute

    The await waits for the query to finish and returns a Result object.
  2. Step 2: Use scalars().all() on Result

    Calling scalars().all() extracts all values from the first column as a list.
  3. Final Answer:

    A list of user names from the database -> Option B
  4. Quick Check:

    await + scalars().all() = list output [OK]
Hint: await session.execute returns Result; scalars().all() gives list [OK]
Common Mistakes:
  • Thinking fetch_users returns a coroutine, not awaited
  • Expecting a Result object instead of list
  • Assuming scalars() is async and causes error
4. Identify the error in this FastAPI async database query code:
async def get_items(session):
    result = session.execute("SELECT * FROM items")
    return await result.fetchall()
medium
A. Function should not be async
B. Cannot await fetchall() method
C. session.execute should not be async
D. Missing await before session.execute call

Solution

  1. Step 1: Check usage of async session.execute

    session.execute is an async method and must be awaited to get the Result.
  2. Step 2: Understand fetchall() usage

    fetchall() is called on the awaited Result; awaiting fetchall() is incorrect because it returns a list synchronously.
  3. Final Answer:

    Missing await before session.execute call -> Option D
  4. Quick Check:

    await session.execute needed before fetchall() [OK]
Hint: Always await async session.execute calls first [OK]
Common Mistakes:
  • Not awaiting session.execute causing coroutine error
  • Awaiting fetchall() which is not async
  • Confusing async with sync methods
5. You want to fetch all active users asynchronously and return their emails in FastAPI. Which code snippet correctly uses async database queries and filters results?
hard
A. async def get_active_emails(session): result = await session.execute("SELECT email FROM users WHERE active=1") return result.scalars().all()
B. def get_active_emails(session): result = session.execute("SELECT email FROM users WHERE active=1") return result.scalars().all()
C. async def get_active_emails(session): result = session.execute("SELECT email FROM users WHERE active=1") return await result.scalars().all()
D. async def get_active_emails(session): result = await session.execute("SELECT email FROM users") return [email for email in result.scalars().all() if email.active == 1]

Solution

  1. Step 1: Use async def and await session.execute

    The function must be async and await the async session.execute call with the correct SQL filter.
  2. Step 2: Extract emails with scalars().all()

    Calling scalars().all() on the awaited result returns a list of emails matching the filter.
  3. Final Answer:

    async def get_active_emails(session): result = await session.execute("SELECT email FROM users WHERE active=1") return result.scalars().all() -> Option A
  4. Quick Check:

    Async + await + filtered query = correct [OK]
Hint: Await session.execute with filter, then scalars().all() [OK]
Common Mistakes:
  • Using sync def with async calls
  • Not awaiting session.execute
  • Filtering results in Python instead of SQL
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard