Add rate limiting to Dropwizard using token buckets. The buckets are stored in memory using a Guava LoadingCache.
This project uses bucket4j and Hazelcast.
In your Dropwizard initialize method add the following:
@Override
public void initialize(Bootstrap<Configuration> bootstrap) {
CacheBuilderSpec cacheBuilderSpec = new CacheBuilderSpec.parse("expireAfterWrite=1m")
long overdraft = 50L;
Refill refill = Refill.smooth(10, Duration.ofSeconds(5));
RateLimitProvider rateLimitProvider = new TokenBucketRateLimitProvider(
cacheBuilderSpec, overdraft, refill);
bootstrap.addBundle(new RateLimitBundle(rateLimitProvider));
}
Finally, add the following annotation to your rate limited routes:
@GET
@Path("index")
@RateLimited(cost = 1)
Response getIndex() {
// etc.
}
Adapted from ZIVVER B.V.'s dropwizard-ratelimit
Licensed under Apache 2.0