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
- allow(t) runs in O(1) and stores O(1) state
- Request times arrive in non-decreasing order
- Bursts up to capacity are allowed; the long-run rate is capped at
rateper second
Edge cases to test
- A burst right at start (full bucket)
- Long idle periods (cap at capacity)
- Requests at the same timestamp
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 FalseC++
#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
- LRU Cache (Medium)
- LFU Cache (Hard)
- Min Stack (Medium)
- Insert Delete GetRandom O(1) (Medium)
- Design Circular Queue (Medium)
- Flatten Nested List Iterator (Medium)
- Rate Limiter: Sliding Window Log (Medium)
- Logger Rate Limiter (Easy)
- Design Hit Counter (Medium)
- Design Parking System (Easy)
- Design Tic-Tac-Toe (Medium)
- Design Twitter (Medium)
- Design Snake Game (Medium)
- Vending Machine (State pattern) (Medium)
- Elevator System (LOOK scheduling) (Medium)
- Splitwise (expense sharing) (Medium)
- Movie Ticket Booking (BookMyShow) (Medium)