For those interested in the subject, spring-boot-throttling seems no longer maintained.
So, I take a look on bucket4j
The use is quite simple: There are 3 main objects:
- Bucket : Interface allowing to define the total capacity of available tokens. It also provides the methods to consume the tokens.
- Bandwidth : Class allowing to define the limits of the bucket.
- Refill : Class allowing to define the way the bucket will be fed, with new tokens.
Example with simple Spring Boot controller:
@RestController
public class TestLimit {
private Bucket bucket = null;
public MsGeneratorController() {
Bandwidth limit = Bandwidth.classic(120, Refill.greedy(120, Duration.ofMinutes(1)));
this.bucket = Bucket4j.builder().addLimit(limit).build();
}
@RequestMapping(path = "/test-limit/", method = RequestMethod.GET)
public ResponseEntity<String> download() throws IOException {
if (this.bucket.tryConsume(1)) {
return ResponseEntity.status(HttpStatus.OK).build();
}else {
return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).build();
}
}
}
In this case, we have a limit of 120 requests per minute, with bucket capacity 120 and a refill rate of 120 tokens per minute.
If we exceed this limit, we will receive an HTTP 429 code (TOO_MANY_REQUESTS).
request throttling
. This is best done either at the Intrusion Detection System (which should detect DDoS attacks) or Internet Gateway (if you do not have an IDS). Failing that, the best place to implement throttling would be at the web server. Apache, IIS and Nginx all support throttling. – Amary