Rate Limiting LLM API Calls with Token Buckets
Shape outbound model traffic with token buckets, respect provider limits and Retry-After, and keep one abusive tenant from starving every other caller.
On this page
Introduction
Model providers enforce several limits at once: requests per minute, tokens per minute and sometimes concurrent requests per account. Exceeding any of them returns a 429 that wastes a round trip and, if you retry blindly, deepens the hole. Rate limiting your own outbound calls is therefore not optional politeness but the mechanism that keeps a burst from one feature from degrading every other caller. A token bucket is the simplest shape that handles both sustained throughput and short bursts, and it maps cleanly onto how providers describe their quotas.
Why Provider Limits Are Multi-Dimensional
A request counted against requests per minute may contain ten tokens or ten thousand, so a request limit alone does not protect the token limit. A single large summarisation can exhaust the token budget that hundreds of small calls would have used. You must track and limit both dimensions, because satisfying one while breaching the other still yields a 429. Read the provider headers that report remaining quota and reset time, and treat them as the authority over your own estimates.
import time, threading
class TokenBucket:
def __init__(self, rate_per_sec: float, capacity: float):
self.rate = rate_per_sec
self.capacity = capacity
self.tokens = capacity
self.updated = time.monotonic()
self.lock = threading.Lock()
def _refill(self) -> None:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
def acquire(self, cost: float, timeout: float = 5.0) -> bool:
deadline = time.monotonic() + timeout
while True:
with self.lock:
self._refill()
if self.tokens >= cost:
self.tokens -= cost
return True
missing = cost - self.tokens
wait = missing / self.rate
if time.monotonic() + wait > deadline:
return False
time.sleep(min(wait, 0.05))
Token Bucket Mechanics
A token bucket holds up to a capacity of tokens and refills at a fixed rate. Each request removes tokens equal to its estimated cost and proceeds only if enough are available; otherwise it waits or is rejected. The refill rate caps sustained throughput while the capacity allows a burst, which is exactly the behaviour of most provider quotas. Choose the refill rate below the provider limit and the capacity small enough that a burst cannot exceed it, and you have a limiter that never surprises the provider.
import random, time
def call_with_limits(bucket, semaphore, call, est_tokens: int, max_retries: int = 3):
for attempt in range(max_retries + 1):
if not bucket.acquire(est_tokens):
raise TimeoutError("local rate limit exceeded")
with semaphore:
resp = call()
if resp.status != 429:
return resp
# Honour Retry-After, add jitter, never retry immediately.
retry_after = float(resp.headers.get("retry-after", 1))
time.sleep(retry_after + random.uniform(0, retry_after * 0.5))
raise RuntimeError("provider kept returning 429 after retries")
Limiting Concurrency, Not Just Rate
Rate alone does not bound how many requests are in flight at once, and a provider may cap concurrency separately. Track outstanding requests with a semaphore in addition to the bucket, so a large batch cannot open a hundred sockets and trigger connection errors. Concurrency also bounds memory, because each in-flight request holds a response buffer. Set the concurrency limit from measured per-request latency and the throughput target rather than guessing.
Handling 429 and Retry-After
When the provider returns 429, the response usually carries a Retry-After header or a reset hint; honour it rather than retrying immediately. Retrying without waiting triples the request count exactly when the provider is already saturated, which turns a brief throttle into an outage. Add jitter so many workers do not wake at the same instant, and cap total retries so a sustained 429 fails the job instead of looping. Distinguish a quota 429 from a transient overload by reading the error code, because the remedies differ.
Fairness Across Tenants
A single shared bucket lets one noisy tenant consume the whole budget and starve everyone else. Use per-tenant buckets for isolation and a global bucket to respect the provider ceiling, then admit a request only when both allow it. When a tenant exceeds its fair share, queue or reject its excess rather than slowing the platform. This two level scheme makes abuse a local problem and keeps well behaved callers at their expected latency.
Cost as a Limit
Token quota is really a cost ceiling, so track spend as a first class limit rather than only counting requests. A per-tenant daily cost budget with a hard stop prevents a runaway loop from producing a surprising invoice. Weight each request by its estimated tokens and model price, and reset the budget on a rolling window. When the budget is exhausted, degrade to a cheaper model or queue the work rather than failing silently.
Backpressure and Queueing
A limiter without a queue simply drops work, which is fine for best effort traffic and wrong for user-facing requests. Put a bounded queue in front of bursty producers and let the limiter drain it, so callers absorb latency instead of errors. Bound the queue so memory stays finite and reject new work when it is full, returning a clear retry signal. Expose queue depth and wait time as metrics, because a growing queue is the earliest sign that capacity is too low.
Observability and Alerts
Count admissions, rejections, queue depth, wait time and 429s by tenant and by feature. A rising rejection rate means your limits are below real demand, while a rising 429 rate means you underestimated the provider quota or a retry storm is underway. Alert on sustained queue depth and on 429 bursts before users feel them. These metrics also justify raising limits with evidence rather than by argument.
Testing the Limiter
Test the limiter with a clock you control, asserting that a burst is admitted up to capacity, that sustained requests are spaced by the refill rate, and that a 429 with Retry-After pauses exactly that long. Verify fairness by running two tenants through one bucket and confirming neither can exceed its share. These tests are deterministic and fast, and they catch the off by one errors that make limiters either useless or too strict.
Sources
Sources: OpenAI rate limits, Redis rate limiting patterns, Google SRE book retry storms.
FAQ
- Why do I still get 429 despite a token bucket?
- You are likely limiting only one dimension or ignoring concurrency. Providers cap requests, tokens and simultaneous calls separately, so track all three and trust the quota headers over your own estimate.
- Should every worker share one limiter?
- Yes for the provider ceiling. Keep a shared bucket so the fleet respects the account limit, and add per-tenant buckets on top so one tenant cannot consume the shared capacity.
Report a problem with this articleOpens a pre-filled issue on GitHub.