I need a component/class that throttles execution of some method to maximum M calls in N seconds (or ms or nanos, does not matter).
In other words I need to make sure that my method is executed no more than M times in a sliding window of N seconds.
If you don't know existing class feel free to post your solutions/ideas how you would implement this.
In concrete terms, you should be able to implement this with a
DelayQueue
. Initialize the queue withM
Delayed
instances with their delay initially set to zero. As requests to the method come in,take
a token, which causes the method to block until the throttling requirement has been met. When a token has been taken,add
a new token to the queue with a delay ofN
.If you need a Java based sliding window rate limiter that will operate across a distributed system you might want to take a look at the https://github.com/mokies/ratelimitj project.
A Redis backed configuration, to limit requests by IP to 50 per minute would look like this:
See https://github.com/mokies/ratelimitj/tree/master/ratelimitj-redis fore further details on Redis configuration.
Although it's not what you asked,
ThreadPoolExecutor
, which is designed to cap to M simultaneous requests instead of M requests in N seconds, could also be useful.Try to use this simple approach:
}