Fix API Rate Limit Exhaustion in Spring Boot
API Rate Limit Exhaustion (CWE-770) is a low-complexity, high-impact DoS vector. In Spring Boot, default endpoint configurations allow unlimited requests, enabling attackers to perform credential stuffing, scrape data, or trigger resource exhaustion. To mitigate this, we must move beyond the 'open-door' policy and implement robust throttling at the filter level.
The Vulnerable Pattern
@RestController
@RequestMapping("/api/v1")
public class VulnerableController {
@GetMapping("/resource")
public ResponseEntity getResource() {
// VULNERABILITY: No throttling or rate limiting applied.
// An attacker can flood this endpoint to deplete CPU/Memory or DB connections.
return ResponseEntity.ok("Resource accessed");
}
}
The Secure Implementation
The secure implementation utilizes the Bucket4j library to implement the Token Bucket algorithm. The filter intercepts incoming requests before they reach the controller logic. If a 'token' is available, the request proceeds; otherwise, it returns an HTTP 429 (Too Many Requests). For production environments, the bucket should be keyed per-user (via JWT claim) or per-IP (via X-Forwarded-For) using a distributed cache like Redis to ensure limits persist across multiple microservice instances.
import io.github.bucket4j.*; import java.time.Duration;@Component public class RateLimitFilter extends OncePerRequestFilter { private final Bucket bucket = Bucket.builder() .addLimit(Bandwidth.classic(10, Refill.intervally(10, Duration.ofMinutes(1)))) .build();
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (bucket.tryConsume(1)) { filterChain.doFilter(request, response); } else { response.setStatus(429); response.setHeader("X-Rate-Limit-Retry-After-Seconds", "60"); response.getWriter().write("Too Many Requests - Rate limit exceeded."); } }
}
Your Spring Boot API
might be exposed to API Rate Limit Exhaustion
74% of Spring Boot apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.