Sub topic 11
Staying under limits with client-side throttling
This chapter assumes you can write async Python and know what a 429 response and the Retry-After header mean from the earlier chapters on rate limits and backoff.
Why throttle on the client
Retries handle a 429 after it happens. Throttling tries to prevent it. Every rejected request still costs a round trip, and with many concurrent workers a burst of 429s can set off synchronized retries. If you know your provider's limits, the client can pace itself.
Providers usually enforce two limits at once:
- Requests per minute (RPM), which counts calls.
- Tokens per minute (TPM), which counts input and output tokens across calls.
Whichever limit you reach first causes the 429. A few large prompts can hit TPM long before RPM.
Two controls: rate and concurrency
Client-side throttling uses two separate controls.
| Control | Limits | Typical tool |
|---|---|---|
| Rate limiter | How fast requests start | Token bucket |
| Concurrency limit | How many requests are in flight | `asyncio.Semaphore` |
A rate limiter alone does not cap in-flight requests. If each call takes 20 seconds and you start 2 per second, about 40 calls will be running at once. A semaphore caps that number.
A token bucket
A token bucket holds up to burst tokens and refills at rate_per_sec. Each request takes one token. If the bucket is empty, the caller sleeps until a token is available. The bucket allows short bursts and enforces the average rate over time.
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 call_model(i, limiter, semaphore):
await limiter.acquire() # wait for permission to start
async with semaphore: # wait for a free in-flight slot
print(f"start {i} at {time.monotonic():.2f}")
await asyncio.sleep(0.5) # stands in for the real API call
return i
async def main():
limiter = RateLimiter(rate_per_sec=2, burst=2)
semaphore = asyncio.Semaphore(3)
results = await asyncio.gather(*(call_model(i, limiter, semaphore) for i in range(8)))
print(results)
asyncio.run(main())The first two calls start immediately, using the burst. After that, calls start about every half second. The lock is released before sleeping, so one waiting caller does not block the others.
Setting the numbers
- Start below the published limit. A common choice is 80 percent, which leaves room for clock differences and other processes using the same key.
- Divide the limit across processes. If four workers share a 600 RPM key, each gets about 150 RPM, or 2.5 requests per second.
- For TPM, estimate the tokens before sending (prompt tokens plus your
max_tokenssetting) and take that many units from a bucket whose capacity is measured in tokens. - Keep retries. Throttling lowers the number of 429s but does not remove them.
Exercise
Your service allows 60 requests per minute and each call takes about 10 seconds. You use a token bucket at 1 request per second and no semaphore. Roughly how many calls can be in flight at once, and what would you add?
Show answer
About 10 calls (1 per second times 10 seconds each). Add an asyncio.Semaphore to cap in-flight calls at whatever concurrency the provider and your own resources can handle, for example 5. The rate limiter then controls how fast calls start, and the semaphore controls how many run at the same time.