Rate Limiting When Requests Aren't Equal: Token Buckets, Sliding Windows and LLM Traffic
Classic rate limiting counts requests. That works until one request costs a hundred times more than the next, which is exactly what LLM-backed endpoints look like. A tour of the four rate limiting algorithms worth knowing, what each gets wrong, and how to limit by cost instead of by count, with a Redis token bucket you can drop into a Spring service.
- #backend
- #distributed-systems
- #redis
- #llm
- #api-design
A rate limit that says "100 requests per minute" assumes requests are roughly the same size. For most APIs that's close enough. A GET /orders/42 and a GET /orders/43 cost about the same.
Now put a language model behind an endpoint. One request asks for a one-line summary. The next pastes in a 60-page contract and asks for a detailed comparison. Both are "one request". One of them costs a couple of hundred tokens, the other costs tens of thousands. Counting them the same is like a restaurant pricing by number of orders instead of what's on the plate. Somebody is going to order the whole menu.
So this post covers two things: the four classic algorithms (because you still need them), and how to switch from counting requests to counting cost.
The four algorithms, quickly
1. Fixed window
Count requests in the current minute. Reset the counter when the minute changes. In Redis it's INCR plus EXPIRE, and you can write it in five lines.
The flaw is the edge. A client can send 100 requests at 12:00:59 and another 100 at 12:01:00. That's 200 requests in two seconds, and your limit said 100 per minute. Fixed windows are fine for "stop obvious abuse" and bad for "protect a fragile downstream".
2. Sliding window log
Store a timestamp for every request. To check the limit, count the timestamps in the last 60 seconds. It's perfectly accurate and has no edge problem.
The flaw is memory. You store one entry per request, per client. At low volume, lovely. At high volume, you've built a second database whose only job is remembering when people clicked things.
3. Sliding window counter
The compromise most production limiters use. Keep counts for the current and previous fixed windows, then estimate:
estimate = current_count + previous_count × (time left in current window / window size)If you're 15 seconds into a minute, you take 75% of the previous minute's count plus all of this minute's. It's an approximation, but a good one, and it costs two counters per client instead of a list.
4. Token bucket
Each client has a bucket that holds up to capacity tokens and refills at a steady rate. Each request removes tokens. If there aren't enough, the request is rejected (or waits).
Two numbers, two meanings:
- Capacity is how big a burst you allow.
- Refill rate is the long-run average you allow.
That separation is why token buckets are the usual choice for APIs: you can say "average 10 per second, but bursts of 50 are fine", which matches how real clients behave. (A leaky bucket is the close cousin that smooths output to a fixed rate. Same idea, used more for shaping traffic than for rejecting it.)
The key insight: a token bucket doesn't care what a token is
This is what makes token buckets useful for LLM traffic. Nothing says one request must cost one token. A request can take as many tokens as it costs.
So instead of "100 requests per minute", you say "50,000 model tokens per minute", and each request removes its actual cost from the bucket. The one-line summary takes 200. The contract comparison takes 30,000. The bucket enforces fairness in the unit that matters: money and GPU time.
The same trick works outside AI. A bulk export endpoint can cost 50 tokens while a single read costs 1. A search with ten filters can cost more than a search with one. Weighted limits let one limiter protect a service with very uneven endpoints.
The awkward part: you don't know the cost yet
With LLMs, you know the input size when the request arrives, but you don't know how many output tokens the model will produce until it's done. So you can't charge the exact cost up front.
The usual approach is reserve, then reconcile:
- Estimate the cost on arrival: input tokens plus the request's
max_tokens(the most output it can produce). - Reserve that much from the bucket. If the bucket can't cover it, reject with 429.
- Call the model.
- Reconcile: the response tells you the actual token usage. Refund the difference between the reservation and the real cost.
Reserving the maximum is pessimistic on purpose. It means a burst of big requests can't all sneak in on optimistic estimates and blow through the limit together. The refund afterwards keeps it fair.
One more reason to set max_tokens on every call: without it, your worst-case reservation is "whatever the model feels like", and that's not a number you can rate limit.
A Redis token bucket with cost
For anything running on more than one instance, the bucket has to live somewhere shared. Redis with a Lua script is the standard answer, because the script runs atomically. No two instances can read the same balance and both spend it.
-- KEYS[1] = bucket key
-- ARGV[1] = capacity, ARGV[2] = refill per second
-- ARGV[3] = now (ms), ARGV[4] = cost
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
-- refill for the time that has passed
tokens = math.min(capacity, tokens + (now - ts) / 1000 * rate)
local allowed = 0
if tokens >= cost then
-- min() caps refunds (negative cost) at capacity
tokens = math.min(capacity, tokens - cost)
allowed = 1
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate * 1000) + 1000)
-- how long until enough tokens exist for this cost
local wait_ms = 0
if allowed == 0 then
wait_ms = math.ceil((cost - tokens) / rate * 1000)
end
return { allowed, wait_ms }Calling it from Spring with StringRedisTemplate:
public RateDecision tryConsume(String tenantId, long cost) {
List<Long> result = redis.execute(
tokenBucketScript,
List.of("rl:" + tenantId),
String.valueOf(capacity),
String.valueOf(refillPerSecond),
String.valueOf(System.currentTimeMillis()),
String.valueOf(cost));
return new RateDecision(result.get(0) == 1, result.get(1));
}The refund step is the same script with a negative cost. A negative cost always passes the check, and the math.min on that line stops a refund from overfilling the bucket.
One detail that saves a debugging afternoon: pass the time in from one clock, or better, use Redis's own TIME inside the script. If your app instances disagree about what time it is, the refill math disagrees with them.
Tell the client what happened
A 429 with no information makes clients guess, and guessing clients retry immediately, which is the opposite of what you want.
At minimum, return:
429 Too Many RequestsRetry-Afterwith the seconds until there's enough budget. The script above already calculates it.
There's also an IETF draft for standard RateLimit headers that describe the policy and remaining quota. It's still a draft, so treat it as a nice extra rather than something every client will understand. Retry-After is the one everybody already knows.
Where to put the limits
One limiter is rarely enough. A sensible layering:
- Per-tenant limits, so one customer can't use everyone's capacity.
- Per-endpoint or per-capability limits, so a cheap feature isn't starved by an expensive one.
- A global limit set below your provider's quota, so you hit your own wall before you hit theirs. Getting rate limited by your own service is mildly embarrassing. Getting rate limited by your model provider means every tenant is down at once.
- A concurrency limit on top for long-running calls. Token buckets limit throughput, not how many slow requests are in flight at the same time. Streaming responses that each take 40 seconds can pile up even when the token rate looks fine.
Choosing, in one table
| Situation | Use |
|---|---|
| Stop obvious abuse, simplicity matters | Fixed window |
| Exact limits, low volume | Sliding window log |
| General API limits at scale | Sliding window counter |
| Allow bursts, control average | Token bucket |
| Requests vary widely in cost | Token bucket with weighted cost |
| Long-running calls | Concurrency limit, alongside one of the above |
The takeaway
Counting requests only works when requests cost roughly the same, and LLM requests miss that by orders of magnitude. The four classic algorithms still earn their place: a fixed window for stopping obvious abuse, a sliding window counter for general limits at scale. But the token bucket is the one that adapts, because it separates burst size from long-run rate and never asked what a token was in the first place. Let each request take as many tokens as it costs and the same limiter protects a chat endpoint, a bulk export and a ten-filter search.
The catch with models is that you only learn the real cost after you've paid it. So reserve the worst case on arrival, input plus max_tokens, and refund the difference once the response reports actual usage. Keep the bucket in Redis behind one atomic Lua script so instances can't spend the same balance twice, return Retry-After so clients stop guessing, and layer per-tenant, per-feature, global and concurrency limits, because a token rate says nothing about how many 40-second streams are open at once.
Rate limiting was never really about requests. It was always about protecting something expensive. With LLMs, the expensive thing finally has a unit you can count.
/share

Kishore K Sharma
Module Lead | Senior Full Stack Engineer | Java · Spring Boot · Distributed Systems · AWS | Building Scalable Cloud-Native Platforms
Available for contract work and remote full-time roles. See what I take on.
/seen in production