Sub topic 7
Sliding window counter: a cheap approximation
This chapter assumes you know how the fixed window counter works and its boundary burst problem. You should also be comfortable reading short Python.
The idea
A fixed window counter resets at each window boundary. A client can send the full limit just before the boundary and the full limit again just after it, so up to twice the limit passes in a short span.
The sliding window log fixes this by storing every request timestamp. That is exact, but memory grows with the limit and the number of keys.
The sliding window counter keeps only two numbers per key: the count for the current fixed window and the count for the previous one. It estimates the request count in the last window seconds by weighting the previous count by how much of that window is still inside the sliding range:
estimated = previous * (1 - fraction) + currentfraction is how far you are into the current window, from 0 to 1. At 25% into the window, 75% of the previous window still overlaps the sliding range.
Implementation
import time
class SlidingWindowCounter:
"""Approximates a sliding window using the current and previous fixed windows."""
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.state = {} # key -> (window_index, current_count, previous_count)
def allow(self, key, now=None):
now = time.time() if now is None else 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
limiter = SlidingWindowCounter(limit=10, window=60)
print([limiter.allow("alice", now=70.0) for _ in range(8)]) # eight True
print([limiter.allow("alice", now=135.0) for _ in range(6)]) # four True, then False, FalsePassing now explicitly keeps the example deterministic. It also makes the class easy to test with a fake clock.
Worked example
Alice sends 8 requests in window 1 (seconds 60 to 119). At second 135, she is 15 seconds, or 25%, into window 2. The previous count is 8 and the current count is 0.
- The estimate starts at
8 * 0.75 + 0 = 6. - Each allowed request raises the current count by 1, so the estimate rises by 1.
- At a current count of 3 the estimate is 9.
9 + 1is not greater than 10, so the request is allowed and the count becomes 4. - At a current count of 4 the estimate is 10.
10 + 1 > 10, so the request is rejected.
Four requests pass, which matches the weighted view. A fixed window would have allowed all 10 immediately.
Gotchas
- It is an estimate. It assumes the previous window's requests were spread evenly. If they all arrived at the end of that window, the estimate undercounts what is really in the sliding range, and the limiter admits slightly more than the limit. If they all arrived at the start, it overcounts and rejects some requests a log would have allowed.
- Skipped windows reset history. If a client is idle for more than one full window,
previousbecomes 0. This is correct, because nothing from that period is still in range. - Rejected requests are not counted. Only allowed requests increment
current, so a client that keeps hammering the limiter does not extend its own penalty. - Not thread-safe or shared. This version lives in one process. In a distributed limiter, the read and write must be atomic, which later chapters cover.
Exercise
With limit=100 and window=60, a key has previous=80 and current=30. It is now 30 seconds into the current window. Is the next request allowed?
Show answer
fraction is 0.5, so estimated = 80 * 0.5 + 30 = 70. Since 70 + 1 = 71 does not exceed 100, the request is allowed.
Exercise
Name one situation where the sliding window counter admits more requests than the true sliding window log would.
Show answer
When the previous window's requests were bunched near its end. The weighted estimate treats them as evenly spread and gives them less weight than they deserve, so it undercounts the real load in the sliding range.