Design a rate limiter as a service
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite now runs 20 API servers behind a load balancer, and one customer's requests land on all of them. Each server counts only what it sees, so a limit of 100 a minute quietly becomes 2,000.
Your turn: 100 requests a minute on 20 servers
A customer's app may send 100 requests a minute. Their requests are spread over 20 servers, and each server keeps its own count. Think first:
- How many requests can the customer really send before anyone says no?
- Where could the count live so that every server sees the same number?
- Two servers read the count 99 at the same moment. What goes wrong, and how would you prevent it?
Write down your answers, then compare them with the design below.
Requirements: one shared limit, low added latency
Distributed rate limiter makes many servers enforce one shared limit, such as 100 requests per minute per API key, by counting in one place that every server can see.
The requirements, then a program in which three servers count locally and let one client through three times.
Example 1 · Local counters let a client through 3 times
import java.util.HashMap;import java.util.Map;
class LocalLimiter { private final Map<String, Integer> counts = new HashMap<>(); private final int limit;
LocalLimiter(int limit) { this.limit = limit; }
boolean allow(String client) { int used = counts.merge(client, 1, Integer::sum); return used <= limit; }}
public class LocalVsSharedLimitDemo { public static void main(String[] args) { int limit = 5; // 5 requests per minute per client int servers = 3;
LocalLimiter[] local = new LocalLimiter[servers]; for (int i = 0; i < servers; i++) { local[i] = new LocalLimiter(limit); } LocalLimiter shared = new LocalLimiter(limit); // one counter that every server uses
int allowedLocal = 0; int allowedShared = 0; for (int request = 0; request < 15; request++) { int server = request % servers; // the load balancer uses round robin if (local[server].allow("key_42")) { allowedLocal++; } if (shared.allow("key_42")) { allowedShared++; } } System.out.println("Limit: " + limit + " per minute, requests sent: 15"); System.out.println("Each server counts alone: " + allowedLocal + " allowed"); System.out.println("Shared counter: " + allowedShared + " allowed"); }}Limit: 5 per minute, requests sent: 15 Each server counts alone: 15 allowed Shared counter: 5 allowed
What this code does
- Round robin sends each fifth of the traffic to a different server, so each local counter sees only 5 requests and allows all of them.
- One shared counter sees all 15 and allows exactly the 5 the rule permits.
Functional requirements: limit requests per client key (API key, user id or IP) per time window, with different limits per plan, and answer 429 Too Many Requests with a Retry-After header when a client is over.
Non-functional requirements: the check adds only about 1–2 ms because it runs on every request, it is correct across all servers, and if the limiter itself breaks the API keeps working in a planned way. If each server counts alone, a client spread over 3 servers gets 3 times its limit.
Placement: gateway, sidecar or library
API gateway is one entry point in front of all services that also handles authentication and routing. Putting the limiter there gives one place and one config, and blocked traffic never reaches the app.
Three places to put the limiter, drawn as request paths; all three use the same shared counter store.
Gateway: [Client] --> [API gateway + limiter] --> [App x20]Sidecar: [Client] --> [LB] --> ( [limiter sidecar] --> [App] ) x20Library: [Client] --> [LB] --> [App x20, limiter code inside]All three: limiter --INCR--> [(Redis: shared counters)]A sidecar is a small helper process that runs next to each app server and handles every request before the app. A library is limiter code inside the app itself. Both can use app details, such as the user's plan from the database, but every service must include and update them.
The gateway is the usual choice. In every placement the limiter still needs a shared counter store, because the gateway itself runs as several copies.
Shared counter store: atomic increment with expiry
Atomic means an operation happens as one indivisible step, so no other client can run in the middle of it. Redis INCR key adds 1 and returns the new value atomically, so two servers never read the same old count.
Redis, an in-memory store for shared counters, in a short session of INCR and EXPIRE on one window key, then Java where three servers share one counter.
redis> INCR rl:key_42:29380621(integer) 1redis> EXPIRE rl:key_42:29380621 60 NX(integer) 1redis> INCR rl:key_42:29380621(integer) 2redis> TTL rl:key_42:29380621(integer) 57Example 2 · A shared counter with expiry across three servers
import java.util.HashMap;import java.util.Map;
/** A tiny stand-in for Redis: INCR with an expiry, done as one atomic step. */class CounterStore { private record Entry(long count, long expiresAt) { }
private final Map<String, Entry> data = new HashMap<>(); long now = 0; // fake clock in seconds
synchronized long incrWithExpiry(String key, long ttlSeconds) { Entry e = data.get(key); if (e == null || now >= e.expiresAt()) { e = new Entry(0, now + ttlSeconds); // first hit in this window sets the expiry } e = new Entry(e.count() + 1, e.expiresAt()); data.put(key, e); return e.count(); }}
class ApiServer { private final String name; private final CounterStore store; private final int limitPerMinute;
ApiServer(String name, CounterStore store, int limitPerMinute) { this.name = name; this.store = store; this.limitPerMinute = limitPerMinute; }
String handle(String client) { long window = store.now / 60; String key = "rl:" + client + ":" + window; long count = store.incrWithExpiry(key, 60); String result = count <= limitPerMinute ? "200" : "429"; return name + " " + key + " count=" + count + " -> " + result; }}
public class SharedCounterStoreDemo { public static void main(String[] args) { CounterStore redis = new CounterStore(); ApiServer[] servers = { new ApiServer("api-1", redis, 3), new ApiServer("api-2", redis, 3), new ApiServer("api-3", redis, 3) }; for (int i = 0; i < 5; i++) { redis.now = 10 + i; System.out.println("t=" + redis.now + " " + servers[i % 3].handle("key_42")); } redis.now = 61; System.out.println("t=61 " + servers[2].handle("key_42")); }}t=10 api-1 rl:key_42:0 count=1 -> 200 t=11 api-2 rl:key_42:0 count=2 -> 200 t=12 api-3 rl:key_42:0 count=3 -> 200 t=13 api-1 rl:key_42:0 count=4 -> 429 t=14 api-2 rl:key_42:0 count=5 -> 429 t=61 api-3 rl:key_42:1 count=1 -> 200
What this code does
incrWithExpiryissynchronized, so the increment and the expiry check happen as one step, like RedisINCR.- All three servers build the same key
rl:key_42:0for the first minute, so they share one count; the 4th and 5th requests get 429. - At t=61 the window number becomes 1, a new key starts at 1, and the client is allowed again.
For a fixed window of 60 seconds, the key holds the client and the window number, such as rl:key_42:29380621 (seconds since 1970 divided by 60). The first INCR of a window sets an expiry of 60 seconds so old keys delete themselves.
The session is reading code for Redis 7 or later (the NX option sets the expiry only if none exists). If the app could crash between INCR and EXPIRE, teams run both in one Lua script, which Redis also runs atomically.
Race conditions and fail-open vs fail-closed
Fail-open / fail-closed are the two answers to a broken limiter. Fail-open allows the request when the counter store cannot be reached; fail-closed rejects it.
A read-then-write counter that lets six requests through a limit of five, then fail-open and fail-closed policies per endpoint.
Example 3 · Read-then-write race vs atomic increment
import java.util.HashMap;import java.util.Map;
public class RaceInterleavingDemo { static final int LIMIT = 5; static Map<String, Integer> store = new HashMap<>();
public static void main(String[] args) { store.put("rl:key_42", 4); // 4 requests already used in this minute
System.out.println("Read-then-write (two steps):"); int seenByA = store.get("rl:key_42"); // server A reads 4 int seenByB = store.get("rl:key_42"); // server B reads 4 before A writes store.put("rl:key_42", seenByA + 1); store.put("rl:key_42", seenByB + 1); System.out.println(" A sees " + seenByA + " -> " + (seenByA < LIMIT ? "allowed" : "rejected")); System.out.println(" B sees " + seenByB + " -> " + (seenByB < LIMIT ? "allowed" : "rejected")); System.out.println(" Counter now " + store.get("rl:key_42") + ", but 6 requests were allowed");
store.put("rl:key_42", 4); System.out.println("Atomic increment (one step):"); int afterA = store.merge("rl:key_42", 1, Integer::sum); int afterB = store.merge("rl:key_42", 1, Integer::sum); System.out.println(" A gets " + afterA + " -> " + (afterA <= LIMIT ? "allowed" : "rejected")); System.out.println(" B gets " + afterB + " -> " + (afterB <= LIMIT ? "allowed" : "rejected")); }}Read-then-write (two steps): A sees 4 -> allowed B sees 4 -> allowed Counter now 5, but 6 requests were allowed Atomic increment (one step): A gets 5 -> allowed B gets 6 -> rejected
What this code does
- The steps are written in the order two servers could run them: both read 4 before either writes.
- Both allow, and the counter ends at 5 even though 6 requests passed. The lost update hides the overrun.
mergeadds 1 and returns the new value in one call, so B sees 6 and is rejected. RedisINCRgives the same guarantee across servers.
Example 4 · Fail-open for browsing, fail-closed for OTP
enum FailPolicy { FAIL_OPEN, FAIL_CLOSED }
class StoreDownException extends RuntimeException { StoreDownException() { super("counter store timed out"); }}
class GuardedLimiter { boolean storeUp = true; private long count = 0;
private long increment() { if (!storeUp) { throw new StoreDownException(); } return ++count; }
String check(int limit, FailPolicy policy) { try { return increment() <= limit ? "200 allowed" : "429 Too Many Requests"; } catch (StoreDownException e) { return policy == FailPolicy.FAIL_OPEN ? "allowed (fail-open: " + e.getMessage() + ")" : "503 rejected (fail-closed: " + e.getMessage() + ")"; } }}
public class FailPolicyDemo { public static void main(String[] args) { GuardedLimiter limiter = new GuardedLimiter(); System.out.println("GET /products -> " + limiter.check(100, FailPolicy.FAIL_OPEN));
limiter.storeUp = false; System.out.println("GET /products -> " + limiter.check(100, FailPolicy.FAIL_OPEN)); System.out.println("POST /auth/otp -> " + limiter.check(3, FailPolicy.FAIL_CLOSED)); }}GET /products -> 200 allowed GET /products -> allowed (fail-open: counter store timed out) POST /auth/otp -> 503 rejected (fail-closed: counter store timed out)
What this code does
- The store call throws when Redis is down; the
catchapplies the endpoint's policy. - Product browsing stays up (fail-open); OTP sending is refused with 503 so an outage cannot be used to send unlimited paid SMS.
A race condition happens when the result depends on the timing of two requests. If a server first reads the count and then writes count + 1, two servers can both read 4, both allow, and both write 5, so six requests got through a limit of 5. Atomic INCR removes this gap.
Fail-open keeps the shop running during a Redis outage, so it fits normal browsing. Fail-closed protects things that are dangerous to leave open, such as login attempts and OTP SMS that cost money. Decide per endpoint, and set a short timeout (a few ms) on the store call so a slow Redis does not slow every request.
Predict the output
Two servers, one count
The limit is 5 and the count is 4. Two requests arrive at the same moment.
Round 1 of 2
Each server reads, then writes. How many requests are allowed?
Rule configuration per tier and monitoring
Rules written as configuration for tiers and the login path, then a program that applies them and counts allowed and rejected requests.
rules: - name: free-tier match: { tier: free } limit: 60 per minute per API key - name: pro-tier match: { tier: pro } limit: 600 per minute per API key - name: login-per-ip match: { path: /api/v1/auth/login } limit: 5 per minute per IP onStoreDown: fail-closedExample 5 · Tiered rules with allowed/rejected metrics
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.TreeMap;
record Rule(String name, int limitPerMinute) {}
record Request(String client, String tier, String path) {}
public class TierRulesDemo { static final Map<String, Rule> RULES = Map.of( "free", new Rule("free-tier", 3), "pro", new Rule("pro-tier", 10), "login", new Rule("login-per-ip", 2));
static Rule ruleFor(Request r) { return r.path().equals("/api/v1/auth/login") ? RULES.get("login") : RULES.get(r.tier()); }
public static void main(String[] args) { Map<String, Integer> counters = new HashMap<>(); Map<String, int[]> metrics = new TreeMap<>(); // rule -> {allowed, rejected}
List<Request> traffic = new ArrayList<>(); for (int i = 0; i < 5; i++) { traffic.add(new Request("college-app", "free", "/api/v1/products")); traffic.add(new Request("big-reseller", "pro", "/api/v1/products")); traffic.add(new Request("103.21.4.9", "free", "/api/v1/auth/login")); }
for (Request r : traffic) { Rule rule = ruleFor(r); int used = counters.merge(rule.name() + ":" + r.client(), 1, Integer::sum); int[] m = metrics.computeIfAbsent(rule.name(), k -> new int[2]); if (used <= rule.limitPerMinute()) { m[0]++; } else { m[1]++; } }
System.out.println("rule allowed rejected"); metrics.forEach((rule, m) -> System.out.printf("%-15s %7d %8d%n", rule, m[0], m[1])); }}rule allowed rejected free-tier 3 2 login-per-ip 2 3 pro-tier 5 0
What this code does
ruleForpicks the login rule for the login path and the plan's rule for everything else.- The counter key joins rule name and client, so each client has its own count under each rule.
- The metrics table is what you would graph: the login rule rejecting 3 of 5 from one IP is a sign of guessing passwords.
Rules live in configuration, not in code, so the team can change a limit without a deploy. Each rule names what it matches (a plan, a path), the limit, the key (API key or IP) and what to do when the store is down.
Monitoring tells you whether the rules are right. Count allowed and rejected requests per rule and per client, and alert when rejections jump. A sudden rise can mean an attack, a client with a retry bug, or a limit set too low after a sale was announced.
Next step
Check your understanding
12 quick questions