Implementing token-bucket and sliding-window limiters
Build a token bucket, a fixed window, a sliding log and a sliding counter in plain Python with an injectable clock, prove their behaviour with deterministic checks, and compare their bursts, memory and accuracy on one seeded trace.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Write the token bucket
- Step 2: Watch the bucket on a fake clock
- Step 3: Write the window limiters
- Step 4: Check the behaviour, including the boundary burst
- Step 5: Compare all four on the same traffic
- Step 6: Switch to a real clock
- Check your understanding
- Apply it
- Review prompt
Lessons of Rate Limiting
- Why limit: abuse, fairness, cost and overload Concept · 15 min
- Token bucket, leaky bucket, fixed and sliding windows Concept · 20 min
- Implementing token-bucket and sliding-window limiters Lab · 30 min
- Going distributed: atomic counters, races and store outages Worked example · 25 min
- Where to enforce limits and how clients should react Concept · 15 min
- Rate limiter check Knowledge check · 6 questions
What you will learn
- Implement token-bucket and sliding-window rate limiters and compare their burst behavior, memory and accuracy.
01. Goal and setup
Lesson 02 described the algorithms. In this lab you build four of them in plain Python and test them so that every machine gives the same answer. The trick is an injectable clock: each limiter receives a function that returns the current time instead of calling time.time() itself. Tests pass a fake clock that moves only when the test moves it, so "ten requests at t=59, then ten at t=60.5" takes no real time and does not depend on how fast your computer is.
You will finish with a short token-bucket demo, seven checks with no randomness (including the fixed window's boundary burst and how the sliding window handles it), and a table that compares the limiters on one seeded stream of requests.
You need Python 3.10 or newer and a terminal; nothing is installed. The lab was run with Python 3.12.13 and 3.10.12 on Linux. Create an empty folder and save every file inside it.
mkdir ratelimit-lab && cd ratelimit-lab
python3 --versionPython 3.12.1302. Step 1: Write the token bucket
Save the file below as bucket.py. Calling FakeClock returns the fake time, and advance() moves it forward. TokenBucket keeps two numbers per key, the tokens left and when they were counted. tokens() applies the lazy refill from lesson 02: it adds elapsed × rate and caps the result at capacity, so no background timer is needed.
allow() takes a cost, so an expensive operation can spend several tokens. It is all or nothing: a request that costs more than the tokens left is rejected and spends nothing. stored() reports how many numbers the limiter keeps for a key; step 5 uses it to compare memory.
"""A token-bucket rate limiter that reads time from an injectable clock."""
class FakeClock:
"""A clock that only moves when a test moves it."""
def __init__(self, start: float = 0.0) -> None:
self.now = start
def __call__(self) -> float:
return self.now
def advance(self, seconds: float) -> None:
self.now += seconds
class TokenBucket:
"""Up to `capacity` tokens per key, refilled at `rate` tokens per second."""
def __init__(self, capacity: float, rate: float, clock) -> None:
self.capacity = capacity
self.rate = rate
self.clock = clock # any function that returns seconds as a float
self.state: dict[str, tuple[float, float]] = {} # key -> (tokens, last)
def tokens(self, key: str) -> float:
"""Tokens the key has now. No timer refills buckets: we compute it."""
now = self.clock()
tokens, last = self.state.get(key, (self.capacity, now))
return min(self.capacity, tokens + (now - last) * self.rate)
def allow(self, key: str, cost: float = 1) -> bool:
tokens = self.tokens(key)
allowed = tokens >= cost # all or nothing: a rejected request spends 0
if allowed:
tokens -= cost
self.state[key] = (tokens, self.clock())
return allowed
def stored(self, key: str) -> int:
"""How many numbers this limiter keeps for the key."""
return 2 if key in self.state else 0python3 -m py_compile bucket.py && echo bucket.py okbucket.py ok03. Step 2: Watch the bucket on a fake clock
Save this as try_bucket.py. It gives the key alice a bucket of 5 tokens refilled at 1 token per second, sends a few groups of requests and prints Y for each admitted request and n for each rejected one.
"""Watch one token bucket: capacity 5, refilled at 1 token per second."""
from bucket import FakeClock, TokenBucket
clock = FakeClock()
bucket = TokenBucket(capacity=5, rate=1, clock=clock)
def send(n: int, cost: float = 1) -> None:
marks = ''.join('Y' if bucket.allow('alice', cost) else 'n' for _ in range(n))
left = bucket.tokens('alice')
print(f't={clock():5.1f} cost {cost:g} {marks:<8} tokens left {left:.1f}')
send(7) # a full bucket: 5 pass at once
clock.advance(1.5)
send(2) # 1.5 tokens came back: one more passes
clock.advance(0.5)
send(1) # 0.5 left + 0.5 new = 1 token
clock.advance(60)
send(7) # a minute idle: the bucket holds 5, not 60
clock.advance(3)
send(1, cost=5) # 3 tokens, the request needs 5
send(1, cost=3)python3 try_bucket.pyt= 0.0 cost 1 YYYYYnn tokens left 0.0
t= 1.5 cost 1 Yn tokens left 0.5
t= 2.0 cost 1 Y tokens left 0.0
t= 62.0 cost 1 YYYYYnn tokens left 0.0
t= 65.0 cost 5 n tokens left 3.0
t= 65.0 cost 3 Y tokens left 0.0A full bucket absorbs a burst of 5 and rejects the rest at once. After 1.5 seconds, 1.5 tokens have come back: one request passes and half a token stays, which the next half second completes. After a minute of silence the bucket holds 5 tokens, not 60, because the refill is capped. The last two lines show the all-or-nothing rule: a request that costs 5 is rejected and the 3 tokens remain for a request that costs 3.
04. Step 3: Write the window limiters
Save the three window-based limiters as windows.py. Each takes limit, window (in seconds) and clock.
FixedWindownumbers the windows (time // window) and keeps the window number and a count per key. When the number changes, the count starts again from zero.SlidingLogkeeps adeque(a list with fast removal at the front) of admission times per key. It drops times that are a full window old, then compares how many are left with the limit.SlidingCounterkeeps the window number and two counts. In a new window the current count becomes the previous one, weighted by the share of the previous window still inside the lastwindowseconds.
Only admitted requests are recorded, so a blocked client that keeps retrying does not extend its own block. Some anti-abuse limiters deliberately count rejected attempts too.
"""Window-based rate limiters: fixed window, sliding log, sliding counter."""
from collections import deque
class FixedWindow:
"""At most `limit` requests per key in each window [k*W, (k+1)*W)."""
def __init__(self, limit: int, window: float, clock) -> None:
self.limit = limit
self.window = window
self.clock = clock
self.state: dict[str, tuple[int, int]] = {} # key -> (window number, count)
def allow(self, key: str) -> bool:
number = int(self.clock() // self.window)
start, count = self.state.get(key, (number, 0))
if start != number: # another window: forget the old count
count = 0
allowed = count < self.limit
self.state[key] = (number, count + 1 if allowed else count)
return allowed
def stored(self, key: str) -> int:
return 2 if key in self.state else 0
class SlidingLog:
"""At most `limit` requests per key in any span of `window` seconds."""
def __init__(self, limit: int, window: float, clock) -> None:
self.limit = limit
self.window = window
self.clock = clock
self.logs: dict[str, deque[float]] = {} # key -> times of admitted requests
def allow(self, key: str) -> bool:
now = self.clock()
log = self.logs.setdefault(key, deque())
while log and log[0] <= now - self.window: # forget times older than W
log.popleft()
if len(log) >= self.limit:
return False
log.append(now)
return True
def stored(self, key: str) -> int:
return len(self.logs.get(key, ()))
class SlidingCounter:
"""Estimates the last W seconds from this window's count and the last one's."""
def __init__(self, limit: int, window: float, clock) -> None:
self.limit = limit
self.window = window
self.clock = clock
self.state: dict[str, tuple[int, int, int]] = {} # key -> (number, cur, prev)
def estimate(self, key: str) -> float:
now = self.clock()
number = int(now // self.window)
start, current, previous = self.state.get(key, (number, 0, 0))
if number == start + 1: # next window: this count becomes "previous"
current, previous = 0, current
elif number > start + 1: # quiet for two windows or more
current, previous = 0, 0
self.state[key] = (number, current, previous)
gone = (now % self.window) / self.window # share of this window used up
return current + previous * (1 - gone)
def allow(self, key: str) -> bool:
if self.estimate(key) >= self.limit:
return False
number, current, previous = self.state[key]
self.state[key] = (number, current + 1, previous)
return True
def stored(self, key: str) -> int:
return 3 if key in self.state else 0python3 -m py_compile windows.py && echo windows.py okwindows.py ok05. Step 4: Check the behaviour, including the boundary burst
Now turn the claims of lesson 02 into checks. Save this as check_limiters.py. Each check builds a fresh limiter on a fake clock and asserts what must happen; the script prints ok or FAIL and exits with code 1 if anything failed, so it could run in continuous integration. The three boundary checks send the same traffic to three limiters: 10 requests at t=59 and 10 at t=60.5, with a limit of 10 per 60 seconds.
"""Deterministic checks for the four limiters. Run: python check_limiters.py"""
import sys
from bucket import FakeClock, TokenBucket
from windows import FixedWindow, SlidingCounter, SlidingLog
CHECKS = []
def check(fn):
CHECKS.append(fn)
return fn
def admitted(limiter, n: int, key: str = 'alice') -> int:
return sum(limiter.allow(key) for _ in range(n))
@check
def bucket_burst_then_rate():
"""token bucket: a full bucket of 5 admits 5 at once, then 1 per second"""
clock = FakeClock()
bucket = TokenBucket(capacity=5, rate=1, clock=clock)
assert admitted(bucket, 8) == 5
clock.advance(1)
assert admitted(bucket, 3) == 1
@check
def bucket_refill_is_capped():
"""token bucket: after an hour idle it holds capacity, not 3,600 tokens"""
clock = FakeClock()
bucket = TokenBucket(capacity=5, rate=1, clock=clock)
admitted(bucket, 5)
clock.advance(3600)
assert admitted(bucket, 10) == 5
@check
def bucket_cost_is_all_or_nothing():
"""token bucket: a request costing more than is left spends nothing"""
clock = FakeClock()
bucket = TokenBucket(capacity=5, rate=1, clock=clock)
admitted(bucket, 2)
assert not bucket.allow('alice', cost=4)
assert bucket.tokens('alice') == 3
@check
def fixed_window_boundary_burst():
"""fixed window, 10 per 60: 20 pass between t=59 and t=60.5"""
clock = FakeClock(start=59)
fixed = FixedWindow(limit=10, window=60, clock=clock)
first = admitted(fixed, 10)
clock.advance(1.5) # t=60.5: a new window number, so a fresh count
second = admitted(fixed, 10)
assert (first, second) == (10, 10)
@check
def sliding_log_holds_the_boundary():
"""sliding log, 10 per 60: the same burst gets 10, then 0 until t=119"""
clock = FakeClock(start=59)
log = SlidingLog(limit=10, window=60, clock=clock)
first = admitted(log, 10)
clock.advance(1.5)
second = admitted(log, 10)
clock.advance(58.5) # t=119: the first ten are exactly 60 s old
third = admitted(log, 10)
assert (first, second, third) == (10, 0, 10)
@check
def sliding_counter_estimates_the_boundary():
"""sliding counter, 10 per 60: the burst gets 10 + 1 (an estimate)"""
clock = FakeClock(start=59)
counter = SlidingCounter(limit=10, window=60, clock=clock)
first = admitted(counter, 10)
clock.advance(1.5) # estimate = 0 + 10 * (1 - 0.5/60), about 9.92
second = admitted(counter, 10)
assert (first, second) == (10, 1)
@check
def keys_are_independent():
"""every limiter: alice running out does not slow down bob"""
clock = FakeClock()
limiters = [
TokenBucket(capacity=3, rate=1, clock=clock),
FixedWindow(limit=3, window=60, clock=clock),
SlidingLog(limit=3, window=60, clock=clock),
SlidingCounter(limit=3, window=60, clock=clock),
]
for limiter in limiters:
assert admitted(limiter, 5, 'alice') == 3
assert admitted(limiter, 5, 'bob') == 3
if __name__ == '__main__':
failed = 0
for fn in CHECKS:
try:
fn()
print(f'ok {fn.__doc__}')
except AssertionError:
failed += 1
print(f'FAIL {fn.__doc__}')
print(f'{len(CHECKS) - failed} of {len(CHECKS)} checks passed')
sys.exit(1 if failed else 0)python3 check_limiters.pyok token bucket: a full bucket of 5 admits 5 at once, then 1 per second
ok token bucket: after an hour idle it holds capacity, not 3,600 tokens
ok token bucket: a request costing more than is left spends nothing
ok fixed window, 10 per 60: 20 pass between t=59 and t=60.5
ok sliding log, 10 per 60: the same burst gets 10, then 0 until t=119
ok sliding counter, 10 per 60: the burst gets 10 + 1 (an estimate)
ok every limiter: alice running out does not slow down bob
7 of 7 checks passedThe fourth check is the boundary burst. t=59 is in window 0 and t=60.5 in window 1, so the fixed window sees two fresh counts and admits all 20 requests within a second and a half, twice the limit. The sliding log admits the first 10, rejects the next 10 because the earlier ten are still inside the last 60 seconds, and admits again at t=119, when they become 60 seconds old. The sliding counter admits 11: at t=60.5 it weights the previous count of 10 by (1 − 0.5/60), gets about 9.92, which is below 10, and lets one more through. That extra request is the price of storing three numbers instead of a timestamp per request.
Change an expected value, for example (10, 10) to (10, 9), run the script to see a FAIL line, then change it back.
06. Step 5: Compare all four on the same traffic
Checks prove single cases; a trace shows typical behaviour. Save compare.py. A seeded random generator builds the same 122 requests for everyone: about one request every 4 seconds over 240 seconds, plus 25 requests in the 5 seconds before t=60 and 25 in the 5 seconds after it. Every limiter allows 20 requests per 60 seconds; the two token buckets have the "obvious" settings (capacity 20, 20 tokens per 60 seconds) and half of each. The script prints the requests admitted, the most admitted in any 60-second span, and the most numbers stored for the key.
"""Replay one seeded traffic trace through every limiter: 20 requests per 60 s."""
import random
from bucket import FakeClock, TokenBucket
from windows import FixedWindow, SlidingCounter, SlidingLog
LIMIT, WINDOW = 20, 60
def make_trace(seed: int = 7) -> list[float]:
rng = random.Random(seed)
times, t = [], 0.0
while t < 240: # background: one request every 4 s on average
t += rng.expovariate(1 / 4)
times.append(t)
times += [55 + i * 0.2 for i in range(25)] # burst just before t=60
times += [60 + i * 0.2 for i in range(25)] # and just after it
return sorted(times)
def worst_span(admitted: list[float]) -> int:
"""Most admitted requests inside any span (t - WINDOW, t]."""
best, start = 0, 0
for end, t in enumerate(admitted):
while admitted[start] <= t - WINDOW:
start += 1
best = max(best, end - start + 1)
return best
def replay(name: str, make, trace: list[float]) -> None:
clock = FakeClock()
limiter = make(clock)
admitted, most_stored = [], 0
for t in trace:
clock.now = t
if limiter.allow('client'):
admitted.append(t)
most_stored = max(most_stored, limiter.stored('client'))
print(f'{name:<22}{len(admitted):>9}{worst_span(admitted):>13}{most_stored:>9}')
trace = make_trace()
print(f'{len(trace)} requests over 240 s, limit {LIMIT} per {WINDOW} s')
print(f'{"algorithm":<22}{"admitted":>9}{"worst 60 s":>13}{"stored":>9}')
replay('fixed window', lambda c: FixedWindow(LIMIT, WINDOW, c), trace)
replay('sliding log', lambda c: SlidingLog(LIMIT, WINDOW, c), trace)
replay('sliding counter', lambda c: SlidingCounter(LIMIT, WINDOW, c), trace)
replay('bucket 20, 20 per 60 s', lambda c: TokenBucket(20, 20 / 60, c), trace)
replay('bucket 10, 10 per 60 s', lambda c: TokenBucket(10, 10 / 60, c), trace)python3 compare.py122 requests over 240 s, limit 20 per 60 s
algorithm admitted worst 60 s stored
fixed window 70 38 2
sliding log 67 20 20
sliding counter 68 21 3
bucket 20, 20 per 60 s 87 39 2
bucket 10, 10 per 60 s 50 19 2- Accuracy. Only the sliding log keeps every 60-second span at 20 or fewer. The sliding counter goes one over, as in step 4. The fixed window lets 38 through around t=60.
- Bursts. The token bucket with the obvious settings admits 39 in one span: a full bucket of 20, then the 20 tokens that drip in during the next minute. That matches the rule from lesson 02, at most
capacity + rate × W= 20 + 20 = 40. Halving both settings keeps it at 19, but it admits only 50 requests overall instead of 87, because its long-run rate is halved too. A token bucket cannot give a large burst, a high average and a strict per-minute cap at once. - Memory. The sliding log stored 20 timestamps for this key; the others stored 2 or 3 numbers. With a limit of 1,000 per hour and a million active keys, that difference decides whether the limiter fits in memory.
07. Step 6: Switch to a real clock
In a running service, pass time.monotonic, not time.time. time.time() is wall-clock time, which the operating system can step backwards or forwards when it synchronises with a time server, so a limiter that reads it can refill buckets wrongly or reset windows early. The Python documentation describes time.monotonic() as a clock that cannot go backwards. Save this as real_clock.py and run it:
"""The same bucket on a real clock. time.monotonic never jumps backwards."""
import time
from bucket import TokenBucket
bucket = TokenBucket(capacity=5, rate=1, clock=time.monotonic)
print([bucket.allow('alice') for _ in range(6)])python3 real_clock.py[True, True, True, True, True, False]Six calls take microseconds, so the bucket cannot refill and the sixth is rejected. Two limits of these classes matter in a server. They are not thread-safe: two threads can both read 1 token and both spend it, so wrap allow() in a threading.Lock. And they live in one process: run three copies of your service and a client gets three times the limit. Lesson 04 moves the token bucket into a shared store to fix that.
08. Check your understanding
09. Apply it
Extend the lab, one change at a time, and keep check_limiters.py passing:
- Make
TokenBucketthread-safe with athreading.Lock, then add a check that starts 8 threads which callallow()100 times each on a bucket of 50 with a rate of 0, and asserts that exactly 50 pass. - Add
retry_after(key, cost=1)toTokenBucket: the seconds untilcosttokens will be available,(cost - tokens) / rate, or 0. Lesson 05 sends this value to clients in theRetry-Afterheader. - Write a
LeakyQueuelimiter from the simulation in lesson 02 and add it tocompare.py. Add a column for the longest time a request waited.
Then read the practice task of this skill again: the next lesson does the same work with a token bucket kept in Valkey or Redis, shared by two application instances.
10. Review prompt
Without looking back: explain why the limiters take a clock as a parameter and which clock a production service should pass. Describe what the fixed window, the sliding log and the sliding counter each did with 10 requests at t=59 and 10 at t=60.5. Then explain, with the formula, why a token bucket with capacity 20 and 20 tokens per minute admitted 39 requests in one minute, and what you give up when you halve both settings.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.