Token Bucket Rate Limiter

Implement a token bucket that refills at a steady rate and allows short bursts, a standard algorithm for shaping request traffic.

PythonResilience

Code

pythonsnippet
24 lines
import time
from dataclasses import dataclass, field


@dataclass
class TokenBucket:
    capacity: float
    refill_rate: float
    tokens: float = field(init=False)
    updated_at: float = field(init=False)

    def __post_init__(self) -> None:
        self.tokens = self.capacity
        self.updated_at = time.monotonic()

    def allow(self, cost: float = 1.0) -> bool:
        now = time.monotonic()
        elapsed = now - self.updated_at
        self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
        self.updated_at = now
        if self.tokens >= cost:
            self.tokens -= cost
            return True
        return False

Inside the snippet

The working surface is the class class and the functions __post_init__ and allow — everything else is wiring.

Using it

Signature: def allow(self, cost: float = 1.0) -> bool

allow is what another module would consume; nothing else here is load-bearing for callers.

Key statements

def __post_init__(self) -> None:
    self.tokens = self.capacity
    self.updated_at = time.monotonic()
def allow(self, cost: float = 1.0) -> bool:
    now = time.monotonic()
    elapsed = now - self.updated_at
    self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
    self.updated_at = now
    if self.tokens >= cost:
        self.tokens -= cost
        return True
    return False

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. The file defines `__post_init__`, `allow` at load time.