5. Testing, Background Jobs & Deployment

Async Endpoints, Background Tasks & Caching Patterns

Avoid freezing your FastAPI event loop: know when to write async def vs def routes, offload slow emails/reports with BackgroundTasks, and speed up hot reads with caching.

5 min readUpdated 2026-11-30
In This Lesson
  • Choose accurately between async def and regular def routes in FastAPI
  • Offload non-critical post-response work using FastAPI BackgroundTasks
  • Understand when to introduce TTL caches or dedicated job queues (Celery/ARQ/Redis)

FastAPI runs on an asynchronous event loop—which gives it huge concurrency when used properly, and terrible latency stalls if misused! Mastering async def vs def, post-response background work, and caching prevents 90% of production FastAPI bottlenecks.

1. async def vs def Threadpool Behavior in FastAPI

How FastAPI executes your route depends entirely on whether you write async def or plain def:

FastAPI Dispatch: async def vs def Routes

async def route()

Runs directly on the Main Event Loop. Must use await (e.g. httpx.AsyncClient). Never call time.sleep()!

def route()

Offloaded to AnyIO Thread Pool automatically. Safe for blocking sqlite3, requests, and sync SQLAlchemy.

async def shares the main event loop directly; plain def runs safely inside AnyIO's worker thread pool so blocking I/O won't stall other users.

Route SignatureExecution ContextUse When Calling...
async def endpoint():Main asyncio event loopawait httpx.AsyncClient, asyncpg, redis.asyncio, await asyncio.sleep()
def endpoint():AnyIO thread poolsqlite3, requests, sync SQLAlchemy sessions, blocking file/CPU calls
Never Put Blocking Calls Inside async def

If you declare async def get_users() and call synchronous time.sleep(2), sqlite3, or requests.get() inside it, every single concurrent user hitting your server freezes for 2 seconds because you blocked the single event loop thread! When in doubt with sync libraries, use plain def.

2. Returning Fast Responses with BackgroundTasks

Suppose POST /signup saves a user to SQLite in 8 ms, and then needs to send a welcome email taking 600 ms. Don't make the user stare at a loading spinner for 600 ms!

FastAPI's BackgroundTasks runs non-critical work immediately after the HTTP 201 response is flushed to the client:

python
from fastapi import BackgroundTasks, FastAPI

app = FastAPI()

def send_welcome_email(email: str):
    # Runs after the HTTP 201 response has already returned to the client!
    print(f"Sending welcome email to {email}...")

@app.post("/signup", status_code=201)
def signup(email: str, background_tasks: BackgroundTasks):
    # 1. Save user to DB quickly
    # 2. Schedule email after response
    background_tasks.add_task(send_welcome_email, email)
    return {"message": "Account created", "email": email}

BackgroundTasks vs Durable Worker Queues (Redis + ARQ / Celery)

  • BackgroundTasks runs inside the same API server process RAM—great for quick emails, webhook pings, or audit logs where occasional loss on a crash is acceptable.
  • Dedicated Queue (Celery / ARQ + Redis) persists jobs outside the web server—required when tasks take minutes (video transcoding, PDF reports), need automatic retries, or must survive server restarts and deploys.

3. Speeding Up Hot Reads with TTL Caching (+ Invalidation)

If GET /courses/catalog executes a heavy 5-table join 200 times per second while catalog data rarely changes, cache the result with a TTL (Time-To-Live)—e.g. 60 seconds:

  • In-process TTL cache: Zero network hop, ideal for single-worker apps—just remember each Uvicorn worker process (--workers 4) keeps its own separate RAM!
  • Redis cache: Shared across all server containers and survives app restarts; invalidate keys (redis.delete("catalog")) whenever an admin updates or deletes a course so users see fresh edits immediately.
Avoid @functools.lru_cache for Live Database Data

@lru_cache never expires entries by time and grows until maxsize in RAM. An admin editing a course title wouldn't appear in the API until you restart the server! Always attach a TTL or invalidate on writes.

4. Real-Time APIs: Polling vs SSE vs WebSockets

Standard REST GET/POST connections close after each response. Choose real-time transport based on directionality:

PatternDirectionBest Used For
Short Polling (GET /jobs/123 every 2s)Client → ServerBackground job status checks, simple dashboards
Server-Sent Events (SSE)Server → Client streamLive AI token streaming, notifications, progress bars
WebSockets (@app.websocket("/ws"))Full bidirectionalLive chat rooms, collaborative editors, multiplayer games
python
from fastapi import WebSocket

@app.websocket("/ws/chat")
async def chat_socket(websocket: WebSocket):
    await websocket.accept()
    while True:
        msg = await websocket.receive_text()
        await websocket.send_text(f"Echo: {msg}")

Try It Yourself in the Playground

Test a clean TTL (Time-To-Live) cache decorator and non-blocking asyncio post-response simulation in Python:

Python 3Try It Live: TTL Cache Decorator & Async Tasks
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Why is @functools.lru_cache (without expiration) risky for caching live database queries in a web API?

Quick Checkpoints

Check Your Understanding

You are writing a FastAPI endpoint that queries PostgreSQL using a synchronous (blocking) driver. Should the route be def or async def?

Check Your Understanding

When should you move a job out of FastAPI BackgroundTasks into a dedicated queue like Celery or ARQ with Redis?