Rate limiting requests and tokens across many servers
- Find which of a provider's limits stops an LLM product first, and how prompt caching moves it
- Write a token bucket, and say what its capacity and its refill rate each control
- Limit tokens as well as requests, when an answer's length isn't known until it ends
- Share one limit across many servers, and decide what happens when the shared store is down
- Answer a limited client with 429 and Retry-After, and keep room for the requests that matter most
A rate limiter for an LLM API, the way the design round asks
OpenAI candidates report rate limiting as a system design question (1 report), a guide lists a distributed rate limiter for the design round and an implementation for coding (2 sources), and an ML engineer candidate had to find the bug in a Django app's rate limiter (1 report). This lesson's practice problem builds the limiter, in three levels:
TokenBucket(capacity, rate), withallow(now, cost)andretry_after(now, cost): a burst, then a steady rate, and when to come back.LLMLimiter(rpm, itpm, otpm), withstart(...)andfinish(...): requests, input tokens and output tokens, all or nothing, with the answer's tokens reserved and the unused ones given back.KeyedLimiter(capacity, rate, global_capacity, global_rate): a bucket for each customer and one for everyone, with no memory kept for customers whose buckets are full.
Call Returns 8 questions in a second, against a burst of 5 True five times, then False retry_afterat 10.5 s, for that customer2.5 s, so the header says 3 startreserving max_tokens of 4,096, under 400,000 a minuteroom for 97 answers a minute keys(now)an hour after the last question0 buckets kept
The lesson follows the outdoor shop's assistant at 120,000 questions a day: the provider's limits, the token bucket, limits on tokens, one limit across many servers, and how many requests run at once. Seven steps end with a small task in the editor.
An LLM product sits between its provider's limits and its own
An LLM product needs two limiters: the provider limits you, and you limit your customers.
The outdoor shop's assistant is the running example: 120,000 questions a day with a peak of 5 a second. Each request carries 1,800 shared tokens of instructions and catalog, a 60-token question, and an answer of about 250 tokens.
Anthropic's docs measure the Messages API's limits in requests per minute (RPM), input tokens per minute (ITPM) and output tokens per minute (OTPM). OpenAI's add per-day limits too. OpenAI says its limits are set for the organization and the project, not the user, and the same holds for Anthropic's.
One of the shop's customers runs a script that asks the assistant 30 questions a second. Who gets the provider's 429 errors?
With the prefix cached, which limit stops the shop first?
A token bucket allows a burst, then a steady rate
Anthropic's docs say the API uses the token bucket algorithm: capacity is replenished continuously up to the maximum, instead of reset at fixed intervals. AWS's API Gateway docs name its two settings. The rate is how fast tokens are added, and the burst is the bucket's capacity.
Each customer gets a bucket. A request spends a token, and the bucket refills at a steady rate up to its capacity.
A customer's bucket holds 5 and refills 10 a minute. They've been quiet for an hour. How many questions can they send at once?
The burst leaves the bucket almost empty. Which of the questions at 4, 8 and 10 seconds get through?
Say no with 429, and say when to come back
RFC 6585 defines 429 Too Many Requests: the user has sent too many requests in a given amount of time. RFC 9110's Retry-After header holds a date or a number of seconds to wait, and Anthropic's docs tell clients to wait that many seconds before retrying. The bucket knows the answer: the missing tokens divided by the refill rate.
# the bucket's tokens at 10.5 s, after the refill
tokens = min(bucket.capacity, bucket.tokens + (10.5 - bucket.last) * bucket.rate)
wait = (1 - tokens) / bucket.rate
print(round(wait, 2), "seconds, so the header says", retry_after_header(tokens, bucket.rate, 1, bucket.capacity))
Retry-After takes whole seconds, and the bucket says 2.5. What goes in the header?
Limit tokens, because one question can cost a hundred times another
Where's my order? takes a 30-token answer. Compare these three tents for winter camping takes 1,500.
Two customers each stay under a limit of 10 questions a minute. One asks where orders are, the other asks for long comparisons. How do their costs compare?
Reserve the answer's tokens, or count them as they're written
An answer's length isn't known until it ends, so providers count it two ways:
- Reserve up front. OpenAI's docs say a request counts as the larger of its max_tokens and an estimate from its character count.
- Count as it's written. Anthropic's docs say output tokens are counted in real time as they're produced, and max_tokens doesn't factor in. Input tokens are estimated at the start and adjusted.
Say the shop's own limiter gave the assistant 400,000 output tokens a minute and reserved max_tokens when each answer started:
OTPM = 400_000
for max_tokens in (4_096, 300):
print(f"reserving max_tokens {max_tokens:>5,}: {OTPM // max_tokens:>5,} answers can start in a minute")
print(f"counting the 250 tokens actually written: {OTPM // 250:,}")
Answers average 250 tokens, but each one reserves a max_tokens of 4,096. How many answers can start in a minute under 400,000?
A request needs room in every bucket
One question spends from three buckets at once: a request, its input tokens and its output tokens. Check all three, then take from all three.
The request bucket has room, so the limiter takes a request from it. Then the output bucket turns out to be short, and the question is denied. What went wrong?
One limit across many servers needs a shared count
The shop runs 5 API servers behind a load balancer. Each could keep its own buckets, holding a fifth of each customer's limit. Envoy's local rate limits work that way: per process, by default.
Here's a script that asks once a second for 10 minutes, against the shop's limit of a burst of 5, then 10 a minute. The first two runs split the limit across 5 servers. The last one shares a single bucket.
import random
def served(route, servers=5, seconds=600):
"""A script asks once a second for 10 minutes. Its limit: a burst of 5, then 10 a minute."""
local = [TokenBucket(5 / servers, 1 / 6 / servers) for _ in range(servers)]
return sum(local[route()].allow(t) for t in range(seconds))
rng = random.Random(7)
print("5 local buckets, requests spread at random:", served(lambda: rng.randrange(5)))
print("5 local buckets, one connection to one server:", served(lambda: 0))
shared = TokenBucket(5, 1 / 6)
print("one shared bucket:", sum(shared.allow(t) for t in range(600)))
One shared bucket lets 104 of the script's requests through. All of them ride one connection, so one server sees every request. About how many get through the 5 local buckets?
One bucket per customer, in Redis, changed in one step
Stripe keeps a bucket for every user and implements its limiters on Redis. Reading the bucket, refilling it, checking and writing it back has to happen as one step.
Two servers read the same customer's bucket at the same moment: 1 token left. Each one lets its question through and writes back 0. How many questions got through?
Decide what happens when the shared store is down
Stripe catches exceptions at every level so that errors fail open and the API stays up. For the shop, failing fully open turns off every customer's limit at once, which is when a script can drain the provider's limit for everyone.
Redis is down for 10 minutes. What should each server's limiter do?
A rate limit counts starts, not what's running
A rate limit says how often requests may start. It says nothing about how many run at once, and LLM requests run for seconds. Little's law links the two: the average number in flight is the arrival rate times the time each one takes. At the shop's peak, 5 questions a second that take 7.82 s each, the figure the latency lesson worked out, put about 39 conversations in flight.
A customer may start 10 agent runs a minute, and each run takes 30 seconds. Using the full rate, how many run at once?
Keep room for the requests that matter
For the shop, chat is critical, and the nightly summary job, a batch of work that can wait, isn't.
The nightly summaries want the whole provider limit, and a customer asks a question at 2 a.m. What keeps the answer fast?
A worked example: rate limits for the shop's assistant
The prompt, from a guide to OpenAI interviews: design a distributed rate limiter (1 source). For the shop, that means limiting every customer of the assistant and keeping the whole shop inside its provider's limits.
1. Clarify. Who gets limited: signed-in customers by account, visitors by IP address. What counts: questions, tokens and runs in flight. How exact it must be: a few percent over for a minute is fine, and a script running for an hour isn't. What a limited customer sees, and how many servers and active customers there are.
A visitor who isn't signed in has no account. What should their bucket be keyed on?
The plan sets each customer's Redis key to expire at the moment its bucket would be full again. Why is deleting it safe?
Why set the shop's own bucket at 90% of the provider's limits, not 100%?
Two counters instead of a bucket
Cloudflare limits with a sliding window counter: last minute's count, weighted by how much of that minute the window still covers, plus this minute's count. Their post works an example: 42 requests last minute and 18 so far this minute, 15 seconds in.
def sliding_estimate(previous: int, current: int, elapsed: float, window: float = 60) -> float:
"""Last window's count, weighted by how much of it still overlaps, plus this window's count."""
return previous * (window - elapsed) / window + current
print(sliding_estimate(42, 18, 15))
With a limit of 50 a minute, does the next request pass?
Four more follow-ups
Four shorter follow-ups come up too: limits over short spans, pacing from the headers, Redis replicas, and separate workspaces.
Limits apply over shorter spans than a minute
Anthropic's docs warn that 60 requests a minute might be enforced as 1 a second.
A nightly job is allowed 60 requests a minute and sends all 60 in the first second. If the limit is enforced as 1 a second, what happens?
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.A token bucket holds 5 and refills 10 a minute. What do those two numbers control?
2.Why do providers limit output tokens and not only requests?
3.A limiter takes a request token, then finds the output bucket short and denies the question. What's the bug?
4.The shop runs 5 servers, each with a fifth of every customer's limit. A customer's requests all arrive on one connection. What happens?
5.The bucket says the next request passes in 2.5 seconds. What should the Retry-After header say?
Practice
Sources (29)
- Rate limits · Anthropic, Claude Platform Docs · Nov 19, 2026
“The rate limits for the Messages API are measured in requests per minute (RPM), input tokens per minute (ITPM), and output tokens per minute (OTPM) for each model class.”
- Rate limits · Anthropic, Claude Platform Docs · Nov 19, 2026
“Start tier Model Maximum requests per minute (RPM) Maximum input tokens per minute (ITPM) Maximum output tokens per minute (OTPM) ... Claude Sonnet 5.5 4,000 2,000,000 400,000”
- Rate limits · Anthropic, Claude Platform Docs · Nov 19, 2026
“The API's default ITPM rate limits count only uncached input tokens.”
- Rate limits · OpenAI API docs · Nov 19, 2026
“Rate limits use metrics such as RPM (requests per minute), RPD (requests per day), TPM (tokens per minute), TPD (tokens per day), IPM (images per minute)”
- Rate limits · OpenAI API docs · Nov 19, 2026
“Rate limits are defined at the organization level and at the project level, not user level.”
- Rate limits · Anthropic, Claude Platform Docs · Nov 19, 2026
“The API uses the token bucket algorithm to do rate limiting. This means that your capacity is continuously replenished up to your maximum limit, rather than being reset at fixed intervals.”
- Throttle requests to your REST APIs for better throughput in API Gateway · Amazon Web Services, API Gateway Developer Guide · Nov 19, 2026
“You can specify a throttling rate, which is the rate, in requests per second, that tokens are added to the token bucket. You can also specify a throttling burst, which is the capacity of the token bucket.”
- RFC 6585: Additional HTTP Status Codes · IETF, RFC Editor · Apr 1, 2012
“The 429 status code indicates that the user has sent too many requests in a given amount of time”
- RFC 9110: HTTP Semantics · IETF, RFC Editor · Jun 1, 2022
“The Retry-After field value can be either an HTTP-date or a number of seconds to delay after receiving the response.”
- Rate limits · Anthropic, Claude Platform Docs · Nov 19, 2026
“If you exceed any of the rate limits, you get a 429 error describing which rate limit was exceeded. When the response has a retry-after header, wait that many seconds before retrying.”
- Rate limits · OpenAI API docs · Nov 19, 2026
“Your rate limit is calculated as the maximum of max_tokens and the estimated number of tokens based on the character count of your request.”
- Rate limits · Anthropic, Claude Platform Docs · Nov 19, 2026
“OTPM rate limits are evaluated in real time as output tokens are produced, counting only the actual tokens generated. The max_tokens parameter does not factor into OTPM rate limit calculations”
- Rate limits · Anthropic, Claude Platform Docs · Nov 19, 2026
“ITPM rate limits are estimated at the beginning of each request, and the estimate is adjusted during the request to reflect the actual number of input tokens used.”
- Local rate limit · Envoy Proxy docs · Nov 19, 2026
“This results in the local rate limits being applied either per Envoy process or per downstream connection. By default the rate limits are applied per Envoy process.”
- Scaling your API with rate limiters · Stripe Blog · Mar 30, 2017
“In our case, every Stripe user has a bucket, and every time they make a request we remove a token from that bucket. We implement our rate limiters using Redis.”
- How we scaled the GitHub API with a sharded, replicated rate limiter in Redis · The GitHub Blog · Apr 5, 2021
“Implement the storage logic in Lua, to guarantee atomicity of operations (this was an improvement over the previous design)”
- Global rate limiting · Envoy Proxy docs · Nov 19, 2026
“Local rate limiting can be used in conjunction with global rate limiting to reduce load on the global rate limit service. For example, a local token bucket rate limit can absorb very large bursts in load that might otherwise overwhelm a global rate limit service.”
- Scaling your API with rate limiters · Stripe Blog · Mar 30, 2017
“This means catching exceptions at all levels so that any coding or operational errors would fail open and the API would still stay functional.”
- Scaling your API with rate limiters · Stripe Blog · Mar 30, 2017
“At Stripe, we operate 4 different types of limiters in production.”
- Scaling your API with rate limiters · Stripe Blog · Mar 30, 2017
“Concurrent request limiters manage resource contention for CPU-intensive API endpoints.”
- Scaling your API with rate limiters · Stripe Blog · Mar 30, 2017
“We always reserve a fraction of our infrastructure for critical requests. If our reservation number is 20%, then any non-critical request over their 80% allocation would be rejected with status code 503.”
- RateLimit header fields for HTTP (draft-ietf-httpapi-ratelimit-headers-11) · IETF HTTPAPI Working Group · May 23, 2026
“This document defines the RateLimit-Policy and RateLimit HTTP header fields for servers to advertise their quota policies and the current service limits, thereby allowing clients to avoid being throttled.”
- How we built rate limiting capable of scaling to millions of domains · Cloudflare Blog · Jun 7, 2017
“rate = 42 * ((60-15)/60) + 18 = 42 * 0.75 + 18 = 49.5 requests”
- How we built rate limiting capable of scaling to millions of domains · Cloudflare Blog · Jun 7, 2017
“It is still very accurate, as an analysis on 400 million requests from 270,000 distinct sources shown: 0.003% of requests have been wrongly allowed or rate limited”
- Rate limits · Anthropic, Claude Platform Docs · Nov 19, 2026
“You might hit rate limits over shorter time intervals. For instance, a rate of 60 requests per minute (RPM) might be enforced as 1 request per second.”
- Rate limits · Anthropic, Claude Platform Docs · Nov 19, 2026
“The anthropic-ratelimit-tokens-* headers display the values for the most restrictive limit currently in effect.”
- Rate limits · OpenAI API docs · Nov 19, 2026
“x-ratelimit-remaining-tokens 149984 The remaining number of tokens that are permitted before exhausting the rate limit.”
- How we scaled the GitHub API with a sharded, replicated rate limiter in Redis · The GitHub Blog · Apr 5, 2021
“replicas don't expire data until they receive instructions to do so from their primaries, and primaries don't expire keys until they're accessed”
- Rate limits · Anthropic, Claude Platform Docs · Nov 19, 2026
“To protect workspaces in your organization from potential overuse, you can set custom spend and rate limits for each workspace.”