Skip to lesson

Where to apply limits and returning 429

Four hundred students in one hostel share a single IP address, and a client that ignores errors keeps hammering the API. Whom should ShopLite count, and how does it tell a client to slow down?

Your turn: who do you count, and what do you answer?

ShopLite has signed-in shoppers, partner apps with API keys and anonymous visitors. It runs 3 servers. Think before you read on.

  • Which key would you count by for each of the three kinds of client?
  • What should a rejected response contain so a polite client can recover by itself?
  • With 3 servers, where would the counters live?
Jot down your answers, then compare them with the design that follows.

Choosing the key: user, IP, API key or endpoint

Rate-limit key is the identity a limiter counts requests by: the signed-in user id, the API key of a partner app, the client's IP address, or a mix with the endpoint.

Count by the most precise identity you have: user id first, then API key, then IP address.

Example 1 · Choosing the key, and the hostel Wi-Fi problem

RateLimitKeyDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class RateLimitKeyDemo {    record Request(String userId, String apiKey, String ip, String path) { }
    /** Most precise identity first: signed-in user, then API key, then IP address. */    static String keyFor(Request r) {        if (r.userId() != null) return "user:" + r.userId();        if (r.apiKey() != null) return "key:" + r.apiKey();        return "ip:" + r.ip();    }
    public static void main(String[] args) {        System.out.println(keyFor(new Request("42", null, "49.36.10.5", "/api/v1/orders")));        System.out.println(keyFor(new Request(null, "kirana-app-7f3a", "13.233.1.9", "/api/v1/products")));        System.out.println(keyFor(new Request(null, null, "103.21.8.9", "/api/v1/products")));
        // 300 students in a hostel share one public IP through the Wi-Fi router (NAT)        String hostelIp = "117.200.4.20";        int perIpLimit = 100, perUserLimit = 20;        Map<String, Integer> byIp = new HashMap<>();        Map<String, Integer> byUser = new HashMap<>();        int blockedByIp = 0, blockedByUser = 0;        for (int student = 1; student <= 300; student++) {            for (int click = 0; click < 5; click++) {               // 5 normal clicks each                if (byIp.merge(hostelIp, 1, Integer::sum) > perIpLimit) blockedByIp++;                if (byUser.merge("user:" + student, 1, Integer::sum) > perUserLimit) blockedByUser++;            }        }        System.out.println("Per-IP limit 100/min:  " + blockedByIp + " of 1500 clicks blocked");        System.out.println("Per-user limit 20/min: " + blockedByUser + " of 1500 clicks blocked");    }}
Output
user:42
key:kirana-app-7f3a
ip:103.21.8.9
Per-IP limit 100/min:  1400 of 1500 clicks blocked
Per-user limit 20/min: 0 of 1500 clicks blocked

What this code does

  • keyFor picks the most precise identity it has. A signed-in user is counted by user id, a partner app by its API key, and only anonymous traffic falls back to the IP address.
  • Behind a hostel or office router, hundreds of people share one public IP. A per-IP limit of 100 a minute blocks 1,400 innocent clicks, while a per-user limit blocks none.
  • IP limits are still useful for anonymous traffic and for login, but set them generously and never as the only key for signed-in users.

A key can also include the endpoint, such as user:42:POST /api/v1/orders. IP addresses are shared: NAT (network address translation) lets a whole hostel, office or mobile network reach the internet through one public IP, so a strict per-IP limit punishes hundreds of innocent people, while an attacker can switch IPs cheaply.

So count signed-in users by user id and partners by API key. Use the IP for anonymous traffic and as a second key on login, with a generous limit.

Predict the output

Predict the key

The code picks the most precise identity. Read it, then pick what it prints.

Round 1 of 2

A partner app calls without a signed-in user.

String user = null;
String apiKey = "partner-9";
String ip = "103.5.5.5";
String who = user != null ? "user:" + user
: apiKey != null ? "key:" + apiKey
: "ip:" + ip;
System.out.println(who);

Tiered limits, and stricter limits on login and OTP

Tiered limit is a limit that depends on the kind of client, such as anonymous visitors, free accounts and paying partners. Sensitive endpoints ignore the tier and keep one strict limit for everyone.

Normal endpoints get a limit by tier, but login and OTP get their own strict limit for every client.

Example 2 · Tiered and per-endpoint limits in one policy table

LimitPolicyDemo.javaJava
import java.util.List;import java.util.Map;
public class LimitPolicyDemo {    enum Tier { ANONYMOUS, FREE, PAID }
    record Limit(int requests, int perSeconds, String keyType) {        @Override public String toString() {            return requests + " per " + perSeconds + " s by " + keyType;        }    }
    // Sensitive endpoints first: they ignore the tier.    static final Map<String, Limit> STRICT = Map.of(            "POST /api/v1/auth/login", new Limit(5, 900, "e-mail and IP"),            "POST /api/v1/auth/otp", new Limit(3, 600, "phone number"));
    static final Map<Tier, Limit> BY_TIER = Map.of(            Tier.ANONYMOUS, new Limit(60, 60, "IP"),            Tier.FREE, new Limit(300, 60, "user"),            Tier.PAID, new Limit(3_000, 60, "API key"));
    static Limit limitFor(String endpoint, Tier tier) {        Limit strict = STRICT.get(endpoint);        return strict != null ? strict : BY_TIER.get(tier);    }
    public static void main(String[] args) {        List<String[]> calls = List.of(                new String[] {"GET /api/v1/products", "ANONYMOUS"},                new String[] {"GET /api/v1/products", "FREE"},                new String[] {"GET /api/v1/products", "PAID"},                new String[] {"POST /api/v1/auth/login", "PAID"},                new String[] {"POST /api/v1/auth/otp", "FREE"});        for (String[] c : calls) {            System.out.printf("%-24s %-9s -> %s%n", c[0], c[1], limitFor(c[0], Tier.valueOf(c[1])));        }    }}
Output
GET /api/v1/products     ANONYMOUS -> 60 per 60 s by IP
GET /api/v1/products     FREE      -> 300 per 60 s by user
GET /api/v1/products     PAID      -> 3000 per 60 s by API key
POST /api/v1/auth/login  PAID      -> 5 per 900 s by e-mail and IP
POST /api/v1/auth/otp    FREE      -> 3 per 600 s by phone number

What this code does

  • Normal endpoints get a limit by tier: anonymous visitors less, signed-in users more, paying partners the most.
  • Login and OTP ignore the tier on purpose. A paid customer's account is no less worth protecting, so "5 attempts per 15 minutes" applies to everyone.
  • Keeping all rules in one table makes them easy to review and change without hunting through code.

A tier is a fair way to share capacity and part of a paid API product. Sensitive endpoints get their own limits that ignore the tier: login per e-mail and per IP, OTP sends per phone number, password reset per account. A paid customer's password deserves the same protection as anyone's.

429 Too Many Requests, Retry-After and X-RateLimit headers

Retry-After is the HTTP header that tells a client how many seconds to wait before trying again. It is sent with 429 Too Many Requests, so a good client waits instead of retrying in a loop.

A rejected request gets 429 Too Many Requests and a Retry-After header, so a good client waits instead of retrying in a loop.

Example 3 · A real 429 with Retry-After and X-RateLimit headers

Http429Demo.javaJava
import com.sun.net.httpserver.Headers;import com.sun.net.httpserver.HttpServer;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.util.List;
public class Http429Demo {    static final int LIMIT = 3;    static int used = 0;    static final long NOW_MILLIS = 18_000;      // fake clock: 18 s into the current minute
    public static void main(String[] args) throws Exception {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/products", exchange -> {            long resetSeconds = (60_000 - NOW_MILLIS % 60_000 + 999) / 1000;   // until the window ends            Headers h = exchange.getResponseHeaders();            h.set("X-RateLimit-Limit", String.valueOf(LIMIT));            h.set("X-RateLimit-Reset", String.valueOf(resetSeconds));            String body;            int status;            synchronized (Http429Demo.class) {                if (used < LIMIT) {                    used++;                    status = 200;                    h.set("X-RateLimit-Remaining", String.valueOf(LIMIT - used));                    h.set("Content-Type", "application/json");                    body = "{\"content\":[]}";                } else {                    status = 429;                    h.set("X-RateLimit-Remaining", "0");                    h.set("Retry-After", String.valueOf(resetSeconds));                    h.set("Content-Type", "application/problem+json");                    body = "{\"type\":\"https://shoplite.example/problems/too-many-requests\","                            + "\"title\":\"Too many requests\",\"status\":429,"                            + "\"detail\":\"Rate limit reached. Try again later.\","                            + "\"instance\":\"/api/v1/products\"}";                }            }            byte[] bytes = body.getBytes(StandardCharsets.UTF_8);            exchange.sendResponseHeaders(status, bytes.length);            try (var out = exchange.getResponseBody()) {                out.write(bytes);            }        });        server.start();
        HttpClient client = HttpClient.newHttpClient();        URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/products");        List<String> shown = List.of("X-RateLimit-Limit", "X-RateLimit-Remaining", "X-RateLimit-Reset", "Retry-After");        for (int i = 1; i <= 4; i++) {            HttpResponse<String> r = client.send(HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.ofString());            System.out.println("Request " + i + " -> " + r.statusCode());            for (String name : shown) {                r.headers().firstValue(name).ifPresent(v -> System.out.println("  " + name + ": " + v));            }            if (r.statusCode() == 429) System.out.println("  " + r.body());        }        server.stop(0);    }}
Output
Request 1 -> 200
  X-RateLimit-Limit: 3
  X-RateLimit-Remaining: 2
  X-RateLimit-Reset: 42
Request 2 -> 200
  X-RateLimit-Limit: 3
  X-RateLimit-Remaining: 1
  X-RateLimit-Reset: 42
Request 3 -> 200
  X-RateLimit-Limit: 3
  X-RateLimit-Remaining: 0
  X-RateLimit-Reset: 42
Request 4 -> 429
  X-RateLimit-Limit: 3
  X-RateLimit-Remaining: 0
  X-RateLimit-Reset: 42
  Retry-After: 42
  {"type":"https://shoplite.example/problems/too-many-requests","title":"Too many requests","status":429,"detail":"Rate limit reached. Try again later.","instance":"/api/v1/products"}

What this code does

  • A tiny server built with the JDK's com.sun.net.httpserver applies a limit of 3 per minute; a Java HttpClient calls it 4 times. The server's clock is fixed at 18 s into the minute so the numbers repeat on every run.
  • Every response carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset, so a well-behaved client can slow down before it hits the wall.
  • The 4th response is 429 with Retry-After: 42 (seconds until the window resets) and a Problem Details body using the too-many-requests kind ShopLite added in the Spring Security section.

Many APIs also send X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset on every response, so clients can see the limit coming. These X- names are a common convention, not an official standard; an IETF draft proposes standard RateLimit headers, and some APIs already use them.

ShopLite's 429 body uses the same Problem Details shape as every other error, with the too-many-requests kind.

Find the bug

Spot the 429 bug

Each snippet has one wrong line. Tap it, then read the fix.

Tell the client how long to wait.

Round 1 of 2
429 is about one client sending too much. When the whole server is overloaded, 503 Service Unavailable (also with Retry-After) is the right answer.

Reading code: a Spring HandlerInterceptor with the token bucket

HandlerInterceptor is a Spring MVC hook that runs before controller methods. Its preHandle method returns true to let the request continue, so one interceptor can guard every endpoint.

Register one HandlerInterceptor for /api/v1/**, and every ShopLite endpoint is limited in one place without touching a controller.

Example 4 · src/main/java/com/shoplite/common/ratelimit/RateLimitInterceptor.java and WebConfig.java

Runs in: the shoplite-api Spring Boot project

RateLimitInterceptor.javaJava
// src/main/java/com/shoplite/common/ratelimit/RateLimitInterceptor.java@Componentpublic class RateLimitInterceptor implements HandlerInterceptor {
    private static final int LIMIT_PER_MINUTE = 100;
    private final ConcurrentHashMap<String, TokenBucket> buckets = new ConcurrentHashMap<>();    private final LongSupplier clock = () -> System.nanoTime() / 1_000_000;
    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {        String key = keyFor(request);        TokenBucket bucket = buckets.computeIfAbsent(key,                k -> new TokenBucket(LIMIT_PER_MINUTE, LIMIT_PER_MINUTE / 60.0, clock));        response.setHeader("X-RateLimit-Limit", String.valueOf(LIMIT_PER_MINUTE));        if (bucket.tryAcquire()) {            response.setHeader("X-RateLimit-Remaining", String.valueOf((long) bucket.available()));            return true;                                   // continue to the controller        }        long waitSeconds = Math.max(1, (bucket.millisUntilNextToken() + 999) / 1000);        throw new TooManyRequestsException("Rate limit reached. Try again later.",                Duration.ofSeconds(waitSeconds));          // GlobalExceptionHandler -> 429    }
    private static String keyFor(HttpServletRequest request) {        Principal user = request.getUserPrincipal();        return user != null ? "user:" + user.getName() : "ip:" + request.getRemoteAddr();    }}
@Configurationpublic class WebConfig implements WebMvcConfigurer {
    private final RateLimitInterceptor rateLimitInterceptor;
    public WebConfig(RateLimitInterceptor rateLimitInterceptor) {        this.rateLimitInterceptor = rateLimitInterceptor;    }
    @Override    public void addInterceptors(InterceptorRegistry registry) {        registry.addInterceptor(rateLimitInterceptor).addPathPatterns("/api/v1/**");    }}
Sample output
$ curl -i http://localhost:8080/api/v1/products?size=2
HTTP/1.1 200
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 99
Content-Type: application/json
...

(the 101st call within the same moment)
$ curl -i http://localhost:8080/api/v1/products?size=2
HTTP/1.1 429
X-RateLimit-Limit: 100
Retry-After: 1
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/too-many-requests","title":"Too many requests","status":429,"detail":"Rate limit reached. Try again later.","instance":"/api/v1/products"}

What this code does

  • A HandlerInterceptor runs code before every controller method. preHandle returns true to continue; here a full bucket throws TooManyRequestsException, and the existing GlobalExceptionHandler turns it into the 429 Problem Details with Retry-After.
  • The interceptor runs after Spring Security's filters, so getUserPrincipal() already holds the signed-in user and the key can be per user. TokenBucket is the class from the previous lesson, with a millisUntilNextToken() method added.
  • This is a one-server version: the buckets live in this server's memory. Unused buckets also need the idle clean-up from the previous lesson.

The preHandle method runs before each controller method. ShopLite's interceptor picks the key, takes a token from that key's bucket and adds the X-RateLimit-* headers. With no token left it throws TooManyRequestsException, so the existing exception handler builds the 429 response and Retry-After.

Spring Security's filters run first, so the signed-in user is already known when the key is chosen.

Order of execution

From request to 429

Put the steps in the order they happen.

Distributed limits: why a shared counter is needed

Distributed limit is a limit whose counter lives in one shared store, such as Redis, that every server uses, so the limit holds however many servers there are.

With several servers behind a load balancer, each server counts only its own share. Keep one counter in a shared store instead.

Terminal
# one key per user per minute (here: minute number 29348460)redis> INCR rl:user:42:29348460(integer) 1redis> EXPIRE rl:user:42:29348460 60(integer) 1redis> INCR rl:user:42:29348460(integer) 2
Left, local counters: three servers each count Asha separately with a limit of 10, so she gets 30 requests through, three times her limit. Right, a shared counter: the same three servers all add to one Redis key, rl:asha, so she gets exactly 10.

Example 5 · Three servers, one limit: local counters vs a shared counter

SharedCounterDemo.javaJava
import java.util.HashMap;import java.util.Map;
/** Stands in for Redis: one shared store with INCR and key expiry. */class FakeRedis {    private final Map<String, Long> values = new HashMap<>();    private final Map<String, Long> expiresAt = new HashMap<>();
    synchronized long incr(String key, long nowMillis) {        Long exp = expiresAt.get(key);        if (exp != null && nowMillis >= exp) {                 // expired keys disappear            values.remove(key);            expiresAt.remove(key);        }        return values.merge(key, 1L, Long::sum);    }
    synchronized void expire(String key, long ttlMillis, long nowMillis) {        expiresAt.put(key, nowMillis + ttlMillis);    }}
class AppServer {    private final Map<String, Integer> localCounts = new HashMap<>();
    boolean allowLocal(String user, int limit) {        return localCounts.merge(user, 1, Integer::sum) <= limit;    }
    boolean allowShared(FakeRedis redis, String user, int limit, long now) {        String key = "rl:" + user + ":" + now / 60_000;          // one key per user per minute        long count = redis.incr(key, now);        if (count == 1) redis.expire(key, 60_000, now);           // first hit sets the expiry        return count <= limit;    }}
public class SharedCounterDemo {    public static void main(String[] args) {        int limit = 10;        AppServer[] servers = {new AppServer(), new AppServer(), new AppServer()};        FakeRedis redis = new FakeRedis();
        int allowedLocal = 0, allowedShared = 0;        for (int i = 0; i < 30; i++) {            AppServer s = servers[i % 3];            long now = 5_000 + i * 1_000L;            if (s.allowLocal("asha", limit)) allowedLocal++;            if (s.allowShared(redis, "asha", limit, now)) allowedShared++;        }        System.out.println("Limit: " + limit + " per minute, 30 requests over 3 servers");        System.out.println("Each server counts alone: " + allowedLocal + " allowed");        System.out.println("Shared counter:           " + allowedShared + " allowed");    }}
Output
Limit: 10 per minute, 30 requests over 3 servers
Each server counts alone: 30 allowed
Shared counter:           10 allowed

What this code does

  • Behind a round-robin load balancer, each server sees only a third of Asha's traffic. With local counters, each allows 10, so she gets 30: three times her limit.
  • With one shared counter, every server increments the same key, rl:asha:<minute>, so the limit holds no matter which server gets the request.
  • FakeRedis copies the two Redis commands real code uses: INCR (add 1 atomically and return the new value) and EXPIRE (delete the key after a time), so old minutes clean themselves up.

With in-memory buckets a user gets the limit times the number of servers. Redis is an in-memory key-value database. The simplest version is a fixed window per key: INCR adds 1 to a key such as rl:user:42:<minute> and returns the new count in one atomic step, and EXPIRE deletes the key after 60 seconds.

Token buckets in Redis use a small Lua script so the read-refill-take steps run as one atomic step.

Next step

Check your understanding

12 quick questions