Sub topic 11
Staying under limits with client-side throttling
This chapter assumes you can read basic asyncio code and know what a 429 response and the Retry-After header are. Retrying after a 429 works, but each rejected request still costs a round trip and counts against your traffic. Client-side throttling avoids the problem. Your code waits before sending, so the provider rarely has to reject anything.
Why throttle when you already retry
Retries react to failure. Throttling prevents it. Without throttling, a batch job that starts 200 concurrent requests will get a wave of 429 responses. Every rejected request then backs off, wakes up, and competes again. The job finishes, but slowly, and the logs fill with errors that were avoidable.
Throttling also protects other work. If a batch job and your user-facing endpoint share one API key, the batch job can use up the whole limit. Interactive users then see 429 errors.
Throttling does not replace retries. Your estimate of the limit can be wrong, other services may share the key, and the provider may lower limits during busy periods. Keep both: throttle to stay under the limit, and retry for the cases that slip through.
The three limits to respect
Providers usually enforce several limits at once. A request is rejected when it crosses any one of them.
| Limit | What it counts | How you enforce it |
|---|---|---|
| Requests per minute (RPM) | Number of calls, whatever their size | Token bucket on request count |
| Tokens per minute (TPM) | Input plus output tokens | Sliding window on estimated tokens |
| Concurrency | Requests in flight at the same moment | Semaphore |
Check your provider's dashboard or response headers for the real numbers. They differ by account tier and model, and they change.
In the diagram, each "no" branch loops back to the same gate. In code, that loop is an await that sleeps until the gate opens.
Limiting request rate with a token bucket
A token bucket holds up to burst tokens. It refills at rate_per_sec. Each request takes one token, and a request that finds the bucket empty sleeps until a token exists. This allows short bursts while keeping the long-run average at the rate you set.
The bucket's "tokens" are unrelated to LLM tokens. They are permission slips for requests.
Save this as throttle.py:
import asyncio
import time
class RateLimiter:
"""Token bucket: allows `rate_per_sec` requests per second with bursts up to `burst`."""
def __init__(self, rate_per_sec: float, burst: int):
self.rate = rate_per_sec
self.capacity = burst
self.tokens = float(burst)
self.updated = time.monotonic()
self.lock = asyncio.Lock()
async def acquire(self) -> None:
while True:
async with self.lock:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= 1:
self.tokens -= 1
return
wait = (1 - self.tokens) / self.rate
await asyncio.sleep(wait)
async def main():
limiter = RateLimiter(rate_per_sec=2, burst=2)
for i in range(5):
await limiter.acquire()
print(i, round(time.monotonic(), 2))
if __name__ == "__main__":
asyncio.run(main())Running it prints two timestamps immediately, which is the burst. The next three come about 0.5 seconds apart, which is the refill rate.
Three details matter here:
time.monotonic()is used because the wall clock can jump backward or forward. The monotonic clock cannot.- The sleep happens outside the lock. If the code slept while holding the lock, every other waiting task would be blocked behind it.
- The
while Trueloop re-checks the bucket after sleeping. Another task may have taken the token that just refilled.
Limiting tokens per minute
A request limiter does not help when a few huge prompts use up your TPM budget. For that you need a second gate that counts tokens. A sliding window works well. It remembers (timestamp, tokens) for each recent request and drops entries older than 60 seconds.
You must send an estimate, because the true usage is only known after the response. A rough estimate is the prompt length divided by 4 (for English text), plus the max_tokens you set for the output. Many providers count max_tokens against your limit at admission time, so including it is the safer choice.
Capping concurrency and combining the gates
An asyncio.Semaphore caps how many requests are in flight. Concurrency matters even when RPM is fine. Slow requests pile up, each holds a connection, and the number of open requests grows far beyond what you intended.
This example combines all three gates. It imports RateLimiter from the throttle.py file above.
import asyncio
import time
from collections import deque
from throttle import RateLimiter
class TokenWindowLimiter:
"""Allows at most `limit` estimated tokens in any rolling 60-second window."""
def __init__(self, limit: int):
self.limit = limit
self.events = deque() # (timestamp, tokens)
self.used = 0
self.lock = asyncio.Lock()
async def acquire(self, tokens: int) -> None:
if tokens > self.limit:
raise ValueError("request is larger than the whole token budget")
while True:
async with self.lock:
now = time.monotonic()
while self.events and now - self.events[0][0] >= 60:
_, old = self.events.popleft()
self.used -= old
if self.used + tokens <= self.limit:
self.events.append((now, tokens))
self.used += tokens
return
# Wait until the oldest entry leaves the window.
wait = 60 - (now - self.events[0][0])
await asyncio.sleep(wait)
class Throttle:
def __init__(self, rpm: int, tpm: int, max_concurrent: int, burst: int):
self.requests = RateLimiter(rate_per_sec=rpm / 60, burst=burst)
self.tokens = TokenWindowLimiter(tpm)
self.slots = asyncio.Semaphore(max_concurrent)
async def run(self, estimated_tokens: int, call):
async with self.slots:
await self.requests.acquire()
await self.tokens.acquire(estimated_tokens)
return await call()
async def fake_api_call():
await asyncio.sleep(0.1) # stands in for a real network call
return "ok"
async def main():
throttle = Throttle(rpm=60, tpm=6000, max_concurrent=3, burst=2)
start = time.monotonic()
async def job(i):
result = await throttle.run(500, fake_api_call)
print(f"job {i} {result} at {time.monotonic() - start:.1f}s")
await asyncio.gather(*(job(i) for i in range(8)))
asyncio.run(main())The first two jobs start at once because of the burst of 2. The rest start about one second apart, because 60 RPM is one request per second. The 6000 TPM budget is not the limit here (8 jobs of 500 tokens is 4000), so you can lower tpm to 2000 and watch the token window become the limit instead.
To replace a real call, pass a function that sends the request. For example, await throttle.run(est, lambda: client.chat.completions.create(...)) works with an async SDK client.
Settings that make this work in practice
- Leave headroom. Set your limits to about 80% of the provider's published numbers. Estimates are imprecise, and clocks and counting windows differ between you and the provider.
- Divide across processes. Each process has its own limiter. With 4 workers sharing a 600 RPM limit, each worker should be configured for at most 150 RPM, before headroom. For many workers, a shared limiter in Redis or a single gateway service is easier to reason about.
- Use the right lock for threads. The classes above are for
asyncioand are not thread-safe. Threaded code needsthreading.Lockandtime.sleep. - Cap the wait. A throttle that waits forever hides overload. Wrap the call in
asyncio.timeout()orasyncio.wait_for()so a request that cannot be admitted within its deadline fails fast. This ties into the deadlines from the timeouts chapter. - Throttle retries too. Send retry attempts through the same throttle as first attempts. If retries bypass it, a burst of failures turns into a burst of extra traffic.
Common mistakes
- Sleeping inside the lock. This serializes all waiters and can stall the program.
- Using
time.time()for intervals. A system clock adjustment can produce a negative wait or a long stall. - Setting the burst equal to the full minute's budget. A burst of 600 on a 600 RPM limit lets you send the whole minute's quota in the first second, which many providers reject as a spike.
- Counting only input tokens. Output tokens count toward TPM, so include
max_tokensin the estimate. - Forgetting that the semaphore does not limit rate. Ten slots with fast responses can still exceed your RPM. You need both gates.
Exercise
Your provider allows 600 requests per minute for your key. Four worker processes share the key, and you want to leave 20% headroom. What rate_per_sec should each worker's RateLimiter use, and why does a semaphore alone not enforce this?
Show answer
Usable total is 600 × 0.8 = 480 RPM. Divided by 4 workers, each gets 120 RPM, so rate_per_sec = 120 / 60 = 2. A semaphore only caps how many requests are in flight at once. If responses are fast, many requests can still start within one minute, so the request rate can exceed the limit. A rate limiter is needed to control requests per unit of time.
Exercise
In TokenWindowLimiter.acquire, why does the code compute wait from self.events[0], and why is self.events guaranteed not to be empty at that point?
Show answer
The oldest entry is the first one to leave the 60-second window, so waiting 60 - (now - oldest_timestamp) seconds frees at least some budget, and the loop then re-checks. The events list cannot be empty at that point because of the earlier size check. A request larger than the limit raises ValueError. Any request within the limit fits when used is 0, so the code only reaches the wait branch when used > 0, which means at least one event exists.