1.Fixed window, sliding window, token bucket and leaky bucket
A rate limiter decides, for each incoming request, whether to allow it or reject it based on how many requests the same caller has already made recently. The four standard algorithms differ in how they track "recently" and how they handle bursts: fixed window counts requests in a clock-aligned bucket and resets abruptly, sliding window smooths that count across a moving time range, token bucket allows controlled bursts by spending saved-up tokens, and leaky bucket forces a constant output rate regardless of how bursty the input is.
Key features
- Fixed window: count requests in a clock-aligned interval (e.g. per-minute); simplest to implement, but the counter resets abruptly at the window boundary
- The fixed-window boundary-burst problem: because two counters are independent, a caller can send the full limit at the very end of one window and the full limit again at the very start of the next, doubling the effective rate in a short span straddling the boundary
- Sliding window: evaluates the limit over a continuously moving time range (e.g. "the last 60 seconds from now") rather than a clock-aligned bucket, closing the boundary-burst gap at the cost of more state (a log of timestamps, or a weighted blend of the current and previous fixed windows)
- Token bucket: a bucket refills with tokens at a fixed rate up to a cap; each request consumes one token, and unused tokens accumulate — so it naturally allows a burst up to the bucket size after an idle period, then throttles to the refill rate
- Leaky bucket: requests queue into a bucket that drains (is "leaked") at a constant, fixed rate; it smooths bursty arrivals into steady output but can add queuing delay, and requests are dropped if the bucket is full when they arrive
The four algorithms compared
- Fixed window — resets abruptly at the boundary
- Sliding window — a continuously moving range
- Token bucket — allows a burst up to bucket size
- Leaky bucket — constant, fixed drain rate
Command
fixed window: count++ in bucket(now / window_size); reset at boundary
sliding window: count requests where timestamp > (now - window_size)
token bucket: tokens = min(cap, tokens + elapsed * refill_rate); allow if tokens >= 1
leaky bucket: queue.push(request); drain queue at fixed_rate; drop if queue fullFixed window: simple, but up to ~2x the limit can leak through a window boundary. Sliding window: closes that gap, costs more state. Token bucket: allows bursts up to bucket size after idle time. Leaky bucket: forces a constant output rate, queuing or dropping the rest.