Sub topic 10
Choosing an algorithm: accuracy, memory, burst behavior, cost
This chapter assumes you have read the chapters on the fixed window counter, sliding window log, sliding window counter, token bucket, and leaky bucket. You should be comfortable reading short Python and know what a key-value store such as Redis does. The goal here is to compare the five algorithms on the same axes so you can pick one for a given service and defend the choice.
The four axes
Every limiter trades four things against each other.
- Accuracy is how closely the number of admitted requests matches the policy "at most N in any interval of length T".
- Memory is how much state the limiter stores per key. This matters because the number of keys can reach millions.
- Burst behavior is what happens when a client sends many requests at once. Some algorithms forbid bursts, some allow them up to a set size, and some allow them by accident.
- Cost is the work per request: how many store operations, how complex the update, and how hard the update is to make atomic.
A fifth concern, how easy the algorithm is to explain to API users, often decides close calls.
What each algorithm stores and does
| Algorithm | State per key | Accuracy | Burst behavior | Work per request |
|---|---|---|---|---|
| Fixed window counter | One counter and a window index | Low at window edges | Up to 2x the limit across a boundary | One increment |
| Sliding window log | One timestamp per admitted request | Exact | None beyond the limit | Remove old entries, count, append |
| Sliding window counter | Two counters and a window index | Approximate | Small error near edges | Read two counters, one write |
| Token bucket | Token count and last refill time | Exact for its own rule | Up to bucket capacity, then the refill rate | Read, compute refill, write |
| Leaky bucket | Queue length or level and last drain time | Exact for its own rule | None on output, extra requests wait or drop | Read, compute drain, write |
Two points in the table need care.
First, token bucket and leaky bucket do not enforce the same rule as the window algorithms. A window limiter says "no more than N requests in a window". A token bucket says "an average of refill_rate per second, with bursts of at most capacity". A client that has been idle can send capacity requests at once, and then refill_rate per second. Over a window of length T the bucket can admit up to capacity + refill_rate * T requests. "Exact" for these algorithms means exact against their own rule.
Second, sliding window counter is an estimate. It assumes the previous window's requests were spread evenly. If they were all sent at the end of that window, the estimate undercounts the real load in the sliding window, and the limiter admits slightly more than the limit. If they were sent at the start, it overcounts and rejects slightly early. Published measurements of this approach report very small error rates in practice, but the guarantee is statistical, not strict.
Seeing the boundary problem
The fixed window's weakness is easy to demonstrate. This script uses the fixed window and sliding window counter from the earlier chapters and sends requests around a window edge.
import time
class FixedWindowLimiter:
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.counters = {}
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
class SlidingWindowCounter:
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.state = {}
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
def admitted(limiter, times):
return sum(1 for t in times if limiter.allow("alice", now=t))
# 10 requests in the last second of window 0, 10 in the first second of window 1.
times = [59.0 + i * 0.05 for i in range(10)] + [60.0 + i * 0.05 for i in range(10)]
print("fixed: ", admitted(FixedWindowLimiter(limit=10, window=60), times))
print("sliding:", admitted(SlidingWindowCounter(limit=10, window=60), times))The fixed window admits all 20 requests, even though they all arrive within about 1.5 seconds and the limit is 10 per minute. The sliding window counter admits 10 requests in window 0. At the start of window 1 it still counts nearly all of those 10, so it rejects most of the second burst. Because the estimate decays as the window advances, a few of the later requests may be admitted, but the total stays close to the limit.
Memory at scale
Memory per key multiplies by key count. Suppose you limit 5 million API keys.
- The fixed window counter stores a small integer and a window index. Roughly tens of bytes per key plus store overhead.
- The sliding window counter stores about twice that.
- The token bucket stores a float and a timestamp, similar to the sliding window counter.
- The sliding window log stores one entry per admitted request. At a limit of 1,000 requests per minute, a busy key holds up to 1,000 entries. In a Redis sorted set each entry costs tens of bytes, so one busy key can use tens of kilobytes, and 5 million busy keys would be hundreds of gigabytes.
The log's cost grows with the limit, while every other algorithm's cost is constant per key. That is the main reason the log is rarely used for high limits. It is a good fit for low limits where exactness matters, such as "5 password attempts per 15 minutes".
Burst behavior in practice
Bursts are not always bad. A mobile app that opens and fires eight requests to render one screen has a legitimate burst. A strict 10-per-second smoother would delay or drop part of it, and the user would see a slow screen.
- Token bucket is built for this. Set
capacityto the largest legitimate burst andrefill_rateto the sustained rate. It is the most common choice for public APIs for this reason. - Leaky bucket removes bursts on the output side. Requests enter a queue and leave at a constant rate. Use it when the downstream system cannot tolerate spikes, such as a legacy database or a third-party API with its own strict limit. The cost is added latency for queued requests, and a full queue drops requests.
- Fixed window permits a hidden burst at the boundary. Whether that matters depends on the downstream capacity. If the backend can absorb 2x the limit for a second, fixed window is fine.
- Sliding window log and counter do not permit bursts beyond the limit, but they do permit the whole limit at once. A client with a limit of 100 per minute can send all 100 in the first second.
Cost and implementation difficulty
Cost shows up in two places: operations per request, and the effort to make the update atomic in a shared store.
- Fixed window maps to a single Redis
INCRplusEXPIRE, which is atomic without a script. It is the cheapest to run and the easiest to get right. - Sliding window counter needs two reads and a write that must be consistent, so it usually needs a script or a transaction.
- Token bucket needs a read-modify-write cycle on two fields, so it needs a Lua script. The script shown in the distributed chapters does this in one round trip.
- Sliding window log needs trimming, counting, and appending, and the cost of trimming grows with the number of stale entries.
A script that runs in Redis blocks other commands while it executes. For all of these algorithms the script is short, so the cost is small, but it is not free at very high request rates on a hot key.
A decision procedure
Work through these questions in order.
- Is a hidden 2x burst at window edges acceptable? If yes and you want the simplest system, use the fixed window counter.
- Is the limit low and must it be exact? If yes, use the sliding window log.
- Do you want a rolling window with constant memory? Use the sliding window counter, and accept the approximation.
- Do clients have legitimate bursts, and do you want to state the rule as "rate plus burst size"? Use the token bucket.
- Must the downstream system see a constant rate? Use the leaky bucket, with a bounded queue.
Common mistakes
- Choosing by name, not by rule. "Sliding window" and "token bucket" sound similar but state different policies. Write the policy sentence first, then pick the algorithm that enforces it.
- Using the log for large limits. Memory scales with the limit, not the number of keys alone.
- Setting token bucket capacity equal to one second of refill by default. If clients legitimately burst more, they will be rejected despite staying under their average rate.
- Ignoring the explanation cost. If you cannot state the limit to an API user in one sentence, expect support tickets. "100 requests per minute" is simpler than "10 tokens per second with a capacity of 50".
Exercises
Exercise
A service limits 2 million API keys to 600 requests per minute each. Which algorithm would you avoid for memory reasons, and why?
Show answer
The sliding window log. It stores one timestamp per admitted request, so a busy key can hold up to 600 entries, and the memory grows with the limit as well as with the key count. The fixed window counter, sliding window counter, and token bucket each store a fixed small amount per key.
Exercise
A client has been idle for ten minutes. The API uses a token bucket with capacity 20 and refill rate 2 tokens per second. How many requests can the client send in the first second, and how many in the first ten seconds, if it sends as fast as it can?
Show answer
In the first second it can send about 22 requests: 20 from the full bucket plus the 2 tokens refilled during that second. In ten seconds it can send about 40: the 20 stored tokens plus 20 refilled (10 seconds times 2 per second). The general bound is capacity plus refill_rate times the interval.
Exercise
A fixed window limiter allows 100 requests per minute. What is the largest number of requests a client can get through in any 2-second span, and when does it happen?
Show answer
200 requests. The client sends 100 in the last second of one window and 100 in the first second of the next window, because the counter resets at the boundary.