Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Explain the token bucket algorithm and the difference between rate limiting incoming requests on a server and limiting outgoing calls on a client.

A token bucket holds up to a fixed number of tokens and refills them at a steady rate; each request takes one token, and when the bucket is empty the request is rejected or delayed. The capacity decides how big a burst can be, while the refill rate sets the long-run average. Server-side rate limiting protects our service and enforces client quotas, answering 429 with Retry-After, while client-side limiting, such as Resilience4j's RateLimiter, keeps our own calls within a dependency's quota. In a cluster, a per-instance limit is multiplied by the number of instances unless the counters live in a shared store.

Background to this question

Rate limiting appears in two places in almost every system: at the front door, where we protect ourselves from clients, and in our own outgoing clients, where we protect a dependency, or our contract with it, from ourselves. The token bucket is the algorithm behind most implementations, and it is popular because it allows short bursts while still enforcing an average. In this answer, we will build a token bucket step by step, see how capacity and refill rate behave with numbers, compare server-side and client-side limiting, and look at what changes when the service runs on many instances.

1A Quick Recap of Rate Limiting

Rate limiting means controlling how many requests are allowed in a period of time, such as 100 per second or 1,000 per minute. The simplest approach, a fixed window counter, counts requests in each calendar minute and resets at the boundary. Its weakness is that a client can send 1,000 requests at 12:00:59 and another 1,000 at 12:01:00, so 2,000 requests arrive within two seconds. The token bucket avoids that hard reset.

2How a Token Bucket Works

Picture a bucket that holds at most capacity tokens. Tokens are added at a fixed refill rate, and any tokens that would overflow the capacity are discarded. Each request must take one token. If a token is available, the request proceeds; if the bucket is empty, the request is rejected (or, in some designs, waits until a token arrives). Implementations do not run a timer. They compute how many tokens have accumulated since the last request, which makes each check a few arithmetic operations.

Java
class TokenBucket {
private final long capacity; private final double refillPerMs;
private double tokens; private long last = System.currentTimeMillis();
TokenBucket(long capacity, double perSecond) {
this.capacity = capacity; this.refillPerMs = perSecond / 1000.0; this.tokens = capacity;
}
synchronized boolean tryAcquire() {
long now = System.currentTimeMillis();
tokens = Math.min(capacity, tokens + (now - last) * refillPerMs); // add what accumulated
last = now;
if (tokens >= 1) { tokens -= 1; return true; }
return false;
}
}
TokenBucket b = new TokenBucket(10, 5); // burst of 10, average 5 per second
// 12 requests at once: first 10 -> true, 11th and 12th -> false
// one second later: 5 tokens again -> 5 more requests allowed
Bucket of capacity 10, refill 5 per second
TimeRequestsTokens beforeAllowedTokens after
0.0 s1210100
1.0 s3532
2.0 s8770
4.0 s010 (capped)010

Notice the two numbers doing different jobs. The capacity, 10 here, decides how large a burst can pass at once after a quiet period. The refill rate, 5 per second, decides the average over a long time: no client can sustain more than 5 requests per second, however it spreads them. A quiet client saves up tokens to a limit, which is why bursts are allowed but bounded.

3Server-Side Limits: Protecting the Service

On the server, a rate limiter sits at the front door, usually the API gateway or a servlet filter, and keeps one bucket per client, keyed by API key, user or IP address. It protects the service from overload and enforces quotas, such as 1,000 requests per minute on a free plan. When a client is over its limit, the server answers 429 Too Many Requests with a Retry-After header saying when to try again, and often headers showing the remaining quota, so well-behaved clients can slow down instead of hammering.

Server-side limits are about fairness and protection: one noisy client should not be able to degrade the service for everyone else.

4Client-Side Limits: Staying Within a Dependency's Quota

On the client, we limit our own outgoing calls. If a payment provider allows us 50 calls per second, it is far better to queue or reject a few calls ourselves than to get 429s, errors and possibly a suspended account. Resilience4j's RateLimiter does this. It divides time into refresh periods and allows limitForPeriod calls in each one; a call that finds no permit waits up to timeoutDuration and then fails with RequestNotPermitted. Its model is a permits-per-period cycle rather than a classic token bucket, but it serves the same purpose.

Java
resilience4j:
ratelimiter:
instances:
payments-provider:
limit-for-period: 50 # 50 calls
limit-refresh-period: 1s # per second
timeout-duration: 100ms # wait up to 100 ms for a permit
@RateLimiter(name = "payments-provider")
public ChargeResult charge(Charge c) { return provider.charge(c); }
// 51st call within one second waits up to 100 ms, then throws RequestNotPermitted

The difference in direction matters. Server-side limits defend us against others. Client-side limits make us a good citizen towards a dependency, and they keep us from paying for overage or being blocked.

5What Changes in a Cluster

Both kinds of limit get harder when the service runs on many instances. If each of 10 instances keeps its own bucket allowing 100 requests per second, the real limit is 1,000 per second, because a client's requests are spread across all 10. For a client-side limit towards a provider allowing 50 per second, 10 instances each allowing 50 would send up to 500.

There are two fixes. We can divide the limit by the number of instances, 10 per second each in the provider example, which is simple but inaccurate when traffic is uneven or the instance count changes with autoscaling. Or we can keep the counters in a shared store such as Redis, so all instances take tokens from the same bucket, which is accurate but adds a network call per request and a dependency that can fail. Spring Cloud Gateway's Redis rate limiter and Bucket4j with a distributed backend both work this way.

6Follow-up questions

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

A token bucket allows bursts up to its capacity and then limits the average rate. A leaky bucket, used as a queue, releases requests at a constant rate no matter how they arrive, which smooths traffic completely but adds waiting. Token buckets suit APIs where short bursts are fine; leaky buckets suit cases where the downstream needs a steady flow.

Should a rate limiter reject or delay the request?

On a server facing external clients, reject quickly with 429 and Retry-After, because holding requests open costs our resources. On a client calling a dependency, a short wait for a permit is often fine, as long as it stays well inside the caller's timeout.

Which key should a public API limit by?

By API key or authenticated client for quotas, because IP addresses are shared behind proxies and change. An IP limit is still useful as a coarse protection against anonymous abuse before authentication.

7Conclusion

In this answer, we built a token bucket and saw that its capacity sets the largest burst and its refill rate the long-run average. Server-side limits protect our service and enforce quotas with 429 and Retry-After, while client-side limits like Resilience4j's RateLimiter keep our calls within a dependency's quota. In a cluster, per-instance buckets multiply by the number of instances unless we divide the limit or share counters in a store such as Redis.

What to say in the interviewAbout 90 seconds aloud

Open with

A token bucket has a capacity and a refill rate. Tokens are added at the refill rate, up to the capacity, and every request takes one token; if the bucket is empty, the request is rejected or delayed.

Then, if they want more

In practice nothing runs on a timer, we just compute how many tokens accumulated since the last request. The capacity controls bursts: after a quiet period, a client can send up to capacity requests at once. The refill rate controls the average: over time nobody can exceed it.

So a bucket of ten with a refill of five per second lets ten requests through at once but only five per second sustained. On the server side, rate limiting protects our service and enforces quotas per API key, and when a client is over the limit we return 429 Too Many Requests with Retry-After and remaining-quota headers.

On the client side, we limit our own calls to stay within a dependency's quota, for example with Resilience4j's RateLimiter, limit-for-period fifty per one-second refresh period, which throws RequestNotPermitted after its timeout. The cluster point is important: if ten instances each enforce a hundred per second locally, the real limit is a thousand.

So either we divide the limit per instance, which is approximate with autoscaling, or we keep the counters in a shared store like Redis, accepting an extra network hop.

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 documentation below. 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 algorithm and the difference between rate limiting incoming...": https://scrivio-interview-library.netlify.app/spring-boot/resilience/3c29446707/