Fixed window, sliding window and token bucket
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's limiter must decide which requests count as recent. Count in fixed minutes and a client can double its limit at the edge; remember every timestamp and memory grows. Which counting rule do you pick?
Your turn: design the counting rule
ShopLite allows 5 login attempts a minute per user. Before you read on, think about how you would count them.
- What would you store per user: one number, a list, or something else?
- A user sends 5 attempts at 0:59 and 5 more at 1:01. Should all 10 pass?
- How much memory is that for a million users?
Fixed window counter and the boundary-burst problem
Fixed window is a limiter that cuts time into equal blocks, such as one minute, and counts each client's requests in the current block. At the next block the counter goes back to 0.
The simplest limiter cuts time into one-minute blocks and counts each client's requests in the current block.
Example 1 · Fixed window counter: 5 requests a minute
class FixedWindowLimiter { private final int limit; private final long windowMillis; private long windowStart = -1; private int count;
FixedWindowLimiter(int limit, long windowMillis) { this.limit = limit; this.windowMillis = windowMillis; }
boolean tryAcquire(long nowMillis) { long start = nowMillis / windowMillis * windowMillis; // 0:00, 1:00, 2:00 ... if (start != windowStart) { // a new window: reset windowStart = start; count = 0; } if (count < limit) { count++; return true; } return false; }}
public class FixedWindowDemo { public static void main(String[] args) { FixedWindowLimiter limiter = new FixedWindowLimiter(5, 60_000); long[] seconds = {2, 10, 15, 20, 30, 41, 55, 61, 62}; for (long s : seconds) { boolean ok = limiter.tryAcquire(s * 1000); System.out.println("t=" + s + "s -> " + (ok ? "allowed" : "rejected")); } }}t=2s -> allowed t=10s -> allowed t=15s -> allowed t=20s -> allowed t=30s -> allowed t=41s -> rejected t=55s -> rejected t=61s -> allowed t=62s -> allowed
What this code does
- Time is cut into fixed blocks of 60 seconds.
nowMillis / windowMillis * windowMillisgives the start of the block the request falls in. - Inside one block the counter goes up to 5; requests 6 and 7 (at 41 s and 55 s) are rejected.
- At 61 s a new block starts, the counter resets to 0 and requests are allowed again. Memory per client: one start time and one counter.
Example 2 · The boundary burst: 10 requests in 2 seconds
class FixedWindowLimiter { private final int limit; private final long windowMillis; private long windowStart = -1; private int count;
FixedWindowLimiter(int limit, long windowMillis) { this.limit = limit; this.windowMillis = windowMillis; }
boolean tryAcquire(long nowMillis) { long start = nowMillis / windowMillis * windowMillis; if (start != windowStart) { windowStart = start; count = 0; } if (count < limit) { count++; return true; } return false; }}
public class BoundaryBurstDemo { public static void main(String[] args) { FixedWindowLimiter limiter = new FixedWindowLimiter(5, 60_000); long[] millis = {59_000, 59_200, 59_400, 59_600, 59_800, 60_000, 60_200, 60_400, 60_600, 60_800}; int allowed = 0; for (long t : millis) { if (limiter.tryAcquire(t)) allowed++; } System.out.println("Limit: 5 per minute"); System.out.println("Allowed between 59.0 s and 60.8 s: " + allowed); }}Limit: 5 per minute Allowed between 59.0 s and 60.8 s: 10
What this code does
- A smart client sends 5 requests just before the window ends and 5 more just after the new one starts.
- Both windows see only 5 requests, so all 10 pass: double the limit inside 2 seconds. This is the boundary-burst problem of fixed windows.
When the count reaches the limit, the rest of that block is rejected. The cost is two numbers per client and one division per request.
Its weak spot is the edge between two windows. A client can use the full limit at the end of one window and again at the start of the next, so it gets twice the limit within a few seconds. This is the boundary burst.
Predict the output
Predict how many requests pass
The limit is 3 a minute. Read the code, then pick what it prints.
Six requests arrive around the minute boundary at 60,000 ms.
Sliding window log with a Deque of timestamps
Sliding log is a limiter that keeps the time of every allowed request in a queue. On each request it removes times older than the window and allows the request only if fewer than the limit remain.
Keep a timestamp for every allowed request, and on each new request forget the ones older than 60 seconds.
Example 3 · Sliding window log with a Deque of timestamps
import java.util.ArrayDeque;import java.util.Deque;
class SlidingLogLimiter { private final int limit; private final long windowMillis; private final Deque<Long> log = new ArrayDeque<>(); // oldest at the front
SlidingLogLimiter(int limit, long windowMillis) { this.limit = limit; this.windowMillis = windowMillis; }
boolean tryAcquire(long nowMillis) { while (!log.isEmpty() && log.peekFirst() <= nowMillis - windowMillis) { log.pollFirst(); // older than one window: forget it } if (log.size() < limit) { log.addLast(nowMillis); return true; } return false; }
int stored() { return log.size(); }}
public class SlidingLogDemo { public static void main(String[] args) { SlidingLogLimiter limiter = new SlidingLogLimiter(5, 60_000); long[] millis = {59_000, 59_200, 59_400, 59_600, 59_800, 60_000, 60_200, 60_400, 60_600, 60_800, 119_100}; for (long t : millis) { boolean ok = limiter.tryAcquire(t); System.out.println("t=" + t / 1000.0 + "s -> " + (ok ? "allowed" : "rejected") + " (stored " + limiter.stored() + ")"); } }}t=59.0s -> allowed (stored 1) t=59.2s -> allowed (stored 2) t=59.4s -> allowed (stored 3) t=59.6s -> allowed (stored 4) t=59.8s -> allowed (stored 5) t=60.0s -> rejected (stored 5) t=60.2s -> rejected (stored 5) t=60.4s -> rejected (stored 5) t=60.6s -> rejected (stored 5) t=60.8s -> rejected (stored 5) t=119.1s -> allowed (stored 5)
What this code does
- The log keeps the time of every allowed request. Before each check it drops times older than 60 seconds from the front.
- The same boundary traffic now gets only 5 through: at 60.0 s the last 60 seconds already hold 5 requests. At 119.1 s the request from 59.0 s has expired, so one more is allowed.
- It is exact, but it stores up to
limittimestamps per client. With a limit of 1,000 a minute and a million clients that is a lot of memory.
The window "slides" with the clock: it always covers exactly the last 60 seconds, so there is no boundary burst. An ArrayDeque<Long> fits well, because old times leave from the front and new times join at the back.
The cost is memory: up to limit timestamps per client, which grows with both the limit and the number of clients.
Find the bug
Spot the sliding log bug
Each snippet has one wrong line. Tap it, then read the fix.
Remove the times that are older than the window.
Round 1 of 2Sliding window counter approximation
Sliding counter is a limiter that keeps only two counts per client, the previous window and the current one, and estimates the last full window as previous × (share of previous still inside) + current.
Keep two numbers per client, last window's count and this window's count, then blend them by how far into the current window you are.
Example 4 · Sliding window counter: two counters and a weighted guess
class SlidingCounterLimiter { private final int limit; private final long windowMillis; private long currentStart = 0; private int currentCount; private int previousCount; String lastInfo = "";
SlidingCounterLimiter(int limit, long windowMillis) { this.limit = limit; this.windowMillis = windowMillis; }
boolean tryAcquire(long nowMillis) { long start = nowMillis / windowMillis * windowMillis; if (start != currentStart) { // moved on: the old current becomes previous (or 0 if we skipped a whole window) previousCount = (start - currentStart == windowMillis) ? currentCount : 0; currentCount = 0; currentStart = start; } double intoWindow = (double) (nowMillis - start) / windowMillis; // 0.0 to 1.0 double estimate = previousCount * (1 - intoWindow) + currentCount; lastInfo = String.format("prev=%d curr=%d estimate=%.2f", previousCount, currentCount, estimate); if (estimate < limit) { currentCount++; return true; } return false; }}
public class SlidingCounterDemo { public static void main(String[] args) { SlidingCounterLimiter limiter = new SlidingCounterLimiter(8, 60_000); for (int i = 0; i < 8; i++) limiter.tryAcquire(50_000); // 8 requests at 50 s fill the first minute long[] millis = {75_000, 75_000, 75_000, 90_000, 90_000, 105_000}; for (long t : millis) { boolean ok = limiter.tryAcquire(t); System.out.println("t=" + t / 1000 + "s " + limiter.lastInfo + " -> " + (ok ? "allowed" : "rejected")); } }}t=75s prev=8 curr=0 estimate=6.00 -> allowed t=75s prev=8 curr=1 estimate=7.00 -> allowed t=75s prev=8 curr=2 estimate=8.00 -> rejected t=90s prev=8 curr=2 estimate=6.00 -> allowed t=90s prev=8 curr=3 estimate=7.00 -> allowed t=105s prev=8 curr=4 estimate=6.00 -> allowed
What this code does
- Only two numbers per client: the count of the previous window and of the current one. The previous window is assumed to be spread evenly over time.
- At 75 s we are 25% into the new window, so 75% of the previous 8 requests still count: 8 × 0.75 = 6. With a limit of 8, two more fit; the third sees an estimate of 8 and is rejected.
- At 90 s only half of the previous window counts (4), and at 105 s only a quarter (2), so room opens up smoothly instead of all at once at the boundary.
For example, 25% into the current minute, 75% of the previous minute is still inside the sliding window. With 80 previous and 30 current requests the estimate is 80 × 0.75 + 30 = 90.
The guess assumes the previous window's requests were spread evenly, so it is approximate. In return it needs tiny, fixed memory and has no sharp boundary burst, which is why large services often use it.
Token bucket and leaky bucket: capacity, refill rate, bursts
Token bucket is a limiter with a bucket that holds up to capacity tokens and gains tokens at a fixed refill rate. Each request takes one token; with no token left, the request is rejected.
Picture a bucket that gains one token a second. Each request takes a token, and a full bucket lets a short burst through.
Example 5 · Token bucket vs leaky bucket on a burst of 8
public class BucketsDemo { public static void main(String[] args) { int burst = 8; // 8 requests arrive at t = 0
// Token bucket: capacity 5 tokens, starts full, 1 token comes back every second int tokens = 5; System.out.println("Token bucket (capacity 5, refill 1/s):"); for (int i = 1; i <= burst; i++) { if (tokens > 0) { tokens--; System.out.println(" #" + i + " runs now"); } else { System.out.println(" #" + i + " rejected (no token)"); } }
// Leaky bucket: a queue of size 5, drained at exactly 1 request per second int queueSize = 5; System.out.println("Leaky bucket (queue 5, leak 1/s):"); for (int i = 1; i <= burst; i++) { if (i <= queueSize) { System.out.println(" #" + i + " queued, runs at t=" + (i - 1) + "s"); } else { System.out.println(" #" + i + " rejected (queue full)"); } } }}Token bucket (capacity 5, refill 1/s): #1 runs now #2 runs now #3 runs now #4 runs now #5 runs now #6 rejected (no token) #7 rejected (no token) #8 rejected (no token) Leaky bucket (queue 5, leak 1/s): #1 queued, runs at t=0s #2 queued, runs at t=1s #3 queued, runs at t=2s #4 queued, runs at t=3s #5 queued, runs at t=4s #6 rejected (queue full) #7 rejected (queue full) #8 rejected (queue full)
What this code does
- The token bucket lets a burst through at once, up to its capacity, then allows about 1 request a second as tokens come back.
- The leaky bucket never lets work out faster than its fixed rate: the burst is queued and leaves one per second, so the server behind it sees perfectly smooth traffic.
- Both reject what does not fit. The difference is whether an allowed burst runs now (token) or is smoothed out (leaky).
A full bucket allows a short burst, then the long-run rate equals the refill rate. That is why token buckets are common for public APIs.
A leaky bucket is the queue version: requests wait in a queue that is emptied at a fixed rate, like water dripping from a hole. It smooths bursts completely, but a queued request has to wait, so it suits steady outgoing traffic such as sending SMS or calling a partner API.
Trace the code
Watch the bucket empty and refill
Step through six requests. The bucket holds 3 tokens and gains 1 token a second.
Variables
- tokens
- 3
Output
(nothing printed yet)Line 3The bucket starts full with 3 tokens.
Comparison: memory, accuracy, burst behaviour
Each algorithm makes a different trade. Run all four on the same traffic and compare how many requests get through.
Example 6 · All four algorithms on the same traffic
import java.util.ArrayDeque;import java.util.Deque;import java.util.List;
interface Limiter { boolean tryAcquire(long nowMillis); String name(); String memory();}
class FixedWindow implements Limiter { private final int limit = 5; private long start = -1; private int count;
public boolean tryAcquire(long now) { long s = now / 60_000 * 60_000; if (s != start) { start = s; count = 0; } if (count < limit) { count++; return true; } return false; } public String name() { return "Fixed window"; } public String memory() { return "2 numbers"; }}
class SlidingLog implements Limiter { private final Deque<Long> log = new ArrayDeque<>();
public boolean tryAcquire(long now) { while (!log.isEmpty() && log.peekFirst() <= now - 60_000) log.pollFirst(); if (log.size() < 5) { log.addLast(now); return true; } return false; } public String name() { return "Sliding log"; } public String memory() { return "up to 5 timestamps"; }}
class SlidingCounter implements Limiter { private long start = 0; private int prev, curr;
public boolean tryAcquire(long now) { long s = now / 60_000 * 60_000; if (s != start) { prev = (s - start == 60_000) ? curr : 0; curr = 0; start = s; } double estimate = prev * (1 - (now - s) / 60_000.0) + curr; if (estimate < 5) { curr++; return true; } return false; } public String name() { return "Sliding counter"; } public String memory() { return "3 numbers"; }}
class TokenBucket implements Limiter { private double tokens = 5; private long last = 0;
public boolean tryAcquire(long now) { tokens = Math.min(5, tokens + (now - last) * 5 / 60_000.0); // 5 tokens a minute last = now; if (tokens >= 1) { tokens--; return true; } return false; } public String name() { return "Token bucket"; } public String memory() { return "2 numbers"; }}
public class CompareLimitersDemo { public static void main(String[] args) { long[] traffic = {59_000, 59_100, 59_200, 59_300, 59_400, 60_000, 60_100, 60_200, 60_300, 60_400, 90_000, 90_100, 90_200}; System.out.println("Limit: 5 per minute, 13 requests (burst at 59 s, burst at 60 s, 3 at 90 s)"); for (Limiter l : List.of(new FixedWindow(), new SlidingLog(), new SlidingCounter(), new TokenBucket())) { int allowed = 0; for (long t : traffic) if (l.tryAcquire(t)) allowed++; System.out.printf("%-16s allowed %2d memory: %s%n", l.name(), allowed, l.memory()); } }}Limit: 5 per minute, 13 requests (burst at 59 s, burst at 60 s, 3 at 90 s) Fixed window allowed 10 memory: 2 numbers Sliding log allowed 5 memory: up to 5 timestamps Sliding counter allowed 8 memory: 3 numbers Token bucket allowed 7 memory: 2 numbers
What this code does
- Fixed window lets 10 through around the boundary, double the limit. The sliding log is exact: 5.
- The sliding counter allows a few more than the log (8), because its estimate assumes the previous window was spread evenly. The token bucket allows 7: the first burst empties it, and by 90 s about 2.5 tokens have come back.
- No algorithm is "the right one": each trades accuracy, memory and burst behaviour differently, which is exactly what the comparison section sums up.
Pick by asking how exact the limit must be, how much memory per client you can afford, and whether short bursts are fine:
- Fixed window: 2 numbers per client, simple; allows up to 2× the limit at the window edge.
- Sliding log: exact; memory grows to
limittimestamps per client. - Sliding counter: 2–3 numbers, close to exact; assumes even traffic in the previous window.
- Token bucket: 2 numbers, allows controlled bursts up to the capacity. Leaky bucket: smooth output, adds waiting time.
For ShopLite, a token bucket suits the public API, a sliding log suits the few-user login endpoint, and a fixed window is enough for a rough daily quota.
Next step
Check your understanding
12 quick questions