CodexBloom - Programming Q&A Platform

Spring Boot REST API: How to Handle X-Rate-Limit Header for Throttling Requests?

šŸ‘€ Views: 80 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-14
Spring Boot REST API Rate Limiting Java

I'm converting an old project and Can someone help me understand I'm currently developing a Spring Boot REST API that needs to implement rate limiting to control how often users can hit certain endpoints... I've been using the `Bucket4j` library for token bucket algorithms and need to include an `X-Rate-Limit` header in the response to convey how many requests the client has left. My current setup looks like this: ```java import net.jodah.expiringmap.ExpiringMap; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RestController; @RestController public class RateLimitedController { private final ExpiringMap<String, Integer> requestCounts = ExpiringMap.builder() .variableExpiration() .build(); @GetMapping("/api/resource") public ResponseEntity<String> getResource(@RequestHeader("User-ID") String userId) { int requests = requestCounts.getOrDefault(userId, 0); if (requests >= 100) { return ResponseEntity.status(429).body("Rate limit exceeded"); } requestCounts.put(userId, requests + 1); HttpHeaders headers = new HttpHeaders(); headers.add("X-Rate-Limit", String.valueOf(100 - (requests + 1))); return ResponseEntity.ok().headers(headers).body("Resource data"); } } ``` However, I’m facing a couple of issues. Firstly, the `X-Rate-Limit` header does not seem to be updating correctly in the response. When I call the endpoint repeatedly with the same `User-ID`, the header remains at a constant value instead of decrementing. Secondly, I need help ensuring that the rate limit resets after a certain time period. Currently, I'm using an `ExpiringMap`, but the logic for expiring entries seems unreliable with concurrent requests. I see issues in production where entries are not expiring as expected. I've also tried using a `ScheduledExecutorService` to reset counts, but that complicates the implementation and adds overhead. What strategies or best practices can I apply to handle the `X-Rate-Limit` header correctly and ensure the rate limit resets reliably? Are there better libraries or methods for implementing this in a Spring Boot application? What am I doing wrong? This is happening in both development and production on Linux. Could this be a known issue?