- What: LLM token rate limiting means admitting requests by tokens, not request count, before they reach the provider.
- Why it matters: You only learn a request’s real token cost after it finishes, so counting afterwards lets tenants overrun your shared limit.
- What to do: Reserve an estimate before the call, then reconcile against the
usageobject and refund the difference. - Key stat: OpenAI counts the larger of
max_tokensand the estimated tokens against your limit, per its rate limits guide.
LLM token rate limiting gives every tenant a token bucket measured in tokens per minute. Before each call, the gateway reserves estimated input tokens plus expected output. After the call, it reads the real usage and refunds or debits the difference. This keeps shared provider limits safe without wasting the capacity a worst-case reservation would lock up.
LLM token rate limiting is a way of controlling access to a language model API by the number of tokens consumed per time window (tokens per minute, or TPM) rather than by requests alone. Because the output length is unknown until generation ends, token limiters usually reserve an estimate at admission time and correct it once the provider reports actual usage.
LLM token rate limiting is the part of an AI gateway that most teams get wrong on the first try. A request counter is easy: one request, one unit. Tokens are not. A 50-token question and a 40,000-token RAG prompt look identical to a requests-per-minute limiter, yet one of them can eat most of your minute. Providers already meter you on tokens: Anthropic enforces requests, input tokens and output tokens per minute for each model class. If several tenants, features or agents share one API key, you need your own token limiter in front of theirs.
The hard part is timing. You know the input size before the call, but the output size only arrives in the final usage block. Count too late and tenants overrun the shared limit. Count the worst case and you throttle traffic that would have fit. This guide shows the reserve-and-reconcile design that fixes both, the provider differences that change the maths, a Redis Lua script we ran, and a Node.js simulation with the raw numbers.
Why does LLM token rate limiting need more than a request counter?
A request counter treats every call as the same cost, but LLM calls vary in token cost by orders of magnitude. OpenAI’s guide notes that limits can be hit on RPM, RPD, TPM or TPD, whichever runs out first. Its own example: 20 tiny requests fill a 20 RPM limit long before a 150k TPM limit is touched.
The reverse failure hurts more in practice. A few long-context requests can drain TPM while RPM looks healthy. Anthropic also warns that a 60 RPM limit might be enforced as 1 request per second, so short bursts fail even under the per-minute number.
Provider limits are also shared at the wrong level for a multi-tenant app. OpenAI sets limits at the organization and project level, not user level. One noisy customer can therefore 429 everyone else on the same project. Stripe’s engineering team describes the same problem for classic APIs: one user’s spike should not take the API down for everyone else.
If you have not built a token bucket before, start with our rate limiter system design guide on token bucket versus sliding window. This post builds on it for the variable-cost case.
How do OpenAI and Anthropic count tokens against rate limits?
They count differently, and your gateway’s cost function must copy the provider it fronts. The table below lists the documented rules that change a reservation.
| Behaviour | OpenAI | Anthropic (Claude API) |
|---|---|---|
| Token limit dimensions | TPM and TPD, plus RPM and RPD | Separate ITPM and OTPM, plus RPM |
Does max_tokens count up front? |
Yes: the larger of max_tokens and the character-based estimate |
No: max_tokens does not factor into OTPM |
| Output counting | Reserved via the estimate | Counted in real time as tokens are produced |
| Cached prompt tokens | Not stated in the rate limits guide | cache_read_input_tokens do not count toward ITPM on most models |
| Algorithm | Not stated | Token bucket, continuously replenished |
| Failed requests | Unsuccessful requests count toward the per-minute limit | Not stated |
| Growth limits | Above 1M TPM, grow by no more than 50% every 15 minutes | Ramp limits return ramp_limit_exceeded |
Two rules matter most. First, OpenAI’s guide says your rate limit is calculated as the maximum of max_tokens and the estimated token count, and recommends setting max_tokens close to the expected response size. A lazy max_tokens: 16000 on every call burns limit you never use.
Second, Anthropic’s docs say OTPM counts only the actual tokens generated, and cache reads skip ITPM. Their worked example: a 2,000,000 ITPM limit with an 80 percent cache hit rate can process 10,000,000 total input tokens per minute. If your gateway counts cached tokens anyway, it throttles Claude traffic five times too early in that scenario.
What is the reserve-and-reconcile pattern?
Reserve-and-reconcile takes an estimated token cost from the tenant’s bucket before the call, then corrects it once real usage is known. It is the same idea as a card pre-authorisation: hold an amount, then settle the real charge. Anthropic does something similar internally: ITPM is estimated at the beginning of each request and adjusted during the request.
- Estimate input. Count prompt tokens locally or with the provider’s counter. Anthropic’s token counting endpoint is free and has limits separate from message creation.
- Estimate output. Use
max_tokensfor OpenAI. For Anthropic, use a per-route expected output, such as your p95. - Reserve atomically. Take
input + outputfrom the tenant bucket. If it does not fit, return 429 with a computedRetry-After. - Call the provider. Keep the reservation for the whole call, including streaming.
- Reconcile. Read
usageand give backreserved − actual. A negative value is a debit, so overruns are still paid for. - Refund on failure. If the call failed before any tokens were generated, refund in full.
One counterintuitive property makes this safe. With a token bucket, a reservation leaked by a crashed worker is not lost forever. The bucket refills continuously, so the leak heals within one window. A concurrency semaphore has no such healing and needs leases with TTLs, which is why Stripe tracks in-flight requests separately in its concurrent requests limiter.
How much does reconciliation matter? Our Node.js simulation
It matters a lot: in our simulation, reconciling doubled throughput compared with reserving the worst case. We ran a small discrete-event simulation on Node.js v22.23.5 in the NexGismo sandbox. It is a model, not a benchmark of any real provider. The script is included in this post’s review files.
Setup: 2,400 requests over 600 seconds (4 per second), input 300–1,799 tokens, skewed output with a mean of about 400 tokens, max_tokens: 2000, 2–10 s latency. The simulated upstream is a 100,000 tokens/minute bucket that reserves input + max_tokens and refunds after completion. Mean actual cost was 1,457 tokens per request. Mean reserved cost was 3,044.
| Gateway strategy | Admitted | Upstream 429s | Rejected at gateway | Served tokens/min |
|---|---|---|---|---|
| No token limiter | 836 | 1,564 (65.2%) | 0 | 108,340 |
| Count actual usage after the call | 836 | 1,564 (65.2%) | 0 | 108,340 |
| Reserve worst case, never refund | 399 | 0 | 2,001 | 46,094 |
| Reserve and reconcile | 836 | 0 | 1,564 | 108,340 |
Three results stand out. Counting after the call behaved exactly like having no limiter. The gateway only saw actual usage, so its bucket never ran dry while the upstream was rejecting 65% of calls. Worst-case reservation stopped every 429 but served 57% fewer tokens. Reserve-and-reconcile kept full throughput with zero upstream 429s.
The rejected-at-gateway number is the point. Those 1,564 requests were refused locally in microseconds, with an exact Retry-After, instead of hitting the provider. That matters because OpenAI counts unsuccessful requests toward the per-minute limit. Our model did not charge failed calls, so the no-limiter rows are optimistic. Pair local rejection with the backoff rules in our retry storm prevention guide so clients do not hammer the gateway either.
How do you implement LLM token rate limiting in Node.js?
Wrap every provider call in a function that reserves, calls, and reconciles in a finally block. The cost function is per provider, following the table above. We ran this module on Node.js v22.23.5 with an in-memory bucket and a fake clock.
// In-memory version for tests; in production, back tryTake/give with the Redis script.
export class TokenBucket {
constructor(perMinute, now = () => Date.now()) {
this.cap = perMinute; this.level = perMinute; this.now = now; this.ts = now();
}
#refill() {
const t = this.now();
this.level = Math.min(this.cap, this.level + (t - this.ts) * this.cap / 60_000);
this.ts = t;
}
tryTake(n) { this.#refill(); if (this.level < n) return false; this.level -= n; return true; }
give(n) { this.#refill(); this.level = Math.min(this.cap, this.level + n); } // n < 0 = debit
}
// How each provider counts a request against its token limits.
const COST = {
// OpenAI: limit uses max_tokens up front, so reserve it.
openai: {
reserve: (r) => r.inputEstimate + r.maxTokens,
actual: (u) => u.input_tokens + u.output_tokens,
},
// Anthropic: OTPM counts generated tokens only; cache reads skip ITPM.
anthropic: {
reserve: (r) => r.uncachedInputEstimate + r.expectedOutput,
actual: (u) => u.input_tokens + (u.cache_creation_input_tokens ?? 0) + u.output_tokens,
},
};
export async function callWithBudget(bucket, provider, req, send) {
const reserved = COST[provider].reserve(req);
if (reserved > bucket.cap) { // can never fit: fail fast, don't retry
const err = new Error('request_larger_than_tenant_budget');
err.status = 400;
throw err;
}
if (!bucket.tryTake(reserved)) {
const err = new Error('tenant_token_budget_exceeded');
err.status = 429;
err.retryAfterSeconds = Math.ceil(((reserved - bucket.level) * 60) / bucket.cap);
throw err;
}
let used = 0;
try {
const res = await send();
used = COST[provider].actual(res.usage);
return res;
} catch (err) {
used = err.usage ? COST[provider].actual(err.usage) : 0; // partial stream usage, if any
throw err;
} finally {
bucket.give(reserved - used); // refund the unused part (or debit an overrun)
}
}
Our test run printed the following. The Anthropic call overran its 800-token output estimate, so the bucket was debited the extra 300 tokens. Its 50,000 cache-read tokens were ignored, as the docs specify.
$ node test_gateway.mjs
after openai call, level = 8520
after anthropic call (overrun, cache reads ignored), level = 7040
rejected: 400 request_larger_than_tenant_budget
rejected: 429 tenant_token_budget_exceeded retryAfter 6 s; level = 7040
upstream error, full refund; level = 7040
30 s later, level = 10000
Notice the 400 response. A request whose reservation exceeds the bucket’s capacity can never succeed, so retrying it is pointless. Trim it first; our guide to LLM context length errors in Node.js covers token counting and history trimming.
The Redis Lua script for shared buckets
With more than one gateway instance, keep the bucket in Redis and update it in one script. Redis guarantees atomic execution of scripts, so no other client can interleave between the read and the write. The same script handles reserve (positive cost) and refund (negative cost).
-- KEYS[1] = bucket key, ARGV[1] = capacity (tokens/min), ARGV[2] = cost (negative = refund)
local cap = tonumber(ARGV[1])
local cost = tonumber(ARGV[2])
local t = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
local s = redis.call('HMGET', KEYS[1], 'level', 'ts')
local level = tonumber(s[1]) or cap
local ts = tonumber(s[2]) or now
level = math.min(cap, level + (now - ts) * cap / 60000)
local ok = 0
if cost <= 0 or level >= cost then
level = math.min(cap, level - cost)
ok = 1
end
redis.call('HSET', KEYS[1], 'level', level, 'ts', now)
redis.call('PEXPIRE', KEYS[1], 120000)
return {ok, math.floor(level)}
The script reads the clock with Redis TIME rather than trusting each gateway’s clock. That is allowed because effects replication has been the default since Redis 5.0. We ran it with fakeredis 2.40.0 (Python 3.10.12, Lua via lupa), not a live Redis server:
$ python3 test_lua.py
reserve 3044 -> [1, 96956]
after 32 reserves, next reserve -> [0, 2602]
refund 1587 -> [1, 4189]
reserve again -> [1, 1145]
What are the gotchas in LLM token rate limiting?
Most production bugs come from estimates drifting away from what the provider actually counts. Watch for these.
- Tokenizer changes. Anthropic says Claude 4.7 and later models produce approximately 30 percent more tokens for the same text. Re-measure estimates whenever you switch models.
- Counts are estimates. The token counting docs state the count might differ by a small amount from actual usage. Reconciliation absorbs this.
- Rounded headers. Anthropic’s
anthropic-ratelimit-tokens-remainingheader is rounded to the nearest thousand. Use headers to calibrate, not as your source of truth. - Cancelled streams. If a client disconnects, reconcile with the partial usage you received, or refund the reservation minus input. Do not leave the full reservation held.
- Cache-aware costs. For Claude, charge
input_tokens + cache_creation_input_tokens, not total input. Pairing this with a semantic cache for LLMs cuts token spend further. - Fail-open decisions. Stripe advises that limiter bugs or a Redis outage should fail open, and that each limiter is dark-launched first. For LLM spend, consider failing open on rate but keeping a hard daily budget.
The NexGismo verdict: If more than one tenant or feature shares a provider key, build reserve-and-reconcile from day one. Counting after the call gives a false sense of safety, and worst-case reservation wastes about half your capacity. My recommendation: one bucket per tenant per provider limit, a provider-specific cost function, and a Redis script for shared state.
- LLM token rate limiting must meter tokens, because request counts hide cost differences of several orders of magnitude.
- OpenAI counts the larger of
max_tokensand the estimated tokens against TPM, so oversizedmax_tokenswastes limit. - Anthropic counts output tokens as they are generated and excludes cache reads from ITPM on most models.
- Counting usage only after a call let 65.2% of requests hit upstream 429s in our simulation.
- Reserve-and-reconcile matched full throughput with zero upstream 429s; worst-case reservation served 57% fewer tokens.
- A token bucket heals leaked reservations within one refill window, so crashed workers do not drain capacity permanently.
Frequently Asked Questions
What is TPM in LLM rate limits?
TPM means tokens per minute: the number of tokens an API key, project or organization may process each minute. OpenAI applies TPM alongside requests per minute, while Anthropic splits it into input tokens per minute (ITPM) and output tokens per minute (OTPM). Whichever limit runs out first triggers an HTTP 429 response, so a gateway should track tokens as well as request counts.
Does max_tokens count toward rate limits?
It depends on the provider. OpenAI’s rate limits guide says the limit uses the larger of max_tokens and the estimated token count, so an oversized max_tokens reduces how many requests fit. Anthropic’s documentation says max_tokens does not factor into OTPM, because output tokens are counted as they are generated. Set your gateway reservation to match the provider you call.
How do you rate limit LLM API calls per user?
Give each user or tenant its own token bucket, stored in Redis for multi-instance gateways. Before each call, reserve the estimated input tokens plus expected output. After the call, read the usage object and refund or debit the difference. Reject requests that do not fit with HTTP 429 and a Retry-After value computed from the bucket’s refill rate.
Do cached tokens count toward rate limits?
On the Claude API, cache_read_input_tokens do not count toward input tokens per minute for most models, although they are still billed. Only input_tokens and cache_creation_input_tokens count. Anthropic’s example shows a 2,000,000 ITPM limit handling 10,000,000 total input tokens per minute at an 80 percent cache hit rate. Check each provider’s documentation, because rules differ.
What happens when you exceed an LLM rate limit?
The API returns HTTP 429, often with a Retry-After header saying how many seconds to wait. Wait at least that long, add random jitter, and cap the number of retries. OpenAI notes that unsuccessful requests still count toward the per-minute limit, so blind retries make things worse. Separate spend-cap errors, which retrying cannot fix, from temporary rate limits.
Conclusion: where should you start?
Start with the cost function, because it is where most limiters are wrong. Write down how your provider counts input, output and cached tokens, then reserve exactly that. Add the reconcile step in a finally block so every exit path settles the bucket. Move the bucket to a Redis script once you run more than one gateway instance, and dark-launch it to see what it would reject before enforcing it.
The result is a gateway that refuses excess traffic locally, tells clients exactly when to retry, and keeps your shared provider limit healthy. If you build this, I’d like to hear how your estimates compare with real usage. Subscribe to the NexGismo newsletter for the next system design deep dive.
