Algo-Sim › Low-Level Design

Rate Limiter: Token Bucket

Medium · Low-Level Design · step through it in Java, Python and C++ on your own input

Allow bursts up to a capacity and a steady refill rate after that: tokens accrue with elapsed time, and each request spends one.

Problem

Design a rate limiter: a bucket holds up to capacity tokens and starts full, and rate tokens are added each second, never beyond capacity. A request at time t is allowed if a token is available, and then uses it; otherwise it is rejected. Return the decision for each request.

Constraints

Edge cases to test

Follow-up questions

How does it work across many servers?
Store the bucket in Redis and update it atomically (a Lua script), or give each server a share of the rate.
Token bucket or sliding window?
Token bucket allows bursts up to capacity and smooths the average; a sliding window enforces an exact count in any window.

Solution

Java

class TokenBucket {
    private final int capacity, rate;      // rate: tokens added per second
    private int tokens, last;

    public TokenBucket(int capacity, int rate) {
        this.capacity = capacity;
        this.rate = rate;
        tokens = capacity;
    }

    public boolean allow(int t) {
        tokens = Math.min(capacity, tokens + (t - last) * rate);
        last = t;
        if (tokens > 0) {
            tokens--;
            return true;
        }
        return false;
    }
}

Python

class TokenBucket:
    def __init__(self, capacity, rate):     # rate: tokens added per second
        self.capacity = capacity
        self.rate = rate
        self.tokens = capacity
        self.last = 0

    def allow(self, t):
        self.tokens = min(self.capacity, self.tokens + (t - self.last) * self.rate)
        self.last = t
        if self.tokens > 0:
            self.tokens -= 1
            return True
        return False

C++

#include <bits/stdc++.h>
using namespace std;

class TokenBucket {
  public:
    int capacity, rate; // rate: tokens added per second
    int tokens = 0, last = 0;

    TokenBucket(int capacity, int rate) {
        this->capacity = capacity;
        this->rate = rate;
        tokens = capacity;
    }

    bool allow(int t) {
        tokens = std::min(capacity, tokens + (t - last) * rate);
        last = t;
        if (tokens > 0) {
            tokens--;
            return true;
        }
        return false;
    }
};

More Low-Level Design problems