package com.ankurm.ratelimit;
import io.github.bucket4j.BucketConfiguration;
import io.github.bucket4j.ConsumptionProbe;
import io.github.bucket4j.TokensInheritanceStrategy;
import io.github.bucket4j.distributed.BucketProxy;
import io.github.bucket4j.distributed.proxy.ProxyManager;
import org.springframework.stereotype.Service;
/**
* Decides whether a request may proceed. Two buckets are consulted: the caller's own
* (user, API key or address) and then the one global bucket.
*
*
The order matters. The caller's bucket goes first, so a caller who is already over their own
* limit never spends a global token. The price is the opposite case: when the global bucket
* rejects, the caller has already spent a token of their own.
*/
@Service
public class RateLimiter {
static final String GLOBAL_KEY = "rl:global";
private final ProxyManager buckets;
private final RateLimitProperties props;
RateLimiter(ProxyManager buckets, RateLimitProperties props) {
this.buckets = buckets;
this.props = props;
}
public Decision check(Caller caller, int cost) {
Decision own = consume(caller.bucketKey(), caller.scope(), caller.limit(), cost);
if (!own.allowed()) {
return own;
}
Decision global = consume(GLOBAL_KEY, "global", props.global(), cost);
return global.allowed() ? own : global;
}
private Decision consume(String key, String scope, RateLimitProperties.Limit limit, int cost) {
ConsumptionProbe probe = bucket(key, limit).tryConsumeAndReturnRemaining(cost);
long retry = probe.isConsumed() ? 0 : Math.max(1, ceilSeconds(probe.getNanosToWaitForRefill()));
return new Decision(probe.isConsumed(), scope, limit.capacity(), probe.getRemainingTokens(),
retry, ceilSeconds(probe.getNanosToWaitForReset()));
}
/**
* Cheap to call on every request: nothing touches Redis until a token is consumed. The
* configuration supplier only runs when the key does not exist yet, which is why changing a
* limit in code does not change buckets that already exist. {@code
* withImplicitConfigurationReplacement} is what makes a new {@code configVersion} replace them.
*/
BucketProxy bucket(String key, RateLimitProperties.Limit limit) {
return buckets.builder()
.withImplicitConfigurationReplacement(props.configVersion(), TokensInheritanceStrategy.PROPORTIONALLY)
.build(key, () -> BucketConfiguration.builder()
.addLimit(l -> l.capacity(limit.capacity()).refillGreedy(limit.capacity(), limit.period()))
.build());
}
private static long ceilSeconds(long nanos) {
return (nanos + 999_999_999L) / 1_000_000_000L;
}
}