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.
- 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:
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 Signature | Execution Context | Use When Calling... |
|---|---|---|
async def endpoint(): | Main asyncio event loop | await httpx.AsyncClient, asyncpg, redis.asyncio, await asyncio.sleep() |
def endpoint(): | AnyIO thread pool | sqlite3, requests, sync SQLAlchemy sessions, blocking file/CPU calls |
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:
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)
BackgroundTasksruns 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.
@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:
| Pattern | Direction | Best Used For |
|---|---|---|
Short Polling (GET /jobs/123 every 2s) | Client → Server | Background job status checks, simple dashboards |
| Server-Sent Events (SSE) | Server → Client stream | Live AI token streaming, notifications, progress bars |
WebSockets (@app.websocket("/ws")) | Full bidirectional | Live chat rooms, collaborative editors, multiplayer games |
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:
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
You are writing a FastAPI endpoint that queries PostgreSQL using a synchronous (blocking) driver. Should the route be def or async def?
When should you move a job out of FastAPI BackgroundTasks into a dedicated queue like Celery or ARQ with Redis?