Building a Production Rate Limiter in Java. Here Is Every Decision I Made.
Every serious backend system has one. Stripe uses it to protect their payment API. Cloudflare uses it to absorb traffic spikes at the edge. AWS API Gateway puts it in front of every Lambda. The rate limiter is one of those things you use every day but almost never build yourself.
I built one from scratch in pure Java. No Spring, no frameworks, no dependencies beyond the JDK and JUnit. The whole thing runs, handles thousands of concurrent requests safely, and includes the kind of test that actually proves thread safety, 100 threads hitting the same rate limiter simultaneously, and exactly 10 getting through.
This article covers everything: the two algorithms worth knowing, why the simpler one has a subtle flaw, the concurrency model that makes it production-safe, and how to wrap it in a real API gateway.
The Problem With Simple Rate Limiters
Most tutorials show you a fixed window counter. Keep a map of client IDs to request counts, reset the counts every minute, reject anything over the limit. It takes about fifteen lines and it almost works.
The flaw is at the boundary. Say your limit is 10 requests per minute. A client fires 10 requests at 00:59. The counter resets at 01:00. They fire 10 more at 01:01. They have sent 20 requests in two seconds and violated the spirit of the limit without technically violating the rule. Any production rate limiter you care about handles this.
We are going to build two algorithms that do.
Algorithm One: Token Bucket
This is the one Stripe uses. The mental model is simple.
Each client gets a bucket that holds N tokens. Every request consumes one token. Tokens refill at a steady rate, say 10 per second. When the bucket is empty the request is rejected. When tokens refill, requests are allowed again.
The key property: it handles bursts. If a client has been idle and their bucket is full, they can fire N requests immediately. This is correct behaviour. A client that has been quiet for an hour should not be throttled because they suddenly have a real need. The burst is bounded by the bucket size.
The Interface
Before any implementation, define what a rate limiter is:
public interface RateLimiter {
boolean allowRequest(String clientId);
long getRemainingTokens(String clientId);
void reset(String clientId);
}
public interface RateLimiter {
boolean allowRequest(String clientId);
long getRemainingTokens(String clientId);
void reset(String clientId);
}
clientId is whatever identifies the caller: an API key, a user ID, an IP address. The gateway layer handles that mapping. The rate limiter itself only cares about the string.
The Bucket
Each client gets one Bucket. This is the object that actually tracks their token count.
0) {
availableTokens–;
return true;
}
return false;
}
synchronized long getAvailableTokens() {
refill();
return availableTokens;
}
synchronized void reset() {
availableTokens = maxTokens;
lastRefillTimestampMs = System.currentTimeMillis();
}
long getLastAccessTimestampMs() {
return lastAccessTimestampMs;
}
private void refill() {
long now = System.currentTimeMillis();
long elapsedMs = now – lastRefillTimestampMs;
if (elapsedMs 0) {
availableTokens = Math.min(maxTokens, availableTokens + tokensToAdd);
lastRefillTimestampMs = now;
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
class Bucket {
private final long maxTokens;
private final long refillRatePerSecond;
private long availableTokens;
private long lastRefillTimestampMs;
private long lastAccessTimestampMs;
Bucket(long maxTokens, long refillRatePerSecond) {
this.maxTokens = maxTokens;
this.refillRatePerSecond = refillRatePerSecond;
this.availableTokens = maxTokens;
this.lastRefillTimestampMs = System.currentTimeMillis();
this.lastAccessTimestampMs = System.currentTimeMillis();
}
synchronized boolean tryConsume() {
refill();
lastAccessTimestampMs = System.currentTimeMillis();
if (availableTokens > 0) {
availableTokens--;
return true;
}
return false;
}
synchronized long getAvailableTokens() {
refill();
return availableTokens;
}
synchronized void reset() {
availableTokens = maxTokens;
lastRefillTimestampMs = System.currentTimeMillis();
}
long getLastAccessTimestampMs() {
return lastAccessTimestampMs;
}
private void refill() {
long now = System.currentTimeMillis();
long elapsedMs = now - lastRefillTimestampMs;
if (elapsedMs <= 0) return;
long tokensToAdd = (elapsedMs * refillRatePerSecond) / 1000;
if (tokensToAdd > 0) {
availableTokens = Math.min(maxTokens, availableTokens + tokensToAdd);
lastRefillTimestampMs = now;
}
}
}
class Bucket {
private final long maxTokens;
private final long refillRatePerSecond;
private long availableTokens;
private long lastRefillTimestampMs;
private long lastAccessTimestampMs;
Bucket(long maxTokens, long refillRatePerSecond) {
this.maxTokens = maxTokens;
this.refillRatePerSecond = refillRatePerSecond;
this.availableTokens = maxTokens;
this.lastRefillTimestampMs = System.currentTimeMillis();
this.lastAccessTimestampMs = System.currentTimeMillis();
}
synchronized boolean tryConsume() {
refill();
lastAccessTimestampMs = System.currentTimeMillis();
if (availableTokens > 0) {
availableTokens--;
return true;
}
return false;
}
synchronized long getAvailableTokens() {
refill();
return availableTokens;
}
synchronized void reset() {
availableTokens = maxTokens;
lastRefillTimestampMs = System.currentTimeMillis();
}
long getLastAccessTimestampMs() {
return lastAccessTimestampMs;
}
private void refill() {
long now = System.currentTimeMillis();
long elapsedMs = now - lastRefillTimestampMs;
if (elapsedMs <= 0) return;
long tokensToAdd = (elapsedMs * refillRatePerSecond) / 1000;
if (tokensToAdd > 0) {
availableTokens = Math.min(maxTokens, availableTokens + tokensToAdd);
lastRefillTimestampMs = now;
}
}
}
Two decisions worth explaining here.
synchronized on instance methods, not on a static lock. Each client has their own Bucket object. Synchronizing on the instance means client A’s requests and client B’s requests never block each other. The lock granularity matches the isolation we actually want.
Lazy refill. Tokens do not refill on a timer. They refill when someone asks. On every tryConsume() and getAvailableTokens() call, we calculate how much time has passed since the last refill and add the appropriate tokens. This is how Redis implements it. No background threads, no scheduled tasks for the refill itself.
The lastAccessTimestampMs field is for memory management. We will use it to clean up buckets for clients who have gone quiet.
The Token Bucket Rate Limiter
Now the outer class that manages one bucket per client:
<button data-code="public class TokenBucketRateLimiter implements RateLimiter {
private final int maxTokens;
private final int refillRatePerSecond;
private final ConcurrentHashMap buckets;
private final ScheduledExecutorService cleanupScheduler;
public TokenBucketRateLimiter(int maxTokens, int refillRatePerSecond) {
this.maxTokens = maxTokens;
this.refillRatePerSecond = refillRatePerSecond;
this.buckets = new ConcurrentHashMap();
this.cleanupScheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
Thread thread = new Thread(runnable, "rate-limiter-cleanup");
thread.setDaemon(true);
return thread;
});
cleanupScheduler.scheduleAtFixedRate(
this::removeInactiveBuckets, 5, 5, TimeUnit.MINUTES
);
}
@Override
public boolean allowRequest(String clientId) {
Bucket bucket = buckets.computeIfAbsent(
clientId,
id -> new Bucket(maxTokens, refillRatePerSecond)
);
return bucket.tryConsume();
}
@Override
public long getRemainingTokens(String clientId) {
Bucket bucket = buckets.get(clientId);
if (bucket == null) return maxTokens;
return bucket.getAvailableTokens();
}
@Override
public void reset(String clientId) {
Bucket bucket = buckets.get(clientId);
if (bucket != null) bucket.reset();
}
public void shutdown() {
cleanupScheduler.shutdown();
}
private void removeInactiveBuckets() {
long expiryThresholdMs = System.currentTimeMillis() – TimeUnit.MINUTES.toMillis(10);
var iterator = buckets.entrySet().iterator();
while (iterator.hasNext()) {
if (iterator.next().getValue().getLastAccessTimestampMs()
public class TokenBucketRateLimiter implements RateLimiter {
private final int maxTokens;
private final int refillRatePerSecond;
private final ConcurrentHashMap<String, Bucket> buckets;
private final ScheduledExecutorService cleanupScheduler;
public TokenBucketRateLimiter(int maxTokens, int refillRatePerSecond) {
this.maxTokens = maxTokens;
this.refillRatePerSecond = refillRatePerSecond;
this.buckets = new ConcurrentHashMap<>();
this.cleanupScheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
Thread thread = new Thread(runnable, "rate-limiter-cleanup");
thread.setDaemon(true);
return thread;
});
cleanupScheduler.scheduleAtFixedRate(
this::removeInactiveBuckets, 5, 5, TimeUnit.MINUTES
);
}
@Override
public boolean allowRequest(String clientId) {
Bucket bucket = buckets.computeIfAbsent(
clientId,
id -> new Bucket(maxTokens, refillRatePerSecond)
);
return bucket.tryConsume();
}
@Override
public long getRemainingTokens(String clientId) {
Bucket bucket = buckets.get(clientId);
if (bucket == null) return maxTokens;
return bucket.getAvailableTokens();
}
@Override
public void reset(String clientId) {
Bucket bucket = buckets.get(clientId);
if (bucket != null) bucket.reset();
}
public void shutdown() {
cleanupScheduler.shutdown();
}
private void removeInactiveBuckets() {
long expiryThresholdMs = System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(10);
var iterator = buckets.entrySet().iterator();
while (iterator.hasNext()) {
if (iterator.next().getValue().getLastAccessTimestampMs() < expiryThresholdMs) {
iterator.remove();
}
}
}
}
public class TokenBucketRateLimiter implements RateLimiter {
private final int maxTokens;
private final int refillRatePerSecond;
private final ConcurrentHashMap<String, Bucket> buckets;
private final ScheduledExecutorService cleanupScheduler;
public TokenBucketRateLimiter(int maxTokens, int refillRatePerSecond) {
this.maxTokens = maxTokens;
this.refillRatePerSecond = refillRatePerSecond;
this.buckets = new ConcurrentHashMap<>();
this.cleanupScheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
Thread thread = new Thread(runnable, "rate-limiter-cleanup");
thread.setDaemon(true);
return thread;
});
cleanupScheduler.scheduleAtFixedRate(
this::removeInactiveBuckets, 5, 5, TimeUnit.MINUTES
);
}
@Override
public boolean allowRequest(String clientId) {
Bucket bucket = buckets.computeIfAbsent(
clientId,
id -> new Bucket(maxTokens, refillRatePerSecond)
);
return bucket.tryConsume();
}
@Override
public long getRemainingTokens(String clientId) {
Bucket bucket = buckets.get(clientId);
if (bucket == null) return maxTokens;
return bucket.getAvailableTokens();
}
@Override
public void reset(String clientId) {
Bucket bucket = buckets.get(clientId);
if (bucket != null) bucket.reset();
}
public void shutdown() {
cleanupScheduler.shutdown();
}
private void removeInactiveBuckets() {
long expiryThresholdMs = System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(10);
var iterator = buckets.entrySet().iterator();
while (iterator.hasNext()) {
if (iterator.next().getValue().getLastAccessTimestampMs() < expiryThresholdMs) {
iterator.remove();
}
}
}
}
ConcurrentHashMap is the right data structure here. Multiple threads can read from it simultaneously without any locking. computeIfAbsent is atomic: even if 50 threads all try to create a bucket for the same new client at the same time, exactly one bucket is created and all 50 threads get the same one.
The cleanup scheduler runs every 5 minutes as a daemon thread. If you serve thousands of unique clients, the map would grow unbounded without it. Clients that have not made a request in 10 minutes get their bucket removed. Next time they call, they get a fresh full bucket, which is the correct behavior.
Algorithm Two: Sliding Window
The sliding window fixes the boundary burst problem. Instead of counting requests in a fixed time slot, it tracks the actual timestamp of each request and looks back exactly one window from the current moment.
<button data-code="public class SlidingWindowRateLimiter implements RateLimiter {
private final int maxRequests;
private final long windowSizeMs;
private final ConcurrentHashMap windows;
public SlidingWindowRateLimiter(int maxRequests, long windowSizeSeconds) {
this.maxRequests = maxRequests;
this.windowSizeMs = windowSizeSeconds * 1000;
this.windows = new ConcurrentHashMap();
}
@Override
public boolean allowRequest(String clientId) {
ClientWindow window = windows.computeIfAbsent(
clientId,
id -> new ClientWindow(maxRequests, windowSizeMs)
);
return window.tryAllow();
}
@Override
public long getRemainingTokens(String clientId) {
ClientWindow window = windows.get(clientId);
if (window == null) return maxRequests;
return window.getRemainingRequests();
}
@Override
public void reset(String clientId) {
windows.remove(clientId);
}
private static class ClientWindow {
private final int maxRequests;
private final long windowSizeMs;
private final Deque requestTimestamps;
ClientWindow(int maxRequests, long windowSizeMs) {
this.maxRequests = maxRequests;
this.windowSizeMs = windowSizeMs;
this.requestTimestamps = new ArrayDeque();
}
synchronized boolean tryAllow() {
long now = System.currentTimeMillis();
evictExpired(now);
if (requestTimestamps.size() < maxRequests) {
requestTimestamps.addLast(now);
return true;
}
return false;
}
synchronized long getRemainingRequests() {
evictExpired(System.currentTimeMillis());
return Math.max(0, maxRequests – requestTimestamps.size());
}
private void evictExpired(long now) {
long windowStart = now – windowSizeMs;
while (!requestTimestamps.isEmpty()
&& requestTimestamps.peekFirst()
public class SlidingWindowRateLimiter implements RateLimiter {
private final int maxRequests;
private final long windowSizeMs;
private final ConcurrentHashMap<String, ClientWindow> windows;
public SlidingWindowRateLimiter(int maxRequests, long windowSizeSeconds) {
this.maxRequests = maxRequests;
this.windowSizeMs = windowSizeSeconds * 1000;
this.windows = new ConcurrentHashMap<>();
}
@Override
public boolean allowRequest(String clientId) {
ClientWindow window = windows.computeIfAbsent(
clientId,
id -> new ClientWindow(maxRequests, windowSizeMs)
);
return window.tryAllow();
}
@Override
public long getRemainingTokens(String clientId) {
ClientWindow window = windows.get(clientId);
if (window == null) return maxRequests;
return window.getRemainingRequests();
}
@Override
public void reset(String clientId) {
windows.remove(clientId);
}
private static class ClientWindow {
private final int maxRequests;
private final long windowSizeMs;
private final Deque<Long> requestTimestamps;
ClientWindow(int maxRequests, long windowSizeMs) {
this.maxRequests = maxRequests;
this.windowSizeMs = windowSizeMs;
this.requestTimestamps = new ArrayDeque<>();
}
synchronized boolean tryAllow() {
long now = System.currentTimeMillis();
evictExpired(now);
if (requestTimestamps.size() < maxRequests) {
requestTimestamps.addLast(now);
return true;
}
return false;
}
synchronized long getRemainingRequests() {
evictExpired(System.currentTimeMillis());
return Math.max(0, maxRequests - requestTimestamps.size());
}
private void evictExpired(long now) {
long windowStart = now - windowSizeMs;
while (!requestTimestamps.isEmpty()
&& requestTimestamps.peekFirst() <= windowStart) {
requestTimestamps.pollFirst();
}
}
}
}
public class SlidingWindowRateLimiter implements RateLimiter {
private final int maxRequests;
private final long windowSizeMs;
private final ConcurrentHashMap<String, ClientWindow> windows;
public SlidingWindowRateLimiter(int maxRequests, long windowSizeSeconds) {
this.maxRequests = maxRequests;
this.windowSizeMs = windowSizeSeconds * 1000;
this.windows = new ConcurrentHashMap<>();
}
@Override
public boolean allowRequest(String clientId) {
ClientWindow window = windows.computeIfAbsent(
clientId,
id -> new ClientWindow(maxRequests, windowSizeMs)
);
return window.tryAllow();
}
@Override
public long getRemainingTokens(String clientId) {
ClientWindow window = windows.get(clientId);
if (window == null) return maxRequests;
return window.getRemainingRequests();
}
@Override
public void reset(String clientId) {
windows.remove(clientId);
}
private static class ClientWindow {
private final int maxRequests;
private final long windowSizeMs;
private final Deque<Long> requestTimestamps;
ClientWindow(int maxRequests, long windowSizeMs) {
this.maxRequests = maxRequests;
this.windowSizeMs = windowSizeMs;
this.requestTimestamps = new ArrayDeque<>();
}
synchronized boolean tryAllow() {
long now = System.currentTimeMillis();
evictExpired(now);
if (requestTimestamps.size() < maxRequests) {
requestTimestamps.addLast(now);
return true;
}
return false;
}
synchronized long getRemainingRequests() {
evictExpired(System.currentTimeMillis());
return Math.max(0, maxRequests - requestTimestamps.size());
}
private void evictExpired(long now) {
long windowStart = now - windowSizeMs;
while (!requestTimestamps.isEmpty()
&& requestTimestamps.peekFirst() <= windowStart) {
requestTimestamps.pollFirst();
}
}
}
}
The Deque<Long> holds the timestamp of every request within the current window. On each new request, we first remove all timestamps older than one window ago. If the remaining count is under the limit, the request is allowed and its timestamp is recorded.
The trade-off: the sliding window uses more memory. Instead of one counter per client, you store up to N timestamps per client. For most APIs where N is in the hundreds, this is completely fine. For very high volume with millions of clients, the token bucket’s single counter per client is more memory efficient.
The API Gateway
The rate limiter is just a library until you put it in front of real HTTP traffic. Java ships with a built-in HTTP server that handles this without any external dependencies.
handleApiRequest(exchange, "data"));
server.createContext("/api/status", this::handleStatusRequest);
server.createContext("/health", this::handleHealthRequest);
server.setExecutor(Executors.newFixedThreadPool(50));
}
private void handleApiRequest(HttpExchange exchange, String endpoint) throws IOException {
String clientId = extractClientId(exchange);
boolean allowed = rateLimiter.allowRequest(clientId);
long remaining = rateLimiter.getRemainingTokens(clientId);
if (allowed) {
String body = String.format(
"{"status":"ok","client":"%s","remaining":%d}",
clientId, remaining
);
sendJson(exchange, 200, body, remaining);
} else {
String body = String.format(
"{"status":"error","message":"Too Many Requests","client":"%s"}",
clientId
);
exchange.getResponseHeaders().set("Retry-After", "1");
sendJson(exchange, 429, body, 0);
}
}
private String extractClientId(HttpExchange exchange) {
String apiKey = exchange.getRequestHeaders().getFirst("X-API-Key");
if (apiKey != null && !apiKey.isBlank()) {
return "api:" + apiKey;
}
return "ip:" + exchange.getRemoteAddress().getAddress().getHostAddress();
}
private void sendJson(HttpExchange exchange, int status,
String body, long remaining) throws IOException {
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.getResponseHeaders().set("X-RateLimit-Remaining", String.valueOf(remaining));
byte[] bytes = body.getBytes();
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
public class ApiGateway {
private final HttpServer server;
private final RateLimiter rateLimiter;
public ApiGateway(int port, RateLimiter rateLimiter) throws IOException {
this.rateLimiter = rateLimiter;
this.server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/api/data", exchange -> handleApiRequest(exchange, "data"));
server.createContext("/api/status", this::handleStatusRequest);
server.createContext("/health", this::handleHealthRequest);
server.setExecutor(Executors.newFixedThreadPool(50));
}
private void handleApiRequest(HttpExchange exchange, String endpoint) throws IOException {
String clientId = extractClientId(exchange);
boolean allowed = rateLimiter.allowRequest(clientId);
long remaining = rateLimiter.getRemainingTokens(clientId);
if (allowed) {
String body = String.format(
"{"status":"ok","client":"%s","remaining":%d}",
clientId, remaining
);
sendJson(exchange, 200, body, remaining);
} else {
String body = String.format(
"{"status":"error","message":"Too Many Requests","client":"%s"}",
clientId
);
exchange.getResponseHeaders().set("Retry-After", "1");
sendJson(exchange, 429, body, 0);
}
}
private String extractClientId(HttpExchange exchange) {
String apiKey = exchange.getRequestHeaders().getFirst("X-API-Key");
if (apiKey != null && !apiKey.isBlank()) {
return "api:" + apiKey;
}
return "ip:" + exchange.getRemoteAddress().getAddress().getHostAddress();
}
private void sendJson(HttpExchange exchange, int status,
String body, long remaining) throws IOException {
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.getResponseHeaders().set("X-RateLimit-Remaining", String.valueOf(remaining));
byte[] bytes = body.getBytes();
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
}
}
public class ApiGateway {
private final HttpServer server;
private final RateLimiter rateLimiter;
public ApiGateway(int port, RateLimiter rateLimiter) throws IOException {
this.rateLimiter = rateLimiter;
this.server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/api/data", exchange -> handleApiRequest(exchange, "data"));
server.createContext("/api/status", this::handleStatusRequest);
server.createContext("/health", this::handleHealthRequest);
server.setExecutor(Executors.newFixedThreadPool(50));
}
private void handleApiRequest(HttpExchange exchange, String endpoint) throws IOException {
String clientId = extractClientId(exchange);
boolean allowed = rateLimiter.allowRequest(clientId);
long remaining = rateLimiter.getRemainingTokens(clientId);
if (allowed) {
String body = String.format(
"{"status":"ok","client":"%s","remaining":%d}",
clientId, remaining
);
sendJson(exchange, 200, body, remaining);
} else {
String body = String.format(
"{"status":"error","message":"Too Many Requests","client":"%s"}",
clientId
);
exchange.getResponseHeaders().set("Retry-After", "1");
sendJson(exchange, 429, body, 0);
}
}
private String extractClientId(HttpExchange exchange) {
String apiKey = exchange.getRequestHeaders().getFirst("X-API-Key");
if (apiKey != null && !apiKey.isBlank()) {
return "api:" + apiKey;
}
return "ip:" + exchange.getRemoteAddress().getAddress().getHostAddress();
}
private void sendJson(HttpExchange exchange, int status,
String body, long remaining) throws IOException {
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.getResponseHeaders().set("X-RateLimit-Remaining", String.valueOf(remaining));
byte[] bytes = body.getBytes();
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
}
}
The X-API-Key header gets priority for client identification. If it is missing, we fall back to the IP address. The gateway sets two response headers on every request: X-RateLimit-Remaining so clients know how much of their allowance is left, and Retry-After on 429 responses so clients know when to try again. These are not optional niceties. Any API that your clients integrate against should have them.
The thread pool with 50 threads means 50 simultaneous HTTP connections can be handled. Each connection runs allowRequest which hits ConcurrentHashMap.computeIfAbsent (lock-free if the bucket exists, minimally locked if not) and then Bucket.tryConsume (synchronized only on that client’s bucket). The system scales well.
The Test That Actually Proves Thread Safety
Unit tests that run single-threaded do not prove concurrent correctness. The only way to prove it is to throw concurrent load at it and check that the invariant holds.
<button data-code="@Test
@DisplayName("Token bucket allows exactly N requests under 100 concurrent threads")
void tokenBucketIsThreadSafe() throws InterruptedException {
int limit = 10;
int threads = 100;
TokenBucketRateLimiter limiter = new TokenBucketRateLimiter(limit, limit);
AtomicInteger allowed = new AtomicInteger(0);
AtomicInteger rejected = new AtomicInteger(0);
CountDownLatch startGate = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(threads);
for (int i = 0; i {
try {
startGate.await(); // All 100 threads wait here
if (limiter.allowRequest("shared-client")) {
allowed.incrementAndGet();
} else {
rejected.incrementAndGet();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
done.countDown();
}
}).start();
}
startGate.countDown(); // Release all 100 threads simultaneously
done.await(10, TimeUnit.SECONDS);
assertEquals(10, allowed.get(), "Exactly limit requests should be allowed");
assertEquals(90, rejected.get(), "Rest should be rejected");
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
@Test
@DisplayName("Token bucket allows exactly N requests under 100 concurrent threads")
void tokenBucketIsThreadSafe() throws InterruptedException {
int limit = 10;
int threads = 100;
TokenBucketRateLimiter limiter = new TokenBucketRateLimiter(limit, limit);
AtomicInteger allowed = new AtomicInteger(0);
AtomicInteger rejected = new AtomicInteger(0);
CountDownLatch startGate = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(threads);
for (int i = 0; i < threads; i++) {
new Thread(() -> {
try {
startGate.await(); // All 100 threads wait here
if (limiter.allowRequest("shared-client")) {
allowed.incrementAndGet();
} else {
rejected.incrementAndGet();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
done.countDown();
}
}).start();
}
startGate.countDown(); // Release all 100 threads simultaneously
done.await(10, TimeUnit.SECONDS);
assertEquals(10, allowed.get(), "Exactly limit requests should be allowed");
assertEquals(90, rejected.get(), "Rest should be rejected");
}
@Test
@DisplayName("Token bucket allows exactly N requests under 100 concurrent threads")
void tokenBucketIsThreadSafe() throws InterruptedException {
int limit = 10;
int threads = 100;
TokenBucketRateLimiter limiter = new TokenBucketRateLimiter(limit, limit);
AtomicInteger allowed = new AtomicInteger(0);
AtomicInteger rejected = new AtomicInteger(0);
CountDownLatch startGate = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(threads);
for (int i = 0; i < threads; i++) {
new Thread(() -> {
try {
startGate.await(); // All 100 threads wait here
if (limiter.allowRequest("shared-client")) {
allowed.incrementAndGet();
} else {
rejected.incrementAndGet();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
done.countDown();
}
}).start();
}
startGate.countDown(); // Release all 100 threads simultaneously
done.await(10, TimeUnit.SECONDS);
assertEquals(10, allowed.get(), "Exactly limit requests should be allowed");
assertEquals(90, rejected.get(), "Rest should be rejected");
}
The CountDownLatch start gate is important. Without it, threads start at slightly different times and the test is less aggressive. With it, all 100 threads are running, waiting, and then released simultaneously. This maximises the chance of hitting a race condition if one exists.
If synchronization is broken, allowed will be greater than 10 because two threads both see “tokens available” before either has decremented the count. This test catches that.
Running It
# All tests including concurrent load tests
mvn test
# Demo (shows both algorithms then starts the gateway on 8080)
mvn compile exec:java
# All tests including concurrent load tests
mvn test
# Demo (shows both algorithms then starts the gateway on 8080)
mvn compile exec:java
Once the gateway is running:
# Normal request
curl -H "X-API-Key: my-key" http://localhost:8080/api/data
# Check remaining requests
curl -H "X-API-Key: my-key" http://localhost:8080/api/status
# Keep firing until you get 429
for i in {1..15}; do curl -s -H "X-API-Key: test" http://localhost:8080/api/data; echo; done
# Normal request
curl -H "X-API-Key: my-key" http://localhost:8080/api/data
# Check remaining requests
curl -H "X-API-Key: my-key" http://localhost:8080/api/status
# Keep firing until you get 429
for i in {1..15}; do curl -s -H "X-API-Key: test" http://localhost:8080/api/data; echo; done
When to Use Which Algorithm
Use the token bucket when:
- You want to allow short bursts
- Memory efficiency matters (one counter per client)
- The refill rate and burst size have different values
- This is what you are reaching for 90% of the time
Use the sliding window when:
- Burst prevention at window boundaries is a hard requirement
- You are building something like a payment API where 20 requests in 2 seconds genuinely matters
- The higher memory cost is acceptable
Both are correct implementations. The choice comes down to whether controlled bursting is acceptable in your domain.
What This Looks Like in a Real Interview
At Stripe, Wise, or any company with a serious backend interview, a rate limiter question is likely to go through these stages:
Start with requirements: what are we limiting, per client or global, what are the numbers, what happens to rejected requests.
Design the data model: this is where the token bucket or sliding window choice gets made and justified.
Handle concurrency: this is where most candidates struggle. The right answer is per-client locking so clients never block each other, not a global lock that serializes everything.
Handle scale: what happens with 10 million clients? How do you prevent the bucket map from growing unbounded? This is the cleanup scheduler.
Handle edge cases: what if two requests arrive at exactly the boundary? What if the server restarts and loses all state? What if clients collude by splitting across IPs?
The code in this article answers the first four directly. The fifth is where the conversation gets interesting.
The full code with all tests is on GitHub: [link]
Published under Systems Engineering. More articles on building real things in Java.


