# Rate Limiting: Token Bucket vs Sliding Window, With a Java Model You Can Run

I ran the same four traces through a token bucket, a fixed window, a sliding-window log, and a sliding-window counter. Limit 10, window 1000 ms, token-bucket capacity 10 and 10 tokens per second. Pasted from the run on 20 Nov 2026, 08:41 IST:

```text
[burst] 20 requests at t=0, token-bucket -> allowed=10 denied=10
[burst] 20 requests at t=0, fixed-window -> allowed=10 denied=10
[burst] 20 requests at t=0, sliding-log -> allowed=10 denied=10
[burst] 20 requests at t=0, sliding-counter -> allowed=10 denied=10
[bound] 10 at t=999 then 10 at t=1000 -> token-bucket allowed=10 denied=10, fixed-window allowed=20 denied=0, sliding-log allowed=10 denied=10, sliding-counter allowed=10 denied=10
[approx] 10 clustered at t=999, then 10 more at t=1500 -> sliding-log extra allowed=0, sliding-counter extra allowed=5
[steady] 21 requests, one every 100 ms from t=0 to t=2000 -> token-bucket allowed=21 denied=0, fixed-window allowed=21 denied=0, sliding-log allowed=21 denied=0, sliding-counter allowed=20 denied=1
```

The burst agrees. The boundary is where fixed window gives the game away: 10 at the end of one window and 10 at the start of the next, 20 allowed, no delay. The approximation is honest about being approximate: half a window later, the counter let 5 through that the exact log refused. And the "smooth" 100 ms stream is not smooth for the counter — it denied the request at t=1000. That last result is a feature of the formula, not a bug in the test.

## The short version

- A **token bucket** refills continuously. Capacity is the burst. The refill rate is the long-run average.
- A **fixed window** counts requests in aligned buckets (`now / window * window`). Cheap, and it admits a double burst on the boundary.
- A **sliding-window log** stores one timestamp per accepted request and drops anything older than `now - window`. Exact, memory proportional to the limit.
- A **sliding-window counter** keeps two integers and estimates `previous * (1 - fraction) + current`. Cheap, and it assumes the previous window was spread evenly.
- I drove all four with a `FakeClock`. The numbers above are allow/deny counts from that model, not Redis throughput and not a production cluster.

```mermaid
flowchart TD
    R["allow(key) at clock.millis()"] --> TB["token bucket<br/>refill, admit if tokens >= 1"]
    R --> FW["fixed window<br/>count in aligned bucket"]
    R --> SL["sliding log<br/>drop ts <= now - window"]
    R --> SC["sliding counter<br/>estimate previous and current"]
    FW --> SPIKE["boundary: 10 + 10 = 20 allowed"]
    SC --> EDGE["at t=1000, fraction=0, estimate=10, deny"]
```

## What the top results cover, and what they skip

I read the top results for "token bucket vs sliding window rate limiter java" on 20 Nov 2026:

| Result | Good at | Missing |
| --- | --- | --- |
| [Redis: token bucket with Lettuce](https://redis.io/docs/latest/develop/use-cases/rate-limiter/java-lettuce/) | A production distributed pattern: tokens in Redis, Lua, a real client | Not a side-by-side of the four algorithms on the same traces. |
| [OneEnv: Token Bucket vs Sliding Window](https://blog.oneenv.io/articles/token-bucket-vs-sliding-window-choosing-an-api-rate-limiter) | A clear "when to pick which" essay | No runnable Java model, no asserted counts. |
| [codeloopback: LLD of a Rate Limiter in Java](https://codeloopback.dev/articles/lld-rate-limiter) | Interview-style Java structure | Not the same burst, boundary, and steady traces through all four. |
| [mentornxt: fixed window, sliding window, token bucket](https://www.mentornxt.com/learn/java/system-design-fundamentals/rate-limiting-and-protection/rate-limiting-algorithms) | Algorithm overviews | Diagrams and sketches, not a shared test suite. |
| [onblog/java-limiter](https://github.com/onblog/java-limiter) | A library you can depend on | The gap I wanted is a small, tested model you can read in one sitting. |

So the gap is one in-process Java suite that runs the same traces through all four and pastes the allow/deny counts. That's this post.

## Setup

| What | Value |
| --- | --- |
| JDK | Temurin OpenJDK 25.0.5 (`--release 21`) |
| Tests | JUnit 5.13.4, 4 tests |
| Model | `FakeClock` plus four `synchronized` limiters, one key, limit 10, window 1000 ms |
| Token bucket | capacity 10, 10 tokens per second |
| Run it | `./run.sh` in the project folder |

This is not a distributed limiter. There is no Redis, no `synchronized` across processes, and no claim about requests per second on a server.

## 1. Token bucket: burst, then refill

```java
public synchronized boolean allow(String key) {
    long now = clock.millis();
    State s = keys.getOrDefault(key, new State(capacity, now));
    double elapsedSec = (now - s.lastRefillMillis) / 1000.0;
    double tokens = Math.min(capacity, s.tokens + elapsedSec * tokensPerSecond);
    if (tokens >= 1.0) {
        keys.put(key, new State(tokens - 1.0, now));
        return true;
    }
    keys.put(key, new State(tokens, now));
    return false;
}
```

At t=0 the bucket is full, so a burst of 20 is 10 allowed and 10 denied — same as the other three. Tokens refill with wall time, not with aligned windows, so the 10 requests at t=999 use the bucket and the 10 at t=1000 see almost no refill (1 ms × 10 tokens/s = 0.01 token). Allowed=10 denied=10 on that trace. The steady stream, one request every 100 ms, stays within 10/s and all 21 were allowed.

## 2. Fixed window: cheap, and it doubles on the edge

`windowStart = now / windowMillis * windowMillis`. Requests at t=999 and t=1000 land in different windows. The boundary trace is the one to remember: **allowed=20 denied=0**, and only the fixed window did that. The other three stayed at 10 and 10.

A client that can schedule 10 requests at t=999 and 10 at t=1000 has effectively doubled the limit for one millisecond of spacing. If your rule is "10 per second" in the sliding sense, do not ship a fixed window and hope.

On the steady trace the 21 timestamps are 0, 100, …, 2000: 10 in the first window (0…900), 10 in the second (1000…1900), and 1 at t=2000 in a third window. All 21 were allowed.

## 3. Sliding log: exact, and it stores every timestamp

```java
long cutoff = now - windowMillis;
while (!log.isEmpty() && log.peekFirst() <= cutoff) {
    log.removeFirst();
}
if (log.size() < limit) {
    log.addLast(now);
    return true;
}
```

Timestamps equal to the cutoff are evicted (`<=`), so a request at t=0 does not count at t=1000. The boundary trace still denies the second burst: the 10 at t=999 are newer than cutoff 0, so they still occupy the log.

The approximation trace is the contrast I wanted. Ten requests clustered at t=999, then ten more at t=1500: cutoff is 500, the 999 timestamps remain, **extra allowed=0**.

## 4. Sliding counter: two integers, and an assumption

```java
double fraction = (now - start) / (double) windowMillis;
double estimate = s.previous * (1.0 - fraction) + s.current;
if (estimate + 1.0 <= limit) {
    keys.put(key, new State(s.currentStart, s.previous, s.current + 1));
    return true;
}
```

It is cheap. It is also wrong when the previous window was a spike, because it pretends those requests were spread evenly. After 10 requests at t=999, at t=1500 the current window is half elapsed, `fraction=0.5`, `estimate = 10 * 0.5 + 0 = 5`, so five more are admitted. The log admitted zero. **extra allowed=5** is the approximation error on this trace.

The steady deny is the same formula at a window edge. At t=1000, a new window starts, `previous=10`, `current=0`, `fraction=0`, `estimate=10`, and `estimate + 1` is over the limit, so that one request is denied. The next one at t=1100 sees `fraction=0.1` and `estimate=9`, and is allowed. Result: **allowed=20 denied=1**, while token bucket, fixed window, and the log all allowed 21. I asserted 20 and 1 for the counter. If you need a hard "10 in any trailing second," use the log (or Redis) and do not treat the counter's estimate as exact.

## The run

Pasted from `RESULTS.txt`, 20 Nov 2026, 08:41 IST. OpenJDK 25.0.5, JUnit 5.13.4.

```text
[bound] 10 at t=999 then 10 at t=1000 -> token-bucket allowed=10 denied=10, fixed-window allowed=20 denied=0, sliding-log allowed=10 denied=10, sliding-counter allowed=10 denied=10
[approx] 10 clustered at t=999, then 10 more at t=1500 -> sliding-log extra allowed=0, sliding-counter extra allowed=5
[steady] 21 requests, one every 100 ms from t=0 to t=2000 -> token-bucket allowed=21 denied=0, fixed-window allowed=21 denied=0, sliding-log allowed=21 denied=0, sliding-counter allowed=20 denied=1
[burst] 20 requests at t=0, token-bucket -> allowed=10 denied=10
[burst] 20 requests at t=0, fixed-window -> allowed=10 denied=10
[burst] 20 requests at t=0, sliding-log -> allowed=10 denied=10
[burst] 20 requests at t=0, sliding-counter -> allowed=10 denied=10
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
```

The lines are interleaved because the methods did not run in source order. The counts are what matter.

## Checklist

- [ ] Write the rule in words first: burst size, long-run rate, or "N in any trailing T".
- [ ] If the rule is trailing-window exact, do not ship a fixed window — the boundary trace here allowed 20 against a limit of 10.
- [ ] If you use a sliding counter, test a spike in the previous window, not only a smooth stream.
- [ ] Drive tests with a fake clock so a window boundary is a number, not a flake.
- [ ] Assert allow/deny counts. Do not invent a throughput number the model never measured.
- [ ] For a multi-instance API, this in-process model is not enough; you need a shared store (Redis is the usual one). I did not measure Redis in this run.

## Interview follow-ups

**"Which one should I draw on the whiteboard?"** Start with the rule. Burst + average rate: token bucket. Hard trailing window and a small limit: sliding log. Huge limits where you cannot store every timestamp: sliding counter, and say out loud that it is an estimate. Fixed window only if you accept the boundary spike.

**"What does the token bucket admit over an interval T?"** In this model, at most `capacity + rate * T` (here, 10 + 10 * T seconds). I did not run a separate long-T test, so I am not pasting a count for that bound.

**"Distributed?"** Put the state in Redis (or similar) and make the allow-path atomic. The Redis Lettuce article linked above is the right next read. These four classes are `synchronized` maps on one JVM.

**"Leaky bucket?"** A leaky bucket smooths *outbound* rate; a token bucket allows a burst up to capacity. I did not implement a leaky bucket in this suite.

## Related posts

- [Idempotency Keys in Spring Boot: Making POST Safe to Retry](https://gowthammuthuvel.hashnode.dev/idempotency-keys-spring-boot), what you still need when a client retries a request the limiter already accepted.
- [Retrying fetch in Node.js the Right Way: Backoff, Retry-After, Deadlines](https://gowthammuthuvel.hashnode.dev/node-fetch-retry-backoff-retry-after-deadline), the client side of a 429.
- [Stripe Webhooks in Spring Boot: Signatures, Idempotency, Out-of-Order Events](https://gowthammuthuvel.hashnode.dev/stripe-webhooks-spring-boot-signatures-idempotency), another place "exactly once" is a test, not a hope.

## Sources

- [Redis: token bucket rate limiter (Java / Lettuce)](https://redis.io/docs/latest/develop/use-cases/rate-limiter/java-lettuce/)
- [OneEnv: Token Bucket vs Sliding Window](https://blog.oneenv.io/articles/token-bucket-vs-sliding-window-choosing-an-api-rate-limiter)

Written by Gowtham M. Code tested on OpenJDK 25.0.5 / JUnit 5.13.4, 20 Nov 2026.

---

**Preparing for a Java backend interview?** My eBook *Crack the Java Backend Interview* has tested answers with runnable code for questions like this one. [Get it for ₹99](https://topmate.io/gowthammuthuvel/2404119).

