Video in progress

Senior 🌱 Spring

Where and how should you do rate limiting in a Spring application?

If possible at the edge: in an API gateway or reverse proxy, before the request reaches the application. Limits that depend on business rules (a user's plan, sending SMS) live inside the application, with a shared counter (Redis) when there are many instances.

📖 Answer

There are two levels. The first is at the edge (Nginx, Caddy, a cloud LB, Spring Cloud Gateway): general protection by IP, simple kinds of DDoS. It's cheap and puts no load on the application. The second is inside the application: "a user gets 5 SMS codes per hour", "100 requests per day on the free plan". That needs to know who the user is and their plan, and only the application knows that.

An example with Bucket4j:

Bucket bucket = Bucket.builder()
        .addLimit(Bandwidth.builder().capacity(5).refillGreedy(5, Duration.ofHours(1)).build())
        .build();

if (!bucket.tryConsume(1)) {
    throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS);
}

Where people go wrong in practice:

  • With a local counter, 4 pods means 4x the limit. Use Bucket4j with a Redis/JCache backend.
  • Choosing the key. IP is a bad key: behind NAT, hundreds of people share one IP. After authentication use the user id; for login/SMS use phone number + IP.
  • Respond with 429 and a Retry-After header so the client knows when to retry.
  • What happens if Redis goes down: do you let requests through (fail-open) or block them (fail-closed)? Usually closed for login, open for an ordinary API.
  • Watch the number of rejected requests in a metric: a misconfigured limit may be blocking real customers.