Sub topic 6
Sliding window log: exact but memory-hungry
This chapter assumes you know the fixed window counter from the previous chapters, including its boundary burst problem. It also assumes you can read basic Python and have a rough idea of Redis sorted sets. The goal is to understand what the sliding window log guarantees, what it costs, and when that cost is worth paying.
The idea
A fixed window counter stores one number per client and resets it on a clock boundary. A client can send a full quota at the end of one window and another full quota at the start of the next. The sliding window log removes the boundary by dropping the counter and storing the timestamp of every accepted request.
On each new request at time now, the limiter does three things:
- Discard every timestamp that is no longer inside the window, meaning
timestamp <= now - window. - Count the timestamps that remain.
- If the count is below the limit, record
nowand allow the request. Otherwise reject it.
The window is anchored to the current request, not to the wall clock. That is why it is called sliding. At any instant, the limiter answers an exact question: how many requests did this client make in the last window seconds?
A single-process implementation
A queue is the natural structure. Timestamps arrive in increasing order, so the oldest entry is always at the front and eviction only has to look there. Python's collections.deque gives O(1) appends and pops at both ends.
import time
from collections import deque
class SlidingWindowLog:
"""Allows at most `limit` requests per key in any `window` seconds.
Single-process and not thread-safe.
"""
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.logs = {} # key -> deque of accepted request times
def _evict(self, log, now):
cutoff = now - self.window
while log and log[0] <= cutoff:
log.popleft()
def allow(self, key, now=None):
now = time.monotonic() if now is None else now
log = self.logs.setdefault(key, deque())
self._evict(log, now)
if len(log) >= self.limit:
return False # rejected requests are not recorded
log.append(now)
return True
def retry_after(self, key, now=None):
"""Seconds until the oldest entry leaves the window."""
now = time.monotonic() if now is None else now
log = self.logs.get(key)
if not log:
return 0.0
self._evict(log, now)
if len(log) < self.limit:
return 0.0
return max(0.0, log[0] + self.window - now)
limiter = SlidingWindowLog(limit=3, window=10)
times = [0, 1, 2, 3, 10, 10.5, 11, 12]
print([limiter.allow("alice", now=t) for t in times])
# [True, True, True, False, True, False, True, True]Trace the output to see the exact behavior. Requests at 0, 1, and 2 fill the log. The request at 3 is rejected. At 10, the entry for time 0 has left the window, so one slot opens and the request is allowed. At 10.5 the log holds 1, 2, and 10, so it is full again. A fixed window of 10 seconds would have allowed three requests at time 2 and three more at time 10, which is six requests in eight seconds. The log never allows more than three in any ten-second span.
Two details matter here.
- Rejected requests are not logged. If you recorded them, a client that keeps retrying would keep its own window full and never recover. Not recording them means a rejected client regains capacity as soon as its oldest accepted request ages out.
retry_afteris exact. The limiter knows which entry must expire before a slot opens, so it can give a precise wait time. Approximate algorithms can only estimate this. The response chapter uses this value for theRetry-Afterheader.
What it costs
The accuracy comes from storing one entry per accepted request. Memory per client grows with the limit, not with a fixed small constant.
| Algorithm | State per key | Memory grows with |
|---|---|---|
| Fixed window counter | One counter and a window index | Number of keys only |
| Sliding window counter | Two counters and a window index | Number of keys only |
| Token bucket | A token count and a timestamp | Number of keys only |
| Sliding window log | One timestamp per accepted request | Number of keys times the limit |
Consider a service with 1,000,000 active clients and a limit of 100 requests per minute. If each entry costs about 64 bytes, which is a plausible figure for a Redis sorted set member plus its score and overhead, the worst case is 1,000,000 × 100 × 64 bytes, or about 6.4 GB. Raise the limit to 10,000 per hour and the same fleet could need hundreds of gigabytes. Treat these numbers as an estimate and measure your own store, because the per-entry cost depends on encoding and member size.
Time cost also grows. Eviction is amortized O(1) with a deque, but in a Redis sorted set, removing old entries is O(log N + M), where M is the number of removed entries. The cost per request is therefore not constant under heavy load.
Distributed version with a Redis sorted set
In a distributed deployment, the log lives in a Redis sorted set. Each accepted request becomes a member, and its score is the timestamp in milliseconds. Eviction is a range delete by score, and the count is ZCARD.
Members in a sorted set must be unique. If two requests arrive in the same millisecond and you use the timestamp as the member, the second ZADD overwrites the first and the log undercounts. Pass a unique request ID as the member instead.
The steps must run atomically, for the same reason as in the token bucket script. Two servers that each count 99 entries and then each add one would both allow the 100th and 101st request. A Lua script closes that gap.
-- KEYS[1] = log key (sorted set)
-- ARGV[1] = limit, ARGV[2] = window in milliseconds, ARGV[3] = unique request id
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window_ms = tonumber(ARGV[2])
local request_id = ARGV[3]
local t = redis.call('TIME')
local now_ms = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
-- Evict entries at or before the start of the window.
redis.call('ZREMRANGEBYSCORE', key, '-inf', now_ms - window_ms)
local count = redis.call('ZCARD', key)
if count >= limit then
-- Report how long until the oldest entry expires.
local oldest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
local retry_ms = tonumber(oldest[2]) + window_ms - now_ms
return {0, retry_ms}
end
redis.call('ZADD', key, now_ms, request_id)
redis.call('PEXPIRE', key, window_ms)
return {1, 0}Using the Redis server's clock avoids skew between application servers. The PEXPIRE call removes the key of an idle client, so abandoned keys do not accumulate. Because every accepted request refreshes the expiry, the key lives exactly as long as it could still contain a live entry.
When to choose it
The sliding window log fits when all of these hold:
- The limit is small, such as 5 login attempts per 15 minutes or 10 password resets per hour.
- Exactness matters, for example for security or billing rules where "at most N in any interval" must be literally true.
- You want an exact
Retry-Aftervalue without estimating. - The number of distinct keys is modest.
It fits poorly for high limits, such as 10,000 requests per minute per client, or for very large numbers of keys. In those cases the sliding window counter gives most of the benefit for two counters per key, and the token bucket gives burst control at constant memory. The comparison chapter covers that decision in full.
Edge cases
- Window boundary comparison. Decide whether an entry exactly
windowseconds old is inside or outside the window. The code above treatstimestamp <= now - windowas expired, so a window is half-open. Pick one rule and apply it everywhere, including tests. - Non-monotonic clocks. The deque relies on timestamps arriving in order. With
time.time()and a clock step backward, the front of the deque may not be the oldest entry. Usetime.monotonic()in a single process, or the store's clock in a distributed one. - Cost greater than one. The log records one entry per request. To charge a request a cost of 5, you must add five entries, which multiplies memory. If you need weighted requests, prefer a token bucket.
- Counting rejected requests. Some designs log rejections to punish abusive clients. That is a deliberate penalty policy, not the standard algorithm, and it makes recovery slower.
Exercise
A limiter allows 200 requests per hour per user and has 500,000 active users. Each log entry takes about 64 bytes. Estimate the worst-case memory for a sliding window log, and say why a sliding window counter would use far less.
Show answer
Worst case is 500,000 × 200 × 64 bytes = 6.4 GB, because every user at the limit holds 200 entries. A sliding window counter stores only two counters and a window index per user, so memory depends on the number of users and not on the limit. Its cost would be a few tens of bytes per user, on the order of tens of megabytes in total. The trade-off is that the counter only approximates the sliding window.
Exercise
In the Redis script, why should the sorted set member be a unique request ID and not the timestamp?
Show answer
Sorted set members are unique. If two requests share a millisecond and the timestamp is the member, the second ZADD updates the existing member instead of adding a new one. The log then holds fewer entries than the number of accepted requests, and the limiter allows more traffic than the limit.