Fix Lack of Resources & Rate Limiting in Spring Boot
In the wild, an unprotected Spring Boot endpoint is a sitting duck for resource exhaustion. Attackers don't need a botnet; they just need a loop. By spamming expensive endpoints, they can saturate your Tomcat thread pool, exhaust database connections, or trigger an OutOfMemoryError (OOM). We fix this by implementing strict Token Bucket rate limiting and enforcing resource constraints at the controller level.
The Vulnerable Pattern
@RestController @RequestMapping("/api/v1/search") public class SearchController { @Autowired private HeavySearchService searchService;@GetMapping public List<Result> search(@RequestParam String query) { // VULNERABILITY: No rate limiting and no result capping. // An attacker can send 1000 concurrent requests, each triggering a heavy DB scan. return searchService.execute(query); }
}
The Secure Implementation
The secure implementation utilizes the Bucket4j library to implement the Token Bucket algorithm. This ensures that even if an attacker floods the endpoint, only 10 requests per minute are processed, while the rest are immediately rejected with a 429 status code, saving CPU and DB cycles. Furthermore, the use of Spring Data Pagination (Pageable) prevents 'Lack of Resources' by ensuring the application never attempts to load a million-row result set into the JVM heap, which would otherwise lead to a DoS via OOM.
@RestController @RequestMapping("/api/v1/search") public class SearchController { private final Bucket bucket;public SearchController() { // Define a limit: 10 requests per minute Bandwidth limit = Bandwidth.classic(10, Refill.intervally(10, Duration.ofMinutes(1))); this.bucket = Bucket4j.builder().addLimit(limit).build(); } @GetMapping public ResponseEntity<List<Result>> search(@RequestParam String query, @RequestParam(defaultValue = "0") int page) { // SECURE: Consume a token before processing if (bucket.tryConsume(1)) { // SECURE: Enforce pagination to prevent memory exhaustion Pageable pageable = PageRequest.of(page, 20); return ResponseEntity.ok(searchService.execute(query, pageable)); } // SECURE: Return 429 Too Many Requests return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).build(); }
}
Your Spring Boot API
might be exposed to Lack of Resources & Rate Limiting
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.