Video in progress
Your service runs on 6 instances. How do you enforce a limit of 60 requests per minute per user?
The counter must be kept in a shared place, usually Redis, not in each instance's memory, and the check-and-increment must be atomic: INCR + EXPIRE or a Lua script.
📖 Answer
If you put a local limit on each instance (for example, Bucket4j in plain memory), the user can actually send 6 × 60 = 360 requests — the balancer spreads the requests around. Even if you divide the limit by 6 to get 10, the result is unpredictable when the load is uneven.
The simplest shared option is a fixed window in Redis:
String key = "rl:" + userId + ":" + (System.currentTimeMillis() / 60_000);
Long count = redis.opsForValue().increment(key);
if (count != null && count == 1) {
redis.expire(key, Duration.ofSeconds(70));
}
if (count != null && count > 60) {
throw new TooManyRequestsException();
}
INCR is atomic, so the count is right even if two instances increment at the same time. There's one small weak spot: INCR and EXPIRE are separate commands, and if the process dies between them, the key stays without a TTL. You can combine them into one step with a Lua script or a pipeline. Bucket4j's Redis integration (through Lettuce or Redisson) does a token bucket correctly with CAS.
A few more things to think through:
- What happens if Redis goes down? Usually "fail open" — let everything through without limits, because shutting down the whole API because of rate limiting is worse;
- a trip to Redis on every request adds ~1 ms; that's usually acceptable;
- where to put the limit: if it sits in the API gateway, requests never reach the services at all.
Sign up to mark studied questions and save your progress.