Sub topic 5
Fixed Window Counter and Its Boundary Burst Problem
This chapter assumes you know basic HTTP request and response concepts and can read Python. You should also know what a key-value store such as Redis does. It covers the simplest rate limiting algorithm, how to implement it, and the flaw that motivates the algorithms in later chapters.
How the algorithm works
A fixed window counter divides time into equal, aligned windows, such as every 60 seconds starting at the top of the minute. Each client key has one counter per window. Every request increments the counter. When the counter reaches the limit, further requests in that window are rejected. When a new window starts, the count resets to zero.
The window index is floor(now / window). Two timestamps share a window when they produce the same index. Because windows are aligned to the clock rather than to each client's first request, all clients reset at the same moment.
Implementation
The class below stores one (window_index, count) pair per key. It takes now as an optional argument so you can test it without waiting for real time.
import time
class FixedWindowLimiter:
"""Allows at most `limit` requests per key in each window of `window` seconds."""
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.counters = {} # key -> (window_index, count)
def allow(self, key, now=None):
now = time.time() if now is None else 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
limiter = FixedWindowLimiter(limit=2, window=60)
print([limiter.allow("alice", now=100.0) for _ in range(3)]) # True, True, False
print(limiter.allow("alice", now=121.0)) # new window: TrueAt now=100, the index is 1, so the first two calls pass and the third is rejected. At now=121, the index is 2, so the count resets and the call passes.
Strengths
- Memory use is one small record per key.
- Each check is O(1) time.
- The logic is easy to reason about and to implement with Redis
INCRplusEXPIRE.
The boundary burst problem
The limit applies per window, not per any 60-second span. A client can send the full limit just before a boundary and the full limit again just after it. With a limit of 5 per minute, requests at 59 s and 60 s are in different windows, so up to 10 requests fit within about one second. In general, the worst case is twice the limit in a span as short as the gap between two requests.
The following code reproduces the effect:
limiter = FixedWindowLimiter(limit=5, window=60)
burst = [limiter.allow("bob", now=59.5) for _ in range(5)]
burst += [limiter.allow("bob", now=60.5) for _ in range(5)]
print(sum(burst)) # 10 allowed within one secondWhen to use it
Fixed windows suit coarse quotas, such as 10,000 calls per day, where a 2x edge effect is tolerable and simplicity matters. For protection against short bursts, use the sliding window counter or the token bucket, covered in later chapters.
Exercise
A fixed window limiter allows 100 requests per 60 seconds. What is the largest number of requests one client can get accepted between t=119 s and t=121 s, and why?
Show answer
200. Window 1 covers 60 to 120 s and window 2 covers 120 to 180 s. The client sends 100 requests between 119 and 120 s, which fill window 1. It then sends 100 more between 120 and 121 s, which fall in the new window with a reset counter. All 200 are accepted within two seconds.