Bucket4J enable or disable dynamically

554 Views Asked by At

I know than a rate limiter with Bucket4J can be reconfigured dynamically, but can it be dinamically enabled/disabled ?

In my case, if the configurations is 0 permits (per seconds), it means it's disabled. And internally I configure the bucket with a comical high limit rate.

You can see the code code bellow

    public void configure(int permitsPerSecond) {
        if (permitsPerSecond > 0) {
            // Enable rate limit with bucker4j
            Refill refill = Refill.intervally(permitsPerSecond, Duration.ofSeconds(1L));
            Bandwidth currentLimit = Bandwidth.classic(permitsPerSecond, refill);
            BucketConfiguration currentConfiguration =  BucketConfiguration.builder().
                    addLimit(currentLimit).
                    build();
            bucket.replaceConfiguration(currentConfiguration, TokensInheritanceStrategy.RESET);
        } else {
            // Disable rate limit with ludicrous high rate
            BucketConfiguration currentConfiguration =  BucketConfiguration.builder().
                    addLimit(Bandwidth.simple(999_999_999_999L, Duration.ofSeconds(1))).
                    build();
            bucket.replaceConfiguration(DEFAULT_CONFIGURATION,
                    TokensInheritanceStrategy.RESET);
        }
    }

    public boolean allowExecution() {
        return bucket.tryConsume(1L);
    }

I tried searching documentacion and code, expected a method like bucket.enable(boolean) and bucket.getLimit().getCapacty(), but no luck

Is there another way I can disable dinamically the bucket ? Also, can I access the current capacity of the bucket from the Bucket class ?

Thanks

1

There are 1 best solutions below

1
On BEST ANSWER

Bucket4j does not provide direct ability to disable limits. So you need to find some trick that will behave aproximattely in desired way.

Fo example, you can reconfigure(via replaceConfiguration) the bucket with extremelly huge limit each time when you need to disbale limit. Bellow is example of effectivelly infinite limit that is enough for usual cases:

 BucketConfiguration infiniteConfiguration =  BucketConfiguration.builder().
                addLimit(Bandwidth.simple(Long.MAX_VALUE, Duration.ofNanos(Long.MAX_VALUE)).
                build();

Then each time when you need to activate limits again, you should to reconfigure bucket again with regular configuration.