Skip to content

Provide snapshot of numTokens / duration until next refill #8

@mmadson

Description

@mmadson

We're having some trouble generating our rate limit headers with the current TokenBucket API.

For reference, we are trying to generate headers similar to the following:

X-RateLimit-Capacity  // max number of tokens for a user during a given period
X-RateLimit-Cost // the number of tokens that the current request costs
X-RateLimit-Remaining // the number of tokens remaining for the current user
X-RateLimit-Reset // the next timestamp when the user's remaining token buckets will be reset to capacity

The problem is that I need to make multiple calls on the tokenBucket to collect all the information for the headers and between any 2 calls the state of the remaining tokens / and duration until next refill may have changed. Trying to deliver a consistent set of headers that is accurate to the user seems impossible without having the consume/tryConsume methods return a snapshot of the state of the required header information at the time the tokens were consumed:

TokenBucketInfo response = tockenBucket.tryConsume(50);
if(response.isSuccessful()) {
   response.getCapacity(); 
   response.getNumTokens(); // this would not try to refill the token bucket, instead it should report the number of tokens in the token bucket at the point in time immediately following the consume.
   response.getDurationUntilNextRefill(someTimeUnit); // this would report the duration until the next refill at the time the consume occurred.
}

Basically any method that can change the state of the token bucket consume/refill/etc. should return a snapshot of the information for generating accurate headers. Also exposing a method that returns a consistent snapshot would also be handy, should we ever decide to create a resource that simply returns a user's token information without consuming any tokens.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions