Sub topic 2
Rate Limer Design: Sliding Window Log
Assume you know basic HTTP, Python, Redis-like key-value stores, and load-balanced services. A rate limiter decides whether a request may continue based on recent request history.
Sliding window log
A sliding window log stores each request timestamp for a client. For a limit of 3 requests per 10 seconds, remove timestamps older than now - 10, then allow the request only if fewer than 3 remain.
from collections import defaultdict, deque
class SlidingWindowLog:
def __init__(self, limit, window_seconds):
self.limit = limit
self.window = window_seconds
self.requests = defaultdict(deque)
def allow(self, client, now):
log = self.requests[client]
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_seconds=10)
print([limiter.allow("alice", now) for now in (0, 1, 2, 3)])
# [True, True, True, False]This method is exact. Its memory use grows with the number of requests in the window, so busy clients and large limits can make it expensive.
Sliding window counter
A sliding window counter stores only the current and previous fixed-window counts. It weights the previous count by the fraction of that window still overlapping the current window. This uses constant memory, but the result is an estimate. Traffic concentrated at window boundaries can produce different decisions from an exact log.
Token bucket
A token bucket holds tokens up to a capacity. Each allowed request spends tokens, and tokens refill over time. Capacity controls burst size; the refill rate controls the long-run rate. This is useful when short bursts are acceptable.
Leaky bucket
A leaky bucket queues accepted work and releases it at a constant rate. It smooths output better than a token bucket, but the queue adds latency and can overflow. It fits systems that need steady downstream traffic.
Choosing an algorithm
| Algorithm | Memory | Bursts | Accuracy |
|---|---|---|---|
| Sliding log | High | Rejects exact excess | Exact |
| Sliding counter | Low | Boundary approximation | Approximate |
| Token bucket | Low | Controlled | Rate and capacity |
| Leaky bucket | Queue-dependent | Smoothed | Rate and queue behavior |
Choose based on the failure cost of excess traffic, memory budget, acceptable bursts, and implementation cost. In a distributed service, store state centrally and update it atomically.
Exercise
Which algorithm should you choose when exact enforcement matters and request volume is modest?
Show answer
Choose a sliding window log because it records each timestamp and makes an exact decision, at the cost of more memory.