3 Hours

15. Async Programming & Concurrency

Concurrency

FastAPI is built on asynchronous programming principles. Understanding async/await is crucial for building high-performance APIs. This module explains how async works, when to use it, and common pitfalls to avoid. To test these examples, save to a .py file and run python filename.py.

What is Async/Await?

Async/await is a syntax for writing concurrent code that appears synchronous. When you mark a function as async, it returns a coroutine object instead of running immediately. The await keyword pauses the function execution until the awaited operation completes, without blocking the entire thread.

Python 3
import asyncio
import time

# Synchronous (blocking)
def sync_task():
    time.sleep(2)
    return "Sync done"

# Asynchronous (non-blocking)
async def async_task():
    await asyncio.sleep(2)
    return "Async done"

async def main():
    start = time.time()
    results = await asyncio.gather(async_task(), async_task(), async_task())
    elapsed = time.time() - start
    print(f"Three async tasks completed in {elapsed:.1f} seconds")
    print(results)

# asyncio.run(main())
Local Testing: Uncomment asyncio.run(main()) to see three async tasks run concurrently in ~2 seconds instead of ~6 seconds.

Async Endpoints in FastAPI

FastAPI supports both sync and async endpoints. Async endpoints are better for I/O-bound operations.

Python 3
from fastapi import FastAPI
import asyncio

app = FastAPI()

# Synchronous endpoint (fine for CPU work)
@app.get("/sync")
def sync_endpoint():
    return {"message": "This runs synchronously"}

# Asynchronous endpoint (better for I/O)
@app.get("/async")
async def async_endpoint():
    await asyncio.sleep(0.1)
    return {"message": "This runs asynchronously"}

# Mixing sync and async
@app.get("/mixed")
async def mixed_endpoint():
    data = await fetch_from_db()
    result = await asyncio.to_thread(cpu_intensive_work, data)
    return {"result": result}

CPU-Bound vs I/O-Bound Operations

FastAPI Concurrency: async def vs def How FastAPI intelligently dispatches async coroutines vs blocking synchronous functions async def endpoint() — ASYNC EVENT LOOP Runs directly on the main asyncio loop await db.fetch() yields control instantly ✓ Handles 10,000+ concurrent I/O connections ✗ Do NOT call time.sleep() or blocking code here! def endpoint() — ANYIO THREADPOOL FastAPI automatically offloads to separate thread Safe for legacy blocking libraries (requests, time.sleep) ✓ Prevents freezing the entire server event loop Limited by thread pool worker size (~40 threads)

Understanding the difference is critical for effective async usage.

Python 3
# I/O-BOUND (Good for async)
# Waiting for network, database, file system
import aiohttp

async def fetch_data():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://api.example.com/data") as response:
            return await response.json()

# CPU-BOUND (Does NOT benefit from async)
# Heavy calculations, image processing
def process_data(data: list) -> list:
    result = []
    for item in data:
        result.append(item * 2)
    return result

# Run CPU-bound code without blocking
@app.get("/process")
async def process_endpoint(data: list):
    result = await asyncio.to_thread(process_data, data)
    return {"result": result}
CPU-bound code does NOT benefit from async! Heavy calculations still block the event loop. Use asyncio.to_thread() to run them in a separate thread.

Concurrent Execution with asyncio.gather

Run multiple async operations concurrently to reduce total execution time.

Python 3
async def fetch_user(user_id: int):
    await asyncio.sleep(1)
    return {"id": user_id, "name": f"User{user_id}"}

# Sequential (slow) - takes 3 seconds
async def sequential():
    result1 = await fetch_user(1)
    result2 = await fetch_user(2)
    result3 = await fetch_user(3)
    return [result1, result2, result3]

# Concurrent (fast) - takes ~1 second
async def concurrent():
    results = await asyncio.gather(
        fetch_user(1),
        fetch_user(2),
        fetch_user(3)
    )
    return results

# With timeouts
async def with_timeouts():
    try:
        results = await asyncio.gather(
            fetch_user(1),
            asyncio.wait_for(fetch_user(2), timeout=0.5),
            fetch_user(3)
        )
    except asyncio.TimeoutError:
        print("User 2 fetch timed out")

Async Database Operations

Use async database drivers for non-blocking database access.

Python 3
# app/crud/user.py (async version)
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select

async def get_user(db: AsyncSession, user_id: int):
    result = await db.execute(select(User).where(User.id == user_id))
    return result.scalar_one_or_none()

async def get_users(db: AsyncSession, skip: int = 0, limit: int = 100):
    result = await db.execute(select(User).offset(skip).limit(limit))
    return result.scalars().all()

# In endpoint
@router.get("/users")
async def get_users(
    skip: int = 0,
    limit: int = 100,
    db: AsyncSession = Depends(get_db)
):
    users = await get_users(db, skip, limit)
    return users

Common Async Pitfalls

Python 3
# PITFALL 1: Blocking the event loop with sync code
@app.get("/bad")
async def bad_endpoint():
    import time
    time.sleep(5)  # BLOCKS! Use asyncio.sleep instead
    return {"message": "Done"}

# PITFALL 2: Forgetting to await
@app.get("/forgot-await")
async def forgot_await():
    result = fetch_data()  # Missing await - returns coroutine, not data!
    return result

# PITFALL 3: Using asyncio.run() inside async endpoint
@app.get("/nested-loop")
async def nested_loop():
    # asyncio.run() cannot be called from within a running event loop
    result = await some_async_task()  # Use await directly
    return result

# PITFALL 4: Creating many tasks without limiting concurrency
# Use asyncio.Semaphore
semaphore = asyncio.Semaphore(10)

async def limited_task(url):
    async with semaphore:
        return await fetch_url(url)
Local Testing: Run these examples to see common async mistakes and how to fix them. The sandbox validates your syntax, but you need to run locally to see the concurrency benefits.

Knowledge Check

Ready to test your understanding of 15. Async Programming & Concurrency?

Back