-
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.
Without clientId, each annotated method, or each class which declares a class-level annotation, has its own counter per client IP address. With clientId, all methods with the same clientId, maxRequestsPerTimeWindow and timeWindowInSeconds share one counter, so that a clientId can represent a whole API. They also share it with RateLimiter.checkRateLimit(String, int, java.time.Duration, int) invoked with the same values.
The rate limiting is enforced by the RateLimitInterceptor which uses a fixed window algorithm: the time window of a counter starts at its first request, and the counter resets when the time window has expired. 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.
The client IP address is obtained by ServletRequest.getRemoteAddr(), not from proxy headers. See RateLimiter.checkRateLimit(HttpServletRequest, int, java.time.Duration, int) for how to configure this behind a reverse proxy.