Token Bucket

A token bucket is a rate-limiting algorithm with two parameters: a capacity \(C\), the most tokens the bucket can hold, and a refill rate \(r\), the tokens added per second. A request that costs \(n\) tokens is admitted if the bucket holds at least \(n\), and the bucket then drops by \(n\). Otherwise the request is refused or delayed, which is one form of throttling. The tokens are an accounting device and have nothing to do with language-model tokens, although a model gateway can use language-model tokens as the cost \(n\).

The state is two numbers, the current level and the time of the last update. No timer is needed, because the refill is computed on demand: when a request arrives after \(\Delta\) seconds, the level becomes \(\min(C,\ \text{level} + r\Delta)\) and the admission test is applied to that value. If the test fails, the caller can be told how long to wait, \((n – \text{level}) / r\) seconds, for example through a Retry-After header.

What it guarantees

Over any interval of length \(T\), the total cost admitted cannot exceed \(C + rT\). The bucket holds at most \(C\) at the start of the interval and gains at most \(rT\) during it, and every admitted request spends tokens that were there. The capacity therefore bounds the burst and the rate bounds the long-run average. A client that stays idle accumulates credit up to \(C\) and no further, so idleness buys a burst but not an unbounded one.

The class below is the whole algorithm. allow first adds what accrued since the last call, capped at \(C\), and then admits the request only if the level covers its cost. The runs that follow reuse it unchanged and form one script, executed with Python 3.12 on macOS (Darwin 25.6).

class TokenBucket:
    def __init__(self, capacity, rate, now=0.0):
        self.capacity, self.rate = capacity, rate
        self.level, self.last = capacity, now            # starts full
    def allow(self, now, cost=1.0):
        # lazy refill: no timer, add what accrued since the last call, capped at capacity
        self.level = min(self.capacity, self.level + (now - self.last) * self.rate)
        self.last = now
        if cost <= self.level:
            self.level -= cost
            return True
        return False

To see what the bound buys, compare it with a fixed-window counter that allows 60 requests per calendar minute and resets at each minute boundary. The bucket has \(C = 60\) and \(r = 1\) per second, so both express the same “60 requests per minute” limit. The client waits until second 59 and then sends 60 requests per second for two seconds, straddling the boundary.

class FixedWindow:
    def __init__(self, limit, window): self.limit, self.window, self.start, self.count = limit, window, 0.0, 0
    def allow(self, now, cost=1):
        if now - self.start >= self.window: self.start, self.count = now - (now % self.window), 0
        if self.count + cost <= self.limit: self.count += cost; return True
        return False

# A client is idle until t = 59 s, then sends 60 requests per second for 2 seconds,
# straddling the minute boundary.
arrivals = [59.0 + i / 60 for i in range(120)]
for name, lim in (("fixed window", FixedWindow(60, 60.0)), ("token bucket", TokenBucket(60, 1.0, now=0.0))):
    ok = [t for t in arrivals if lim.allow(t)]
    print(f"{name}: {len(ok)} of {len(arrivals)} admitted in 2 seconds")
fixed window: 120 of 120 admitted in 2 seconds
token bucket: 61 of 120 admitted in 2 seconds

The fixed window admits all 120 requests in two seconds, twice the stated rate, because the counter resets between the two bursts. The bucket admits 61, which is within its bound of \(60 + 1 \times 2 = 62\).

Two more runs test the bound itself. In the first, a client offers 20 requests per second for three minutes. In the second, the bucket starts drained, stays idle for 90 seconds, and then receives 100 requests within one second.

# Sustained overload: 20 requests per second for 3 minutes.
tb = TokenBucket(60, 1.0)
admitted = sum(tb.allow(i * 0.05) for i in range(int(180 / 0.05)))
print(f"token bucket, 20 req/s offered for 180 s: {admitted} admitted (bound C + r*T = {60 + 1.0*180:.0f})")

# A drained bucket, 90 s of silence, then a burst of 100 requests within one second.
tb = TokenBucket(60, 1.0)
tb.level = 0.0                              # drained at t = 0
burst = [90.0 + i * 0.01 for i in range(100)]
print("after 90 s idle, burst of 100 in 1 s ->", sum(tb.allow(x) for x in burst), "admitted")
token bucket, 20 req/s offered for 180 s: 239 admitted (bound C + r*T = 240)
after 90 s idle, burst of 100 in 1 s -> 60 admitted

Under sustained overload the bucket admits 239 requests in 180 seconds against a bound of 240, so the long-run rate converges to \(r\). After a long silence the bucket is full, so the 100 requests, which arrive over 0.99 seconds and let less than one token accrue, receive the \(C = 60\) tokens already stored. Tokens keep accruing while requests arrive, so a longer burst gets more: 200 requests spread over 1.99 seconds after the same silence would admit 61, which is the bound \(C + rT = 60 + 1 \times 1.99\) rounded down.

The last run uses costs larger than one: capacity 10,000 units and refill 1,000 per second.

# Cost-weighted: capacity 10,000 units, refill 1,000 per second. A 12,000-unit request can never fit.
tb = TokenBucket(10_000, 1_000.0)
print("4,000-token request:", tb.allow(0.0, 4_000), "| 12,000-token request:", tb.allow(60.0, 12_000))
4,000-token request: True | 12,000-token request: False

A request costing more than \(C\) never fits, however long the caller waits. Treat that as a request that is too large rather than as a rate-limit event, because telling the caller to retry later cannot help.

Choosing C and r

Set \(r\) to the rate the protected resource can sustain and \(C\) to the largest burst it can absorb. A large \(C\) is friendly to bursty but well-behaved clients and weak as protection. A small \(C\) smooths traffic and rejects legitimate bursts. Providers may enforce a per-minute limit at a finer granularity, so a client that spends its minute allowance in a few seconds can still be rejected. A leaky bucket used as a queue differs in that it releases work at a constant rate and does not allow bursts through. In a distributed deployment, the level must be updated atomically in shared state, or each node must receive its own share of \(r\) and \(C\).

References


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.