Log inStart free
LESSON 33.01 · 6 STAGES · 3 CONTROLS · 3 CHECKS

Rate limiting with token buckets

Three API keys share one gateway, and one of them floods it.


EXPLAINER · 33.01 · GATEWAY BAY
01
Stage 1 of 6 · Requests arrive
Three API keys send 67 requests in 30 s. The flood sends 4 large requests a second.
Explain it simply

Each lane is one API key, the name a client signs its requests with. Each bar is one request, and a taller bar asks for more tokens. The chat app sends a small request every 2 seconds. The batch job sends two bursts of 6. The flood sends 4 big requests a second for 10 seconds.

Three lanes on a 30 second time axis. K1, the chat app, sends 15 small requests. K2, the batch job, sends 2 bursts of 6. K3, the flood, sends 40 large requests from 10 to 20 seconds.

requestsbucket, quotaadmitted429GPU queue
Toy: 3 API keys, 67 requests in 30 s
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
6 permits
The most permits a key can save up.
1 a second
Permits added to each bucket every second.
1 permit
One permit, or one permit per token.
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
request=(t,  prompt,  max out)\sy{q}{data}{\text{request}} = (t,\; \text{prompt},\; \text{max out})
K3: 7,008 to 7,495 tokens per request\text{K3: } 7,008 \text{ to } 7,495 \text{ tokens per request}

Each request has an arrival time, a prompt and a maximum output.

Show the code ▾Hide the code ▴ · Try it yourself · Python 3
# One token bucket per API key, on the lesson's 67 requests.
# Times in ms, so every level is exact.
REQUESTS = {  # key: [(arrival ms, prompt tokens, max output tokens), ...]
    "K1": [
        (1000, 571, 256), (3000, 397, 256), (5000, 307, 256), (7000, 618, 256), (9000, 345, 256), (11000, 687, 256),
        (13000, 608, 256), (15000, 229, 256), (17000, 340, 256), (19000, 374, 256), (21000, 316, 256), (23000, 266, 256),
        (25000, 549, 256), (27000, 521, 256), (29000, 656, 256),
    ],
    "K2": [
        (4000, 1211, 512), (4250, 1419, 512), (4500, 1391, 512), (4750, 1248, 512), (5000, 1360, 512), (5250, 1354, 512),
        (19000, 1370, 512), (19250, 1407, 512), (19500, 1232, 512), (19750, 1266, 512), (20000, 1377, 512), (20250, 1201, 512),
    ],
    "K3": [
        (10100, 3324, 4000), (10350, 3477, 4000), (10600, 3358, 4000), (10850, 3065, 4000), (11100, 3092, 4000), (11350, 3345, 4000),
        (11600, 3093, 4000), (11850, 3336, 4000), (12100, 3327, 4000), (12350, 3331, 4000), (12600, 3035, 4000), (12850, 3424, 4000),
        (13100, 3377, 4000), (13350, 3097, 4000), (13600, 3322, 4000), (13850, 3383, 4000), (14100, 3359, 4000), (14350, 3008, 4000),
        (14600, 3223, 4000), (14850, 3065, 4000), (15100, 3051, 4000), (15350, 3495, 4000), (15600, 3205, 4000), (15850, 3184, 4000),
        (16100, 3463, 4000), (16350, 3495, 4000), (16600, 3188, 4000), (16850, 3447, 4000), (17100, 3489, 4000), (17350, 3129, 4000),
        (17600, 3296, 4000), (17850, 3476, 4000), (18100, 3319, 4000), (18350, 3489, 4000), (18600, 3051, 4000), (18850, 3420, 4000),
        (19100, 3311, 4000), (19350, 3404, 4000), (19600, 3103, 4000), (19850, 3453, 4000),
    ],
}
SIZE, RATE, COST = 6, 1, "requests"  # permits, permits a second, "requests" or "tokens"
UNIT = 1000  # one permit per request = 1,000 units; one token = 1 unit

class TokenBucket:
    def __init__(self, size, per_ms):
        self.size, self.per_ms = size, per_ms
        self.level, self.at = size, 0  # starts full

    def allow(self, t, cost):
        self.level = min(self.size, self.level + self.per_ms * (t - self.at))
        self.at = t
        if self.level < cost:
            return False  # HTTP 429
        self.level -= cost
        return True

for key, reqs in REQUESTS.items():
    bucket = TokenBucket(SIZE * UNIT, RATE)  # RATE permits/s = RATE units per ms
    passed = 0
    for t, prompt, max_out in reqs:
        cost = UNIT if COST == "requests" else prompt + max_out
        passed += bucket.allow(t, cost)
    print(key, passed, "of", len(reqs), "admitted")
# K1 15 of 15 admitted
# K2 12 of 12 admitted
# K3 15 of 40 admitted

Copy it into a file and run it.

Common mix-ups

MYTHA rate limit only stops the key that floods.

FIXOnly with a bucket per key. A shared bucket lets the flood take the chat app's permits too.

MYTHA limit on requests per second protects the GPU.

FIXA flood request asks for about 10 times the tokens of a chat request. Count tokens to cap the GPU work.

Predict, then reveal
0 / 3 REVEALED
Q01With a bucket of 2 and a refill of 1 a second, how many of the batch job's 12 pass?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02At the default settings, does R25 still wait for the GPU if requests cost their tokens?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03With a bucket of 6, does a refill of 2 a second let more or fewer flood requests through?
1 · GUESS2 · TRY IT IN THE DIAGRAM

Takeaways

  1. A token bucket allows bursts up to its size, then the refill rate.
  2. Give each key its own bucket, so one client cannot starve the others.
  3. Count tokens, not requests, to cap GPU work and stop model denial of service.