-
The CDI annotation @RateLimit allows you to rate limit method invocations in CDI managed beans based on a configurable client identifier, such as client IP address, user ID, API key, etc.
This annotation can be applied to both methods and classes. When applied to a class, all methods in that class will be rate limited unless they have their own @RateLimit annotation which overrides the class-level configuration.
The rate limiting is enforced by the RateLimitInterceptor which uses a sliding window algorithm to track request counts per client identifier. When the rate limit is exceeded, the interceptor will by default immediately throw a RateLimitExceededException. Optionally, you can configure automatic retries via the maxRetries() attribute, which will retry the request after a calculated delay based on the remaining time window. If all retries are exhausted, a RateLimitExceededException is thrown.
Usage
Here's an example of rate limiting an API endpoint to 10 requests per minute per client IP:
@Named
@RequestScoped
public class ApiController {
@RateLimit(maxRequestsPerTimeWindow = 10, timeWindowInSeconds = 60, maxRetries = 0)
public void processApiRequest() {
// Process API request ...
}
}
Here's an example of rate limiting based on a custom client identifier:
@Named
@RequestScoped
public class ApiController {
@RateLimit(clientId = "FooAPI", maxRequestsPerTimeWindow = 5, timeWindowInSeconds = 30, maxRetries = 1)
public void processFooAPIRequest() {
// Process Foo API request ...
}
}
When no clientId is specified, the rate limiter will automatically use the client IP address from the current HttpServletRequest. If no HTTP request is available in the current context, you must explicitly provide a clientId, otherwise an IllegalArgumentException will be thrown.