Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Explain the token bucket, fixed window and sliding window algorithms for rate limiting, and one weakness of each.

A token bucket refills tokens at a fixed rate up to a capacity, so it allows bursts up to that capacity, which is also its weakness when bursts are harmful. A fixed window counts requests per time window and can let through up to double the limit around a window boundary. A sliding window log stores the timestamp of every request, which is accurate but memory heavy, and a sliding window counter combines the current and previous windows' counts with a weight, which is cheap but approximate. The token bucket is a common default because it is simple and allows controlled bursts.

Why this question is asked

Rate limiting decides how many requests a client may make in a period, and nearly every public API and many internal services have it. The algorithm behind the limit decides how it behaves at the edges: whether a client can send a burst, whether limits can be gamed at window boundaries, and how much memory and computation each check costs. Interviewers ask this question to see whether we understand these trade-offs rather than only naming the algorithms. In this answer, we will walk through the token bucket, the fixed window, the sliding window log and the sliding window counter, each with a small example, its weakness, and a comparison to help choose.

1The Token Bucket

Picture a bucket that holds up to 10 tokens and gains 1 token every second. Each request takes a token; if the bucket is empty, the request is rejected. A client that was quiet has a full bucket, so it can send 10 requests at once, and after that it is held to 1 per second, the refill rate. The state per client is just two numbers: the current token count and the time of the last refill. On each request we add the tokens earned since the last refill, capped at the capacity, then try to take one.

Java
class TokenBucket {
private final long capacity = 10;
private final double refillPerSec = 1.0;
private double tokens = 10;
private long lastNanos = System.nanoTime();
synchronized boolean tryAcquire() {
long now = System.nanoTime();
tokens = Math.min(capacity, tokens + (now - lastNanos) / 1e9 * refillPerSec);
lastNanos = now;
if (tokens >= 1) { tokens -= 1; return true; } // allowed
return false; // rejected
}
}
// 10 requests at once after a quiet minute -> all 10 allowed
// 11th request in the same second -> false
// 1 second later -> true again

Its weakness is the flip side of its strength: it deliberately allows bursts up to the capacity. If the protected resource cannot handle 10 requests arriving together, we must make the capacity small, which then makes the limit feel strict to normal clients. A close relative, the leaky bucket, processes requests at a fixed outflow rate from a queue and smooths bursts out completely, at the cost of adding delay.

2The Fixed Window

A fixed window counter divides time into windows, such as each calendar minute, and counts requests per client in the current window. If the count reaches the limit, further requests are rejected until the next window starts and the counter resets. In Redis it is one INCR on a key like rl:client42:202611061201 with an expiry of one minute. It is the simplest algorithm and uses one small counter per client.

Java
// limit: 100 requests per minute
// 12:00:00 - 12:00:58 client sends 0 requests
// 12:00:59 client sends 100 -> all allowed (window 12:00, count 100)
// 12:01:00 client sends 100 -> all allowed (new window 12:01, count reset)
// result: 200 requests in about 2 seconds, double the intended rate

That is its weakness: around a window boundary a client can send up to twice the limit within a short time, as the example shows. If the limit protects a database that can only take 100 requests per minute, the 200-request spike can still overload it. The windows are also visible to clients, who may all retry at the start of each minute and create synchronised spikes.

3The Sliding Window Log

A sliding window log keeps the timestamp of every accepted request per client, for example in a Redis sorted set. On each request, it removes timestamps older than one window (60 seconds ago), counts what remains, and allows the request only if the count is below the limit, then records its timestamp. The window slides with every request, so there is no boundary to exploit: at any moment, the client has made at most 100 requests in the last 60 seconds. It is exact.

Java
// Redis, per request (in a MULTI block or Lua script so it is atomic):
// ZREMRANGEBYSCORE rl:client42 0 (now - 60000) -> drop entries older than 60 s
// ZCARD rl:client42 -> 99: below 100, so allow
// ZADD rl:client42 now now -> record this request
// EXPIRE rl:client42 60

The weakness is memory and work. It stores one entry per request: a client allowed 10,000 requests per minute needs up to 10,000 entries, and a million such clients need billions. Each check also trims and counts a set, which costs more than incrementing a counter. It suits low limits or cases where precision really matters.

4The Sliding Window Counter

The sliding window counter keeps the fixed window's cheap counters but estimates a sliding window from two of them: the current window and the previous one. It weights the previous window's count by how much of it still overlaps the last 60 seconds. If we are 15 seconds into the current minute, 45 of the previous minute's 60 seconds still count, a weight of 0.75.

Java
// limit 100 per minute; now = 12:01:15 (25 percent into the current window)
long previous = 80; // requests in 12:00 window
long current = 30; // requests so far in 12:01 window
double estimate = previous * (1 - 0.25) + current; // 80 * 0.75 + 30 = 90
boolean allowed = estimate < 100; // true
Comparing the four algorithms
AlgorithmState per clientBurstsWeakness
Token buckettoken count + timestampup to capacity, by designbursts can still hurt a fragile backend
Fixed windowone counterup to 2x around boundariesboundary spikes, synchronised retries
Sliding window logone timestamp per requestnone beyond the limitmemory and CPU heavy
Sliding window countertwo counterssmall over-allowanceapproximate, assumes even spread

Its weakness is that it is approximate: it assumes the previous window's requests were spread evenly, so if they were all at the very end, the estimate is slightly low and a client can briefly exceed the limit by a little. In practice the error is small, and it fixes the fixed window's double-limit problem with only two counters per client, which is why it is popular in large-scale limiters.

5Which One to Choose

The token bucket is a common default. It is simple, its state is tiny, it expresses two intuitive settings, a sustained rate and a burst size, and it allows the controlled bursts real clients produce, such as a page that fires 8 API calls when it loads. Libraries such as Bucket4j in Java and the Redis-based limiter in Spring Cloud Gateway implement it. I would pick the sliding window counter when the limit is phrased as "N per window" and boundary spikes must be avoided at low cost, the sliding window log when limits are small and must be exact, and the fixed window when simplicity matters most and the occasional double spike is harmless, for example a daily quota.

6Follow-up questions

How do you make these algorithms work across several instances?

The state must be shared, usually in Redis, and each check must be atomic so two instances cannot both take the last token or both count the 100th request. A Lua script, which Redis runs atomically, is the usual tool: it reads the state, applies the algorithm and writes the result in one step. Libraries such as Bucket4j's Redis integration and Spring Cloud Gateway's RedisRateLimiter do exactly this.

What is the difference between a token bucket and a leaky bucket?

A token bucket limits the rate of admitted requests but lets bursts through immediately if tokens are available. A leaky bucket puts requests in a queue that drains at a constant rate, so the output is perfectly smooth and bursts are delayed rather than passed on; when the queue is full, new requests are rejected. The leaky bucket is useful for shaping traffic to a backend that needs a steady rate, while the token bucket is more common for API limits.

7Conclusion

In this answer, we walked through four rate limiting algorithms. The token bucket refills at a fixed rate up to a capacity and allows controlled bursts; the fixed window counts per window but can admit double the limit around boundaries; the sliding window log is exact but stores every request; and the sliding window counter weights two windows to approximate a sliding window cheaply. We saw why the token bucket is a common default and when each of the others fits better.

What to say in the interviewAbout 110 seconds aloud

Open with

There are four algorithms I would describe. The token bucket has a bucket with a capacity, say 10 tokens, refilled at a fixed rate, say one per second.

Then, if they want more

Each request takes a token, and if it is empty the request is rejected. That allows a burst up to the capacity after a quiet period and then holds the client to the refill rate. Its weakness is exactly that burst: if the backend cannot handle ten requests at once, you have to make the capacity small.

The fixed window just counts requests per client in each calendar window, like each minute, and resets. It is one counter, very cheap, but around a boundary a client can send the full limit at the end of one minute and again at the start of the next, so up to double the limit in a couple of seconds.

The sliding window log stores the timestamp of every request, for example in a Redis sorted set, removes those older than the window and counts the rest. It is exact, but memory heavy, one entry per request, so it does not scale to high limits.

The sliding window counter keeps the current and previous window counts and weights the previous one by how much it still overlaps, so 80 in the last minute and 30 now, a quarter of the way in, gives an estimate of 90. It is cheap and fixes the boundary problem but is approximate.

I usually default to the token bucket because it is simple, needs two numbers per client, and its rate and burst settings match how real clients behave.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain the token bucket, fixed window and sliding window algorithms for rate limiting...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/9f23b81292/