Custom algorithms¶
An algorithm defines how a rate such as 5/minute is enforced. Algorithms compares the three built-ins. A custom one is a class with a name and a step() method.
Example: per-caller windows¶
The built-in FixedWindow is clock-aligned, so every caller's window ends at the same instant. This algorithm starts each caller's window at their first request:
@dataclass(frozen=True)
class WindowFromFirstUse:
"""Fixed-size window that starts at each caller's first request, not on the clock."""
@property
def name(self) -> str:
# Part of every storage key, so algorithms never read each other's state.
# Change it whenever the meaning of the state changes.
return "window-from-first-use"
def step(
self, state: BucketState | None, rate: Rate, now: float, cost: int, *, force: bool
) -> tuple[BucketState, Decision]:
# `state` is the tuple returned last time for this bucket, or None when the
# store holds nothing (never used, or expired).
started, used = now, 0.0
if state is not None and state[1] and now - rate.period < state[0] <= now + rate.period:
# Reuse the window only if usage was recorded and it is still open. A
# zero-cost peek starts no window. State more than one period ahead means
# the clock moved backwards and is discarded; a smaller regression
# restarts the window from now.
started, used = min(state[0], now), state[1]
left = started + rate.period - now
# Decide whether the cost fits before applying it.
fits = used + cost <= rate.limit
if fits or force:
used += cost
retry_after = 0.0 if fits else (rate.period if cost > rate.limit else left)
decision = Decision(
allowed=fits,
rate=rate,
remaining=max(0, rate.limit - int(used)),
# The state's TTL: stores may drop it afterwards. Zero when nothing was
# counted, so empty buckets are never stored.
reset_after=left if used > 0 else 0.0,
retry_after=retry_after,
)
return (started, used), decision
Pass it when constructing the limiter. An algorithm applies to every limit that Limiter creates:
# An algorithm is a limiter's: every limit this one makes counts this way.
limiter = Limiter(algorithm=WindowFromFirstUse())
Full example: examples/algorithm_window.py.
Contract¶
An Algorithm is a pure function over state: step(state, rate, now, cost, *, force) returns the new state and a Decision. It keeps nothing itself. The store passes in one bucket's state (a short tuple of numbers, or None when nothing is stored) and persists what comes back, so an algorithm works with any store and can be unit-tested without one.
- Decide before counting: Compute whether the cost fits, and
retry_after, before applying it. Apply the cost when it fits or whenforce=True.allowedreports whether it fit, forced or not. - Zero cost is a peek:
cost=0consumes nothing and changes nothing. It must not start a window. retry_after:0when the cost fits; one fullperiodwhencost > limit, since it can never fit.reset_afteris the state's TTL: After that long, the returned state is equivalent to none and the store drops it. Return0when nothing was counted. Too short forgets usage; too long bloats the store.- Clock regressions: When
nowis earlier than the state's own time, behave as if no time has passed. Discard state from more than one period ahead so a clock jump cannot lock a bucket for long. namenamespaces state: It is part of every storage key, so two algorithms never read each other's state. Change it whenever the meaning of the state changes.
Contract tests¶
tests/ratelimit/test_algorithm_contract.py holds four Hypothesis properties that the built-ins pass (100 generated timelines each, using the helper in replay.py). Run them against your algorithm:
@pytest.mark.parametrize(
"rule",
[
contract.test_decisions_are_well_formed,
contract.test_a_denied_request_changes_nothing_for_the_ones_after_it,
contract.test_state_can_be_dropped_once_reset_after_has_passed,
contract.test_a_cost_of_zero_never_uses_anything_up,
],
)
def test_the_example_algorithm_keeps_every_rule_the_built_in_ones_keep(rule: object) -> None:
rule(algorithm=own_window.WindowFromFirstUse()) # type: ignore[operator] # pyright: ignore[reportCallIssue] # ty: ignore[not-callable] - a test called as a function
The properties never force a cost and never move the clock backwards, so an algorithm that ignores force, or that locks a bucket after a clock regression, passes all four. Cover those two rules with explicit cases:
def test_a_forced_cost_is_counted_and_still_says_it_did_not_fit() -> None:
window, rate = own_window.WindowFromFirstUse(), Rate(3, MINUTE)
state, _ = window.step(None, rate, 0.0, 3, force=False)
state, forced = window.step(state, rate, 1.0, 2, force=True)
assert not forced.allowed
assert state[1] == 5 # counted all the same
_, after = window.step(state, rate, 2.0, 0, force=False)
assert after.remaining == 0
def test_a_clock_set_back_cannot_shut_a_bucket_for_longer_than_a_period() -> None:
window, rate = own_window.WindowFromFirstUse(), Rate(3, MINUTE)
full, _ = window.step(None, rate, 10_000.0, 3, force=False)
# Set back by less than a period: nothing is forgotten, and the wait is one period.
state, soon = window.step(full, rate, 9_990.0, 1, force=False)
assert not soon.allowed
assert soon.retry_after == rate.period
assert state[0] == 9_990.0 # the window is not left beginning ahead of now
# Set back by more than a period: what was counted is thrown away.
_, long_ago = window.step(full, rate, 100.0, 1, force=False)
assert long_ago.allowed
With RedisStore¶
Built-in algorithms run inside Redis as a single Lua script. Custom algorithms run in your process with optimistic read-modify-write (2 round trips, retried under contention). That is correct at any load, but slower than the built-ins on hot keys shared across many processes. See Custom algorithms with RedisStore.