System Design · Concept Library · Free article
Sliding Window Counter — a rolling limit without the boundary burst
How to count "requests in the last 60 seconds" over a continuous rolling frame — closing the fixed-window hole a burst can slip through, without storing a timestamp for every request. The boundary burst, the sliding-window log, and the weighted two-counter approximation, for interns through principal engineers.
A fixed-window rate limiter resets its counter on a clock tick, and a burst that straddles that tick sneaks through nearly double the limit — the boundary burst. The sliding window fixes it by counting over a continuous rolling frame (always "the last 60 seconds") instead of snapping to fixed blocks. The exact way — a sliding window log — stores a timestamp for every request and counts the ones still in the frame; perfectly accurate, but its memory grows with traffic, which is fatal for a viral client. The practical way — a sliding window counter — keeps just two numbers (this window’s count and the previous window’s) and estimates the rolling total by weighting the previous window by how much it still overlaps the frame: estimate = current + previous × (window − elapsed) / window. It’s an approximation, but a famously good one (Cloudflare measured ~0.003% error over 400M requests) at flat, O(1) memory — the sweet spot for rate limiting at scale.
The limit that says 100 and lets through 200
Hatch caps link creation at 100 requests per minute per client, and the simplest limiter honors it exactly: a counter per client that resets at the top of each minute. Then a clever abuser notices something. They fire 100 requests at 11:59:59, and another 100 at 12:00:01. Both bursts are allowed — the first minute’s counter saw 100 (fine), and the second minute’s counter, freshly reset, saw 100 (also fine). But step back and look at the clock: that’s 200 requests in about two seconds, double the limit you set, and your logs will swear nothing ever went over 100. Nothing was broken. The limit was gamed through a hole in how time was cut.
Why the fixed window leaks
A fixed window is the cheapest limiter that works: for each client, keep one counter tagged with the current clock-minute (11:59), increment it on every request, and when the minute rolls over, start a fresh counter at zero. One number per client, trivial to store. And for most traffic it’s perfectly fine — the boundary burst only matters when someone is trying to exploit it, or when a natural spike happens to land on the seam.
But the flaw is structural, not a bug you can patch. The counter’s reset is a hard line drawn across time at 12:00:00, and the limiter only ever asks "how many requests in this block?" It has no memory of the block before. So the window that ended at 12:00:00 saw its 100 and was satisfied; the window that began at 12:00:00 saw its 100 and was satisfied; and neither one ever considered the two-second span that crossed the line. In the worst case — a full limit’s worth on each side of the seam — a client gets 2× the limit in an instant, over and over, once per boundary. The tighter and burstier the traffic, the more it hurts.
The sliding window log — exact, but it remembers everything
Here’s the fix that leaves no hole at all. Instead of a counter per block, keep a list of the exact timestamps of a client’s recent requests. When a new request arrives, throw away every timestamp older than 60 seconds, count what’s left, and allow the request only if that running count is under the limit. Because the window is now "the last 60 seconds from right now" — a frame that glides continuously with the clock — there is no reset line for a burst to straddle. Fire 100 at 11:59:59 and the frame at 12:00:01 still sees them (they’re two seconds old), so the next 100 are refused. This is the sliding window log, and it is exact.
The catch is memory. You’re now storing one timestamp for every request, per client — and that cost grows with traffic exactly when you can least afford it. A single viral link or an aggressive bot can rack up hundreds of thousands or millions of requests in a minute, and each one is another entry you have to hold and sweep. Drag one client’s request rate below and watch the log balloon while the thing we’ll build next stays flat:
The interactive version of this example is available when JavaScript loads.
So the sliding window log gives you the perfect answer at a price that explodes under precisely the load a rate limiter exists to handle. For a low-volume, security-critical limit (a few login attempts per hour) that price is nothing and the exactness is worth it. But for a high-throughput public endpoint, you need almost all of that accuracy for almost none of the memory. That’s the sliding window counter.
The sliding window counter — two numbers, one clever weighting
The insight is to keep the shape of a fixed window — cheap per-block counters — but borrow from the block before to smooth over the seam. You store just two numbers per client: the count in the current window, and the count in the previous one. Then you estimate the rolling total by taking all of the current window’s count plus a fraction of the previous window’s — weighted by how much of that previous window still overlaps your rolling 60-second frame. One second into the new window, the frame still covers 59 of the previous 60 seconds, so you count almost all of the previous window; fifty seconds in, the frame has slid mostly off it, so you count almost none. The formula is one line:
Play with the pieces — drag the previous and current counts and the elapsed time, and watch the previous window’s contribution decay as the frame slides forward:
The interactive version of this example is available when JavaScript loads.
Notice what you didn’t do: you never stored a single timestamp. Two counters and a multiply, and the memory is flat no matter whether the client sent 10 requests or 10 million. That’s the whole trade in one move — a rolling window that never resets, at fixed-window cost.
Watch it stop the boundary burst
Back to the exploit that started the page. The abuser fires 100 at 11:59:59 and 100 at 12:00:01. A fixed window resets at the seam and waves both through. The sliding window counter, one second into the new window, is still weighting the previous minute at about 98% — so before the second burst even starts, its estimate is already near 98, and the burst runs straight into the limit. Toggle between the two and see the difference:
The interactive version of this example is available when JavaScript loads.
How good is the approximation, really?
The counter is an estimate, so it’s worth being honest about where it can be wrong. The weighting makes one assumption: that the previous window’s requests were spread evenly across it. Usually they roughly were, and the estimate is excellent. But if the previous window’s traffic was all bunched up at its end — right next to the seam — then the true rolling count is higher than the even-spread math assumes, and a request that should be blocked might slip through. Bunched at the start, and the reverse: the estimate slightly over-counts and might reject a request it could have allowed. Either way the error is small and bounded, never the 2× hole of a fixed window.
Fixed, log, or counter — which one, when
| Strategy | Memory / client | Boundary burst | Accuracy | Reach for it when |
|---|---|---|---|---|
| Fixed window | One counter | Leaks up to 2× | Exact within a block | Cheap internal limits where a 2× burst is harmless |
| Sliding window log | A timestamp per request (grows) | None | Exact | Low-volume, security-critical limits needing precision |
| Sliding window counter | Two counters (flat) | Almost none | ~99.99% (approximate) | High-throughput public limits — the default at scale |
How it’s built (and where the commands live)
In a real distributed limiter, both counters live in a shared store — almost always Redis — so every node reads the same rolling count (the distributed rate limiting flagship is all about why that shared count matters). The log version is a sorted set of timestamps you trim with a range delete; the counter version is just two integer keys per client with a short TTL so old windows expire themselves. The exact Redis commands — and a live fixed-vs-sliding playground — already live on the Redis page, so reach there for the code. The one rule to carry across from it: whichever you use, the read-check-write must happen atomically (a single Lua script), or two nodes racing on the same counter will both think there’s room — the concern the companion atomic counter page is entirely about.
Pitfalls
- Shipping a fixed window on a public endpoint — the 2× boundary burst is a known, easily-exploited hole; use a counter (or a token bucket) for anything user-facing.
- Reaching for the sliding window log at scale — exact, but a viral client’s millions of timestamps can blow your memory budget on a single key. Save the log for low-volume, precision-critical limits.
- Forgetting the TTL on the counters — without an expiry, idle clients’ window keys pile up forever; set a TTL so old windows evict themselves.
- Non-atomic read-modify-write — reading the counts, computing the estimate in app code, then writing back invites the race two nodes can exploit; do it in one atomic step.
- Assuming the estimate is exact — it isn’t, quite; if you truly need to-the-request precision (billing), use the log, not the counter.
Best practices
- Default to the sliding window counter for high-throughput limits — near-exact, flat memory, no boundary hole.
- Keep both counters in a shared store with a TTL, and do the check-and-increment atomically (a Lua script).
- Use the log only where precision beats memory — low-volume, security-critical limits.
- Match the window to the limit — the algorithm caps "N per window"; the window length is a product choice (per-second smoothing vs per-minute fairness).
- Remember it’s an approximation — for anything that must be exact to the request, this isn’t the tool.
The interview deck
- What’s the boundary burst? (intern)
- A fixed-window limiter resets its counter on a clock tick, so a client can fire a full limit just before the reset and another just after — sailing through ~2× the limit in a moment, because each block only saw its own half.
- How does a sliding window fix it? (SDE2)
- It counts over a continuous rolling frame — always "the last N seconds from now" — instead of snapping to fixed blocks, so there’s no reset line for a burst to straddle.
- Log vs counter — what’s the trade? (SDE2 → senior)
- The log stores a timestamp per request: exact, but memory grows with traffic. The counter keeps two numbers (current + previous window) and weights the previous by overlap: approximate, but flat O(1) memory. The counter is the default at scale.
- Give me the counter’s formula. (senior)
estimate = current_count + previous_count × (window − elapsed) / window. The previous window’s weight decays from 1 to 0 as the rolling frame slides off it.- When is the approximation wrong, and does it matter? (senior → staff)
- It assumes the previous window’s requests were evenly spread; if they were bunched at the seam the estimate is slightly off. But the error is small and bounded — Cloudflare measured ~0.003% over 400M requests — and never the 2× of a fixed window. For rate limiting that’s fine; for exact billing, use the log.
The one thing to carry
A rate limit is only as honest as the way it cuts time. Chop time into rigid blocks and a burst slips through the seam; count a continuous rolling frame and the hole closes. You can do that exactly by remembering every request (the log) or approximately by keeping two counters and weighting the previous window by how much of it still overlaps (the counter) — and the approximation is so good, and so cheap, that it’s what the largest systems on the web actually run. Two numbers and a multiply, and "100 per minute" finally means it.
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.