Build an in-memory rate limiter using token buckets
System DesignModel answerLast updated
Design a fast, memory-efficient rate limiter for an API that tracks per-client quotas using a token-bucket algorithm with lazy refill.
You're building an in-memory rate limiter for an HTTP API that needs to enforce per-client quotas.
Requirements
- Each client (identified by user ID or API key) can make at most N requests in any T-second period
- Start with a single-server implementation that keeps state in memory
- Must support:
- Low latency: sub-millisecond decision time per request
- Memory efficiency: handle millions of clients without excessive RAM usage
- Extensibility: the design should translate easily to distributed deployments later
What to cover
Walk through your design in these stages:
-
Initial approach: Describe a straightforward sliding-window implementation. What data do you store per client? How do you decide whether to allow or reject an incoming request? What are the time and space complexities?
-
Scalability analysis: At high scale (millions of clients, hundreds of thousands of requests per second), where does the sliding-window design struggle? Be specific about memory and performance bottlenecks.
-
Optimized design: Redesign using a token bucket with lazy refill:
- Explain the token bucket model: capacity, refill rate, consumption per request
- Specify exactly what state you maintain per client
- Detail the lazy refill strategy: how do you compute token availability on-demand when a request arrives, without background timers?
- Show the calculation step-by-step for a request at time
now, given stored state - Compare memory footprint and throughput characteristics to the sliding-window approach
-
Production considerations:
- How do you handle concurrent requests for the same client from multiple threads?
- How do you prevent unbounded memory growth from inactive clients?
- Sketch how you'd adapt this to run across multiple servers (briefly—focus stays on the core algorithm)
Provide data structures, algorithms, complexity analysis, and trade-offs. Be concrete about edge cases and implementation details.
Hints
Hint 1
The sliding window stores the full request history—can you replace it with a fixed-size summary?
Hint 2
Token buckets refill continuously in theory, but you can calculate the refill mathematically when each request arrives instead of running a timer.
Hint 3
Inactive clients that haven't been accessed in T seconds can be safely evicted—their buckets would be full anyway.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Building a Token-Bucket Rate Limiter
Understanding the Problem Space
Before choosing an algorithm, nail down the parameters:
- Quota: N requests per T seconds (e.g., 1000 requests per 60 seconds per API key)
- Expected scale: potentially millions of distinct clients, tens or hundreds of thousands of requests per second
- Latency target: decision must complete in microseconds, inline with request handling
- Starting constraint: single server, in-memory state
The core API is check_limit(client_id, timestamp) -> (allowed: bool, retry_after: float).
Stage 1: Sliding-Window Baseline
Design
Maintain a timestamp log per client. Store a map from client_id to a queue of request timestamps.
Algorithm for a request at time now:
- Retrieve the client's timestamp queue
- Remove all timestamps older than
now - Tfrom the front - If the queue length is less than N, append
nowand allow the request - Otherwise, reject and return
retry_after = oldest_timestamp + T - now
Complexity
- Time: O(1) amortized per request, since each timestamp is enqueued once and dequeued once. Worst case is O(N) when many timestamps expire simultaneously after an idle period.
- Space: O(N) per active client, so O(C × N) total for C clients.
Accuracy
This approach is exact: no sliding T-second interval ever contains more than N accepted requests.
Stage 2: Scalability Bottlenecks
Consider a deployment with 1 million clients and N = 1000:
Memory explosion:
- Storing up to 1000 timestamps per client means up to 10⁹ timestamps total
- Even at 8 bytes each (conservative for a 64-bit float), that's 8 GB of raw data
- Actual overhead is higher: Python objects, queue pointers, and hash-table load factors push this to 20+ GB
Memory scales with the limit: Raising N for premium users directly multiplies memory consumption.
Performance degradation:
- Constant allocation and deallocation pressure on the memory allocator
- Queue nodes scattered across the heap cause poor cache locality
- Garbage collection overhead increases with object count
- Latency spikes occur when large numbers of timestamps expire at once
Distributed challenges:
- Replicating this to Redis means storing sorted sets per client with the same O(N) memory cost
- Bandwidth and serialization overhead grow proportionally
What we actually need: A constant-size summary of recent usage, not the full request history.
Stage 3: Token Bucket with Lazy Refill
Conceptual Model
Imagine each client owns a bucket:
- Capacity: maximum number of tokens the bucket can hold (set this to N)
- Refill rate: tokens are added continuously at
rate = N / Ttokens per second - Consumption: each request consumes exactly 1 token
- If tokens < 1 when a request arrives, reject it
This naturally enforces a long-run average of N requests per T seconds while allowing short bursts up to the capacity.
State per Client
Store exactly two values:
tokens: float # current token count
last_update: float # timestamp of last refill calculation
That's roughly 16 bytes per client, O(1) regardless of N.
Lazy Refill Algorithm
Instead of running a background thread that ticks every second and adds tokens to every bucket (which would cost O(C) work per tick, mostly wasted on idle clients), compute the refill on demand when a request arrives.
For a request at time now:
elapsed = max(0, now - last_update) # protect against clock drift
accrued_tokens = elapsed * refill_rate
tokens = min(capacity, tokens + accrued_tokens)
last_update = now
if tokens >= 1.0:
tokens -= 1.0
return ALLOW
else:
retry_after = (1.0 - tokens) / refill_rate
return REJECT, retry_after
Why this works: Token accumulation is a deterministic linear function of time (clamped at capacity). Computing it in a single step at request time produces the exact same result a continuous background process would have.
Worked Example
- Capacity = 10, refill rate = 2.0 tokens/second
- At t=0, bucket is full (10 tokens)
- 10 requests arrive at t=0 → all allowed, tokens = 0
- Request at t=0.4:
- Elapsed = 0.4s
- Accrued = 0.4 × 2 = 0.8 tokens
- New total = min(10, 0 + 0.8) = 0.8
- 0.8 < 1, so reject, retry_after = 0.2 / 2 = 0.1s
- Request at t=3:
- Elapsed = 3s (from last update at t=0.4)
- Accrued = 3 × 2 = 6 tokens
- New total = min(10, 0.8 + 6) = 6.8
- Allow, tokens = 5.8
Comparison: Sliding Window vs. Token Bucket
| Dimension | Sliding-window log | Token bucket (lazy) |
|---|---|---|
| Memory per client | O(N) timestamps | O(1): two floats |
| Time per request | Amortized O(1), spikes to O(N) | Strict O(1), no allocation |
| Burst handling | No burst tolerance | Configurable via capacity |
| Accuracy | Exact over any T-second window | Permits up to 2N in T seconds (full burst + continuous refill) |
| Background threads | None | None |
Trade-off: Token buckets sacrifice strict windowing for dramatic memory savings. If exact enforcement is critical, consider a sliding-window counter variant (two fixed windows with weighted interpolation), which is also O(1) memory and nearly exact.
Stage 4: Production Hardening
Concurrency Control
The refill-check-decrement sequence is a read-modify-write race. Without synchronization, two threads can both read tokens = 1.0 and both allow their requests.
Options:
-
Single global lock: Simplest solution. If the critical section is ~1 microsecond and request rates are moderate (< 100k/s), contention is acceptable.
-
Lock striping: Partition the client map into K shards by
hash(client_id) % K, each with its own lock. Threads handling different clients rarely contend. Typical K = 256 or 1024. -
Lock-free CAS: In languages with atomic primitives, pack
(tokens, timestamp)into a single 128-bit value and use compare-and-swap. Best throughput but hardest to implement correctly.
For most systems, lock striping offers the best balance.
Memory Bounds and Eviction
Observation: A client idle for duration ≥ T has a completely refilled bucket. Deleting the entry and recreating it later as a full bucket is behaviorally identical.
Implementation:
- Use an LRU structure (e.g.,
OrderedDictin Python or a hand-rolled doubly-linked hash map) - On each access, move the client to the tail
- Periodically (or on each request), sweep from the head and remove entries with
now - last_update > T - Enforce a hard
max_clientscap: if the map is full and a new client arrives, evict the LRU entry even if not yet expired
This keeps memory bounded with amortized O(1) overhead per operation and no background thread.
Distributed Extension (Sketch)
Store per-client state in Redis as a hash:
HSET client:{id} tokens 100.0 last_update 1698765432.1
Wrap the lazy-refill logic in a Lua script so it executes atomically on the server:
local tokens = tonumber(redis.call('HGET', key, 'tokens') or capacity)
local last = tonumber(redis.call('HGET', key, 'last_update') or now)
local elapsed = math.max(0, now - last)
tokens = math.min(capacity, tokens + elapsed * rate)
if tokens >= 1.0 then
redis.call('HSET', key, 'tokens', tokens - 1, 'last_update', now)
redis.call('EXPIRE', key, ttl)
return 1
else
return 0
end
Additional details:
- Use Redis
TIMEcommand to get a consistent clock across application servers - Set
EXPIREto the refill period so Redis auto-evicts idle clients - For extreme load, servers can locally lease small token batches and sync periodically, trading precision for throughput
Reference Implementation (Python)
import threading
import time
from collections import OrderedDict
class TokenBucketRateLimiter:
def __init__(self, capacity, refill_rate, max_clients=100000):
self.capacity = capacity
self.refill_rate = refill_rate
self.max_clients = max_clients
self.buckets = OrderedDict()
self.lock = threading.Lock()
def allow(self, client_id):
now = time.time()
with self.lock:
self._evict_idle(now)
if client_id not in self.buckets:
if len(self.buckets) >= self.max_clients:
self.buckets.popitem(last=False) # evict LRU
self.buckets[client_id] = (self.capacity, now)
tokens, last_update = self.buckets[client_id]
elapsed = max(0, now - last_update)
tokens = min(self.capacity, tokens + elapsed * self.refill_rate)
if tokens >= 1.0:
self.buckets[client_id] = (tokens - 1.0, now)
self.buckets.move_to_end(client_id) # mark recently used
return True, 0.0
else:
retry_after = (1.0 - tokens) / self.refill_rate
return False, retry_after
def _evict_idle(self, now):
ttl = self.capacity / self.refill_rate
while self.buckets:
client_id, (_, last_update) = next(iter(self.buckets.items()))
if now - last_update > ttl:
del self.buckets[client_id]
else:
break
Complexity: O(1) time and space per request, with O(C) total memory where C is the number of active clients in the last T seconds.