Sub topic 7
Sliding Window Counter: A Cheap Approximation
This chapter assumes you know how the fixed window counter works and why it allows a burst at window boundaries. It also assumes you can read basic Python. The Redis section only needs a rough idea of key-value storage with expiry.
The problem this algorithm solves
The fixed window counter stores one number per client, which makes it cheap. It also lets a client send limit requests at the end of one window and limit more at the start of the next. Those requests all land within a few seconds, so the client sends up to twice the limit.
The sliding window log fixes this by storing a timestamp for every accepted request. It is exact, but its memory grows with the limit, which is costly for large limits and many clients.
The sliding window counter sits between the two. It stores two counters per client and estimates a true sliding window from them. You get most of the accuracy of the log at nearly the memory cost of the fixed window.
How the estimate works
Divide time into fixed windows, as in the fixed window counter. At any moment, the "sliding window" is the last window seconds. That span usually covers part of the previous fixed window and part of the current one.
The algorithm assumes the previous window's requests were spread evenly. If you are 25% of the way into the current window, the sliding window still overlaps the last 75% of the previous window. So it counts 75% of the previous window's requests:
estimated = previous * (1 - fraction) + currentHere fraction is how far you are into the current window, from 0 to 1. A request is allowed if estimated + 1 <= limit. The + 1 accounts for the request being evaluated.
The 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=130.0))Three details matter here:
- Rotation. When the window index changes, the old current count becomes the new previous count. This only happens if the new window directly follows the old one (
index == window_index + 1). If the client was idle for two or more windows, the previous count is 0, because nothing happened in the window just before. - Time is a parameter. Passing
nowmakes the class testable without sleeping. Chapter 17 returns to this idea. - Rejected requests are not counted. The counter only increments on success. A client that keeps retrying while limited does not extend its own penalty. If you want to punish retry storms, increment before the check instead. That is a policy choice, not a bug.
A worked example
With a limit of 10 per 60 seconds, suppose alice sends 8 requests during window 1, then returns 15 seconds into window 2.
limiter = SlidingWindowCounter(limit=10, window=60)
# Window 1 covers t=60..119. Eight requests at t=100.
for _ in range(8):
limiter.allow("alice", now=100.0)
# Window 2 covers t=120..179. Now t=135 is 15s in, so fraction = 0.25.
# The previous window contributes 8 * 0.75 = 6.0 to the estimate.
results = [limiter.allow("alice", now=135.0) for _ in range(6)]
print(results) # [True, True, True, True, False, False]The estimate starts at 6.0. Each accepted request adds 1. After four acceptances the estimate is 10.0, so a fifth request would make 11 and is rejected. Alice sent only 4 requests in this window, but the 8 from the previous window still count at 75% weight.
Now consider the case that breaks the fixed window. Alice sends 10 requests at t=119 and tries again at t=120. At t=120, fraction is 0, so the previous window counts in full. The estimate is 10, and the request is rejected. A fixed window limiter would have allowed 10 more.
Accuracy and its limits
The estimate is only exact if the previous window's requests were evenly distributed. When they were not, the estimate drifts in either direction:
- If the previous window's requests were all near its start, the sliding window no longer contains them, but the estimate still counts a share of them. The limiter rejects requests it should have allowed.
- If they were all near the end, the estimate undercounts. The limiter allows more than
limitrequests in some true 60-second spans.
If you need exact enforcement, such as billing or a hard contractual cap, use the sliding window log. If you want a smooth steady rate with a burst allowance, use the token bucket.
Comparison with neighbors
| Property | Fixed window | Sliding window counter | Sliding window log |
|---|---|---|---|
| State per key | 1 counter + window id | 2 counters + window id | 1 timestamp per request |
| Boundary burst | Up to 2x limit | Mostly smoothed | None |
| Accuracy | Exact per window, wrong across boundaries | Approximate | Exact |
| Cost per request | O(1) | O(1) | O(1) amortized, plus eviction |
Moving to Redis
The in-process version has two gaps. It is not thread-safe, and the state dictionary never evicts idle keys, so it grows without bound. In a distributed deployment, each application server would also see only its own traffic.
The usual remedy is to keep the two counters in Redis. Use one key per client and window, such as rl:alice:2, and set the key to expire after two window lengths. Then a key for an idle client disappears on its own. The read of the previous count, the estimate, and the increment of the current count must run as one atomic step, for example in a Lua script, or two servers can both pass the check at the same moment. Chapters 12 and 13 cover this in detail.
Common errors
- Dividing by the wrong unit.
now % windowandwindowmust use the same unit, such as seconds. Mixing milliseconds and seconds produces a fraction far above 1, which makes the previous weight negative and the estimate too low. - Forgetting the idle gap. Always set
previousto 0 when more than one window has passed. Otherwise a stale count suppresses a client that has been quiet for hours. - Using wall-clock time that jumps.
time.time()can move backward after a clock adjustment. A negative elapsed time can produce an out-of-range index. Production code should clamp or use a trusted single time source. - Treating the estimate as a guarantee. Tell clients the limit is approximate if the exact count matters to them. Return
Retry-Aftervalues with some margin.
Exercise
A limiter allows 100 requests per 60 seconds using a sliding window counter. In the previous window a client made 80 requests. The client is now 30 seconds into the current window and has made 40 requests in it. Is the next request allowed?
Show answer
The fraction is 30/60 = 0.5. The estimate is 80 * (1 - 0.5) + 40 = 80. Adding the new request gives 81, which is not greater than 100, so the request is allowed.
Exercise
A client sends 50 requests in the first second of a window, then nothing for the rest of that window. The limit is 60 per 60 seconds. At 59 seconds into the next window, with no requests yet in that window, the client tries a new request. The limiter's estimate is nearly 0 there, but the true count over the last 60 seconds is also close to 0. Now, at 1 second into the next window, how does the estimate compare with the true count, and in which direction is the error?
Show answer
At 1 second into the next window, the fraction is 1/60, so the previous window is weighted at 59/60 and the estimate is about 49. The true sliding window covers the last 60 seconds. The 50 requests were made 60 seconds earlier, at the very start of the previous window, so they have just left the true window and the true count is about 0. The estimate overcounts, so the limiter wrongly rejects some requests that the exact log would allow. Early-clustered traffic causes over-rejection, and late-clustered traffic causes over-allowing.