Chapter 3 · Production FastAPI
Caching, Rate Limiting and Reliability with Redis
- Page 12 of 22
- 30 min read
An AI product is a chain of slow, expensive, rate-limited calls: an upstream data API, a vector database, an embedding model, an LLM that bills per token. When a hundred users ask for the same weather forecast, you should not pay for a hundred upstream calls. When one script hammers your /chat endpoint in a loop, it should not burn your monthly LLM budget or slow everyone else down. And when an upstream service falls over, your API should degrade politely instead of falling over with it.
This page adds those protections to a FastAPI service with Redis: caching with TTLs and invalidation, three rate-limiting algorithms, concurrency limits, timeouts and deadlines, a circuit breaker, graceful degradation, request IDs and basic metrics. Everything runs against the Practice API and a real Redis server.
What you will learn
- When caching helps, in-process caches vs Redis (and Valkey), keys, TTLs and invalidation
- Cache-aside for an upstream API, and how to cache LLM results without serving one user's answer to another
- Rate limiting with Redis: fixed window, sliding window and token bucket, per user or per IP, with
429andRetry-After - Concurrency limits, timeouts and deadlines, retry vs fail-fast, and a circuit breaker
- Graceful degradation when Redis or an upstream is down, request/correlation IDs and simple shared metrics
Set up the project
A fresh project with FastAPI, the Redis client and httpx (it comes with fastapi[standard]):
mkdir -p ~/projects/bitbyte-weather && cd ~/projects/bitbyte-weather
uv init -q --bare --name bitbyte-weather
uv add -q "fastapi[standard]" redis
source .venv/bin/activate
# with pip instead of uv:
# python -m venv .venv && source .venv/bin/activate
# pip install -q "fastapi[standard]" redisYou also need a Redis server. The quickest way on any OS is Docker (you will meet Docker properly in Docker: Packaging Your API). Either image works; the Python client is the same:
docker run -d --name bitbyte-redis -p 6379:6379 redis:8
# or the BSD-licensed fork:
docker run -d --name bitbyte-redis -p 6379:6379 valkey/valkey:9Check that it answers. (redis-cli -u redis://localhost:6379 ping does the same and prints PONG if you have the command-line tool; here we use the Python client you just installed.)
python -c "import redis; print(redis.Redis.from_url('redis://localhost:6379').ping())"TrueRedis or Valkey? Redis 7.4 changed to source-available licences, and in March 2024 the Linux Foundation forked the last BSD-licensed version as Valkey. Redis 8 (May 2025) added the open-source AGPLv3 as a third licence option. For you as an application developer they speak the same protocol and commands: AWS and Google Cloud offer managed Valkey, Render's "Key Value" is Redis-compatible, and the
redisPython package (8.x) talks to all of them. This page says "Redis" for both.
Why cache, and what
A cache keeps a copy of a result that was expensive to produce, so the next identical request is answered from the copy. It buys you lower latency, lower cost, less load on upstreams and some resilience. It costs you staleness (the copy may be out of date) and complexity (you must decide when copies die). The questions to ask about any value are: how expensive is it to produce, how often is it asked for again, and how wrong may it be?
| Value in an AI backend | Cache? | Typical TTL |
|---|---|---|
| Weather, exchange rates, product catalogue from an upstream API | Yes | Minutes |
| Embeddings of a document chunk (same text + same model = same vector) | Yes, keyed by content hash and model | Days, or until the model changes |
| An ML model's prediction for identical features | Often | Until the model version changes |
| An LLM answer to a deterministic, non-personal prompt (FAQ bot) | Carefully (see below) | Hours |
| A user's account balance, permissions, anything security-relevant | Rarely; very short TTLs and explicit invalidation | Seconds |
Creative LLM output (temperature > 0), streaming chats | No | — |
An in-process cache
The simplest cache is a dictionary in your Python process. Every entry needs an expiry time; the clock is a parameter here so the example is repeatable:
import time
class TTLCache:
"""A tiny in-process cache: a dict whose entries expire."""
def __init__(self, ttl_seconds, clock=time.monotonic):
self.ttl, self.clock, self.data = ttl_seconds, clock, {}
def get(self, key):
item = self.data.get(key)
if item is None:
return None
value, expires_at = item
if self.clock() >= expires_at:
del self.data[key]
return None
return value
def set(self, key, value):
self.data[key] = (value, self.clock() + self.ttl)
now = [1000.0] # a fake clock we can move
cache = TTLCache(ttl_seconds=60, clock=lambda: now[0])
cache.set("weather:dhaka", {"temp_c": 31.5})
print(cache.get("weather:dhaka"))
now[0] += 61 # 61 seconds later
print(cache.get("weather:dhaka")){'temp_c': 31.5}
NoneIn-process caches are the fastest possible (no network hop) and fine for values that are the same everywhere and cheap to recompute, such as a loaded config or a tokenizer. functools.lru_cache is the built-in version, but it has no TTL. Their limits show up in production: every worker process (fastapi run --workers 4) and every container has its own copy, so hit rates fall and invalidation is impossible ("delete Dhaka's forecast" deletes it in one process out of eight); memory grows with the process; and a restart empties it. A shared cache such as Redis fixes all three.
Redis basics: keys, values, TTLs
Redis is an in-memory key-value server. Values can be strings, counters, hashes, lists, sets and sorted sets, and every key can have a time to live. Because the test Redis is shared, everything on this page lives under one key prefix, and a helper deletes only those keys (with SCAN, which walks the keyspace in small steps instead of blocking the server like KEYS *). Never run FLUSHALL on a server other people use.
import redis
r = redis.Redis.from_url("redis://localhost:6379/0", decode_responses=True)
PREFIX = "bitbyte:p12:"
def clear_prefix(prefix=PREFIX):
keys = list(r.scan_iter(match=prefix + "*", count=500))
if keys:
r.delete(*keys)
return len(keys)
clear_prefix()
print(r.ping())
r.set(PREFIX + "demo:greeting", "hello", ex=60) # ex = TTL in seconds
print(r.get(PREFIX + "demo:greeting"))
print(r.ttl(PREFIX + "demo:greeting") <= 60)
print(r.get(PREFIX + "demo:missing")) # a miss is None
print(r.incr(PREFIX + "demo:counter"), r.incr(PREFIX + "demo:counter")) # atomic counter
print(r.set(PREFIX + "demo:lock", "worker-1", nx=True, ex=30))
print(r.set(PREFIX + "demo:lock", "worker-2", nx=True, ex=30))True
hello
True
None
1 2
True
NoneWhat to notice:
- Key names are your schema. Use a prefix per application and environment, then the kind of thing, then its identity:
bitbyte:prod:weather:dhaka. Normalise the identity (dhaka, notDhakaandDHAKA), or the same thing is cached three times. - Every cache key gets a TTL (
ex=). A key without one lives until someone deletes it, and memory fills up with values nobody will ask for again. Setmaxmemoryand an eviction policy such asallkeys-lruon a cache-only server as a safety net. INCRis atomic: two workers incrementing at the same time can never both read 1 and write 2. That is the building block of rate limiting.SET … NXsets only if the key does not exist: the second worker getsNone. With a TTL it becomes a simple lock, so only one worker rebuilds an expensive report.
Cache-aside in a FastAPI service
The most common pattern is cache-aside: look in the cache; on a hit, return the copy; on a miss, call the source, store the result with a TTL, and return it. Here is a small service in front of the Practice API's weather endpoint. It also has the rate limiter, request IDs and metrics that later sections explain, so read it once now and come back to it. Settings come from environment variables, as in Dependencies, Lifespan, Middleware and Settings:
# file: main.py
"""BitByte Weather: a cached, rate-limited proxy in front of the Practice API."""
import json
import logging
import os
import uuid
from contextlib import asynccontextmanager
import httpx
import redis.asyncio as aioredis
from fastapi import Depends, FastAPI, HTTPException, Request, Response
from redis.exceptions import RedisError
PRACTICE_API_URL = os.environ.get("PRACTICE_API_URL", "http://localhost:8800")
REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379/0")
PREFIX = os.environ.get("KEY_PREFIX", "bitbyte:p12:")
WEATHER_TTL = 300 # seconds a cached forecast stays fresh
RATE_LIMIT = 5 # requests ...
RATE_WINDOW = 60 # ... per 60 seconds, per client
logger = logging.getLogger("weather")
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = httpx.AsyncClient(
base_url=PRACTICE_API_URL, timeout=httpx.Timeout(5.0, connect=2.0))
app.state.redis = aioredis.Redis.from_url(
REDIS_URL, decode_responses=True, socket_timeout=0.5, socket_connect_timeout=0.5)
yield
await app.state.http.aclose()
await app.state.redis.aclose()
app = FastAPI(title="BitByte Weather", lifespan=lifespan)
async def count(request: Request, field: str) -> None:
"""Add 1 to a shared counter. Metrics must never break a request."""
try:
await request.app.state.redis.hincrby(PREFIX + "metrics", field, 1)
except RedisError:
pass
@app.middleware("http")
async def request_id_and_metrics(request: Request, call_next):
request.state.request_id = request.headers.get("X-Request-ID") or uuid.uuid4().hex
response = await call_next(request)
response.headers["X-Request-ID"] = request.state.request_id
await count(request, f"status:{response.status_code}")
return response
def client_key(request: Request) -> str:
"""Who is calling: the API key if there is one, else the IP address."""
return request.headers.get("X-API-Key") or request.client.host
async def rate_limit(request: Request, response: Response) -> None:
"""Fixed window: RATE_LIMIT requests per RATE_WINDOW seconds per client."""
key = f"{PREFIX}rate:{client_key(request)}"
try:
async with request.app.state.redis.pipeline() as pipe:
pipe.incr(key)
pipe.expire(key, RATE_WINDOW, nx=True) # the window starts at the first request
pipe.ttl(key)
used, _, ttl = await pipe.execute()
except RedisError:
logger.warning("rate limiter unavailable, allowing the request") # fail open
return
remaining = max(0, RATE_LIMIT - used)
headers = {"X-RateLimit-Limit": str(RATE_LIMIT), "X-RateLimit-Remaining": str(remaining)}
if used > RATE_LIMIT:
raise HTTPException(429, "Rate limit exceeded", headers={**headers, "Retry-After": str(ttl)})
response.headers.update(headers)
@app.get("/health")
async def health(request: Request) -> dict:
try:
await request.app.state.redis.ping()
redis_state = "up"
except RedisError:
redis_state = "down"
return {"status": "ok", "redis": redis_state}
@app.get("/v1/weather/{city}", dependencies=[Depends(rate_limit)])
async def weather(city: str, request: Request, response: Response) -> dict:
key = f"{PREFIX}weather:{city.lower()}"
try:
cached = await request.app.state.redis.get(key)
except RedisError:
cached = None
response.headers["X-Cache"] = "BYPASS" # degrade: no cache, still answer
if cached is not None:
response.headers["X-Cache"] = "HIT"
await count(request, "cache:hit")
return json.loads(cached)
try:
upstream = await request.app.state.http.get(
"/v1/weather", params={"city": city},
headers={"X-Request-ID": request.state.request_id})
except httpx.TimeoutException:
raise HTTPException(504, "Weather service timed out")
except httpx.HTTPError:
raise HTTPException(502, "Weather service unreachable")
if upstream.status_code == 404:
raise HTTPException(404, f"Unknown city: {city}")
if upstream.status_code != 200:
raise HTTPException(502, "Weather service error")
data = upstream.json()
response.headers.setdefault("X-Cache", "MISS")
await count(request, "cache:miss")
try:
await request.app.state.redis.set(key, json.dumps(data), ex=WEATHER_TTL)
except RedisError:
pass
return data
@app.delete("/v1/weather/{city}/cache", status_code=204)
async def forget_weather(city: str, request: Request) -> None:
await request.app.state.redis.delete(f"{PREFIX}weather:{city.lower()}")
@app.get("/metrics")
async def metrics(request: Request) -> dict[str, int]:
raw = await request.app.state.redis.hgetall(PREFIX + "metrics")
return {name: int(value) for name, value in sorted(raw.items())}Start it in the background, wait for it, and ask for Dhaka's weather three times. curl -w prints just the status code and the X-Cache header:
export PRACTICE_API_URL=http://localhost:8800
export REDIS_URL=redis://localhost:6379/0
fastapi run main.py --port 8000 > server.log 2>&1 &
export SERVER_PID=$!
curl -s --retry 20 --retry-connrefused --retry-delay 0 http://localhost:8000/health > /dev/null
for i in 1 2 3; do
curl -s -o /dev/null -w '%{http_code} X-Cache: %header{x-cache}\n' \
-H "X-API-Key: nadia-key" http://localhost:8000/v1/weather/Dhaka
done
curl -s -H "X-API-Key: nadia-key" http://localhost:8000/v1/weather/dhaka200 X-Cache: MISS
200 X-Cache: HIT
200 X-Cache: HIT
{"city":"Dhaka","temp_c":31.5,"humidity":78,"condition":"Humid"}The first request was a MISS: the service called the Practice API and stored the answer for 300 seconds. The next ones were HITs served from Redis without touching the upstream; dhaka hit the same key as Dhaka because the key is normalised. Redis now holds these keys:
python - <<'EOF'
import os, redis
r = redis.Redis.from_url(os.environ["REDIS_URL"], decode_responses=True)
for name in sorted(r.scan_iter(match="bitbyte:p12:*")):
print(name)
print(r.get("bitbyte:p12:weather:dhaka"))
EOFbitbyte:p12:demo:counter
bitbyte:p12:demo:greeting
bitbyte:p12:demo:lock
bitbyte:p12:metrics
bitbyte:p12:rate:nadia-key
bitbyte:p12:weather:dhaka
{"city": "Dhaka", "temp_c": 31.5, "humidity": 78, "condition": "Humid"}Invalidation
"There are only two hard things in computer science: cache invalidation and naming things." You have three tools, usually combined:
- TTL expiry: the copy dies after a while. Simple and always there as the backstop. Choose the TTL from how stale the value may be, not from how often it changes.
- Explicit delete on write: when your own code changes the source (a course is edited), delete the cached copy in the same code path. The next read refills it.
- Versioned keys: put a version in the key (
embeddings:v3:…,model-2026-10:…). Bumping the version makes every old key unreachable at once; their TTLs clean them up.
The service has a delete endpoint. After it, the next read is a miss again:
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE -H "X-API-Key: tanvir-key" \
http://localhost:8000/v1/weather/Dhaka/cache
curl -s -o /dev/null -w '%{http_code} X-Cache: %header{x-cache}\n' \
-H "X-API-Key: tanvir-key" http://localhost:8000/v1/weather/Dhaka204
200 X-Cache: MISSTwo production problems to know by name. A cache stampede happens when a popular key expires and a thousand requests miss at once, all calling the upstream. Fixes: a short lock with SET NX so one request refills while others wait or get the stale copy, or a little random jitter on TTLs so keys do not all expire together. Negative caching is caching "not found" for a short time, so repeated requests for a city that does not exist do not each cost an upstream call; keep that TTL short.
Caching LLM results carefully
LLM calls are the most expensive thing in your stack, so caching them is tempting, and sometimes right: an FAQ bot with temperature=0 gets the same question many times a day. But an LLM cache that is built carelessly leaks data and serves wrong answers. The rules:
- The key must contain everything that affects the answer: provider and model, the system prompt (or its version), every message, and parameters such as temperature and tools. Change the prompt version and old answers must become unreachable.
- Hash a canonical form. Serialise with sorted keys and fixed separators, then hash with SHA-256. Do not put raw prompts in key names (they are long and may contain personal data).
- Scope personal context. If the prompt includes anything about the user (their name, documents, history), put the user ID in the key, or do not cache at all. Otherwise user B gets an answer written for user A.
- Cache only deterministic, successful results: no caching at
temperature> 0, never cache errors or refusals, and give entries a TTL. - Provider-side prompt caching (OpenAI, Anthropic) is different: it makes a repeated long prefix cheaper, but the model still generates a fresh answer. Use both.
import hashlib
import json
import httpx
PROMPT_VERSION = "faq-v3"
CHAT_URL = "http://localhost:8800/v1/chat"
HEADERS = {"Authorization": "Bearer token-nadia-001"}
def llm_cache_key(model, messages, temperature, user_scope=None):
payload = {"model": model, "prompt_version": PROMPT_VERSION, "messages": messages,
"temperature": temperature, "scope": user_scope}
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
return PREFIX + "llm:" + hashlib.sha256(canonical.encode()).hexdigest()[:32]
def cached_chat(messages, model="practice-llm-1", temperature=0.0, user_scope=None):
if temperature > 0: # creative output: never cached
return httpx.post(CHAT_URL, headers=HEADERS, timeout=10,
json={"model": model, "messages": messages}).json(), "SKIP"
key = llm_cache_key(model, messages, temperature, user_scope)
if (hit := r.get(key)) is not None:
return json.loads(hit), "HIT"
resp = httpx.post(CHAT_URL, headers=HEADERS, timeout=10,
json={"model": model, "messages": messages})
resp.raise_for_status() # errors are not cached
data = resp.json()
r.set(key, json.dumps(data), ex=3600)
return data, "MISS"
question = [{"role": "user", "content": "What is a vector database?"}]
saved = 0
for attempt in range(3):
data, status = cached_chat(question)
if status == "HIT":
saved += data["usage"]["total_tokens"]
print(status, data["message"]["content"])
print("tokens saved:", saved)
print(cached_chat([{"role": "user", "content": "what is a vector database"}])[1])
print(cached_chat(question, user_scope="user-42")[1])
print(cached_chat(question, temperature=0.7)[1])MISS This is a practice answer about: What is a vector database. A real model would say more.
HIT This is a practice answer about: What is a vector database. A real model would say more.
HIT This is a practice answer about: What is a vector database. A real model would say more.
tokens saved: 44
MISS
MISS
SKIPThe same question twice more cost nothing. A slightly different spelling missed: exact-match caches only help with exact repeats. Semantic caches match by embedding similarity instead, which raises the hit rate but can return an answer to a similar question that is wrong for this one; use them only with a strict similarity threshold and for low-risk content. The user-scoped request missed too, as it should.
Rate limiting
A rate limit caps how many requests a client may make in a period. It protects your servers from overload and abuse, protects your LLM budget, shares capacity fairly between customers, and lets you sell plans ("free: 20 requests a minute"). In Designing Robust APIs: Pagination, Rate Limits, Retries and Versioning you consumed limits; here you enforce them. Decide three things:
- Who is the client? The authenticated user or API key whenever there is one; the IP address only for anonymous endpoints such as login (and behind a proxy, take the IP from the proxy's trusted header, not from any
X-Forwarded-Fora client sends). - What is counted? Requests, or cost: an LLM endpoint should count tokens, because one 8,000-token request costs as much as a hundred small ones.
- Where is the counter? In Redis, so every worker and container shares it. A per-process counter lets a client make N × workers requests.
Fixed window
Count requests in fixed periods (12:00:00–12:00:59, 12:01:00–…) with INCR, and let the key expire with its window. The functions below take now as a parameter so the examples are repeatable; in production pass time.time():
def fixed_window(key, limit, window, now):
bucket = f"{PREFIX}fw:{key}:{int(now // window)}"
with r.pipeline() as pipe: # MULTI/EXEC: both or neither
pipe.incr(bucket)
pipe.expire(bucket, window)
used, _ = pipe.execute()
return used <= limit
for t in [58, 58.5, 59, 59.5, 60, 60.5, 61, 61.5]:
print(f"t={t:>4}: {'allowed' if fixed_window('nadia', 3, 60, t) else 'rejected'}")t= 58: allowed
t=58.5: allowed
t= 59: allowed
t=59.5: rejected
t= 60: allowed
t=60.5: allowed
t= 61: allowed
t=61.5: rejectedCheap (one counter per client) and easy to explain, but look at the edge: three requests just before second 60 and three just after are all allowed, which is 6 requests in three seconds against a limit of "3 per minute".
Sliding window log
Remember the time of every request in a sorted set (score = timestamp), drop the ones older than the window, and count what is left. The window slides with the clock, so there is no edge to exploit:
def sliding_window(key, limit, window, now, request_id):
zkey = f"{PREFIX}sw:{key}"
with r.pipeline() as pipe:
pipe.zremrangebyscore(zkey, 0, now - window) # forget requests outside the window
pipe.zadd(zkey, {request_id: now})
pipe.zcard(zkey)
pipe.expire(zkey, window)
_, _, used, _ = pipe.execute()
if used > limit:
r.zrem(zkey, request_id) # a rejected request does not count
return False
return True
for n, t in enumerate([58, 58.5, 59, 59.5, 60, 60.5, 61, 61.5]):
print(f"t={t:>4}: {'allowed' if sliding_window('nadia', 3, 60, t, f'req-{n}') else 'rejected'}")t= 58: allowed
t=58.5: allowed
t= 59: allowed
t=59.5: rejected
t= 60: rejected
t=60.5: rejected
t= 61: rejected
t=61.5: rejectedExact, but it stores one entry per request, so memory grows with the limit. A common middle way, the sliding window counter, keeps two fixed-window counters and weights the previous one by how much of it still overlaps the sliding window.
Token bucket
A bucket holds up to capacity tokens and refills at a steady rate. Each request takes tokens (one per request, or its estimated LLM tokens); with too few tokens, it is rejected. This allows short bursts but enforces the average rate, which matches how people really use chat apps. The read-modify-write must be atomic, so it runs inside Redis as a small Lua script:
TOKEN_BUCKET = r.register_script("""
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
local state = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(state[1]) or capacity
local ts = tonumber(state[2]) or now
tokens = math.min(capacity, tokens + (now - ts) * rate)
local allowed = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', KEYS[1], math.ceil(capacity / rate) + 1)
return {allowed, tostring(tokens)}
""")
def token_bucket(key, capacity, rate, now, cost=1):
allowed, tokens = TOKEN_BUCKET(keys=[f"{PREFIX}tb:{key}"], args=[capacity, rate, now, cost])
return bool(allowed), float(tokens)
for t in [0, 0, 0, 0, 0, 0, 2, 2, 2]: # a burst of 6, then 2 seconds later 3 more
ok, left = token_bucket("nadia", capacity=5, rate=1.0, now=t)
print(f"t={t}: {'allowed' if ok else 'rejected'} tokens left {left:g}")
print(token_bucket("nadia", capacity=5, rate=1.0, now=10, cost=4)) # an expensive requestt=0: allowed tokens left 4
t=0: allowed tokens left 3
t=0: allowed tokens left 2
t=0: allowed tokens left 1
t=0: allowed tokens left 0
t=0: rejected tokens left 0
t=2: allowed tokens left 1
t=2: allowed tokens left 0
t=2: rejected tokens left 0
(True, 1.0)Lua scripts run atomically in Redis: no other command runs in the middle, so two workers can never spend the same token. (In production, take now from redis.call('TIME') inside the script so every worker uses one clock.)
| Algorithm | Memory per client | Bursts | Good for |
|---|---|---|---|
| Fixed window | 1 counter | Up to 2× at window edges | Simple quotas, daily limits |
| Sliding window log | 1 entry per request | None | Low limits that must be exact (login attempts) |
| Sliding window counter | 2 counters | Small, approximate | General API limits at scale |
| Token bucket | 2 numbers | Allowed up to capacity | User-facing APIs, cost-based LLM limits |
The limiter in the service
main.py uses the simplest fixed window, with one twist: EXPIRE … NX sets the TTL only on the first request, so each client's window starts when it first calls, and the remaining TTL is exactly the Retry-After value. Nadia has made 4 requests so far. Her fifth is allowed with nothing remaining, and every request after it gets 429 until her window ends; Tanvir has his own counter:
for i in 5 6 7; do
curl -s -o /dev/null -H "X-API-Key: nadia-key" http://localhost:8000/v1/weather/Dhaka \
-w '%{http_code} remaining=%header{x-ratelimit-remaining} retry-after=%header{retry-after}\n'
done | sed -E 's/retry-after=[0-9]+/retry-after=N/' # N = seconds left in her window
curl -s -H "X-API-Key: nadia-key" http://localhost:8000/v1/weather/Dhaka; echo
curl -s -o /dev/null -w 'tanvir: %{http_code}\n' -H "X-API-Key: tanvir-key" \
http://localhost:8000/v1/weather/Dhaka200 remaining=0 retry-after=
429 remaining=0 retry-after=N
429 remaining=0 retry-after=N
{"detail":"Rate limit exceeded"}
tanvir: 200A good 429 says how long to wait (Retry-After, in seconds) and how much quota is left. The X-RateLimit-* names are a widely used convention; an IETF draft standardises RateLimit and RateLimit-Policy headers, so you may meet those too. Put limits at several layers: a generous per-IP limit at the proxy or CDN, per-user or per-key limits in the app, and a strict one on login and password reset.
Concurrency limits
A rate limit counts requests per time; a concurrency limit caps how many run at the same moment. It matters for slow work: if an LLM call takes 20 seconds, even a modest request rate means hundreds of open connections to the provider (whose own limits will then reject you), or a GPU model server with only 4 slots. Inside one process, an asyncio.Semaphore is the tool:
import asyncio
import httpx
async def call_upstream(client, limit, stats):
async with limit: # wait for a free slot
stats["running"] += 1
stats["peak"] = max(stats["peak"], stats["running"])
resp = await client.get("/v1/slow", params={"seconds": 0.2})
stats["running"] -= 1
return resp.status_code
async def main():
stats = {"running": 0, "peak": 0}
limit = asyncio.Semaphore(3) # at most 3 calls in flight
async with httpx.AsyncClient(base_url="http://localhost:8800", timeout=5) as client:
codes = await asyncio.gather(*(call_upstream(client, limit, stats) for _ in range(10)))
print(codes)
print("peak concurrent calls:", stats["peak"])
asyncio.run(main())[200, 200, 200, 200, 200, 200, 200, 200, 200, 200]
peak concurrent calls: 3Ten requests, never more than three at once. A semaphore protects one process; to cap concurrency across all workers (for example "each user may have at most 2 chats streaming"), keep the count in Redis: INCR when the work starts, DECR in a finally block when it ends, and an EXPIRE on the key so a crashed worker cannot leak a slot forever.
Timeouts and deadlines
Every network call needs a timeout. Without one, a hung upstream holds your worker, your connection and your user forever. httpx lets you set separate limits for connecting and for waiting on data:
timeout = httpx.Timeout(5.0, connect=2.0) # connect: 2 s; read, write, pool: 5 s
print(timeout)
try:
httpx.get("http://localhost:8800/v1/slow", params={"seconds": 2}, timeout=0.5)
except httpx.TimeoutException as exc:
print("gave up:", type(exc).__name__)Timeout(connect=2.0, read=5.0, write=5.0, pool=5.0)
gave up: ReadTimeoutPer-call timeouts are not enough when one request makes several calls, or retries. A deadline is a total time budget for the whole job; every step gets only what is left. If your API promises an answer within 3 seconds, a retry that starts at 2.9 seconds is pointless:
import time
def get_with_deadline(path, budget_seconds, max_attempts=4):
deadline = time.monotonic() + budget_seconds
for attempt in range(1, max_attempts + 1):
remaining = deadline - time.monotonic()
if remaining <= 0:
return f"deadline exceeded after {attempt - 1} attempt(s)"
try:
resp = httpx.get("http://localhost:8800" + path, timeout=remaining)
except httpx.TimeoutException:
return f"deadline exceeded after {attempt} attempt(s)"
if resp.status_code not in (429, 502, 503, 504):
return f"{resp.status_code} on attempt {attempt}"
time.sleep(min(0.1 * 2 ** attempt, max(0.0, deadline - time.monotonic())))
return "gave up: too many attempts"
print(get_with_deadline("/v1/flaky?key=deadline-demo&fail_times=2", budget_seconds=3))
print(get_with_deadline("/v1/slow?seconds=5", budget_seconds=1))200 on attempt 3
deadline exceeded after 1 attempt(s)In async code, async with asyncio.timeout(remaining): (Python 3.11+) puts a deadline around any block of awaits. Pass the deadline on to downstream services too (gRPC does this automatically; over HTTP, a header such as X-Request-Deadline is a common convention), so nobody keeps working on an answer the caller has already given up on.
Retry or fail fast?
| Situation | Do |
|---|---|
Connection error, 502/503/504, 429 | Retry with exponential backoff and jitter, honour Retry-After, within the deadline |
400, 401, 403, 404, 422 | Fail fast: retrying the same request gives the same answer |
Non-idempotent call (POST that charges or sends) | Retry only with an idempotency key (see Designing Robust APIs: Pagination, Rate Limits, Retries and Versioning) |
| LLM stream that already sent tokens to the user | Do not silently retry; report the error in the stream |
| The upstream has been failing for a while | Stop calling it for a bit: a circuit breaker |
Retries multiply load: if three layers each retry three times, one user click becomes 27 calls to a struggling service. Retry at one layer only, and keep a retry budget (for example, retries may be at most 10% of requests).
Circuit breaker
When an upstream is down, every call to it waits for a timeout and then fails, which ties up your workers and adds load to a service trying to recover. A circuit breaker watches failures and, after too many in a row, "opens": calls fail immediately without touching the upstream. After a cool-down it lets one trial call through ("half-open"); if that succeeds, it closes again.
failures >= threshold
CLOSED ─────────────────────────▶ OPEN ──── calls fail fast, upstream untouched
▲ │
│ trial call succeeds │ cool-down elapsed
│ ▼
└─────────────────────────── HALF-OPEN ── one trial call allowed
(trial fails ──▶ back to OPEN)class CircuitOpenError(Exception):
pass
class CircuitBreaker:
def __init__(self, threshold=3, cooldown=30.0, clock=time.monotonic):
self.threshold, self.cooldown, self.clock = threshold, cooldown, clock
self.failures, self.opened_at = 0, None
@property
def state(self):
if self.opened_at is None:
return "closed"
return "half-open" if self.clock() - self.opened_at >= self.cooldown else "open"
def call(self, func, *args, **kwargs):
if self.state == "open":
raise CircuitOpenError("upstream marked as down; failing fast")
try:
result = func(*args, **kwargs)
except Exception:
self.failures += 1
if self.state == "half-open" or self.failures >= self.threshold:
self.opened_at = self.clock() # (re)open
raise
self.failures, self.opened_at = 0, None # success closes the circuit
return result
def flaky_upstream():
resp = httpx.get("http://localhost:8800/v1/flaky",
params={"key": "breaker-demo", "fail_times": 3}, timeout=2)
resp.raise_for_status()
return resp.json()
now = [0.0]
breaker = CircuitBreaker(threshold=3, cooldown=30, clock=lambda: now[0])
for step in range(1, 6):
try:
print(step, breaker.state, "->", breaker.call(flaky_upstream))
except CircuitOpenError as exc:
print(step, breaker.state, "->", exc)
except httpx.HTTPStatusError as exc:
print(step, breaker.state, "->", exc.response.status_code)
now[0] += 30 # the cool-down passes
print(6, breaker.state, "->", breaker.call(flaky_upstream))
print("state now:", breaker.state)1 closed -> 503
2 closed -> 503
3 open -> 503
4 open -> upstream marked as down; failing fast
5 open -> upstream marked as down; failing fast
6 half-open -> {'ok': True, 'attempt': 4}
state now: closedCalls 1–3 reached the upstream and failed; then the breaker opened and calls 4 and 5 failed instantly, without an HTTP request. After the cool-down, one trial call went through, succeeded (the Practice API recovers after three failures), and closed the circuit. Libraries such as pybreaker and aiobreaker implement this; keep the state per upstream, and in a multi-worker deployment consider keeping it in Redis so all workers agree.
Graceful degradation
Decide in advance what your service does when each dependency fails, and test it. Typical choices for an AI backend:
- Cache down: serve without it (slower, more upstream calls) — the service above does this.
- Rate limiter down: fail open (allow, log loudly) for ordinary endpoints; fail closed (reject) where abuse is expensive, such as login or an unmetered LLM endpoint.
- Upstream down: serve a stale cached copy marked as stale, a smaller model, a canned answer ("search is temporarily unavailable"), or a clear
503withRetry-After. - LLM provider down or slow: fall back to a second provider or model behind the same adapter (you build that adapter in Building an LLM Backend with Streaming).
Start a second copy of the service pointing at a Redis port where nothing listens, and see it keep working:
REDIS_URL=redis://localhost:6390/0 fastapi run main.py --port 8001 > degraded.log 2>&1 &
export DEGRADED_PID=$!
curl -s --retry 20 --retry-connrefused --retry-delay 0 http://localhost:8001/health; echo
curl -s -o /dev/null -w '%{http_code} X-Cache: %header{x-cache}\n' http://localhost:8001/v1/weather/Sylhet
kill $DEGRADED_PID{"status":"ok","redis":"down"}
200 X-Cache: BYPASSThe health check reports Redis as down (a readiness probe could use that to alert), but users still get their weather. The short socket_connect_timeout in main.py matters here: without it, every request would wait the operating system's default connect timeout before giving up on Redis.
Request IDs and basic metrics
A request ID (or correlation ID) is a unique string attached to a request and to everything it causes: your log lines, the calls you make to other services, the error you show the user. When a user reports "it failed", the ID in the error lets you find every related log line across services. The middleware in main.py keeps an incoming X-Request-ID (so a caller or gateway can set it), creates one otherwise, returns it, and forwards it to the Practice API:
curl -s -o /dev/null -w 'X-Request-ID: %header{x-request-id}\n' \
-H "X-Request-ID: nadia-debug-001" -H "X-API-Key: farhana-key" \
http://localhost:8000/v1/weather/KhulnaX-Request-ID: nadia-debug-001For metrics, the service counts cache hits and misses and responses per status code in one Redis hash, shared by all workers:
curl -s http://localhost:8000/metrics | python -m json.tool
kill $SERVER_PID{
"cache:hit": 5,
"cache:miss": 3,
"status:200": 9,
"status:204": 1,
"status:429": 3
}From this you can already compute a cache hit rate and an error rate. Real systems export metrics in a standard format and graph them: Prometheus counters and histograms, or OpenTelemetry, which FastAPI now supports natively. The four "golden signals" to watch for every service are latency (as percentiles such as p95, not averages), traffic, errors and saturation; for an AI backend add tokens and cost per user and per model, cache hit rate, and how often limits and circuit breakers trip.
Real-world use
- LLM gateways (the internal services companies put in front of OpenAI, Anthropic and local models) are mostly this page: per-team token budgets in Redis, token-bucket limits, response caching for deterministic calls, timeouts, fallbacks between providers and per-request cost metrics.
- RAG pipelines cache embeddings by content hash and model name, so re-indexing unchanged documents costs nothing.
- Public APIs (GitHub, Stripe, the LLM providers themselves) return
429withRetry-Afterand limit headers exactly as your service now does. - Redis also serves as the session store, the job queue broker (Celery, RQ, Arq) and the pub/sub channel in many Python backends, so one managed Redis or Valkey instance usually pays for itself.
Common mistakes
- Cache keys that miss a dimension. Caching an LLM answer by question only, then changing the system prompt or serving another user's personalised answer. Put model, prompt version, parameters and user scope (when there is personal context) in the hashed key.
- Keys without TTLs. Memory fills up, or stale data lives forever. Always pass
ex=, and setmaxmemorywith an eviction policy on cache servers. - Per-process rate limits. A dict counter in each worker multiplies the real limit by the number of workers and resets on every deploy. Count in Redis, atomically (
INCR, pipelines, Lua). - Limiting by
X-Forwarded-Fortaken blindly from the request. Any client can send that header and get a fresh limit per request. Trust it only as set by your own proxy. - No timeouts, or retries at every layer. A hung upstream takes your service down with it, and stacked retries turn a blip into an outage. Set connect and read timeouts, use a deadline, retry in one place, and add a circuit breaker for flaky dependencies.
Try it yourself
- Easy: Write
weather_cached(city)that uses the syncrclient and the Practice API directly: cache-aside with a 120-second TTL underPREFIX + "ex:weather:", returning(data, "HIT"|"MISS"). Call it twice for"Rajshahi". - Medium: Add negative caching: when the Practice API answers
404, store the marker"__none__"for 30 seconds and return(None, "MISS"); on the next call return(None, "HIT")without an HTTP request. Show it with"Atlantis". - Hard: Make the token bucket cost-based for an LLM endpoint: each user has capacity 1,000 tokens refilling at 10 tokens per second, and each call costs its
total_tokensfrom the Practice API's/v1/chatusage. Check the bucket before the call with an estimate (words in the prompt × 2), and print allowed/rejected for five calls atnow=0where each prompt is 200 words long.
Answers
# 1. Easy
def weather_cached(city):
key = PREFIX + "ex:weather:" + city.lower()
if (hit := r.get(key)) is not None:
return json.loads(hit), "HIT"
resp = httpx.get("http://localhost:8800/v1/weather", params={"city": city}, timeout=5)
resp.raise_for_status()
r.set(key, resp.text, ex=120)
return resp.json(), "MISS"
print(weather_cached("Rajshahi"))
print(weather_cached("Rajshahi")[1])({'city': 'Rajshahi', 'temp_c': 33.6, 'humidity': 58, 'condition': 'Sunny'}, 'MISS')
HIT# 2. Medium
def weather_cached(city):
key = PREFIX + "ex:weather:" + city.lower()
if (hit := r.get(key)) is not None:
return (None if hit == "__none__" else json.loads(hit)), "HIT"
resp = httpx.get("http://localhost:8800/v1/weather", params={"city": city}, timeout=5)
if resp.status_code == 404:
r.set(key, "__none__", ex=30) # short TTL for "not found"
return None, "MISS"
resp.raise_for_status()
r.set(key, resp.text, ex=120)
return resp.json(), "MISS"
print(weather_cached("Atlantis"))
print(weather_cached("Atlantis"))(None, 'MISS')
(None, 'HIT')# 3. Hard
def llm_call_with_budget(user, prompt, now):
estimate = len(prompt.split()) * 2
ok, left = token_bucket(f"llm:{user}", capacity=1000, rate=10, now=now, cost=estimate)
if not ok:
return f"rejected (needs ~{estimate}, has {left:g})"
resp = httpx.post(CHAT_URL, headers=HEADERS, timeout=10,
json={"messages": [{"role": "user", "content": prompt}]})
used = resp.json()["usage"]["total_tokens"]
return f"allowed (estimated {estimate}, used {used}, {left:g} left)"
prompt = " ".join(["word"] * 200)
for call in range(1, 6):
print(call, llm_call_with_budget("nadia", prompt, now=0))
print("cleaned up keys:", clear_prefix() > 0)1 allowed (estimated 400, used 412, 600 left)
2 allowed (estimated 400, used 412, 200 left)
3 rejected (needs ~400, has 200)
4 rejected (needs ~400, has 200)
5 rejected (needs ~400, has 200)
cleaned up keys: TrueA production version would also correct the bucket after the call with the difference between estimated and real tokens (spend the extra, or refund the unused part).
Summary
- Cache what is expensive, repeated and allowed to be slightly stale; give every key a prefix, a normalised identity and a TTL; invalidate with TTLs, deletes on write and versioned keys.
- Use Redis (or Valkey, same client) for anything shared between workers: cache, counters, limits, locks, metrics.
- Cache LLM results only for deterministic calls, with model, prompt version, parameters and user scope in a hashed key; never cache errors.
- Rate-limit per user or key in Redis: fixed window for simplicity, sliding window for exactness, token bucket for bursts and token costs; answer
429withRetry-After. - Cap concurrency, set timeouts and deadlines, retry only what is retryable in one layer, and add circuit breakers and planned degradation for every dependency.
- Tag every request with an ID and count hits, misses, errors and costs, so you can see what your limits and caches are doing.
Next: Testing Professional APIs shows how to prove all of this keeps working: fixtures, dependency overrides, mocked HTTP and LLM providers, database tests that roll back, and tests for auth, limits, retries and streaming.

