Rate limiting practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most rate-limiter problems come from a few places: a limit traced wrongly, a race between threads, a refill that loses time, a badly chosen key, or a client that ignores Retry-After. Each one has a short, reliable fix.
Tracing requests: fixed window vs token bucket
Trace a limiter with one row per request: the time, the state before, the decision and the state after. It is the most reliable way to predict a limiter's output or find a bug in one.
Example 1 · Trace: fixed window vs token bucket on the same requests
public class TraceCompareDemo { public static void main(String[] args) { long[] seconds = {0, 1, 2, 9, 10, 11, 12, 20};
// Fixed window: 3 per 10 s long windowStart = -1; int count = 0; // Token bucket: capacity 3, 0.3 tokens a second (3 per 10 s on average) double tokens = 3; long last = 0;
System.out.println("t | fixed window | token bucket"); for (long t : seconds) { long start = t / 10 * 10; if (start != windowStart) { windowStart = start; count = 0; } boolean fixedOk = count < 3; if (fixedOk) count++;
tokens = Math.min(3, tokens + (t - last) * 0.3); last = t; boolean bucketOk = tokens >= 1; if (bucketOk) tokens -= 1;
System.out.printf("%-2d | %-8s count=%d | %-8s tokens=%.1f%n", t, fixedOk ? "allowed" : "rejected", count, bucketOk ? "allowed" : "rejected", tokens); } }}t | fixed window | token bucket 0 | allowed count=1 | allowed tokens=2.0 1 | allowed count=2 | allowed tokens=1.3 2 | allowed count=3 | allowed tokens=0.6 9 | rejected count=3 | allowed tokens=1.7 10 | allowed count=1 | allowed tokens=1.0 11 | allowed count=2 | allowed tokens=0.3 12 | allowed count=3 | rejected tokens=0.6 20 | allowed count=1 | allowed tokens=2.0
What this code does
- Both limiters average 3 requests per 10 seconds, yet they disagree twice. At t = 9 the fixed window is still full, while the bucket has earned 2.1 tokens since t = 2 and allows it. At t = 12 the fixed window has a fresh count, while the bucket, drained at 10 and 11, rejects.
- Tracing a table like this by hand, one row per request, is the fastest way to check a limiter in an interview or a code review.
Fixed windows and token buckets with the same average rate still give different answers. The fixed window resets fully at each boundary; the bucket refills a little every moment and lets short bursts through only up to its capacity.
Fixing a non-thread-safe limiter
Most limiter bugs under load are race conditions: two threads read the same token count or map entry and both act on it.
Example 2 · Why the unsafe limiter fails: two threads, step by step
public class InterleavingDemo { static double tokens = 1.0; // the last token
public static void main(String[] args) { // Without synchronized, the steps of two threads can interleave like this: double seenByA = tokens; // A reads 1.0 double seenByB = tokens; boolean aAllowed = seenByA >= 1; boolean bAllowed = seenByB >= 1; tokens = seenByA - 1; tokens = seenByB - 1;
System.out.println("A allowed: " + aAllowed); System.out.println("B allowed: " + bAllowed); System.out.println("Tokens left: " + tokens + " (one token, two requests)");
tokens = 1.0; boolean a = tokens >= 1; if (a) tokens -= 1; boolean b = tokens >= 1; if (b) tokens -= 1; System.out.println("synchronized -> A: " + a + ", B: " + b); }}A allowed: true B allowed: true Tokens left: 0.0 (one token, two requests) synchronized -> A: true, B: false
What this code does
- The program replays, in a fixed order, what can happen when two threads share an unsynchronized bucket. Both read 1.0 before either writes, so both pass the check and one token serves two requests.
- A real race happens only sometimes, which makes it hard to see in tests. Writing the steps out shows why the read, the check and the write must run as one step:
synchronizedontryAcquire.
The symptom is a limit that leaks a little under heavy traffic but looks fine in slow tests. Two fixes cover nearly every case: make the bucket's tryAcquire synchronized, and create per-key buckets with ConcurrentHashMap.computeIfAbsent instead of get then put.
Choosing keys and limits for real endpoints
For each endpoint ask who should be counted, how costly or sensitive it is, and what abuse it attracts. The answers give the key and a starting limit.
Example 3 · Keys and limits for five ShopLite endpoints
public class ShopLiteLimitsDemo { record Rule(String endpoint, String key, String limit, String why) { }
public static void main(String[] args) { Rule[] rules = { new Rule("GET /api/v1/products", "user id, else IP", "300/min user, 60/min IP", "cheap reads; scrapers come here"), new Rule("POST /api/v1/auth/login", "e-mail AND IP", "5 per 15 min / 20 per 15 min", "password guessing"), new Rule("POST /api/v1/auth/otp", "phone number", "3 per 10 min", "each SMS costs money"), new Rule("POST /api/v1/orders", "user id", "5/min", "scripted buying in a sale"), new Rule("GET /api/v1/me/orders", "user id", "60/min", "normal use, protects the DB")}; for (Rule r : rules) { System.out.printf("%-24s | %-16s | %-28s | %s%n", r.endpoint(), r.key(), r.limit(), r.why()); } }}GET /api/v1/products | user id, else IP | 300/min user, 60/min IP | cheap reads; scrapers come here POST /api/v1/auth/login | e-mail AND IP | 5 per 15 min / 20 per 15 min | password guessing POST /api/v1/auth/otp | phone number | 3 per 10 min | each SMS costs money POST /api/v1/orders | user id | 5/min | scripted buying in a sale GET /api/v1/me/orders | user id | 60/min | normal use, protects the DB
What this code does
- Each endpoint gets a key and a limit that fit what it costs and what abuse it attracts. Product reads are cheap and frequent; login, OTP and order creation are expensive or sensitive.
- Login uses two keys at once: the e-mail limit protects one account, and the IP limit stops one machine trying one password on many accounts.
Start with limits well above normal use and lower them using real traffic numbers; a limit that blocks real shoppers in a sale is a bug too.
Clients that ignore Retry-After
A client that retries a 429 at once, in a loop, turns one rejected request into dozens.
Example 4 · Fix a client that ignores Retry-After
public class RetryAfterClientDemo { /** A fake server: blocked until t = 3,000 ms, and says so with Retry-After: 3. */ static int call(long nowMillis) { return nowMillis >= 3_000 ? 200 : 429; }
public static void main(String[] args) { // Wrong: retry every 100 ms, ignoring the header long t = 0; int calls = 0; int status; do { status = call(t); calls++; if (status == 429) t += 100; } while (status == 429); System.out.println("Ignores Retry-After: " + calls + " calls, success at t=" + t + " ms");
// Right: wait the number of seconds the server asked for t = 0; calls = 0; int retryAfterSeconds = 3; do { status = call(t); calls++; if (status == 429) t += retryAfterSeconds * 1000L; } while (status == 429); System.out.println("Honours Retry-After: " + calls + " calls, success at t=" + t + " ms"); }}Ignores Retry-After: 31 calls, success at t=3000 ms Honours Retry-After: 2 calls, success at t=3000 ms
What this code does
- Both clients succeed at the same moment, t = 3,000 ms, because the server decides when the client is allowed again. Retrying sooner only adds 29 useless rejected calls.
- Each extra call costs the server work and can even extend some limits. Honouring
Retry-After(and backing off when there is no header) is the client's half of the deal.
The fix is on the client: wait for the Retry-After seconds, and when there is no header, back off with growing waits (1 s, 2 s, 4 s…) plus a little randomness so many clients do not retry at the same moment.
Interview drill: the questions that come up
Rate limiting questions in placement interviews usually go in this order. Practise answering each in two or three sentences with a number or an example.
- "Token bucket vs leaky bucket?" Burst then steady rate vs a queue drained at a fixed rate.
- "Fixed window problem?" Up to 2× the limit at the boundary; fix with a sliding log or counter.
- "How do you limit across 10 servers?" Shared counter in Redis:
INCR+EXPIRE, or a Lua script. - "What does the client get?"
429,Retry-After, the normal error body, remaining-quota headers.
Finish up
Mark complete & continue
Next: Project: ShopLite API rate limiter