Rate limiting
Cap how much each client can consume per unit of time so one tenant can't starve the rest; for LLMs, meter tokens per minute, not just requests, and answer excess with 429 plus Retry-After.
Analogy: An arcade card whose credits refill every minute: you can spend a burst at once, but once it's empty you wait for the refill. Big games cost more credits, like long prompts cost more tokens.
How it works
- Token bucket is the default: capacity B allows bursts, refill rate r sets the average.
- A fixed window is cheap but lets up to 2× the limit through around a boundary.
- With many gateway replicas, keep counters in Redis; local limits on N replicas become N× the limit.
- Reserve estimated input +
max_tokenswhen admitting an LLM call, then refund the unused part. - Map plans to bucket sizes per tenant, so one noisy script hits 429s while others never notice.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your LLM gateway runs 8 replicas behind a load balancer, each enforcing a 100 RPM per-tenant limit with in-memory counters. One tenant sustains ~800 RPM without a single 429. Best fix?
Go deeper
Full explanation
A rate limiter decides, per request, whether a client is within its allowance, and rejects or queues the rest. It protects capacity, cost and fairness between tenants.
Algorithms:
- Token bucket: capacity B, refilled at r tokens/s; each request spends tokens. Bursts up to B, average r. The default choice; Anthropic documents using it for its API limits.
- Leaky bucket: a queue drained at a fixed rate. Smooth output, no bursts.
- Fixed window: one counter per minute. Cheap, but up to 2× the limit passes around a boundary.
- Sliding window log: every timestamp stored. Exact; memory grows with traffic.
- Sliding window counter: weights the previous window's count by its overlap. Near-exact with two counters.
Where: at the edge, in the API gateway or LLM gateway, keyed by API key or tenant. With many gateway replicas, keep counters in Redis behind an atomic Lua script; otherwise each replica enforces its own copy and the real limit becomes N×.
LLM twist: one 100k-token request costs as much as hundreds of short ones, so limit tokens per minute (TPM) as well as RPM, plus concurrent streams. Reserve estimated input + max_tokens on admission, then refund the unused part. Plans map to bucket sizes per tenant (Multi-tenancy patterns). Reject with 429 + Retry-After so clients back off precisely.
Code Distributed token bucket in Redis, charged in LLM tokens
import redis
r = redis.Redis()
# Atomic inside Redis: refill by elapsed time, then try to spend `cost`.
# Redis TIME (not the caller's clock) so skew between gateway replicas can't matter.
TOKEN_BUCKET = r.register_script("""
local cap, rate, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local t = redis.call('TIME')
local now = tonumber(t[1]) + tonumber(t[2]) / 1e6
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or cap
tokens = math.min(cap, tokens + (now - (tonumber(b[2]) or now)) * rate)
local ok = tokens >= cost
if ok then tokens = tokens - cost end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', KEYS[1], math.ceil(cap / rate) + 60)
if ok then return 0 end
return math.ceil((cost - tokens) / rate) -- seconds until enough refill
""")
def admit(tenant: str, input_tokens: int, max_tokens: int, tpm: int) -> None:
# Reserve the worst case now; refund unused output tokens after the call
cost = input_tokens + max_tokens
if cost > tpm:
raise RequestTooLarge() # could never fit: 4xx, not a retryable 429
wait_s = TOKEN_BUCKET(keys=[f"tpm:{tenant}"], args=[tpm, tpm / 60, cost])
if wait_s:
raise TooManyRequests(retry_after=wait_s) # -> HTTP 429 + Retry-AfterReal example
A B2B assistant serves 400 tenants from a provider account with 2M TPM. One tenant's nightly script fires 300 requests of 50k tokens in a minute: 15M tokens, 7.5× the whole account's budget. Without per-tenant limits, every customer starts getting provider 429s. With a Redis token bucket per tenant (free 20k TPM, pro 200k, enterprise 1M), the script gets your gateway's 429 + Retry-After after its first few calls, and the other 399 tenants never notice.
Trade-offs +3 · −3
+ You gain
- Isolates tenants: one noisy client can't exhaust shared capacity or the provider quota.
- Caps cost: a token budget bounds what a runaway agent loop can spend.
- Turns overload into a clear, retryable 429 instead of timeouts for everyone.
− You pay
- A central counter adds a network round-trip and a dependency on the hot path.
- An LLM call's token cost is unknown until it finishes; you must estimate and reconcile.
- Static limits waste capacity off-peak and still allow overload when many tenants peak together.
Use it when
Any public or multi-tenant API, every LLM gateway, and in front of expensive dependencies whose quota you share, such as provider TPM or a GPU pool.
Avoid it when
As your only overload defense: it caps clients, not system load, so pair it with load shedding and autoscaling. For internal batch work, a queue smooths load better than rejections.
Numbers to know 5
- HTTP 429 Too Many Requests is defined in RFC 6585; send Retry-After so clients know when to return.
- A fixed window can admit up to 2× the limit in a burst straddling the boundary.
- LLM providers limit RPM and TPM separately; Anthropic splits input (ITPM) and output (OTPM) tokens.
- Token bucket sizing: refill r = limit / 60 per second; capacity B = the largest burst you accept.
- N replicas each enforcing a local limit L give an effective limit of N × L.
Common pitfalls 4
- Limiting only requests per minute: one 100k-token call uses more tokens than 500 typical chat turns.
- In-memory counters per instance behind a load balancer: the limit silently scales with the replica count.
- Failing closed when Redis is down: the limiter becomes the outage. Fail open to a conservative local limit.
- Rejecting without Retry-After or remaining-quota headers: clients guess and retry immediately.
Interview questions 3
Answer out loud first, then reveal.
Design rate limiting for a multi-tenant LLM API.Show answer
I enforce it at the gateway, keyed by tenant, with token buckets in Redis updated by an atomic Lua script. Each plan sets three limits: requests per minute, tokens per minute and concurrent streams. On admission I reserve estimated input plus max_tokens and refund the difference when the response ends. Over-limit requests get 429 with Retry-After and remaining-quota headers. A separate global bucket keeps the sum under our provider quota. If Redis fails, I fail open to a conservative local limit rather than block every customer.
Token bucket or sliding window?Show answer
Token bucket by default: two numbers per key, O(1), and it models what I want, a sustained rate with a bounded burst. It also fits LLM limits naturally, because a request spends its token count. I'd use a sliding window counter if the contract is literally "N per rolling minute" and I need near-exact enforcement for billing or abuse. I avoid fixed windows for anything strict, since a client can double the limit across the boundary, and sliding logs at scale, since memory grows with traffic.
What's the difference between rate limiting and load shedding?Show answer
Rate limiting enforces a per-client allowance whether or not the system is busy; it's about fairness and contracts. Load shedding looks at the server's own state, queue depth or KV-cache use, and drops or defers the lowest-priority work when overloaded, even from clients within quota. I need both: limits stop one tenant from monopolizing, shedding protects the system when everyone is within quota but peaks at once. Stripe describes running both layers for exactly this reason.