Sub topic 17
Testing with a fake clock and monitoring rejections
A rate limiter is a function of time. A test that waits for real seconds to pass is slow and flaky. A limiter nobody watches in production fails silently, either by blocking good users or by letting abuse through. This chapter covers how to test limiters deterministically and which signals to monitor once they are live.
This chapter assumes you can read Python, have written tests with pytest or unittest, and know the algorithms from earlier chapters: fixed window, sliding window counter, and token bucket.
Make time an input
A limiter that calls time.monotonic() inside its methods cannot be tested without sleeping. Two patterns fix this:
- Pass the time into each call, as
FixedWindowLimiter.allow(key, now=...)does. - Inject a clock, which is a callable that returns the current time, through the constructor.
The second pattern keeps the call site clean. In production you pass the real clock. In tests you pass a fake one that only moves when the test says so.
import random
import time
class FakeClock:
"""A clock that only moves when the test advances it."""
def __init__(self, start=0.0):
self.now = start
def __call__(self):
return self.now
def advance(self, seconds):
assert seconds >= 0, "a monotonic clock never goes backward"
self.now += seconds
class TokenBucket:
def __init__(self, capacity, refill_rate, clock=time.monotonic):
self.capacity = capacity
self.refill_rate = refill_rate
self.clock = clock
self.tokens = float(capacity)
self.last = clock()
def allow(self, cost=1):
now = self.clock()
elapsed = now - self.last
self.last = now
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
if self.tokens >= cost:
self.tokens -= cost
return True
return False
class FixedWindowLimiter:
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.counters = {}
def allow(self, key, now):
index = int(now // self.window)
window_index, count = self.counters.get(key, (index, 0))
if window_index != index:
count = 0
if count >= self.limit:
self.counters[key] = (index, count)
return False
self.counters[key] = (index, count + 1)
return True
class SlidingWindowCounter:
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.state = {}
def allow(self, key, now):
index = int(now // self.window)
window_index, current, previous = self.state.get(key, (index, 0, 0))
if index != window_index:
previous = current if index == window_index + 1 else 0
current = 0
window_index = index
fraction = (now % self.window) / self.window
estimated = previous * (1 - fraction) + current
if estimated + 1 > self.limit:
self.state[key] = (window_index, current, previous)
return False
self.state[key] = (window_index, current + 1, previous)
return True
def test_bucket_allows_burst_then_rejects():
bucket = TokenBucket(capacity=5, refill_rate=1, clock=FakeClock())
assert [bucket.allow() for _ in range(6)] == [True] * 5 + [False]
def test_bucket_refills_with_time():
clock = FakeClock()
bucket = TokenBucket(capacity=5, refill_rate=1, clock=clock)
for _ in range(5):
bucket.allow()
clock.advance(2)
assert [bucket.allow() for _ in range(3)] == [True, True, False]
def test_bucket_never_exceeds_capacity():
clock = FakeClock()
bucket = TokenBucket(capacity=5, refill_rate=1, clock=clock)
clock.advance(1000) # a long idle period must not store 1000 tokens
assert sum(bucket.allow() for _ in range(20)) == 5
def test_fixed_window_boundary_burst():
limiter = FixedWindowLimiter(limit=2, window=60)
first = [limiter.allow("a", now=59.0) for _ in range(2)]
second = [limiter.allow("a", now=60.0) for _ in range(2)]
assert all(first + second) # 4 requests in 1 second with limit 2 per 60
def test_sliding_counter_weights_previous_window():
limiter = SlidingWindowCounter(limit=10, window=60)
for _ in range(10):
assert limiter.allow("a", now=119.0)
assert not limiter.allow("a", now=120.0) # previous window counts fully
allowed = sum(limiter.allow("a", now=150.0) for _ in range(10))
assert allowed == 5 # half of the previous window has aged out
def test_bucket_long_run_rate_invariant():
rng = random.Random(42) # fixed seed keeps the test reproducible
clock = FakeClock()
bucket = TokenBucket(capacity=5, refill_rate=2, clock=clock)
allowed = 0
for _ in range(10_000):
clock.advance(rng.random() * 0.5)
allowed += bucket.allow()
assert allowed <= 5 + 2 * clock.now + 1e-6
if __name__ == "__main__":
for name, fn in list(globals().items()):
if name.startswith("test_"):
fn()
print("ok", name)Each test finishes in microseconds and gives the same result on every run.
What to test
| Behavior | Why it matters |
|---|---|
| Burst up to capacity, then rejection | Confirms the limit exists at all |
| Recovery after waiting | Catches refill bugs, such as using integer division |
| Idle time does not accumulate beyond capacity | Prevents a quiet client from banking a huge burst |
| Boundary behavior of windows | Documents the known weakness of the algorithm |
| Keys are independent | One noisy client must not consume another's budget |
| Long-run invariant | Catches drift that example tests miss |
The last row is a property test. Instead of checking one scenario, it runs a random sequence and checks a rule that must always hold: total allowed requests never exceed capacity + rate * elapsed. Seed the random generator so a failure can be replayed.
Testing the Redis script
A script that calls redis.call('TIME') reads the server's clock, and you cannot fake that from the test. You have three options:
- Pass the timestamp as an extra
ARGVvalue in tests and useTIMEonly when it is absent. - Run the script against a real Redis in an integration test, using short real sleeps and generous tolerances.
- Test the algorithm in Python with the fake clock, then run a small number of integration tests to check that the Lua port agrees.
Option 3 is usually the best balance. Keep the Python reference and the Lua script side by side and replay the same request sequence through both. They should return the same decisions.
Also test concurrency. Start many threads or processes that all call the script against one key, and assert that the number of allowed requests never exceeds the capacity. A non-atomic read-modify-write implementation fails this test quickly.
Monitoring in production
A limiter can be wrong without raising any error. If the limit is too low, real customers get 429 responses. If it is too high, it protects nothing. Both problems show up only in metrics.
Track these signals:
- Decisions per rule and outcome. Count
allowedandrejectedseparately, labeled by rule name (for examplelogin_per_ip) and tier. The rejection ratio is your main health signal. - Store errors and timeouts. Count them separately from decisions. Also count how many requests were let through or blocked by the failure policy.
- Limiter latency. The check sits on every request path, so track its p99.
- Top rejected keys. This tells you who is hitting the limit, but it needs care, as explained below.
- Remaining budget. Sample how close clients are to their limit. A rise in near-limit traffic warns you before rejections begin.
A small wrapper shows where the counts belong:
from collections import Counter
decisions = Counter()
def check(limiter, rule, tier, key, now):
try:
ok = limiter.allow(key, now)
except Exception:
decisions[(rule, tier, "store_error")] += 1
return True # fail open; change to False to fail closed
decisions[(rule, tier, "allowed" if ok else "rejected")] += 1
return ok
limiter = FixedWindowLimiter(limit=1, window=60)
check(limiter, "login_per_ip", "free", "1.2.3.4", now=0.0)
check(limiter, "login_per_ip", "free", "1.2.3.4", now=1.0)
print(dict(decisions))In a real service, replace Counter with your metrics client's counter type. The structure stays the same.
Alerts and safe rollout
Alert on changes, not on single values:
- A sudden jump in the rejection ratio for one rule, which may indicate a bad deploy or a legitimate traffic spike.
- A rejection ratio of zero for a rule that normally rejects some traffic. This can mean the limiter stopped being applied.
- Any sustained rate of store errors, since each one triggers your failure policy.
When you introduce a new limit, run it first in shadow mode. The limiter computes decisions and records metrics but never blocks. Compare the "would reject" count against real traffic, adjust the numbers, and then enable enforcement. Shadow mode also verifies that your client identification works, for example that every request really does carry the key you expect.
Exercise
A test for a token bucket with capacity 4 and refill rate 2 tokens per second drains the bucket, advances a fake clock by 1.5 seconds, and then calls allow() repeatedly. How many calls return True before the first False?
Show answer
3. The bucket refills 1.5 seconds times 2 tokens per second, which is 3 tokens. That is below capacity, so nothing is capped. The first three calls each spend one token and return True, and the fourth finds 0 tokens and returns False.
Exercise
Your team wants a dashboard of rejections per user, so an engineer proposes adding user_id as a label on the rejection counter. What is the problem, and what do you do instead?
Show answer
Each distinct user ID creates its own time series, so the number of series grows with the user base and can overload the metrics system. Label the counter by rule and tier only. Get per-user detail from sampled logs or a top-N aggregation that you query on demand.