Sub topic 6
Sliding window log: exact but memory-hungry
This chapter assumes you have read the fixed window chapter and can read basic Python. The fixed window counter allows up to twice the limit across a window boundary. The sliding window log removes that flaw by remembering when every recent request happened.
How it works
For each key, store the timestamp of every accepted request. When a request arrives at time now:
- Remove timestamps older than
now - window. - If the number of remaining timestamps is at least
limit, reject the request. - Otherwise, append
nowand accept the request.
The window is anchored to the current request, not to a clock boundary. That is why it is called sliding. At any instant, the log holds exactly the requests from the last window seconds.
Implementation
A deque works well because timestamps are appended in order, so expired entries are always at the left end.
import time
from collections import deque
class SlidingWindowLog:
"""Allows at most `limit` requests per key in any `window`-second span."""
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.logs = {} # key -> deque of accepted request timestamps
def allow(self, key, now=None):
now = time.time() if now is None else now
log = self.logs.setdefault(key, deque())
cutoff = now - self.window
while log and log[0] <= cutoff:
log.popleft()
if len(log) >= self.limit:
return False
log.append(now)
return True
limiter = SlidingWindowLog(limit=3, window=10)
times = [0, 1, 2, 3, 10.5, 11.5]
print([limiter.allow("alice", now=t) for t in times])
# [True, True, True, False, True, True]The request at 3 seconds is rejected because three requests fall in the last 10 seconds. At 10.5 the entry for time 0 has expired, so a slot is free. Only accepted requests are logged. If rejected requests were logged too, a client that keeps retrying would never recover.
Trade-offs
Accuracy is the strength. No window of length window ever contains more than limit accepted requests, so there is no boundary burst.
Memory is the weakness. Each key stores up to limit timestamps, so memory grows with the limit multiplied by the number of active keys. In a Redis sorted set, an entry can cost several tens of bytes. As a rough estimate, 1 million active users with a limit of 100 requests each is about 100 million entries, which is several gigabytes. Each request also costs time proportional to the number of entries it evicts, plus the cost of the set operations.
| Property | Sliding window log |
|---|---|
| Accuracy | Exact |
| Memory per key | Up to `limit` timestamps |
| Work per request | Eviction plus one insert |
| Bursts | None beyond `limit` per window |
Use it when limits are small and exactness matters, for example 5 login attempts per 15 minutes. Avoid it for high limits across many keys, where the sliding window counter is the usual substitute.
Exercise
A limiter allows 1,000 requests per hour per user. About 200,000 users are active in an hour, and each stored timestamp costs about 40 bytes. Roughly how much memory does a sliding window log need in the worst case, and why might the real figure be lower?
Show answer
The worst case is 1,000 × 200,000 × 40 bytes = 8 GB. The real figure is lower because most users do not reach their limit, and the log only holds accepted requests from the last hour.