Video in progress

Strong Junior 🏗️ System design

How does the token bucket algorithm work, and why is it so widely used for rate limiting?

Each client has a "bucket": tokens are added to it at a steady rate (for example, 10 per second), and its capacity is limited (for example, 50). Each request takes one token, and if there are none, it is rejected. This limits the average rate but allows short bursts.

📖 Answer

A plain "100 per minute" counter (fixed window) has a problem: if a client sends 100 requests at 00:59 and another 100 at 01:00, 200 get through within 2 seconds. Token bucket doesn't have this boundary effect.

The logic is very simple:

class TokenBucket {
    private final long capacity;
    private final double refillPerNano;
    private double tokens;
    private long lastRefill = System.nanoTime();

    TokenBucket(long capacity, double perSecond) {
        this.capacity = capacity;
        this.refillPerNano = perSecond / 1_000_000_000.0;
        this.tokens = capacity;
    }

    synchronized boolean tryAcquire() {
        long now = System.nanoTime();
        tokens = Math.min(capacity, tokens + (now - lastRefill) * refillPerNano);
        lastRefill = now;
        if (tokens < 1) return false;   // we return 429
        tokens -= 1;
        return true;
    }
}

No timer is needed: the token count is computed from the time elapsed since the last request.

There are two parameters and they control different things: the refill rate is the long-term average, the capacity is how big a burst is allowed at once. For example, when a mobile app opens it sends 20 requests at the same time — if the capacity is below 20, even a normal user gets blocked.

With several servers, the bucket state is kept in a shared place — usually Redis, with a Lua script. A ready-made option is the Bucket4j library.