Handling Rate Limiting in a Spring Boot REST API with Redis - Unexpected Behavior
I'm trying to implement rate limiting in my Spring Boot REST API using Redis and the Bucket4j library. My goal is to limit requests to 10 requests per minute per user. However, I'm encountering an issue where the rate limits are not being applied correctly. Instead of blocking the user after 10 requests, the API continues to respond without enforcing the limit. I have the following configuration: ```java @Configuration @EnableCaching public class RedisConfig { @Bean public RedisConnectionFactory redisConnectionFactory() { return new LettuceConnectionFactory(); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory()); return template; } } ``` And hereβs the rate limiting aspect using Bucket4j: ```java @RestController @RequestMapping("/api") public class MyController { private final Refill refill = Refill.greedy(10, Duration.ofMinutes(1)); private final Bucket bucket = Bucket.builder() .addLimit(refill) .build(); @GetMapping("/data") public ResponseEntity<String> getData() { if (bucket.tryConsume(1)) { return ResponseEntity.ok("Data"); } else { return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) .body("Rate limit exceeded"); } } } ``` I have ensured that my Redis server is running and accessible. I've also checked the dependencies and am using the following versions in my `pom.xml`: ```xml <dependency> <groupId>net.jodah</groupId> <artifactId>bucket4j-core</artifactId> <version>7.3.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.6.4</version> </dependency> ``` Despite this configuration, after making 10 requests, I still receive successful responses instead of the expected 429 status code. I suspect it could be an issue with how the Redis connection is managed or perhaps the `Bucket` instance is not properly scoped per user. Any insights on what might be going wrong here? How would you solve this?