What's Actually Happening
FastAPI endpoints respond slowly, taking seconds to return responses.
The Error You'll See
```bash $ curl -w "@curl-format.txt" http://localhost:8000/api/slow
time_total: 5.234s # Too slow! ```
Why This Happens
- 1.Blocking I/O - Synchronous operations in async code
- 2.Database queries slow - N+1 queries, missing indexes
- 3.External API calls - Slow third-party services
- 4.No caching - Recomputing every request
- 5.Heavy serialization - Large response payloads
Step 1: Profile Performance
```python import time from fastapi import FastAPI
app = FastAPI()
@app.middleware("http") async def add_process_time_header(request, call_next): start_time = time.time() response = await call_next(request) process_time = time.time() - start_time print(f"Request took {process_time:.3f}s") return response ```
Step 2: Fix Blocking Operations
```python # BAD: Blocking in async @app.get("/api/slow") async def slow_endpoint(): time.sleep(5) # Blocks event loop! return {"status": "ok"}
# GOOD: Use async operations import asyncio
@app.get("/api/fast") async def fast_endpoint(): await asyncio.sleep(5) # Non-blocking return {"status": "ok"} ```
Step 3: Optimize Database Queries
```python # BAD: N+1 queries @app.get("/users") async def get_users(): users = await db.users.all() for user in users: user.posts = await db.posts.filter(user_id=user.id).all() return users
# GOOD: Eager loading @app.get("/users") async def get_users(): users = await db.users.all().prefetch("posts") return users ```
Step 4: Add Caching
```python from fastapi_cache import FastAPICache from fastapi_cache.decorator import cache
@app.get("/api/cached") @cache(expire=60) async def cached_endpoint(): return {"data": "expensive_computation()"} ```
FastAPI Performance Checklist
| Check | Method | Expected |
|---|---|---|
| Blocking ops | code review | None |
| Query time | profiling | Fast |
| Cache enabled | check config | Yes |
Verify the Fix
curl -w "Time: %{time_total}s\n" http://localhost:8000/api/
# Output: Time: 0.150sRelated Issues
- [Fix FastAPI Dependency Injection Failed](/articles/fix-fastapi-dependency-injection-failed)
- [Fix FastAPI Background Task Not Running](/articles/fix-fastapi-background-task-not-running)