High-Throughput Token-Bucket Rate Limiter with Lazy Refill
Hard · System Design · Software Engineer · Technical Screen
Prompt
Architect and implement an HTTP API rate limiter that restricts each caller (keyed by API token or user ID) to N requests per T seconds. Begin with an in-memory design inside one server process that keeps per-request latency in the microsecond range, stays compact in RAM across millions of distinct callers under heavy throughput, and extends cleanly to a multi-node cluster later.
Structure your design around four milestones:
- Sliding-window baseline: Explain how to build an exact sliding-window limiter, specifying the data stored per caller, the allow/reject check at arrival timestamp
now, and the time and space complexity. - Failure modes at high scale: Analyze what happens to memory consumption, allocations, and tail latency in the sliding-window design when millions of callers each send heavy traffic.
- Token bucket with lazy refill: Re-architect the limiter around a token bucket (
capacity,refill_rate, and per-request token spend) storingO(1)state per caller (current_tokensandlast_refill_time). Derive the exact lazy refill math that computes accrued tokens on demand at request timestampnowwithout background timer threads, and explain how this eliminates the sliding window's memory and latency bottlenecks. - Production hardening & cluster scale-out: Address thread-safe concurrent access to a caller's state, lossless eviction of idle callers so memory stays bounded, and extending the limiter across multiple stateless API servers via a shared store like Redis.
Scope & Expectations
- Algorithmic comparison & memory sizing: Quantify the memory and latency gap between
O(N)sliding-window logs andO(1)token buckets, including burst vs. strict rolling-window trade-offs. - Exact lazy-refill mechanics: Present clear reference code and trace how capacity clamping, fractional token preservation on rejected calls, and monotonic clocks prevent starvation or overflow.
- Concurrency, eviction, & distributed extension: Cover lock striping (or atomic updates),
O(1)LRU/TTL cleanup of inactive buckets, and single-round-trip atomic execution in Redis.
Step-by-step walkthrough
Clarify requirements and exact rate-limit semantics
Before choosing data structures, pin down what "at most
Nrequests perTseconds" means in production and where the rate limiter sits. A rate limiter is a gatekeeper component that caps how many requests each caller can make over a time period so one noisy or abusive client cannot overload the service.Functional requirements
- Caller key (
client_key): Enforce one independent quota per API token when authenticated, falling back touser_idor source IP address on public routes. - Quota policy: Permit up to
Nrequests perT-second interval (such asN = 1,000requests overT = 60seconds), supporting distinct(N, T)plan tiers (free vs. enterprise) and optional per-routecostweights (such ascost = 1for a lightweight read andcost = 5for a bulk export). - Actionable rejection headers: Admitted calls proceed directly to route handlers, whereas throttled calls return HTTP
429 Too Many RequestswithRetry-After(whole seconds until sufficient tokens accrue) so well-behaved SDKs back off cleanly.
Non-functional requirements
- Ultra-low latency: The check runs on every incoming HTTP request, so the single-instance version must finish in microseconds purely in memory, with zero disk or network I/O.
- Bounded, small memory: Millions of distinct clients must fit comfortably inside one server process, even when
Nis large. - Thread safety: Hundreds of worker threads or coroutines may check and update the same client's state concurrently without over-admitting requests.
- Distributed extensibility: The core state transition should be clean enough to move into a shared store like Redis when the service scales from one server to dozens.
Crucial semantics question to state upfront: Does the product need a strict rolling cap ("never more than
Nrequests in anyT-second interval") or a sustained average rate with bounded bursts ("N / Trequests per second on average, allowing short bursts up toN")? Answering that question explains the fundamental trade-off between a sliding window and a token bucket.- Caller key (
Back-of-the-envelope numbers
Let's size a realistic single-instance API server to see why memory layout—not arithmetic speed—drives the design.
Workload assumptions (single API server instance) Tier rule N = 1,000 requests per T = 60 s Active clients 1,000,000 distinct keys active within the last 60 s Daily distinct clients 10,000,000 keys seen across 24 hours Throughput 50,000 requests/s hitting this instance Approach A: Sliding-window log (store every accepted timestamp per client) Worst-case entries 1,000,000 active clients x 1,000 timestamps = 1,000,000,000 timestamps Raw 8-byte int64/float64 1e9 x 8 B = 8 GB of raw timestamps alone CPython deque of floats 24 B float object + ~8 B deque pointer = ~32 B per timestamp 1e9 x 32 B = ~32 GB of RAM (crashes a standard server/container -> OOM) Approach B: Token bucket (store just 2 numbers per client) Raw payload per client current_tokens (8 B) + last_refill_time (8 B) = 16 B 1,000,000 active clients 16 MB raw payload (~220 MB in CPython with dict + __slots__ overhead) 10,000,000 daily clients 160 MB raw payload (~2.2 GB in CPython if idle clients are never evicted) CPU cost per request check 1 hash-table lookup + 4 arithmetic ops ~ 0.5-1.0 microseconds in Python (~50 ns in Go/Rust/Java) 50,000 req/s x 1 microsecond = 0.05 CPU-seconds/s (~5% of a single CPU core)Three design lessons jump right out of this math:
- Per-client state must be
O(1), notO(N). AtN = 1,000, storing two 8-byte numbers (16 B) instead of1,000timestamps (8,000 B) cuts raw per-client payload by 500x. - Idle client eviction is mandatory even with a token bucket. Keeping all 10 million daily clients forever still consumes gigabytes of hash-table overhead.
- Arithmetic is tiny; lock contention and memory churn are the real bottlenecks.
- Per-client state must be
API and high-level architecture
Keep the limiter behind a small, storage-agnostic interface inside an HTTP middleware (a wrapper that runs before business logic handlers). Separating the pure math from where state is stored makes moving from in-memory maps to Redis painless later.
Method signature: allow(client_key: str, cost: int = 1) -> Decision Decision fields: allowed: bool # True -> pass to route handler; False -> return HTTP 429 remaining: int # Whole tokens left after this decision (for RateLimit-Remaining) retry_after_s: float # Seconds until `cost` tokens are available (0.0 if allowed)+------------------------------ Single API Server Process ------------------------------+ | | | HTTP Request --> [Auth / Key Extractor] --> [Rate-Limit Middleware] --> API Handler | | | | | limiter.allow(client_key, cost=1) | | | | | v | | +-----------------------------------------------+ | | | ShardedTokenBucketLimiter | | | | - tier_config: plan -> (capacity, rate) | | | | - shards[0 .. 63] (hash(client_key) % 64): | | | | * mutex lock | | | | * OrderedDict: key -> {tokens, last_ts} | | | | (front = oldest idle client for LRU) | | | +-----------------------------------------------+ | | | | | if not allowed: HTTP 429 + Retry-After: ceil(s) | +---------------------------------------------------------------------------------------+ Later (multi-server fleet): replace the in-process shard lookup with one atomic Redis Lua script per request against a Redis Cluster shard keyed by `rl:{client_key}`.Notice two clean boundaries:
- Tier parameters
(capacity, refill_rate)live in a small read-only config table, not inside each client's state, saving 16 bytes on every single client entry. - Rejected requests stop at the middleware before JSON body parsing or database queries run, so rejecting an abusive flood stays orders of magnitude cheaper than serving it.
- Tier parameters
Baseline design: sliding-window log
To see why we need a token bucket, let's first build the exact sliding-window log baseline. A deque (double-ended queue) lets us append new items to the right end and pop expired items from the left end in
O(1)time per operation.- Data stored per client:
logs[client_id]is adequeof accepted request timestamps sorted from oldest to newest. - Allow/reject rule at timestamp
now: The active rolling window is(now - T, now].- While the oldest timestamp at
log[0]satisfieslog[0] <= now - T, pop it from the left—it has aged out of theT-second window. - If
len(log) < N, appendnowto the right and allow the request. - Otherwise reject the request without appending
now(if you logged rejected attempts, a client retrying once per second would keep extending its own lockout forever!).
- While the oldest timestamp at
Let's trace
N = 3requests perT = 12seconds:now window (now-12, now] expired popped deque before check len < 3? decision deque after 2.0 (-10.0, 2.0] none [] True ALLOW [2.0] 5.0 ( -7.0, 5.0] none [2.0] True ALLOW [2.0, 5.0] 9.0 ( -3.0, 9.0] none [2.0, 5.0] True ALLOW [2.0, 5.0, 9.0] 11.0 ( -1.0, 11.0] none [2.0, 5.0, 9.0] False REJECT [2.0, 5.0, 9.0] 14.0 ( 2.0, 14.0] pop 2.0 (<= 2.0) [5.0, 9.0] True ALLOW [5.0, 9.0, 14.0]from collections import deque class SlidingWindowLogLimiter: def __init__(self, max_requests: int, window_seconds: float): self.max_requests = max_requests self.window_seconds = window_seconds # Per-client state: client_id -> deque of accepted timestamps (oldest -> newest) self.client_logs = {} def allow(self, client_id: str, now: float) -> bool: log = self.client_logs.get(client_id) if log is None: log = deque() self.client_logs[client_id] = log # Evict timestamps at or before (now - T) because the active window is (now - T, now]. window_start = now - self.window_seconds while log and log[0] <= window_start: log.popleft() # Admit if under quota; never record rejected timestamps. if len(log) < self.max_requests: log.append(now) return True return False- Time complexity: Amortized
O(1)per request—every accepted timestamp is appended once and popped once across its lifetime, though a single call after a burst expires can pop up toNtimestamps (O(N)worst-case latency spike). - Space complexity:
O(N)per active client, orO(C * N)acrossCactive clients.
- Data stored per client:
Why the sliding window breaks at scale
When traffic grows to millions of clients sending tens of thousands of requests per second, the sliding-window log breaks down in four distinct ways:
- Memory scales with quota size
N, punishing your highest-tier customers. For 1M active clients withN = 1,000, timestamps alone take8 GBpacked (~32 GBin Python). Raising an enterprise tier toN = 10,000multiplies RAM usage 10x even for the exact same number of clients. - Constant heap allocation and garbage-collection churn. Every allowed request allocates a node/float and later frees it—50,000 allocations and deallocations per second right on the hot path, causing garbage-collection pauses.
- Spiky tail latency under locks. If a client bursts 1,000 requests at
t = 0and sends 1 request att = 61, that single call must pop 1,000 items while holding the lock, stalling concurrent requests. - Poor fit for distributed storage. Porting a sliding log to Redis requires one sorted set (
ZSET) per client (ZREMRANGEBYSCORE+ZCARD+ZADD), which takesO(log N)time per request and still consumes gigabytes of expensive Redis RAM.
What about simpler counter approximations? A fixed-window counter (one integer per
60 sclock bucket, like12:00:00–12:00:59) usesO(1)space, but allows2Nrequests instantaneously across a boundary (Nat12:00:59.9andNat12:01:00.0). A sliding-window counter blends the previous and current fixed windows inO(1)space, which is a reasonable approximation, but the token bucket gives an exact physical model, continuous smooth refill, explicit burst control, and natural variable-cost support inO(1)time and space.- Memory scales with quota size
Improved design: token bucket with lazy refill
Conceptual model. Picture each client having a small bucket that holds at most
capacitytokens. Tokens drip into the bucket continuously atrefill_ratetokens per second (for "Nrequests perTseconds", setcapacity = Nandrefill_rate = N / T), and any tokens abovecapacityoverflow and are discarded. When a request ofcostarrives: - If the bucket holds at leastcosttokens, removecosttokens and allow the request. - Otherwise leave the remaining tokens untouched and reject the request.Exact per-client state (
O(1)memory—just two numbers): -current_tokens: how many tokens were in the bucket after the client's most recent check. -last_refill_time: timestamp of that check from a monotonic clock (time.monotonic()), a clock guaranteed to move only forward since process start so NTP wall-clock jumps cannot delete or fabricate tokens.How lazy refill works. Running a background timer thread to add tokens to 1,000,000 buckets every second would waste
O(C)CPU touching 990,000 idle callers. Instead, because tokens drip at a constant linear rate and stop atcapacity, we leave idle buckets untouched and catch up on the math lazily on demand at arrival timestampnow:1. elapsed = max(0.0, now - last_refill_time) 2. earned_tokens = elapsed * refill_rate 3. current_tokens = min(capacity, current_tokens + earned_tokens) 4. last_refill_time = now 5. if current_tokens >= cost: current_tokens -= cost --> ALLOW else: retry_after_s = (cost - current_tokens) / refill_rate --> REJECTWhy is lazy refill 100% equivalent to a continuous drip? Because
min(capacity, ...)clips overflow identically whether no one looked at the bucket for 1 millisecond or 3 hours! Let's tracecapacity = 6,refill_rate = 2.0tokens/s (6req /3 s),cost = 1:now (s) event elapsed min(6, tokens + elapsed * 2.0) decision tokens_after 0.0 new caller (starts full) 0.0 6.0 ALLOW 5.0 0.0 5 more burst requests 0.0 5.0 -> ... -> 1.0 ALLOW x5 0.0 0.0 7th burst request 0.0 0.0 (< 1) REJECT 0.0 (retry in 0.5 s) 0.2 early retry 0.2 min(6, 0.0 + 0.4) = 0.4 REJECT 0.4 (retry in 0.3 s) 0.5 retry 0.3 s later 0.3 min(6, 0.4 + 0.6) = 1.0 ALLOW 0.0 20.0 request after 19.5 s idle 19.5 min(6, 0.0 + 39.0) = 6.0 ALLOW 5.0 (capped at 6!)Notice
now = 0.2andnow = 0.5: savingcurrent_tokens = 0.4andlast_refill_time = 0.2on the rejected request means0.3 slater it adds0.6to reach1.0—splitting elapsed time across partial steps gives the exact same result!import math class BucketState: # __slots__ avoids allocating a per-instance __dict__, cutting Python object memory by ~60%. __slots__ = ("current_tokens", "last_refill_time") def __init__(self, current_tokens: float, last_refill_time: float): self.current_tokens = current_tokens self.last_refill_time = last_refill_time class TokenBucketLimiter: def __init__(self, capacity: float, refill_rate: float): if capacity <= 0 or refill_rate <= 0: raise ValueError("capacity and refill_rate must be positive") self.capacity = capacity # Max burst size (e.g., N) self.refill_rate = refill_rate # Tokens added per second (e.g., N / T) self.buckets = {} # client_id -> BucketState def _lazy_refill(self, bucket: BucketState, now: float) -> None: # Guard against non-positive elapsed time so out-of-order timestamps never subtract tokens. elapsed = now - bucket.last_refill_time if elapsed > 0.0: refilled = bucket.current_tokens + elapsed * self.refill_rate bucket.current_tokens = min(self.capacity, refilled) bucket.last_refill_time = now def allow(self, client_id: str, now: float, cost: float = 1.0) -> tuple: """Return (allowed, remaining_whole_tokens, retry_after_seconds).""" if cost > self.capacity: # A request costing more than bucket capacity can never succeed. return (False, 0, math.inf) bucket = self.buckets.get(client_id) if bucket is None: # Unseen clients start with a full bucket. bucket = BucketState(self.capacity, now) self.buckets[client_id] = bucket else: self._lazy_refill(bucket, now) if bucket.current_tokens >= cost: bucket.current_tokens -= cost return (True, int(bucket.current_tokens), 0.0) missing_tokens = cost - bucket.current_tokens retry_after_s = missing_tokens / self.refill_rate return (False, int(bucket.current_tokens), retry_after_s)Precision detail (floats vs. exact integers): IEEE-754 floats can round
10 * 0.1to0.9999999999999999and reject a boundary request. If you switch to integers, be careful: naive integer division(elapsed_ns * rate) // 10^9combined withlast_refill_ns = now_nsloses remainder nanoseconds if a client retries faster than 1 token-unit! To get exact, remainder-free integer math forNrequests perT_nsnanoseconds, define 1 token =T_nsinteger units:capacity_units = N * T_ns, each nanosecond addselapsed_ns * Nunits (pure integer multiplication, zero division!), and each request subtractscost * T_nsunits.Explicit burst trade-off: With
capacity = Nandrefill_rate = N / T, a client starting full can spendNtokens immediately att = 0and earn anotherNtokens across(0, T], admitting up to2Nrequests in a singleT-second window (never more, and strictlyN / Tlong-run average). If downstream services can only absorb smaller spikes, keeprefill_rate = N / Tand lowercapacity(for example,capacity = 50instead of1,000).Concurrency: keeping per-client updates atomic
Why isn't the single-threaded
TokenBucketLimitersafe in a multi-threaded web server? Because checking a bucket is a read-modify-write sequence. Even in Python (where the GIL switches threads between bytecode instructions), two threads handling requests from the sameclient_idcan interleave:Initial state for client "k_1": current_tokens = 1.0 Thread A (request 1) Thread B (request 2) --------------------------------------- --------------------------------------- reads current_tokens -> sees 1.0 reads current_tokens -> ALSO sees 1.0! checks 1.0 >= 1.0 -> True checks 1.0 >= 1.0 -> True writes current_tokens = 0.0 -> ALLOW writes current_tokens = 0.0 -> ALLOW (2 requests passed on 1 token!)Let's compare concurrency strategies from simplest to highest throughput:
- Single global mutex: Wrap
allow()in onethreading.Lock(). Simple and correct, and at 50,000 req/s × 1 µs = 5% lock utilization it works initially, but across 32+ CPU cores every unrelated client queues behind one lock. - Lock striping / sharded maps (recommended balance): Partition the hash map into
S = 64(or256) independent shards usinghash(client_id) % S. Each shard owns its ownLockand bucket dictionary. Two requests contend only if they hash to the same shard (1/64chance), eliminating cross-core contention in Go/Java/Rust/free-threaded Python with minimal code. - Lock-free Compare-And-Swap (CAS): Pack a 32-bit fixed-point token count and a 32-bit millisecond timestamp into one 64-bit atomic integer (
AtomicU64). Threads loop oncompare_exchangewith zero kernel locks, at the cost of handling 49-day timestamp wrap-around and separate hash-map insertion synchronization.
Read
now = time.monotonic()inside the shard lock so threads always process timestamps in non-decreasing order.- Single global mutex: Wrap
Evicting inactive clients without losing state
Even at ~220 bytes per client in Python, 10 million one-off clients per day would grow memory by gigabytes every day if we never clean up inactive entries.
The lossless eviction insight: How long does it take a completely empty bucket (
0tokens) to refill all the way back tocapacity?idle_ttl = capacity / refill_rate (for capacity = N and refill_rate = N / T, idle_ttl = T seconds!)Once a client has been silent for at least
idle_ttlseconds, its bucket is guaranteed to be 100% full—which is the exact same state a brand-new client gets (BucketState(capacity, now))! Deleting any bucket withnow - last_refill_time >= idle_ttltherefore loses zero rate-limit accuracy.To evict in amortized
O(1)time without background full-table scans, store each shard's buckets in an LRU (Least Recently Used) ordered map (collections.OrderedDict):- Whenever
client_idmakes a request, updatelast_refill_time = nowand callmove_to_end(client_id), keeping every shard's entries sorted from oldestlast_refill_timeat the front to newest at the back. - Inside
allow(), peek at the front entry. Whilenow - oldest.last_refill_time >= idle_ttl(up to a small cap likemax_evictions = 8so one request never pauses to delete 100,000 keys at once), delete the front entry. Stop immediately at the first entry withnow - oldest.last_refill_time < idle_ttl, because every entry behind it is even newer! - Add a hard
max_keys_per_shardsafety cap against a bot rotating millions of spoofed IPs withinTseconds: if full, drop the oldest LRU entry so process memory can never exceed its ceiling.
import threading import time from collections import OrderedDict class Shard: def __init__(self): self.lock = threading.Lock() # OrderedDict maintains access order: front = oldest last_refill_time, back = newest. self.buckets = OrderedDict() class ShardedTokenBucketLimiter: def __init__( self, capacity: float, refill_rate: float, num_shards: int = 64, max_keys_per_shard: int = 50_000, ): self.capacity = capacity self.refill_rate = refill_rate # Any bucket idle for >= idle_ttl seconds has refilled to `capacity` (identical to a new client). self.idle_ttl = capacity / refill_rate self.max_keys_per_shard = max_keys_per_shard self.shards = [Shard() for _ in range(num_shards)] def _evict_expired(self, shard: Shard, now: float, max_steps: int = 8) -> None: # Pop up to `max_steps` idle buckets from the front so per-request latency stays O(1). for _ in range(max_steps): if not shard.buckets: return oldest_key = next(iter(shard.buckets)) oldest_bucket = shard.buckets[oldest_key] if now - oldest_bucket.last_refill_time < self.idle_ttl: # Because entries are ordered by access time, everything behind `oldest_key` is still active. return del shard.buckets[oldest_key] def allow(self, client_id: str, cost: float = 1.0) -> bool: if cost > self.capacity: return False shard = self.shards[hash(client_id) % len(self.shards)] with shard.lock: now = time.monotonic() self._evict_expired(shard, now) bucket = shard.buckets.get(client_id) if bucket is None: # Enforce hard memory cap under spoofed-key floods by dropping the least-recently-used key. if len(shard.buckets) >= self.max_keys_per_shard: shard.buckets.popitem(last=False) bucket = BucketState(self.capacity, now) shard.buckets[client_id] = bucket else: elapsed = now - bucket.last_refill_time if elapsed > 0.0: bucket.current_tokens = min( self.capacity, bucket.current_tokens + elapsed * self.refill_rate ) bucket.last_refill_time = now shard.buckets.move_to_end(client_id) if bucket.current_tokens >= cost: bucket.current_tokens -= cost return True return False- Whenever
Scaling to multiple servers, failure handling, and trade-off summary
Once we run
K = 20stateless API servers behind a round-robin load balancer, purely local buckets let a client consume20 * Nrequests! Three ways to scale out:- Sticky load-balancer routing (consistent-hash
client_keyto one server): Keeps 1 µs local latency, but server deploys/crashes reset buckets and one abusive key overloads a single API host. - Static
N / Ksplit per server: Zero network calls, but uneven load-balancer routing causes false429rejections long before a client actually reachesN. - Shared Redis Cluster + atomic Lua script (industry standard): Store
{tokens, last_ms}in a Redis hash keyed byrl:{client_key}and run the entire read-refill-consume-expire sequence inside one server-side Lua script (EVALSHA). Because a Redis shard executes Lua scripts single-threaded and atomically, zero distributed locks are needed, andPEXPIRE key ceil(idle_ttl_ms)gives automatic lossless eviction for free! Use Redis server time (redis.call("TIME")) inside the script so clock skew across API servers cannot distortelapsed.
API Server 1 --\ /--> Redis Shard 1 (slots 0..5460) API Server 2 --->-- EVALSHA token_bucket(key, cost) -----> Redis Shard 2 (slots 5461..10922) API Server K --/ (~0.5 ms intra-DC round trip) \--> Redis Shard 3 (slots 10923..16383)Failure modes and resilience: - Redis outage or latency spike: Set a strict
5 mstimeout plus a circuit breaker. For general APIs, fail open to the local in-memoryShardedTokenBucketLimiterconfigured atN / K(protecting API availability while still blocking massive floods); for sensitive endpoints like/loginor/password-reset, fail closed or enforce a strict local cap. - Hot keys: If one enterprise key sends 100,000 req/s, it can saturate its single Redis shard. Add a local token lease: each API server leases batches ofB = 50tokens from Redis and spends them locally in memory, cutting Redis traffic by 50x.Final comparison
Property Sliding-window log Sliding-window counter Token bucket (lazy refill) Per-client memory O(N) timestamps (~8 KB) O(1) (2 counts + window) O(1) (2 numbers = 16 B) Per-request time Amortized O(1), worst O(N) O(1) Strict O(1) Window accuracy Exact: <= N in every T Approximate overlap Exact avg N/T; burst <= capacity (up to capacity + N in one T) Idle background CPU None None None (lazy math on arrival) Redis extension ZSET: O(log N), high RAM 2 keys + INCR + EXPIRE 1 Hash + Lua + PEXPIRE: O(1)- Sticky load-balancer routing (consistent-hash
Intuition & how it works
Imagine an amusement park restricting each visitor to 6 rides per 3 minutes. One obvious way is to hire an attendant with a giant notebook who writes down the exact timestamp of every single ride each visitor takes, and before letting someone board, crosses out timestamps older than 3 minutes and counts how many lines remain—that is a sliding-window log (an exact rate-limiting algorithm that stores every accepted request's timestamp in a queue per client). Now imagine a much lighter system: every visitor gets a small pouch (token bucket, a fixed-capacity container that refills at a constant rate and spends tokens on each request) that holds at most 6 tokens and earns 2 new tokens every minute. Better yet, nobody walks around the park dropping tokens into a million empty pouches every minute! Instead, the pouch simply has two numbers printed on a tag—current_tokens and last_refill_time—and when a visitor walks up at now, the attendant checks a monotonic clock (a timer guaranteed to move only forward regardless of system wall-clock adjustments), calculates elapsed = now - last_refill_time, adds elapsed * refill_rate capped at capacity, and checks if enough tokens exist. That on-demand catch-up calculation is called lazy refill (computing accumulated tokens mathematically at arrival time rather than running a periodic background timer).
Why do the naive approaches fall short at scale? Storing every accepted timestamp in a sliding-window log means memory grows with clients * N: 1 million active callers with a quota of N = 1,000 requests hold up to 1 billion timestamps (8 GB of raw 64-bit numbers, or ~32 GB of Python objects), while popping hundreds of expired entries at once creates spiky tail latency. Conversely, implementing a token bucket with a background cron/timer thread that loops over 1 million buckets every second wastes CPU updating 990,000 idle callers that are not sending traffic. Lazy refill + LRU (Least Recently Used) idle eviction (keeping callers ordered by last access so buckets idle long enough to refill completely can be discarded in O(1) time) keeps per-request work strictly O(1) and memory tiny (16 bytes of raw payload per active caller).
Let's trace a compact bucket with capacity = 6 tokens (N = 6), refill_rate = 2.0 tokens/second (T = 3 s), and cost = 1 per request:
Arrival time Elapsed since last Lazy refill: min(6, tokens + elapsed * 2) Decision & tokens left
t = 0.0 s 0.0 s (new caller) starts full at 6.0 ALLOW -> 5.0 left
t = 0.0 s 0.0 s (5 more hits) 5.0 -> 4.0 -> 3.0 -> 2.0 -> 1.0 ALLOW -> 0.0 left
t = 0.2 s 0.2 s min(6, 0.0 + 0.4) = 0.4 (< 1.0 needed) REJECT -> 0.4 left (Retry-After: 1s)
t = 0.5 s 0.3 s min(6, 0.4 + 0.6) = 1.0 (>= 1.0 needed) ALLOW -> 0.0 left
t = 20.0 s 19.5 s (long pause) min(6, 0.0 + 39.0) = 6.0 (capped at 6!) ALLOW -> 5.0 left
Key trade-offs
- Strict rolling-window cap vs.
O(1)memory and burst tolerance. A sliding-window log guarantees at mostNrequests in everyT-second interval, but costsO(N)memory per caller. A token bucket withcapacity = Nandrefill_rate = N / TusesO(1)memory (2 numbers), enforces an exact long-run average ofN / T, and absorbs legitimate parallel requests—at the price of allowing up tocapacity + refill_rate * T = 2Nrequests inside a singleT-second window if a caller starts with a full bucket. Shrinkingcapacitysmooths bursts at the cost of rejecting legitimate parallel page-load calls. - Lazy refill vs. timer-driven background refill. Lazy refill touches zero idle callers, needs no background threads, and has continuous sub-millisecond precision because
min(capacity, current_tokens + elapsed * refill_rate)matches a continuous drip at every instant. A background refill job burnsO(clients)CPU every tick and suffers coarse tick-boundary jumps. - Floating-point math vs. exact integer units. Floats are concise for single-node prototypes, but binary rounding (
10 * 0.1 == 0.9999999999999999) can falsely reject an exact-boundary request. Expressing 1 token asT_nsinteger units (capacity = N * T_ns, addingelapsed_ns * Nper check) makes every update exact deterministic integer arithmetic with zero division remainder loss. - Lock granularity (
1global lock vs.64striped shard locks vs. lock-free CAS). A single global lock serializes all cores; lock striping (hashing keys across 64 independent mutexes and maps) eliminates almost all cross-thread contention in ~15 lines of code; Compare-And-Swap (CAS) (an atomic CPU instruction that updates a 64-bit word only if no other thread modified it first) avoids locks altogether but complicates timestamp wrap-around and map resizing. - Lossless TTL eviction vs. hard memory bound. Evicting callers idle for
>= capacity / refill_rateseconds is 100% lossless because their buckets have already refilled tocapacity, matching a brand-new entry. Adding a hardmax_keys_per_shardLRU cap bounds RAM during spoofed-IP attacks, trading slight leniency (evicted active keys get a fresh bucket) for guaranteed server survival. - In-process state vs. shared Redis Cluster. Local memory checks take
< 1 µswith zero network failure modes, whereas a shared Redis atomic Lua script (a short script executed single-threaded inside Redis so read, refill, and write cannot interleave) enforces a single global limit acrossKservers at the cost of~0.5 msintra-datacenter latency and needing a fail-open (defaulting to allow or local fallback when Redis is unreachable) or fail-closed (blocking requests when Redis is unreachable) policy.
Common mistakes
- Running a background thread to add tokens to all callers every second. That turns an
O(1)per-request problem into anO(total_clients)sweep that wastes CPU on idle keys. - Forgetting
min(capacity, ...)during lazy refill. Without the capacity ceiling, a caller that goes quiet overnight accumulates millions of tokens and can unleash an unbounded flood later. - Advancing
last_refill_time = nowon rejected requests without saving fractional earned tokens (or truncating integer division remainders while resettinglast_refill_time). A caller retrying every100 msfor a1 token/slimit will repeatedly earn0whole tokens, lose its elapsed time, and starve forever. - Using wall-clock time (
time.time()) instead oftime.monotonic()in-process. An NTP clock adjustment backward produces negativeelapsed(subtracting tokens if unguarded) or freezes refills until the clock catches up, while a forward jump hands out free tokens. - Assuming Python's GIL or map lookups make
allow()thread-safe. Two threads can still interleave between readingcurrent_tokensand writingcurrent_tokens - cost, admitting double the allowed burst unless synchronized per shard or per key. - Logging rejected requests in the sliding-window baseline. Appending rejected timestamps keeps the deque full, permanently locking out any caller that retries faster than
N / T. - Setting eviction TTL shorter than
capacity / refill_rate. Expiring a half-empty bucket after5 swhen full recovery takes60 slets an attacker pause briefly and receive a brand-new full bucket early.
Follow-up questions
- Can per-caller state be compressed from two numbers down to a single timestamp without changing admission behavior? Yes, using GCRA (Generic Cell Rate Algorithm), which is mathematically equivalent to a token bucket while storing only one timestamp per caller:
TAT(Theoretical Arrival Time, the instant when the bucket will next reach full capacity). Defining emission intervaltau = 1 / refill_rateseconds per token, an incoming call ofcostatnowcomputesnew_tat = max(TAT, now) + cost * tauand admits the call if and only ifnew_tat - now <= capacity * tau, updatingTAT = new_tatwhen allowed. Becausemax(TAT, now) - nowequals(capacity - current_tokens) * tau, GCRA produces identical decisions in8 bytesinstead of16 bytes. - How would you enforce multiple simultaneous quotas per caller, such as a 20-requests-per-second burst cap alongside a 10,000-requests-per-day ceiling? Represent each quota rule as its own
(capacity, refill_rate)bucket inside the caller's shard lock (or inside one Redis Lua script) and verify that every bucket holds sufficient tokens before deducting from any bucket. Running check-all before deduct-all atomically ensures a request blocked by the daily quota never drains tokens from the per-second bucket, whileRetry-Afterreports the largest recovery delay among violated rules. - In a Redis-backed fleet, how do you stop a single ultra-hot API key sending 100,000 requests per second from saturating one Redis shard? Add hierarchical local token leasing (batch allocation) on API nodes for high-volume keys. Rather than calling Redis on every arrival, each API node checks out batches of
B = 50tokens at once (cost = 50in the Lua script) and deducts up to 50 local arrivals in memory before requesting another batch, paired with a brief200 mslocal negative cache once Redis reports an empty bucket so flood traffic is rejected in process without hitting Redis.
Follow-up questions
- Can per-caller state be compressed from two numbers down to a single timestamp without changing admission behavior?
- How would you enforce multiple simultaneous quotas per caller, such as a 20-requests-per-second burst cap alongside a 10,000-requests-per-day ceiling?
- In a Redis-backed fleet, how do you stop a single ultra-hot API key sending 100,000 requests per second from saturating one Redis shard?
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System