436. 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 1
Input: requests [(0, 60), (1, 50), (2, 30), (10, 90)], rate 10, capacity 100
Output: ([True, True, False, True], 0.0)
Example 2
Input: requests = [(0, 150), (0, 100)], rate = 5, capacity = 100
Output: ([False, True], 0.0)
Example 3
Input: requests = [(0, 10), (100, 120)], rate = 2, capacity = 100
Output: ([True, False], 100.0)
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Refill with elapsed time first, cap at capacity, then decide.
Hint 2
Track the level and the last refill time.
Hint 3
Apply min(capacity, ...) when refilling.
Hint 4
Do not subtract on rejection.
Common mistakes
- Letting the bucket overflow past capacity.
- Subtracting tokens even when the request is rejected.
- Refilling from time 0 every time instead of from the last request.
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.
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.
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.
Companies1
- xAI a candidate reported this question What xAI's coding loop makes you actually build
From public interview reports and guides. Not affiliated with or endorsed by these companies.