#FastAPI#Python#Backend#Performance#Redis

Optimizing APIs with FastAPI and Python: From 100ms to 12ms Latency

Proven techniques to boost your endpoints' performance: real async I/O, connection pooling, Pydantic v2, and strategic caching with Redis.

Alberto Sanz
Alberto Sanz
Full-Stack Developer | Backend & AI
Nov 20, 2026β€’3 min read

When building modern APIs with FastAPI, it’s easy to assume performance comes out of the box thanks to Starlette and Pydantic. However, under high-concurrency production workloads, blocking I/O pitfalls and serialization overhead can severely degrade response times.

In this article, I break down the core architectural patterns I use across my projects to slash average response times from over 100ms down to under 12ms.


1. The Trap of Blocking I/O in async def Endpoints

The most frequent performance issue in FastAPI is declaring a route with async def and invoking a library that blocks the event loop (for example, requests, time.sleep, or synchronous database drivers):

# ❌ INCORRECT: Blocks the entire asyncio event loop
@app.get("/api/external-data")
async def get_data():
    response = requests.get("https://api.service.com/data") # Blocking!
    return response.json()

When synchronous code executes inside a coroutine, no other client request can be processed on that thread during the network wait.

The Solution:

  1. Use genuinely asynchronous HTTP clients such as httpx or aiohttp.
  2. If you must use a blocking third-party library with no async alternative, declare the route as a regular def (FastAPI automatically delegates it to an external worker threadpool) or wrap it with run_in_threadpool:
# βœ… CORRECT: Utilizing an async HTTP client
import httpx

@app.get("/api/external-data")
async def get_data():
    async with httpx.AsyncClient() as client:
        response = await client.get("https://api.service.com/data")
        return response.json()

2. Pydantic v2 and Rust-Powered Serialization

Recent versions of FastAPI leverage Pydantic v2, with a core (pydantic-core) implemented in Rust. This delivers 5x to 20x speedups in JSON schema validation and data parsing.

Key recommendations:

  • Avoid .dict() (deprecated). Use .model_dump() or .model_dump_json().
  • Always declare an explicit response_model so FastAPI can pre-compile serializers at application startup and filter sensitive fields efficiently.
from pydantic import BaseModel, ConfigDict

class ItemResponse(BaseModel):
    id: int
    title: str
    price: float
    
    model_config = ConfigDict(from_attributes=True)

3. Database Connection Pooling with SQLAlchemy 2.0 & asyncpg

Opening and tearing down TCP connections to PostgreSQL on every incoming request introduces an overhead of 15ms to 40ms.

Employing the asyncpg driver along with an adequately sized connection pool keeps connections warm and ready for reuse:

from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker

DATABASE_URL = "postgresql+asyncpg://user:pass@localhost:5432/mydb"

engine = create_async_engine(
    DATABASE_URL,
    pool_size=20,
    max_overflow=10,
    pool_timeout=30,
    pool_recycle=1800,
)

AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)

4. Cache-Aside Pattern with Redis

For read-intensive endpoints (such as catalog listings, app configs, or user profiles), hitting the database on every single request wastes compute and increases latency.

Implementing a Cache-Aside strategy with Redis drops lookup times to 1-2ms:

import json
import redis.asyncio as redis

redis_client = redis.from_url("redis://localhost:6379", decode_responses=True)

@app.get("/items/{item_id}")
async def get_item(item_id: str):
    cache_key = f"item:{item_id}"
    
    # 1. Attempt to fetch from Redis
    cached = await redis_client.get(cache_key)
    if cached:
        return json.loads(cached)
        
    # 2. Query database on cache miss
    item = await fetch_item_from_db(item_id)
    
    # 3. Store back in cache with TTL
    await redis_client.setex(cache_key, 300, json.dumps(item))
    return item

Conclusion

High performance is never accidental; it is the natural consequence of respecting the non-blocking event loop, leveraging Pydantic v2 serialization, and avoiding redundant compute with database pooling and Redis caching.

With these methodical adjustments, a FastAPI service can easily scale from bottle-necking at 200 requests/second to handling over 3,000 req/s with sub-15ms latencies.

Share
Alberto Sanz

Alberto Sanz

Full-Stack Developer | Backend & AI

Full-Stack Developer focused on scalable backend architectures, high-performance APIs with Python and FastAPI, and Artificial Intelligence integrations.

Recommended articles