Guava’s RateLimiter per minutes instead of seconds?

Johny19 picture Johny19 · Dec 30, 2014 · Viewed 12.2k times · Source

I'm trying to rate-limit the the number of accounts a user can create with my REST API.

I would have liked to use Guava's RateLimiter to only allow an IP to create, let's say, 5 accounts within 10 minutes, but the RateLimiter.create method only takes a double specifying the number of permits "per second".

Is there a way to configure RateLimiter to release permits at a granularity greater than one second?

Answer

Jeffrey Bosboom picture Jeffrey Bosboom · Dec 30, 2014

From the RateLimiter.create javadoc:

When the incoming request rate exceeds permitsPerSecond the rate limiter will release one permit every (1.0 / permitsPerSecond) seconds.

So you can set permitsPerSecond to less than 1.0 to release a permit less often than once per second.

In your specific case, five accounts in ten minutes simplifies to one account per two minutes, which is one account per 120 seconds. You'd pass 1.0/120 for permitsPerSecond.

In your use case you probably want to accommodate bursty requests for account creations. The RateLimiter specification doesn't seem to define what happens to unused permits, but the default implementation, SmoothRateLimiter, seems to let permits accrue up to some maximum to satisfy bursts. This class is not public, so there's no javadoc documentation, but the SmoothRateLimiter source has a lengthy comment with a detailed discussion of the current behavior.