Rate limit API requests with a token bucket
Why it matters Every hosted LLM API enforces tokens-per-minute limits like this, and client SDKs mirror the bucket to avoid 429 errors.
LLM APIs limit tokens per minute. A token bucket refills at a steady rate up to a capacity, and each request spends its token count from the bucket.
Write token_bucket(requests, rate, capacity). The bucket starts full at capacity at time 0. requests is a list of (time_s, tokens) sorted by time. For each request, first refill: level = min(capacity, level + rate * (time_s - last_time)), then set last_time = time_s. If tokens <= level, accept it and subtract tokens; otherwise reject it and leave the level unchanged. Return (decisions, final_level) where decisions is a list of booleans.
def token_bucket(requests, rate, capacity)Example
requests [(0, 60), (1, 50), (2, 30), (10, 90)], rate 10, capacity 100 gives ([True, True, False, True], 0.0).
Understand the idea
A token bucket is like a water tank filled by a steady tap. You can draw a large bucket at once if the tank is full, but if you keep drawing faster than the tap, you run dry and must wait. The tank has a fixed size, so leaving it alone for an hour does not store an hour of water. Worked example: capacity 100, rate 10 per second. At t = 0 a 60-token request leaves 40. At t = 1 the tank is back to 50, so a 50-token request just fits and empties it. Rule: level = min(capacity, level + rate x elapsed); accept if tokens <= level and subtract. This allows short bursts up to capacity while holding the long-run average at rate. API gateways use it per key to share GPU capacity fairly across customers.