22.7.2020 |

Bucket4J to Rate-Limit certain Endpoints

Reference: https://github.com/vladimir-bukhtoyarov/bucket4j

Configuration

@Bean
public LoadingCache<Farm, Bucket> buildRateLimitBucketCache() {
    LoadingCache<Farm, Bucket> cache = CacheBuilder.newBuilder()
        .maximumSize(100)
        .expireAfterWrite(10, TimeUnit.MINUTES)
        .build(new CacheLoader<>() {
            @Override
            public Bucket load(Farm farm) {
                Bandwidth limit = Bandwidth.simple(capacity, duration);
                return Bucket4j.builder().addLimit(limit).build();
            }
        });

    return cache;
}

Usage:

Bucket bucket = rateLimitBucketCache.get(farmerPrincipal.getFarm());
if (!bucket.tryConsume(1)) {
    throw Problem.builder()
        .withTitle("To many requests")
        .withStatus(Status.TOO_MANY_REQUESTS)
        .build();
}
Zur Übersicht

Mehr vom DevSquad...

Jonathan Zbick

Customizing "Nicht planbar" in moco

Adrian Görisch

Prerendering angular pages with scully.io