Sub topic 17
Testing with a fake clock and monitoring rejections
This chapter assumes you can read the Python limiters from earlier chapters and know what a metrics counter is. It covers how to test time-dependent limiter logic without sleeping, and which signals to watch once the limiter is in production.
Why tests need a fake clock
A limiter's behavior depends on elapsed time. A test that calls time.sleep(2) is slow and flaky, and it cannot reproduce edge cases such as a request arriving exactly at a window boundary. The fix is to inject the clock. The limiter takes a function that returns the current time, and tests pass in one they control.
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):
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
def test_burst_then_reject():
bucket = TokenBucket(5, 1, FakeClock())
assert [bucket.allow() for _ in range(5)] == [True] * 5
assert bucket.allow() is False
def test_refill_over_time():
clock = FakeClock()
bucket = TokenBucket(5, 1, clock)
for _ in range(5):
bucket.allow()
clock.advance(2)
assert [bucket.allow() for _ in range(3)] == [True, True, False]
def test_idle_time_does_not_exceed_capacity():
clock = FakeClock()
bucket = TokenBucket(5, 1, clock)
clock.advance(1000)
assert [bucket.allow() for _ in range(6)] == [True] * 5 + [False]
if __name__ == "__main__":
test_burst_then_reject()
test_refill_over_time()
test_idle_time_does_not_exceed_capacity()
print("all passed")The default time.monotonic keeps production behavior unchanged. The fixed window and sliding window limiters from earlier chapters already accept a now argument, so they need no change.
Cases worth testing
- Boundaries. With a fixed window of 60 seconds and a limit of 2, send two requests at
59.9and two at60.0. All four pass, which confirms the boundary burst. A sliding window counter should reject some of them. - Idle periods. A long gap must not push a bucket above capacity.
- Keys. Exhausting one key must not affect another.
- Cost. A request with
cost=3against two remaining tokens is rejected and consumes nothing. - Clock going backwards. Check that elapsed time is never negative, as the Lua script does with
math.max(0, ...).
Unit tests with a fake clock cannot catch races. Test atomicity separately, by running concurrent clients against a real Redis and checking that the number of allowed requests never exceeds the limit.
Monitoring rejections
A limiter that works silently is hard to tune. Emit these signals:
| Signal | What it tells you |
|---|---|
| Allowed and rejected counts, per rule | The rejection ratio. A sudden rise means abuse, a client bug, or a limit set too low. |
| Rejections per client tier | Whether paying customers are being throttled. |
| Limiter errors | How often the store failed and the fail-open or fail-closed policy applied. |
| Store latency (p99) | The time the limiter adds to every request. |
| Top rejected keys | Which clients to contact or block. |
Alert on a sustained change in rejection ratio, not on single rejections. Rejections are the limiter doing its job. Also consider a shadow mode, where a new limit logs would-be rejections without enforcing them, so you can check a limit against real traffic first.
Exercise
Why does the TokenBucket above take a clock argument instead of calling time.monotonic directly, and what test becomes possible as a result?
Show answer
Injecting the clock lets a test control time with a FakeClock. The test can advance time by exact amounts, for example 2 seconds, and check that exactly 2 tokens refill. It needs no sleeping, runs instantly, and gives the same result every run.