
This post is for backend developers who have to pick a limiter and are tired of comparisons that stop at diagrams. Every article on rate limiting algorithms says fixed window “allows bursts at the boundary” and token bucket “handles bursts gracefully”. None of them says how big the burst is, how much legal traffic each one throws away, or what a decision costs. So this post replays the same request traces through five algorithms, with leaky bucket in both of its forms and bucket4j 8.23.0 as a library reference, all set to the same 10 requests per second. As a result, you get the numbers behind the usual claims, the Java code that produced them, and a clear recommendation for which limiter to put in front of which kind of client.
The results in this post came from this environment:
Measured 2026-11-27
Windows 11 Pro 25H2 (build 26200), AMD Ryzen 5 8600G (6C/12T), 16 GB RAM
Oracle JDK 18.0.2.1 (Java HotSpot 64-Bit Server VM), single-file source launcher
bucket4j_jdk17-core 8.23.0 from Maven Central (sha1 5ad4d157e5727599fc5c3d8c3bf207895c66b9b6)
Limit for every limiter: 10 requests per second, burst capacity 10, one client key
Raw data: data/rate-limiting-algorithms-2026-11-27.tsv in the publisher repo
Two kinds of numbers follow, and they age differently. The admit and reject counts run on a virtual clock, so they are deterministic: the same trace produces the same decisions on any machine, and the trace pass was run three times with identical output. In contrast, the nanoseconds per decision come from a Windows desktop and a single thread. They are medians of five timed rounds after three warmup rounds, repeated in two separate JVMs, and they will not transfer exactly to a Linux server.
Rate Limiting Algorithms Compared: The Short Answer
Here is what each limiter did with the same traffic. “Max in any 1 s” is the largest number of requests that reached the backend inside any rolling one-second window. That number matters most, because it is what your database or downstream API actually feels.
| Algorithm | Boundary bursts: max in any 1 s | Poisson 9/s: legal calls rejected | Steady 15/s: max in any 1 s | Added delay | ns per decision | Bytes per key |
|---|---|---|---|---|---|---|
| Fixed window | 20 | 38 of 532 (7.1%) | 10 | none | 21.1 | 24.0 |
| Sliding window log | 10 | 79 of 532 (14.8%) | 10 | none | 33.1 to 33.4 | 120.1 |
| Sliding window counter | 10 | 82 of 532 (15.4%) | 10 | none | 28.2 to 29.2 | 32.0 |
| Token bucket | 11 | 5 of 532 (0.9%) | 15 | none | 22.1 to 22.2 | 32.0 |
| Leaky bucket, meter | 11 | 5 of 532 (0.9%) | 15 | none | 23.8 to 24.4 | 32.0 |
| Leaky bucket, queue | 10 | 3 of 532 (0.6%) | 10 | p50 190 ms, max 973 ms on Poisson | 148.5 to 152.9 | 355.5 |
| bucket4j greedy (default sync) | 11 | 5 of 532 (0.9%) | 15 | none | 392.4 to 394.5 | 360.2 |
The nanosecond ranges span the medians of the two JVM runs, and the percentages are rejected divided by 532 offered.
Three findings stand out. First, token bucket and leaky bucket as a meter made the same admit or reject call on every single request in every trace. They are one algorithm described from two sides. Second, a fixed window let twice the limit through in one second, which is the boundary problem as a number. Third, the strict limiters punished clients who were under the limit on average: the sliding log rejected 14.8% of a 9 per second Poisson stream, while token bucket rejected 0.9%.
If you want the conceptual walkthrough of each algorithm first, the earlier guide on token bucket, leaky bucket and fixed window strategies covers the mechanics with diagrams. This post assumes you know roughly how each one works and want to know how they behave.
How the Test Works: One Limit, Five Traces
To compare rate limiting algorithms fairly, every limiter gets the same nominal limit: 10 requests per second for one client key. For the window algorithms that means 10 per one-second window. For the bucket algorithms it means a capacity of 10 that refills or drains at 10 per second. The leaky queue holds up to 10 waiting requests and releases one every 100 ms. In other words, each limiter is configured the way its documentation would tell you to configure “10 per second”.
Time is virtual. Each limiter receives a timestamp in nanoseconds instead of reading the system clock, so every algorithm sees exactly the same arrival times and the decisions are reproducible. The bucket math uses integers scaled by one billion, so refill never accumulates floating-point drift. The five traces are:
- Steady 10/s for 10 s: 100 requests evenly spaced, exactly at the limit. Every limiter should admit all of them.
- Steady 10/s shifted by 50 ms: the same trace moved off the window boundaries, to check whether any result above is an alignment artifact.
- Steady 15/s for 10 s: 150 requests, a client running 50% over the limit.
- Boundary bursts: 20 requests 10 ms apart, starting 100 ms before each odd second, five times. That is 100 requests in 10 seconds, so the client averages exactly the limit, yet half of each burst lands on each side of a window edge.
- Poisson at 9/s for 60 s: 532 random arrivals with a fixed seed, averaging below the limit. Real API clients look much more like this than like a metronome.
For each run, the harness records admitted and rejected counts, the most requests that reached the backend in any rolling second, and, for the queue, how long each admitted request waited. It also compares the full admit and reject sequence between algorithms, so “identical” in the output below means identical request by request, not merely the same totals.
The Five Limiters in Java
The whole harness for the rate limiting algorithms is one file, RateLimits.java, shown here in four parts. Paste them in order into a single file to run it. The limiters themselves are deliberately plain and single-threaded, so the code shows the algorithm and nothing else. The common mistakes section below covers what changes for a multi-threaded or multi-node setup.
The first part holds the three window algorithms. The sliding log keeps the last 10 admit times in a ring buffer instead of an unbounded list, because a log never needs more entries than the limit.
import io.github.bucket4j.Bucket;
import io.github.bucket4j.TimeMeter;
import io.github.bucket4j.local.SynchronizationStrategy;
import java.lang.management.ManagementFactory;
import java.time.Duration;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
public class RateLimits {
static final long SECOND = 1_000_000_000L;
static final int LIMIT = 10; // requests per window / bucket capacity
static final long INTERVAL = SECOND / LIMIT; // 100 ms between leaks
interface Limiter {
/** @return delay in ns before the request reaches the backend, or -1 if rejected */
long acquire(long now);
}
// 1. Fixed window: one counter per calendar second
static final class FixedWindow implements Limiter {
long window = -1;
int count;
public long acquire(long now) {
long w = now / SECOND;
if (w != window) { window = w; count = 0; }
if (count < LIMIT) { count++; return 0; }
return -1;
}
}
// 2. Sliding window log: the last LIMIT admit times in a ring buffer
static final class SlidingLog implements Limiter {
final long[] times = new long[LIMIT];
int head, size;
public long acquire(long now) {
if (size == LIMIT) {
if (now - times[head] < SECOND) return -1; // oldest of the last 10 is under 1 s old
times[head] = now; head = (head + 1) % LIMIT; // overwrite the oldest
return 0;
}
times[(head + size) % LIMIT] = now; size++;
return 0;
}
}
// 3. Sliding window counter: previous window weighted by how much of it still overlaps
static final class SlidingCounter implements Limiter {
long window = -1;
int current, previous;
public long acquire(long now) {
long w = now / SECOND;
if (w != window) {
previous = (w == window + 1) ? current : 0;
current = 0; window = w;
}
double elapsed = (double) (now - w * SECOND) / SECOND;
double estimate = previous * (1.0 - elapsed) + current;
if (estimate + 1 <= LIMIT) { current++; return 0; }
return -1;
}
}
The second part holds the bucket algorithms and the bucket4j reference. Note how the token bucket and the leaky meter mirror each other: one starts full and spends, the other starts empty and fills. The queue version is different in kind, because it delays a request instead of answering yes or no.
// 4. Token bucket: tokens scaled by 1e9 so refill is exact integer math (10 tokens/s = 10 units/ns)
static final class TokenBucket implements Limiter {
static final long ONE = SECOND, CAPACITY = LIMIT * SECOND;
long tokens = CAPACITY, last;
public long acquire(long now) {
tokens = Math.min(CAPACITY, tokens + (now - last) * LIMIT);
last = now;
if (tokens >= ONE) { tokens -= ONE; return 0; }
return -1;
}
}
// 5a. Leaky bucket as a meter: water level drains at 10/s, a request adds one unit if it fits
static final class LeakyMeter implements Limiter {
static final long ONE = SECOND, CAPACITY = LIMIT * SECOND;
long level, last;
public long acquire(long now) {
level = Math.max(0, level - (now - last) * LIMIT);
last = now;
if (level + ONE <= CAPACITY) { level += ONE; return 0; }
return -1;
}
}
// 5b. Leaky bucket as a queue: up to 10 waiting, released one every 100 ms
static final class LeakyQueue implements Limiter {
final ArrayDeque<Long> departures = new ArrayDeque<>();
long lastDeparture = Long.MIN_VALUE / 2;
public long acquire(long now) {
while (!departures.isEmpty() && departures.peekFirst() <= now) departures.pollFirst();
if (departures.size() >= LIMIT) return -1;
long departure = Math.max(now, lastDeparture + INTERVAL);
departures.addLast(departure);
lastDeparture = departure;
return departure - now;
}
}
// Reference: bucket4j local bucket on the same virtual clock
static final class VirtualClock implements TimeMeter {
long now;
public long currentTimeNanos() { return now; }
public boolean isWallClockBased() { return false; }
}
static final class Bucket4j implements Limiter {
final VirtualClock clock;
final Bucket bucket;
Bucket4j(VirtualClock clock, boolean greedy) {
this(clock, greedy, SynchronizationStrategy.LOCK_FREE); // bucket4j's default
}
Bucket4j(VirtualClock clock, boolean greedy, SynchronizationStrategy sync) {
this.clock = clock;
this.bucket = Bucket.builder()
.addLimit(l -> greedy
? l.capacity(LIMIT).refillGreedy(LIMIT, Duration.ofSeconds(1))
: l.capacity(LIMIT).refillIntervally(LIMIT, Duration.ofSeconds(1)))
.withCustomTimePrecision(clock)
.withSynchronizationStrategy(sync)
.build();
}
public long acquire(long now) {
clock.now = now;
return bucket.tryConsume(1) ? 0 : -1;
}
}
record Algo(String name, Supplier<Limiter> make) {}
static List<Algo> algos() {
return List.of(
new Algo("fixed window", FixedWindow::new),
new Algo("sliding log", SlidingLog::new),
new Algo("sliding counter", SlidingCounter::new),
new Algo("token bucket", TokenBucket::new),
new Algo("leaky meter", LeakyMeter::new),
new Algo("leaky queue", LeakyQueue::new),
new Algo("bucket4j greedy", () -> new Bucket4j(new VirtualClock(), true)),
new Algo("bucket4j interval", () -> new Bucket4j(new VirtualClock(), false)),
new Algo("bucket4j greedy NONE", () -> new Bucket4j(new VirtualClock(), true, SynchronizationStrategy.NONE)));
}
bucket4j appears three times. refillGreedy is its token bucket, refillIntervally adds all 10 tokens at once every second, and the NONE variant switches off bucket4j’s thread safety so its speed can be compared fairly with the unsynchronized hand-written limiters.
The third part generates the traces, replays them, and groups algorithms whose decisions match request by request:
static long[] steady(int perSecond, int seconds) {
long[] t = new long[perSecond * seconds];
for (int i = 0; i < t.length; i++) t[i] = (long) i * SECOND / perSecond;
return t;
}
/** 20 requests 10 ms apart, starting 100 ms before each odd second: 100 requests in 10 s. */
static long[] boundaryBursts() {
long[] t = new long[100];
int i = 0;
for (int b = 1; b <= 9; b += 2)
for (int j = 0; j < 20; j++) t[i++] = b * SECOND - 100_000_000L + j * 10_000_000L;
return t;
}
/** Poisson arrivals at 9 requests/s for 60 s, fixed seed. */
static long[] poisson(double rate, int seconds, long seed) {
Random r = new Random(seed);
List<Long> out = new ArrayList<>();
double t = 0;
while (true) {
t += -Math.log(1 - r.nextDouble()) / rate;
if (t >= seconds) break;
out.add((long) (t * SECOND));
}
return out.stream().mapToLong(Long::longValue).toArray();
}
static int maxInAnySecond(long[] sorted) {
int best = 0, lo = 0;
for (int hi = 0; hi < sorted.length; hi++) {
while (sorted[hi] - sorted[lo] >= SECOND) lo++;
best = Math.max(best, hi - lo + 1);
}
return best;
}
static void traces() {
record Trace(String name, long[] times) {}
List<Trace> traces = List.of(
new Trace("steady 10/s x10s", steady(10, 10)),
new Trace("steady 10/s +50ms", Arrays.stream(steady(10, 10)).map(t -> t + 50_000_000L).toArray()),
new Trace("steady 15/s x10s", steady(15, 10)),
new Trace("boundary bursts", boundaryBursts()),
new Trace("poisson 9/s x60s", poisson(9, 60, 42)));
for (Trace tr : traces) {
System.out.printf("%n== %s: %d requests, offered max in any 1 s: %d%n",
tr.name, tr.times.length, maxInAnySecond(tr.times));
System.out.printf("%-20s %8s %8s %11s %10s %10s %10s%n",
"algorithm", "admitted", "rejected", "max in 1 s", "delay p50", "delay p99", "delay max");
List<String> signatures = new ArrayList<>();
for (Algo a : algos()) {
Limiter l = a.make.get();
long[] arrivals = new long[tr.times.length];
long[] delays = new long[tr.times.length];
StringBuilder sig = new StringBuilder();
int n = 0;
for (long t : tr.times) {
long d = l.acquire(t);
sig.append(d >= 0 ? '1' : '0');
if (d >= 0) { arrivals[n] = t + d; delays[n] = d; n++; }
}
signatures.add(sig.toString());
long[] adm = Arrays.copyOf(arrivals, n);
Arrays.sort(adm);
long[] del = Arrays.copyOf(delays, n);
Arrays.sort(del);
System.out.printf("%-20s %8d %8d %11d %8.0fms %8.0fms %8.0fms%n",
a.name, n, tr.times.length - n, maxInAnySecond(adm),
del[n / 2] / 1e6, del[Math.min(n - 1, (int) Math.ceil(n * 0.99) - 1)] / 1e6, del[n - 1] / 1e6);
}
// which algorithms made the same admit/reject call on every single request
List<Algo> all = algos();
boolean[] seen = new boolean[all.size()];
StringBuilder groups = new StringBuilder("identical decisions:");
for (int i = 0; i < all.size(); i++) {
if (seen[i]) continue;
List<String> g = new ArrayList<>(List.of(all.get(i).name));
for (int j = i + 1; j < all.size(); j++)
if (!seen[j] && signatures.get(i).equals(signatures.get(j))) { seen[j] = true; g.add(all.get(j).name); }
if (g.size() > 1) groups.append(" [").append(String.join(" = ", g)).append("]");
}
System.out.println(groups);
}
}
For the queue, the “arrival” used for the rolling-second count is the moment the request leaves the queue, since that is when the backend sees it. For every other limiter, admission and arrival happen at the same instant.
Raw Output: Five Traces Through Nine Limiters
Here is the command, run from the folder holding RateLimits.java and a lib folder with the bucket4j jar:
java -cp lib/bucket4j_jdk17-core-8.23.0.jar RateLimits.java traces
And here is the output, unedited:
Java HotSpot(TM) 64-Bit Server VM 18.0.2.1
== steady 10/s x10s: 100 requests, offered max in any 1 s: 10
algorithm admitted rejected max in 1 s delay p50 delay p99 delay max
fixed window 100 0 10 0ms 0ms 0ms
sliding log 100 0 10 0ms 0ms 0ms
sliding counter 91 9 10 0ms 0ms 0ms
token bucket 100 0 10 0ms 0ms 0ms
leaky meter 100 0 10 0ms 0ms 0ms
leaky queue 100 0 10 0ms 0ms 0ms
bucket4j greedy 100 0 10 0ms 0ms 0ms
bucket4j interval 100 0 10 0ms 0ms 0ms
bucket4j greedy NONE 100 0 10 0ms 0ms 0ms
identical decisions: [fixed window = sliding log = token bucket = leaky meter = leaky queue = bucket4j greedy = bucket4j interval = bucket4j greedy NONE]
== steady 10/s +50ms: 100 requests, offered max in any 1 s: 10
algorithm admitted rejected max in 1 s delay p50 delay p99 delay max
fixed window 100 0 10 0ms 0ms 0ms
sliding log 100 0 10 0ms 0ms 0ms
sliding counter 91 9 10 0ms 0ms 0ms
token bucket 100 0 10 0ms 0ms 0ms
leaky meter 100 0 10 0ms 0ms 0ms
leaky queue 100 0 10 0ms 0ms 0ms
bucket4j greedy 100 0 10 0ms 0ms 0ms
bucket4j interval 100 0 10 0ms 0ms 0ms
bucket4j greedy NONE 100 0 10 0ms 0ms 0ms
identical decisions: [fixed window = sliding log = token bucket = leaky meter = leaky queue = bucket4j greedy = bucket4j interval = bucket4j greedy NONE]
== steady 15/s x10s: 150 requests, offered max in any 1 s: 15
algorithm admitted rejected max in 1 s delay p50 delay p99 delay max
fixed window 100 50 10 0ms 0ms 0ms
sliding log 100 50 10 0ms 0ms 0ms
sliding counter 91 59 10 0ms 0ms 0ms
token bucket 109 41 15 0ms 0ms 0ms
leaky meter 109 41 15 0ms 0ms 0ms
leaky queue 110 40 10 967ms 1000ms 1000ms
bucket4j greedy 109 41 15 0ms 0ms 0ms
bucket4j interval 100 50 10 0ms 0ms 0ms
bucket4j greedy NONE 109 41 15 0ms 0ms 0ms
identical decisions: [fixed window = sliding log = bucket4j interval] [token bucket = leaky meter = bucket4j greedy = bucket4j greedy NONE]
== boundary bursts: 100 requests, offered max in any 1 s: 20
algorithm admitted rejected max in 1 s delay p50 delay p99 delay max
fixed window 100 0 20 0ms 0ms 0ms
sliding log 50 50 10 0ms 0ms 0ms
sliding counter 50 50 10 0ms 0ms 0ms
token bucket 55 45 11 0ms 0ms 0ms
leaky meter 55 45 11 0ms 0ms 0ms
leaky queue 60 40 10 540ms 990ms 990ms
bucket4j greedy 55 45 11 0ms 0ms 0ms
bucket4j interval 100 0 20 0ms 0ms 0ms
bucket4j greedy NONE 55 45 11 0ms 0ms 0ms
identical decisions: [fixed window = bucket4j interval] [sliding log = sliding counter] [token bucket = leaky meter = bucket4j greedy = bucket4j greedy NONE]
== poisson 9/s x60s: 532 requests, offered max in any 1 s: 17
algorithm admitted rejected max in 1 s delay p50 delay p99 delay max
fixed window 494 38 16 0ms 0ms 0ms
sliding log 453 79 10 0ms 0ms 0ms
sliding counter 450 82 12 0ms 0ms 0ms
token bucket 527 5 17 0ms 0ms 0ms
leaky meter 527 5 17 0ms 0ms 0ms
leaky queue 529 3 10 190ms 912ms 973ms
bucket4j greedy 527 5 17 0ms 0ms 0ms
bucket4j interval 494 38 16 0ms 0ms 0ms
bucket4j greedy NONE 527 5 17 0ms 0ms 0ms
identical decisions: [fixed window = bucket4j interval] [token bucket = leaky meter = bucket4j greedy = bucket4j greedy NONE]
Before reading anything into it, check the library rows. bucket4j’s greedy bucket matched the hand-written token bucket request for request on all five traces, and its interval refill matched the hand-written fixed window on all five. That agreement is the evidence that the hand-written limiters implement their algorithms the way a widely used library does. Note also that the sliding log and the sliding counter agreed on every boundary-burst request but split apart on the Poisson trace, which the sliding counter section below explains.
Token Bucket vs Leaky Bucket: Same Decisions, Different Promise
A token bucket and a leaky bucket used as a meter are the same algorithm. In this test they made identical admit and reject decisions on every request of every trace, because a bucket that starts full and spends tokens is the mirror image of one that starts empty and fills with water. The real choice is between a leaky bucket that rejects and a leaky bucket that queues.
That distinction explains why so many explanations of token bucket vs leaky bucket contradict each other. Some authors describe the leaky bucket as a meter that answers yes or no, which is the version that matched token bucket here. Others describe it as a FIFO queue that drains at a fixed rate, which is a traffic shaper rather than a limiter. Both readings exist in the networking literature, so the name alone does not tell you which one a gateway implements.
The queue form behaves very differently. Under a steady 15 per second, the queue stayed full the whole time, so the median admitted request waited 967 ms and the worst waited a full second. It admitted 110 requests, one more than the token bucket, but it also delivered no more than 10 to the backend in any second. In short, the queue trades latency for a perfectly flat output rate. On the Poisson trace, which never exceeded the limit on average, the median wait was still 190 ms, with a worst case of 973 ms.
So the practical rule is short. If the caller is waiting on an HTTP response, a queue that adds up to a second of latency is usually worse than a fast 429 with a Retry-After header. On the other hand, if the work is asynchronous, such as jobs pushed to a fragile third-party API, a queue is exactly what you want. The post on backpressure patterns for queues goes further into that side of the design.
The Boundary Burst: Fixed Window Lets Twice the Limit Through
The boundary burst trace averages exactly 10 requests per second, so a fair limiter should not need to do much. Instead, each burst puts 10 requests in the last 100 ms of one window and 10 in the first 100 ms of the next. The fixed window counts them in separate windows, admits all 20, and so lets 20 requests reach the backend within 200 ms. That is double the configured limit, and bucket4j’s interval refill produced the same 20.
At the other end, the sliding log and the sliding window counter capped every rolling second at 10 and rejected half of each burst. The token bucket landed in between at 11 per rolling second. It spent its 10 stored tokens on the first 10 requests, then refilled one more token during the 100 ms the burst took. That extra request is the burst capacity doing its job, and it is bounded: the most a token bucket can ever pass in one second is the capacity plus one second of refill, so 20 in theory for this configuration.
The steady 15 per second trace shows that bound in practice. The token bucket let all 15 requests in the first second through, because it started full and refilled 9 more tokens while those requests arrived. After that it settled to the refill rate. So if your downstream can only survive 10 per second, a token bucket with a capacity of 10 is not the right tool. Set the capacity to what the downstream can absorb in a spike, not to the average rate.
Do Strict Limiters Reject Legal Traffic?
Yes, and by more than most people expect. The Poisson trace averages 9 requests per second, below the 10 per second limit. However, random arrivals cluster, and in the busiest second of the trace 17 requests arrived. A limiter that enforces “never more than 10 in any rolling second” has to reject the excess, even though the client is well behaved over any longer period.
The sliding window log rejected 79 of 532 requests, 14.8% of a client that never exceeded its average quota. The sliding window counter rejected 82. Meanwhile, the token bucket rejected 5, because the stored tokens absorbed the clusters. The fixed window sat in between at 38 rejections, while still letting 16 requests through in one rolling second.
This is the core trade-off between rate limiting algorithms, and the numbers make it concrete. A strict rolling-window limiter protects the backend precisely and pays for it in false rejections. A bucket forgives clusters and pays for it with short spikes above the nominal rate. Neither is wrong, but you should pick one knowing which side of that trade you are on.
The Sliding Window Counter Rejects Traffic at Exactly the Limit
The steady 10 per second trace exposed one more behaviour. Every limiter admitted all 100 requests except the sliding window counter, which rejected 9. Shifting the trace by 50 ms did not change that, so it is not a timestamp alignment artifact. Printing the rejected timestamps of the shifted trace showed one rejection per second after the first:
sliding counter rejects at: 1.05s 2.55s 3.55s 4.55s 5.55s 6.55s 7.55s 8.55s 9.55s
The cause is the estimate itself. The counter assumes the previous window’s requests were spread evenly and weights them by how much of that window still overlaps. When the previous window was full, the estimate rounds up past 10 somewhere in the middle of the current window, and the request at that moment is refused. Cloudflare’s write-up on counting requests with this technique found 0.003% of 400 million requests wrongly allowed or limited, and no false positives, on its real traffic. That is a fair result for messy traffic, and for most APIs it is fine. However, a perfectly even client at exactly the limit is the worst case for the estimate, so a client that meters itself to exactly your published limit will see a steady trickle of 429s from a sliding counter, and it will open a support ticket about it.
The Poisson trace also showed the opposite error. The sliding counter let 12 requests through in one rolling second, two more than a true sliding log ever allows. So it is an approximation in both directions, cheaper in memory than a log but not a drop-in equivalent.
Speed and Memory per Key, Measured
Among rate limiting algorithms, decision cost matters less than most people assume, and the next result shows why. The speed pass gives each algorithm one million client keys, then makes 20 million decisions on keys drawn from a fixed pseudo-random sequence. Virtual time advances 50 ns per call, so each key sees about 20 requests per second against its limit of 10, and roughly half the calls are rejected. Each algorithm runs three warmup rounds and five timed rounds; the median, minimum and maximum of the timed rounds are printed. The last row times a plain ConcurrentHashMap<Long, Long> lookup over the same keys, which is what any real limiter pays to find a client’s state before deciding anything.
static final int KEYS = 1_000_000;
static final int CALLS = 20_000_000;
static void speed() {
int[] keys = new int[CALLS];
long x = 88172645463325252L;
for (int i = 0; i < CALLS; i++) { // xorshift64, fixed sequence
x ^= x << 13; x ^= x >>> 7; x ^= x << 17;
keys[i] = (int) Long.remainderUnsigned(x, KEYS);
}
System.out.printf("%-20s %10s %10s %10s %12s%n", "algorithm", "median ns", "min ns", "max ns", "admitted");
for (Algo a : algos()) {
Limiter[] state = new Limiter[KEYS];
for (int k = 0; k < KEYS; k++) state[k] = a.make.get();
double[] runs = new double[8];
long admitted = 0;
long clock = 0;
for (int r = 0; r < runs.length; r++) { // 3 warmup + 5 measured
admitted = 0;
long start = System.nanoTime();
for (int i = 0; i < CALLS; i++) {
clock += 50; // 20M calls span 1 virtual second, ~20 calls per key
if (state[keys[i]].acquire(clock) >= 0) admitted++;
}
runs[r] = (double) (System.nanoTime() - start) / CALLS;
}
double[] measured = Arrays.copyOfRange(runs, 3, 8);
Arrays.sort(measured);
System.out.printf("%-20s %10.1f %10.1f %10.1f %12d%n",
a.name, measured[2], measured[0], measured[4], admitted);
}
// the lookup a real limiter pays before any of the above
ConcurrentHashMap<Long, Long> map = new ConcurrentHashMap<>();
for (long k = 0; k < KEYS; k++) map.put(k, k);
double[] runs = new double[8];
long sink = 0;
for (int r = 0; r < runs.length; r++) {
long start = System.nanoTime();
for (int i = 0; i < CALLS; i++) sink += map.get((long) keys[i]);
runs[r] = (double) (System.nanoTime() - start) / CALLS;
}
double[] measured = Arrays.copyOfRange(runs, 3, 8);
Arrays.sort(measured);
System.out.printf("%-20s %10.1f %10.1f %10.1f %12s%n", "CHM<Long> get", measured[2], measured[0], measured[4], sink > 0 ? "-" : "");
}
// ---------- memory: bytes per key with 1M keys ----------
static long usedHeap() {
for (int i = 0; i < 4; i++) { System.gc(); try { Thread.sleep(200); } catch (InterruptedException e) { } }
return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
}
static void memory() {
System.out.printf("%-20s %14s%n", "algorithm", "bytes per key");
for (Algo a : algos()) {
Limiter[] state = new Limiter[KEYS]; // array itself allocated before the baseline
long before = usedHeap();
for (int k = 0; k < KEYS; k++) {
Limiter l = a.make.get();
for (int j = 0; j < LIMIT; j++) l.acquire(j * 1_000_000L); // fill logs and queues
state[k] = l;
}
long after = usedHeap();
System.out.printf("%-20s %14.1f%n", a.name, (double) (after - before) / KEYS);
if (state[KEYS - 1] == null) System.out.println();
}
ConcurrentHashMap<Long, Object> map = new ConcurrentHashMap<>(KEYS * 2);
Object v = new Object();
long before = usedHeap();
for (long k = 0; k < KEYS; k++) map.put(k, v);
long after = usedHeap();
System.out.printf("%-20s %14.1f%n", "CHM<Long> entry", (double) (after - before) / KEYS);
if (map.size() != KEYS) System.out.println();
}
public static void main(String[] args) {
System.out.println(System.getProperty("java.vm.name") + " " + System.getProperty("java.version"));
switch (args.length == 0 ? "traces" : args[0]) {
case "speed" -> speed();
case "memory" -> memory();
default -> traces();
}
}
}
The speed pass ran twice, each time in a fresh JVM with a fixed 6 GB heap:
java -Xms6g -Xmx6g -cp lib/bucket4j_jdk17-core-8.23.0.jar RateLimits.java speed
Java HotSpot(TM) 64-Bit Server VM 18.0.2.1
algorithm median ns min ns max ns admitted
fixed window 21.1 21.0 21.4 9991934
sliding log 33.1 32.9 33.2 9991934
sliding counter 29.2 29.1 29.8 8835057
token bucket 22.2 22.0 22.6 9993339
leaky meter 24.4 24.0 24.6 9993339
leaky queue 152.9 149.7 153.8 9997737
bucket4j greedy 392.4 391.6 393.5 9993339
bucket4j interval 306.3 300.3 309.1 9991934
bucket4j greedy NONE 243.1 241.9 243.5 9993339
CHM<Long> get 53.7 53.2 56.5 -
Java HotSpot(TM) 64-Bit Server VM 18.0.2.1
algorithm median ns min ns max ns admitted
fixed window 21.1 21.0 22.0 9991934
sliding log 33.4 32.9 33.6 9991934
sliding counter 28.2 27.8 28.7 8835057
token bucket 22.1 22.0 22.2 9993339
leaky meter 23.8 23.8 23.9 9993339
leaky queue 148.5 147.7 148.8 9997737
bucket4j greedy 394.5 391.7 396.5 9993339
bucket4j interval 303.7 299.9 307.7 9991934
bucket4j greedy NONE 241.4 240.3 242.2 9993339
CHM<Long> get 51.8 51.3 52.3 -
The memory pass builds one million limiter objects, fills the logs and queues with 10 entries each, and divides the heap growth by the key count:
java -Xms6g -Xmx6g -cp lib/bucket4j_jdk17-core-8.23.0.jar RateLimits.java memory
Java HotSpot(TM) 64-Bit Server VM 18.0.2.1
algorithm bytes per key
fixed window 24.0
sliding log 120.1
sliding counter 32.0
token bucket 32.0
leaky meter 32.0
leaky queue 355.5
bucket4j greedy 360.2
bucket4j interval 360.0
bucket4j greedy NONE 344.2
CHM<Long> entry 77.0
What the Speed and Memory Numbers Mean
All five hand-written algorithms decide in 21 to 34 ns, which is less than the 52 to 54 ns the hash map lookup in front of them costs. In other words, for an in-process limiter the choice between rate limiting algorithms barely moves the latency, and the map, the lock and the clock read dominate. A Redis-backed limiter adds a network round trip on top, which was not measured here but sits orders of magnitude above these figures on any real network. The Redis cache integration guide for Spring shows that setup.
bucket4j is the outlier at 392 to 395 ns per decision with its default lock-free strategy, and 241 to 243 ns with synchronization switched off. That is roughly 11 to 18 times the hand-written token bucket. Even so, 400 ns still allows about 2.5 million decisions per second per core, far beyond what most services handle. You also get thread safety, multiple bandwidths per bucket, and distributed backends from the library, so the cost buys real features. Treat it as headroom information, not as a reason to hand-roll a limiter.
Memory is where the choice can matter at scale. At one million active keys, a token bucket costs about 32 MB of state and a sliding log about 120 MB. Meanwhile, a boxed ArrayDeque queue and a bucket4j bucket each cost around 350 MB. Add 77 bytes per key for the map entry, which costs more than most of the limiters it holds. If you rate limit per IP address on a public endpoint, those per-key bytes multiply by every address that touched you in the last window.
Which Rate Limiting Algorithm Should You Use?
For most HTTP APIs, use a token bucket. It rejected 0.9% of a below-limit Poisson client, versus 14.8% for a sliding log, while still capping sustained traffic at the refill rate. It costs 32 bytes per key, every serious library implements it, and its one weakness, a spike of up to capacity plus refill, is something you control by sizing the capacity.
Use a sliding window log when the limit is a hard contract, such as a partner API that bans you after 10 calls in any rolling second. It never let more than 10 through in this test, at the cost of rejecting legal clusters and storing one timestamp per allowed request.
Use a leaky queue for asynchronous work in front of a backend that must see a flat rate. It never exceeded 10 per second downstream and rejected the fewest requests, but every admitted request can wait up to a full second.
Finally, use a fixed window only when a short double-rate spike is harmless, such as daily or monthly quotas where the boundary effect averages out. For per-second limits, its 20-in-200-ms burst defeats the purpose.
Real-World Scenario: A Partner API With a Rolling Quota
Consider a small backend team integrating with a payment or shipping provider that allows 10 calls per second per account and returns 429 on the 11th call inside any rolling second. The team wraps outgoing calls in the token bucket their framework provides, configured at 10 per second with a capacity of 10, and it works in staging, where traffic is a trickle.
In production, traffic is bursty. Order confirmations arrive in clusters after a marketing email, much like the Poisson trace. The token bucket happily passes 15 to 17 calls in a busy second, exactly as it did in this test, and the provider starts returning 429s. The team reads “token bucket handles bursts gracefully” in their notes and lowers the capacity to 5, which reduces the spike but does not remove it, because capacity plus one second of refill is still 15.
The fix that matches the contract is whichever of the rate limiting algorithms enforces the same rule the provider enforces. A sliding log on the client side, or better, a leaky queue in front of the asynchronous confirmation job, keeps outgoing calls at 10 or fewer in any rolling second. The trade-off is that some confirmations wait up to a second, which nobody notices for an email. For calls the user waits on, the team keeps a fast failure path with retry and backoff, the same pattern the LLM rate limiting and retry strategies post walks through for model APIs.
When to Use a Token Bucket Rate Limiter
- Public or internal HTTP APIs where clients send in bursts but stay within the average
- Per-user or per-API-key limits where false rejections create support load
- In-process limits on a hot path, where 32 bytes per key and about 22 ns per decision matter
- Any case where a library such as bucket4j, or your API gateway, already provides one
When NOT to Use a Token Bucket
- The downstream enforces a strict rolling-window quota and punishes the 11th call
- A backend falls over under short spikes, and a capacity small enough to prevent them would starve normal clients
- The work is asynchronous and smoothing it to a flat rate is the actual goal, which a leaky queue does better
- Billing or quota accounting needs exact counts per calendar period, which a fixed window per day or month gives you directly
Common Mistakes With Rate Limiting Algorithms
- Treating capacity as the per-second limit; a token bucket can pass capacity plus one second of refill in a single second
- Assuming a leaky bucket smooths traffic when the gateway implements the meter form, which makes the same decisions as a token bucket
- Picking a sliding window counter for a published per-second limit, then getting tickets from clients that meter themselves exactly to it
- Using fixed windows for short limits; the boundary burst in this test doubled the configured rate
- Keeping limiter state in a plain
HashMapacross request threads; the limiters here are single-threaded on purpose, and production code needs atomic updates per key or a library that provides them - Never evicting idle keys; at 77 bytes of map entry plus 32 to 360 bytes of state, one million stale IP addresses cost real heap
- Running one in-memory limiter per instance behind a load balancer and calling the total a global limit; three instances allow three times the rate, which the rate limiter system design walkthrough covers in depth
What This Test Did Not Cover
First, every result for these rate limiting algorithms is single-threaded and single-node. Contention between threads updating the same key, and the round trip to a shared store such as Redis, both cost far more than the decision itself and were not measured. Second, the traces are synthetic. Real traffic has heavier tails than Poisson, so the gap between strict and forgiving limiters will usually be larger, not smaller. Third, the speed numbers come from JDK 18 on a Windows desktop, and a current JDK on a Linux server will produce different absolute figures, although the ordering is unlikely to change. Finally, only one configuration was tested: 10 per second with a capacity of 10. Larger capacities make the token bucket more forgiving and its spikes larger, in proportion. The admit and reject results will be re-run when bucket4j ships its next major version, and the timings on a current JDK.
Conclusion
Measured on the same traffic, the five rate limiting algorithms split into two camps. Fixed windows and buckets forgive clusters and allow short spikes, up to twice the limit for a fixed window. Sliding logs and counters cap every rolling second and reject up to 15% of clients who stay under the limit on average. Token bucket and leaky bucket as a meter are the same algorithm, and the leaky queue is a different tool that buys a flat rate with up to a second of latency.
So start with a token bucket for anything a user waits on, size its capacity to what the backend can absorb in a spike, and switch to a sliding log or a queue only where a downstream contract demands a strict rolling cap. Next, read the API rate limiting basics for the response headers and client-side retry behaviour that make whichever limiter you choose easier to live with.