Professional Code Generator
Generates clean, well-documented, production-ready code from your requirements, following best practices in any language.
Example run
Generated by Claude Opus 5.5 on November 24, 2026
Inputs used
- Programming language
- Python 3.11
- Describe the functionality
- A token-bucket rate limiter implemented as FastAPI middleware that throttles incoming requests per API key, with burst allowance and configurable refill rate
- Framework or library
- FastAPI 0.115 + redis-py 5.x (async client) for shared state across instances
- List specific requirements
- - Identify clients by the `X-API-Key` header; reject requests with no key using HTTP 401. - Implement token-bucket algorithm: each key gets a bucket with configurable capacity (burst size) and refill rate (tokens/second). - Store bucket state (tokens remaining, last refill timestamp) in Redis so multiple API instances share the same limit. - Use a single atomic Redis operation (Lua script or MULTI/EXEC) to avoid race conditions between read-and-update of the bucket under concurrent requests. - On allowed requests, decrement one token and let the request proceed to the downstream handler. - On exceeded limit, return HTTP 429 with a JSON body `{"error": "rate_limit_exceeded", "retry_after_seconds": <float>}` and a `Retry-After` header. - Expose the limiter as reusable middleware class `TokenBucketRateLimiter` that can be added via `app.add_middleware(...)` with constructor params: `capacity`, `refill_rate`, `redis_url`. - Include a fallback in-memory bucket implementation (dict + asyncio.Lock) used automatically when Redis is unreachable, so the API degrades gracefully instead of failing closed or open silently without logging. - Log (via standard `logging` module) every time the limiter falls back to in-memory mode and every time a request is rejected, including the API key (hashed, not raw) and remaining tokens. - Provide a `/health` endpoint unaffected by rate limiting (exempt path list).
- Constraints
- No external deps beyond fastapi, redis, and pytest/fakeredis/httpx for tests; must run fully offline (tests use fakeredis, no real network); target modest scale of ~500 requests/sec across up to 5 API instances; keep middleware overhead under 2ms p50 per request
- Target use case
- Protecting a small public SaaS REST API (a document-conversion service) from abusive or runaway clients, deployed as 3-5 stateless FastAPI instances behind a load balancer sharing rate-limit state via a single Redis instance
1. Solution
rate_limiter.py
"""Token-bucket rate limiting for FastAPI, with shared state in Redis.
Bucket state is kept in Redis so that every API instance enforces the same
per-key limit. If Redis becomes unreachable, the limiter switches to a
per-process in-memory bucket. It logs the switch so the degraded mode is
visible, and it does not silently fail open or closed.
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import logging
import math
import time
from collections import OrderedDict
from collections.abc import Awaitable, Callable, Iterable
from dataclasses import dataclass
from redis.asyncio import Redis
from redis.exceptions import RedisError
from starlette.types import ASGIApp, Message, Receive, Scope, Send
logger = logging.getLogger(__name__)
Clock = Callable[[], float]
MAX_API_KEY_LENGTH = 256
_LOG_KEY_ID_LENGTH = 12
# Refill, take and persist run in one atomic script, so concurrent requests
# across instances can never interleave between the read and the write.
# Numbers are formatted with %.17g so floats round-trip without precision loss.
_LUA_TOKEN_BUCKET = """
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local state = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = capacity
local last = now
if state[1] and state[2] then
tokens = tonumber(state[1])
last = tonumber(state[2])
end
-- Clamp negative elapsed time (clock skew between instances) and never
-- move the timestamp backwards.
local elapsed = math.max(0, now - last)
tokens = math.min(capacity, tokens + elapsed * rate)
last = math.max(last, now)
local allowed, retry_after = 0, 0
if tokens >= 1 then
tokens = tokens - 1
allowed = 1
else
retry_after = (1 - tokens) / rate
end
redis.call('HSET', KEYS[1],
'tokens', string.format('%.17g', tokens),
'ts', string.format('%.17g', last))
redis.call('PEXPIRE', KEYS[1], ARGV[4])
return {allowed, string.format('%.17g', tokens), string.format('%.17g', retry_after)}
"""
@dataclass(frozen=True, slots=True)
class RateLimitDecision:
allowed: bool
remaining: float
retry_after: float
def take_token(
tokens: float, last_ts: float, now: float, capacity: int, refill_rate: float
) -> tuple[float, float, RateLimitDecision]:
"""Pure token-bucket step. It mirrors the Lua script for the in-memory path."""
elapsed = max(0.0, now - last_ts)
tokens = min(float(capacity), tokens + elapsed * refill_rate)
last_ts = max(last_ts, now)
if tokens >= 1.0:
tokens -= 1.0
return tokens, last_ts, RateLimitDecision(True, tokens, 0.0)
return tokens, last_ts, RateLimitDecision(False, tokens, (1.0 - tokens) / refill_rate)
def _to_float(value: bytes | str | float) -> float:
return float(value.decode() if isinstance(value, bytes) else value)
class RedisTokenBucket:
"""Bucket store shared across instances. One EVALSHA round trip per request."""
def __init__(
self, client: Redis, capacity: int, refill_rate: float, key_prefix: str = "ratelimit:"
) -> None:
self._capacity = capacity
self._refill_rate = refill_rate
self._key_prefix = key_prefix
# Idle buckets expire after twice the time needed for a full refill.
# At that point they would be full anyway, so the key can be dropped.
self._ttl_ms = max(1000, math.ceil(2 * capacity / refill_rate * 1000))
# register_script uses EVALSHA and reloads the script on NOSCRIPT.
self._script = client.register_script(_LUA_TOKEN_BUCKET)
async def acquire(self, key: str, now: float) -> RateLimitDecision:
allowed, remaining, retry_after = await self._script(
keys=[self._key_prefix + key],
args=[self._capacity, self._refill_rate, now, self._ttl_ms],
)
return RateLimitDecision(bool(int(allowed)), _to_float(remaining), _to_float(retry_after))
class InMemoryTokenBucket:
"""Per-process fallback. Uses an LRU-bounded dict so memory stays capped."""
def __init__(self, capacity: int, refill_rate: float, max_keys: int = 100_000) -> None:
self._capacity = capacity
self._refill_rate = refill_rate
self._max_keys = max_keys
self._buckets: OrderedDict[str, tuple[float, float]] = OrderedDict()
self._lock = asyncio.Lock()
async def acquire(self, key: str, now: float) -> RateLimitDecision:
async with self._lock:
# pop and re-insert moves the key to the MRU end.
tokens, last_ts = self._buckets.pop(key, (float(self._capacity), now))
tokens, last_ts, decision = take_token(
tokens, last_ts, now, self._capacity, self._refill_rate
)
self._buckets[key] = (tokens, last_ts)
if len(self._buckets) > self._max_keys:
self._buckets.popitem(last=False)
return decision
def _extract_header(scope: Scope, name: bytes) -> str | None:
for header_name, value in scope.get("headers", ()):
if header_name == name:
return value.decode("latin-1").strip()
return None
def _hash_api_key(api_key: str) -> str:
return hashlib.sha256(api_key.encode()).hexdigest()
async def _send_json(
send: Send, status: int, payload: dict, extra_headers: Iterable[tuple[bytes, bytes]] = ()
) -> None:
body = json.dumps(payload).encode()
headers = [
(b"content-type", b"application/json"),
(b"content-length", str(len(body)).encode()),
*extra_headers,
]
await send({"type": "http.response.start", "status": status, "headers": headers})
await send({"type": "http.response.body", "body": body})
class TokenBucketRateLimiter:
"""Pure-ASGI middleware that throttles requests per ``X-API-Key``.
Usage: ``app.add_middleware(TokenBucketRateLimiter, capacity=20,
refill_rate=5.0, redis_url="redis://redis:6379/0")``.
"""
def __init__(
self,
app: ASGIApp,
*,
capacity: int,
refill_rate: float,
redis_url: str | None = None,
redis_client: Redis | None = None,
exempt_paths: Iterable[str] = ("/health",),
api_key_header: str = "X-API-Key",
redis_timeout_seconds: float = 0.25,
redis_retry_interval_seconds: float = 5.0,
max_fallback_keys: int = 100_000,
clock: Clock = time.time,
) -> None:
if isinstance(capacity, bool) or not isinstance(capacity, int) or capacity < 1:
raise ValueError(f"capacity must be an int >= 1, got {capacity!r}")
if not isinstance(refill_rate, int | float) or not math.isfinite(refill_rate) or refill_rate <= 0:
raise ValueError(f"refill_rate must be a finite number > 0, got {refill_rate!r}")
if (redis_url is None) == (redis_client is None):
raise ValueError("provide exactly one of redis_url or redis_client")
if redis_url is not None and not redis_url.strip():
raise ValueError("redis_url must be non-empty")
self.app = app
self._capacity = capacity
self._exempt_paths = frozenset(exempt_paths)
self._header_name = api_key_header.lower().encode("latin-1")
self._retry_interval = redis_retry_interval_seconds
self._clock = clock
self._owns_redis = redis_client is None
self._redis: Redis = redis_client or Redis.from_url(
redis_url, # type: ignore[arg-type]
socket_timeout=redis_timeout_seconds,
socket_connect_timeout=redis_timeout_seconds,
)
self._redis_bucket = RedisTokenBucket(self._redis, capacity, float(refill_rate))
self._memory_bucket = InMemoryTokenBucket(capacity, float(refill_rate), max_fallback_keys)
self._in_fallback = False
self._redis_retry_at = 0.0 # monotonic time; acts as a simple circuit breaker
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "lifespan":
await self.app(scope, self._close_on_shutdown(receive), send)
return
if scope["type"] != "http" or scope["path"] in self._exempt_paths:
await self.app(scope, receive, send)
return
api_key = _extract_header(scope, self._header_name)
if not api_key or len(api_key) > MAX_API_KEY_LENGTH:
await _send_json(
send,
401,
{"error": "missing_or_invalid_api_key"},
[(b"www-authenticate", b'ApiKey header="X-API-Key"')],
)
return
key_hash = _hash_api_key(api_key)
decision = await self._acquire(key_hash)
if not decision.allowed:
await self._reject(send, key_hash, decision)
return
await self.app(scope, receive, self._with_rate_limit_headers(send, decision))
async def _acquire(self, key_hash: str) -> RateLimitDecision:
now = self._clock()
if time.monotonic() >= self._redis_retry_at:
try:
decision = await self._redis_bucket.acquire(key_hash, now)
except (RedisError, OSError) as exc: # OSError covers TimeoutError and socket errors
self._enter_fallback(exc)
else:
self._leave_fallback()
return decision
return await self._memory_bucket.acquire(key_hash, now)
def _enter_fallback(self, exc: BaseException) -> None:
# Skip Redis for a short while so a dead Redis does not add a
# socket timeout to every request.
self._redis_retry_at = time.monotonic() + self._retry_interval
if not self._in_fallback:
self._in_fallback = True
logger.warning(
"Redis unavailable (%s: %s); rate limiter falling back to in-memory "
"buckets. Limits are now enforced per instance, not globally. "
"Retrying Redis in %.1fs.",
type(exc).__name__, exc, self._retry_interval,
)
else:
logger.debug("Redis still unavailable: %s", exc)
def _leave_fallback(self) -> None:
if self._in_fallback:
self._in_fallback = False
logger.info("Redis reachable again; rate limiter back to shared Redis buckets.")
async def _reject(self, send: Send, key_hash: str, decision: RateLimitDecision) -> None:
retry_after = round(decision.retry_after, 3)
logger.info(
"Rate limit exceeded key_id=%s remaining_tokens=%.3f retry_after=%.3fs backend=%s",
key_hash[:_LOG_KEY_ID_LENGTH], decision.remaining, retry_after,
"memory" if self._in_fallback else "redis",
)
await _send_json(
send,
429,
{"error": "rate_limit_exceeded", "retry_after_seconds": retry_after},
[
# Retry-After must be an integer (delta-seconds), so round up.
(b"retry-after", str(max(1, math.ceil(decision.retry_after))).encode()),
(b"x-ratelimit-limit", str(self._capacity).encode()),
(b"x-ratelimit-remaining", b"0"),
],
)
def _with_rate_limit_headers(self, send: Send, decision: RateLimitDecision) -> Send:
extra = [
(b"x-ratelimit-limit", str(self._capacity).encode()),
(b"x-ratelimit-remaining", str(int(decision.remaining)).encode()),
]
async def send_with_headers(message: Message) -> None:
if message["type"] == "http.response.start":
message = {**message, "headers": [*message.get("headers", []), *extra]}
await send(message)
return send_with_headers
def _close_on_shutdown(self, receive: Receive) -> Callable[[], Awaitable[Message]]:
async def receive_and_maybe_close() -> Message:
message = await receive()
if message["type"] == "lifespan.shutdown":
await self.aclose()
return message
return receive_and_maybe_close
async def aclose(self) -> None:
"""Close the Redis pool if this middleware created it."""
if not self._owns_redis:
return
try:
await self._redis.aclose()
except RedisError as exc:
logger.warning("Error closing rate limiter Redis client: %s", exc)
2. How it works
- Pure ASGI middleware, not
BaseHTTPMiddleware. This avoids the extra task and stream wrapping thatBaseHTTPMiddlewareadds. A healthy request costs one SHA-256 hash (about 1µs) plus oneEVALSHAround trip (about 0.2–0.5ms on a LAN), which stays well under the 2ms p50 budget. It still works withapp.add_middleware(...). - The Lua script makes each step atomic. Read, refill, take and write happen in one atomic Redis call with one round trip. Concurrent requests across all 5 instances are therefore serialized per key. Negative elapsed time is clamped, so clock skew between instances can never mint extra tokens.
- A pure
take_tokenfunction mirrors the Lua logic. The in-memory fallback uses it, so both backends behave identically and the math can be unit-tested without Redis. - Fallback works like a circuit breaker. On any
RedisErrororOSError, the limiter logs a WARNING (once per transition), serves from the in-memory bucket, and skips Redis forredis_retry_interval_seconds. This prevents a dead Redis from adding a socket timeout to every request. Recovery is logged at INFO. - Raw keys are never stored or logged. Redis keys and log lines use the SHA-256 of the API key; logs show only its first 12 hex characters as
key_id. - Housekeeping. Idle Redis keys expire after twice the time needed for a full refill. The in-memory store is LRU-capped. If the middleware created the Redis pool, it closes the pool on ASGI lifespan shutdown.
3. Usage
main.py
import logging
from fastapi import FastAPI
from rate_limiter import TokenBucketRateLimiter
logging.basicConfig(level=logging.INFO)
app = FastAPI()
app.add_middleware(
TokenBucketRateLimiter,
capacity=3, # burst size
refill_rate=0.5, # 1 token every 2s
redis_url="redis://localhost:6379/0",
)
@app.get("/health")
async def health() -> dict:
return {"status": "ok"}
@app.post("/convert")
async def convert() -> dict:
return {"status": "queued"}
$ uvicorn main:app
$ for i in 1 2 3 4; do curl -s -X POST -H 'X-API-Key: demo-key' localhost:8000/convert; echo; done
{"status":"queued"}
{"status":"queued"}
{"status":"queued"}
{"error": "rate_limit_exceeded", "retry_after_seconds": 2.0} # with header Retry-After: 2
$ curl -s -X POST localhost:8000/convert
{"error": "missing_or_invalid_api_key"} # HTTP 401
$ curl -s localhost:8000/health
{"status":"ok"} # never throttled
Server log for the rejected request:
INFO:rate_limiter:Rate limit exceeded key_id=2f0a7c1e9b3d remaining_tokens=0.000 retry_after=2.000s backend=redis
4. Tests
test_rate_limiter.py. Install with pip install pytest httpx "fakeredis[lua]". The lua extra is required for EVALSHA. Async tests use anyio's pytest plugin, which ships with FastAPI, so pytest-asyncio is not needed.
import logging
import fakeredis
import httpx
import pytest
from fastapi import FastAPI
from redis.exceptions import ConnectionError as RedisConnectionError
from rate_limiter import TokenBucketRateLimiter
HEADERS = {"X-API-Key": "test-key-123"}
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
class FakeClock:
def __init__(self, start: float = 1_000.0) -> None:
self.now = start
def __call__(self) -> float:
return self.now
def advance(self, seconds: float) -> None:
self.now += seconds
class UnreachableRedis:
"""Stub that behaves like a Redis client whose server is down."""
def register_script(self, _script: str):
async def run(**_kwargs):
raise RedisConnectionError("connection refused")
return run
def build_app(**limiter_kwargs) -> FastAPI:
app = FastAPI()
app.add_middleware(TokenBucketRateLimiter, **limiter_kwargs)
@app.get("/health")
async def health() -> dict:
return {"status": "ok"}
@app.post("/convert")
async def convert() -> dict:
return {"status": "queued"}
return app
def client_for(app: FastAPI) -> httpx.AsyncClient:
return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test")
@pytest.mark.anyio
async def test_burst_then_429_then_refill() -> None:
clock = FakeClock()
app = build_app(capacity=3, refill_rate=1.0,
redis_client=fakeredis.FakeAsyncRedis(), clock=clock)
async with client_for(app) as client:
for _ in range(3):
assert (await client.post("/convert", headers=HEADERS)).status_code == 200
rejected = await client.post("/convert", headers=HEADERS)
assert rejected.status_code == 429
assert rejected.json() == {"error": "rate_limit_exceeded", "retry_after_seconds": 1.0}
assert rejected.headers["retry-after"] == "1"
clock.advance(1.0) # one token refilled
ok = await client.post("/convert", headers=HEADERS)
assert ok.status_code == 200
assert ok.headers["x-ratelimit-remaining"] == "0"
@pytest.mark.anyio
async def test_missing_key_is_401_and_health_is_exempt() -> None:
app = build_app(capacity=1, refill_rate=1.0, redis_client=fakeredis.FakeAsyncRedis())
async with client_for(app) as client:
assert (await client.post("/convert")).status_code == 401
assert (await client.post("/convert", headers={"X-API-Key": " "})).status_code == 401
assert (await client.post("/convert", headers={"X-API-Key": "k" * 257})).status_code == 401
for _ in range(5): # far above capacity, still never limited
assert (await client.get("/health")).status_code == 200
@pytest.mark.anyio
async def test_falls_back_to_memory_and_logs_when_redis_down(caplog) -> None:
app = build_app(capacity=1, refill_rate=0.1,
redis_client=UnreachableRedis(), clock=FakeClock())
caplog.set_level(logging.INFO, logger="rate_limiter")
async with client_for(app) as client:
assert (await client.post("/convert", headers=HEADERS)).status_code == 200
assert (await client.post("/convert", headers=HEADERS)).status_code == 429
messages = [r.getMessage() for r in caplog.records]
assert sum("falling back to in-memory" in m for m in messages) == 1
rejection = next(m for m in messages if "Rate limit exceeded" in m)
assert "backend=memory" in rejection
assert "test-key-123" not in "\n".join(messages) # raw key never logged
def test_rejects_invalid_config() -> None:
with pytest.raises(ValueError):
TokenBucketRateLimiter(lambda *_: None, capacity=0, refill_rate=1.0, redis_url="redis://x")
with pytest.raises(ValueError):
TokenBucketRateLimiter(lambda *_: None, capacity=5, refill_rate=0, redis_url="redis://x")
5. Notes
Assumptions
- 401 for oversized or blank keys. An empty, whitespace-only or over-256-character key returns 401, the same as a missing key. A malformed credential is treated as an authentication failure.
- Logging on fallback. "Log every time it falls back" is read as one WARNING per transition into fallback mode, not one per request. Per-request logging would flood the logs during an outage. Recovery is logged at INFO.
- Rejection log level. Rejections are logged at INFO, one line per rejection, as required.
- Clock. Timestamps come from each instance's wall clock, and NTP sync is assumed. Skew can only delay refills slightly, never grant extra tokens, because elapsed time is clamped at zero. The alternative is Redis
TIMEinside the script; it removes skew entirely but makes tests non-deterministic. - Exempt paths. Exempt paths match the path exactly.
/health/with a trailing slash is not exempt. WebSocket traffic passes through unthrottled. - Test dependency. Tests need
fakeredis[lua]. Theluaextra pulls inlupa, because fakeredis needs it to execute scripts.
Known limitations
- Fallback limits are per instance. During a Redis outage the effective limit becomes N × capacity across N instances, so up to 5× with 5 instances. The WARNING log says so explicitly. After recovery, Redis state is used again, and a client may get a small one-off bonus burst.
- Keys are not authenticated. The limiter does not check whether a key is real. An attacker sending random keys gets a fresh bucket each time. Run real key validation before this middleware, or only count keys that are known to be valid.
- Single Redis instance. Redis is a single point of degradation. Fallback keeps the API up, but limits become per instance.
Improvements for this use case
- Weighted costs and an IP limit. Charge tokens by work done, for example scaled by uploaded file size or page count for document conversion, instead of one token per request; this requires a
costargument to the script. Also add a coarse per-IP bucket for requests with missing or invalid keys, so 401 floods are throttled too. - Metrics and log volume. Replace per-rejection log lines with sampled logs plus a Prometheus counter, labelled by backend and outcome. During an abuse burst at about 500 rps, one INFO line per rejection is a lot of log volume. Also set
max_connectionson the Redis pool to bound connections per instance.
Related prompts
Python Development Specialist
Generates production-ready, fully typed Python code with tests, docstrings, and usage examples to your spec.
SQL Query Optimizer
Diagnoses a slow SQL query and returns an optimized rewrite, index plan, and execution-plan reasoning.
Code Review Expert
Performs a rigorous senior-level code review covering correctness, design, performance, and security with prioritized, actionable fixes.
Algorithm Design Expert
Designs, analyzes, and optimizes algorithms with multiple approaches, Big-O complexity analysis, production code, and tests.