Sub topic 5
Fixed window counter and its boundary burst problem
This chapter assumes you can read short Python programs and know what an HTTP request is. It also assumes you have a rough idea of what a key-value store such as Redis does. The earlier chapters covered why services limit request rates and which requirements shape a limiter. Here you build the simplest counting algorithm, measure where it fails, and decide when the failure is acceptable.
How the algorithm works
A fixed window counter divides time into equal, clock-aligned intervals. With a 60-second window, one window covers seconds 0 to 59 of each minute, the next covers 60 to 119, and so on. Each client key has a counter for the current window. A request increments the counter if it is below the limit and is rejected otherwise. When a new window starts, the counter goes back to zero.
The window number comes from integer division of the timestamp:
window_index = floor(now / window_size)All requests with the same window_index share one counter. Because the index comes from the wall clock and not from the client's first request, every key's windows line up with the same boundaries.
A working implementation
Save this as fixed_window.py. The __main__ guard lets the next example import the class without running the demo.
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
if __name__ == "__main__":
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: TrueThe code makes these choices:
- Injectable clock.
allowacceptsnowas a parameter. Tests can then control time without sleeping. A later chapter builds on this. - Per-key state. Each key stores one tuple of two integers, so memory is O(1) per active key.
- Lazy reset. Nothing runs at the window boundary. The counter resets the next time that key makes a request and the stored index no longer matches.
- Rejected requests are not counted. The counter stops at
limit, so a client that keeps retrying does not push its count higher.
With a limit of 2 and a 60-second window, requests at t=100 fall in window 1 (seconds 60 to 119). The third is rejected. A request at t=121 falls in window 2, so the count starts again.
The boundary burst problem
The limit says "at most N requests per window," but clients experience time as continuous. They do not see the window boundaries. A client can send N requests at the very end of one window and N more at the very start of the next. Both batches are within the limit, yet the server receives 2N requests in a very short span.
from fixed_window import FixedWindowLimiter
limiter = FixedWindowLimiter(limit=5, window=60)
# Five requests just before the boundary at t=60, five just after it.
times = [59.0, 59.1, 59.2, 59.3, 59.4, 60.0, 60.1, 60.2, 60.3, 60.4]
results = [limiter.allow("alice", now=t) for t in times]
print(results)
print("allowed:", sum(results), "in", round(times[-1] - times[0], 1), "seconds")Every call returns True, and the last line prints allowed: 10 in 1.4 seconds. The configured rate is 5 per minute, but the server absorbed 10 requests in under two seconds.
How bad can it get
Take any interval as long as one window, for example 59.0 to 119.0 in the demo. The limiter can admit up to 2 * limit requests inside it. The worst case is a factor of two over the stated rate. The overshoot is also concentrated into a burst instead of being spread out.
| Property | Value |
|---|---|
| Stated limit | N requests per window |
| Worst case in any window-length interval | 2N requests |
| Worst-case burst duration | As short as one request interval |
| Requires | Client sends at both edges of a boundary |
An honest client rarely does this by accident. A client that retries on a timer, or a script that starts at a round clock time, can hit it often. A deliberate client can do it every window.
Other side effects of aligned windows
The boundary burst is the main issue, but aligned windows have several more:
- Synchronized resets. If you return a reset time, many rejected clients will retry at the same instant, the start of the next window. The burst is then at the start of every window. Adding random jitter to client retry delays reduces the spike.
- Unfair behavior near the edge. A client that arrives one second before a boundary gets one second of quota, then a full fresh quota. A client that arrives at the start gets the full window and nothing more.
- Stale keys. The dictionary above never removes entries, so memory grows with the number of distinct keys ever seen. In production, expire old entries. In Redis, set a TTL of one window or slightly more when you create the counter.
Strengths and when to use it
Fixed window is cheap and easy to explain. It needs one integer per key and one increment per request. It also maps directly onto quota language, such as "1,000 calls per day" or "100 per minute," which clients understand.
It is a good fit when:
- The window is long (hours or a day) and a 2x burst at the edge is acceptable, for example billing quotas.
- The protected resource has headroom for twice the nominal rate.
- You need the cheapest possible shared-state design.
It is a poor fit when the limit protects something fragile, such as a database with a hard throughput ceiling, and 2x of the rate would hurt it. Later chapters cover the sliding window variants and the token bucket, which reduce or remove the boundary burst.
Fixed window on a shared store
In a multi-server deployment the counter usually lives in Redis. The key combines the client identity and the window index, for example rl:alice:28. Each request runs INCR on that key and compares the result to the limit. The first request in a window also sets an expiry of about one window.
Because the window index is part of the key, you do not need a reset step. Old keys expire on their own.
Computing retry information
A rejected request should tell the client when to try again. For a fixed window the answer is exact: the time left in the current window.
import math
def retry_after_seconds(now, window):
window_end = (int(now // window) + 1) * window
return math.ceil(window_end - now)
print(retry_after_seconds(now=121.0, window=60)) # 59At t=121 the window ends at 180, so the client should wait 59 seconds. Returning this in a Retry-After header is covered in the chapter on HTTP 429 responses.
Summary
- A fixed window counter keeps one count per key per clock-aligned window.
- It uses little memory and is simple to implement and share across servers.
- It can admit up to twice the limit within one window-length interval across a boundary.
- Aligned windows also cause synchronized retries at reset time.
- Use it when quotas are coarse and the burst is tolerable. Use a different algorithm when the protected resource cannot take 2x.
Exercise
A fixed window limiter allows 100 requests per 60-second window. A client sends 100 requests at t=119.5 and 100 more at t=120.5. How many are allowed, and what is the actual rate the server sees over that one-second interval?
Show answer
All 200 are allowed. The first batch falls in window 1 (60 to 119, index 1)... more precisely, t=119.5 is in the window covering 60 to 119.999, and t=120.5 is in the next window covering 120 to 179.999. Each batch is within its own window's limit of 100. The server sees 200 requests in one second, which is 2x the limit concentrated into about one second, even though the configured rate is 100 per minute.
Exercise
Why does the Redis version of a fixed window limiter put the window index in the key, and what problem does this avoid?
Show answer
With the index in the key (for example rl:alice:28), each window gets a fresh counter, so no reset step is needed at the boundary. Old keys expire through their TTL. This avoids a race where one server resets a shared counter while another increments it, and it avoids having to track when each window started.