Search Topics

Search across all FastAPI topics

GitHub

Background & Async

3 topics

Master async/await for high-performance endpoints and background tasks for deferred work like sending emails or processing files.

Tip

FastAPI runs async def endpoints on the event loop and plain def endpoints in a thread pool. Choose async def when doing I/O-heavy work with async libraries, and plain def for CPU-bound tasks.

How Async Requests Flow

Step 1: Request Arrives

An HTTP request hits your async def endpoint.

Try It: Event Loop Simulator

These are the patterns that trip up developers most often. Switch between Wrong and Fixed to compare the code side by side.

1
Blocking the event loop
Running CPU-heavy or synchronous I/O in async endpoints
Don't do this
main.py
@app.get("/report")
async def generate_report():
    # Blocks the entire event loop!
    data = requests.get("https://api.example.com/data")
    result = heavy_computation(data.json())
    return result
In async endpoints, never use blocking libraries like requests or time.sleep(). Use async-compatible libraries (httpx, aiohttp) for I/O and run_in_threadpool for CPU-bound work.