Implementing an API rate limiter on a whiteboard takes five minutes. Implementing one that survives a reverse proxy, an IPv6 address spray, and a noisy tenant without locking out legitimate users takes getting four specific details right.
Across Durable Runner, Service Monitor, and Colophon CMS, we hit almost every classic rate-limiter failure—from collapsing every customer into 127.0.0.1 behind Caddy to a global login throttle that rejected 19 of 20 valid logins under noise (the fixes landed, and the reviews found bugs in the fixes).
Here is how to pick the right algorithm, write a bounded token bucket that cannot be OOMed or evicted by an attacker, return proper 429 headers, and split work cleanly between an API gateway and your app.
Pick the right rate-limiting algorithm
| Algorithm | Memory per key | Burst handling | Best fit | Main drawback |
|---|---|---|---|---|
| Fixed window | O(1) (1 counter) | Allows 2× burst across window boundary | Coarse edge caps | Edge-of-minute spikes slip through |
| Sliding window log | O(N) timestamps | Exact | Low-volume sensitive actions (password reset) | High memory under heavy traffic |
| Sliding window counter | O(1) (2 counters) | Smooth approximation | Distributed Redis rate limits | Slightly less intuitive burst semantics |
| Token bucket | O(1) (2 floats) | Controlled burst (capacity) + steady refill_rate | General REST / GraphQL / MCP APIs | Needs atomic update if shared across nodes |
| GCRA (virtual scheduling) | O(1) (1 timestamp) | Smooth burst + exact Retry-After | High-throughput Rust/Go gateways | Slightly harder to read at a glance |
For most APIs, token bucket is the sweet spot: O(1) memory per key, natural support for short legitimate bursts (e.g., a browser loading 10 assets at once), and an exact Retry-After calculation when empty.
A production-safe bounded token bucket (with overflow protection)
Most tutorial rate limiters use an unbounded dict or an LRU cache. Both fail under attack:
- Unbounded map: An attacker spraying random IPs exhausts RAM and OOM-kills your server.
- LRU eviction: An attacker sprays fresh IPs to evict their own throttled bucket and reset their rate limit to full.
The pattern we use in Durable Runner caps the map (MAX_KEYS), reclaims only idle full buckets when full, and routes any remaining unknown key into a shared overflow bucket so active abusers are never evicted and memory stays flat. It also normalizes IPv4-mapped IPv6 (::ffff:...) and masks IPv6 clients to /64 so one residential subnet cannot mint 2^64 fresh buckets.
import ipaddress
import math
import time
from dataclasses import dataclass
def normalize_client_key(raw_ip: str) -> str:
"""Unwrap IPv4-mapped IPv6 and bucket IPv6 by /64 to stop /128 address sprays."""
addr = ipaddress.ip_address(raw_ip.strip())
if isinstance(addr, ipaddress.IPv6Address):
if addr.ipv4_mapped is not None:
return f"v4:{addr.ipv4_mapped}"
net = ipaddress.IPv6Network(f"{addr}/64", strict=False)
return f"v6:{net.network_address}/64"
return f"v4:{addr}"
@dataclass
class Bucket:
tokens: float
last_refill: float
class BoundedTokenBucketLimiter:
def __init__(self, rate_per_sec: float, burst: float, max_keys: int = 65_536, idle_ttl: float = 60.0):
self.rate = rate_per_sec
self.burst = burst
self.max_keys = max_keys
self.idle_ttl = idle_ttl
self.buckets: dict[str, Bucket] = {}
self.overflow = Bucket(tokens=burst, last_refill=time.monotonic())
def _consume(self, bucket: Bucket, now: float, cost: float) -> tuple[bool, int]:
elapsed = max(0.0, now - bucket.last_refill)
bucket.tokens = min(self.burst, bucket.tokens + elapsed * self.rate)
bucket.last_refill = now
if bucket.tokens >= cost:
bucket.tokens -= cost
return True, 0
retry_after = math.ceil((cost - bucket.tokens) / self.rate)
return False, max(1, retry_after)
def _reclaim_idle(self, now: float) -> None:
stale = [
k for k, b in self.buckets.items()
if (now - b.last_refill) >= self.idle_ttl
and (b.tokens + (now - b.last_refill) * self.rate) >= self.burst
]
for k in stale:
del self.buckets[k]
def allow(self, key: str, cost: float = 1.0, now: float | None = None) -> tuple[bool, int]:
now = time.monotonic() if now is None else now
bucket = self.buckets.get(key)
if bucket is None:
if len(self.buckets) >= self.max_keys:
self._reclaim_idle(now)
if len(self.buckets) >= self.max_keys:
return self._consume(self.overflow, now, cost)
bucket = Bucket(tokens=self.burst, last_refill=now)
self.buckets[key] = bucket
return self._consume(bucket, now, cost)
Notice two small details that prevent real incidents:
time.monotonic(), never wall-clocktime.time()—an NTP clock jump backward should never freeze or break refill math.- Cost parameter (
cost): expensive routes (search, PDF export, LLM calls) can chargecost=5against the same tenant bucket while cheap reads chargecost=1.
Return clean 429 responses (so good clients back off)
When allow() returns (False, retry_after), respond immediately with HTTP 429 Too Many Requests and machine-readable backoff headers:
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 4
RateLimit-Limit: 60
RateLimit-Remaining: 0
RateLimit-Reset: 4
{"error":"rate_limited","retry_after_seconds":4}
Always return 429 before touching PostgreSQL or allocating large buffers—if your rate limiter still runs expensive middleware or parses a 10 MB body first, an attacker still saturates CPU and RAM.
API gateway rate limiting vs. in-app rate limiting
| Layer | What it knows | What to enforce here |
|---|---|---|
| Edge / API Gateway (Cloudflare, Caddy, Nginx, AWS API Gateway) | TCP peer IP, TLS fingerprint, path, connection count | Coarse per-IP DDoS ceilings, connection caps, body-size limits |
| Application layer (Rust/Go/Node/Python server) | Authenticated user ID, tenant ID, plan tier, endpoint cost, MCP tool permissions | Per-tenant isolation, per-account login throttles, per-session AI/agent tool budgets |
Never put only a global or per-IP limit on a multi-tenant API. In our noisy-neighbor isolation drill, isolating by tenant/agent key kept legitimate traffic healthy while refusing 600 noisy requests/sec. Conversely, behind a reverse proxy like Caddy or Cloudflare, never key on CF-Connecting-IP or X-Forwarded-For unless the TCP peer is in an explicit TrustedProxies list (why every rate limiter behind Caddy saw 127.0.0.1).
Four tests that prove your rate limiter works
- Trusted vs. untrusted proxy header test: Send a spoofed
CF-Connecting-IPfrom an untrusted peer and verify it is ignored. - Tenant isolation test: Exhaust Tenant A’s bucket until it receives
429, then verify Tenant B still receives200. - Table-full spray test: Fill
max_keyswith random IPs while keeping one abusive key active; verify the abusive key stays throttled and memory stays flat. - IPv6
/64rotation test: Rotate the host bits inside2001:db8:1:2::/64and confirm every address hits the same bucket.
For the complete set of surrounding API guards, see our API security checklist with concrete tests.
Frequently asked questions
When do I need Redis for rate limiting instead of in-memory buckets? Use in-memory buckets when running a single instance (or when approximate per-node enforcement is acceptable at high throughput with zero network hops). Move shared counters to Redis (using an atomic Lua script for token-bucket or sliding-window updates) when you run multiple stateless API replicas and need strict global quotas per user or API key.
Why not use one global rate limit on /login?
A single global bucket lets one attacker (or noisy bot) consume every login slot and lock out every legitimate customer on your platform. Key login throttles on (normalized_ip, normalized_account) plus a higher per-IP ceiling.
How should rate limiting fail if Redis goes down? Decide per endpoint before an outage happens: fail open (with a local in-memory fallback bucket) for ordinary read routes so a cache blip doesn’t take down the site, and fail closed (or fall back to strict local limits) on high-risk endpoints like password resets, OTP checks, or paid AI generation.