Rate Limit with a Token Bucket
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write createTokenBucket({ capacity, refillPerSecond, now }), a rate limiter. now is a function returning the current time in milliseconds: read the time only by calling it. Return an object with a method take(). The bucket starts full, holding capacity tokens. take() returns true and removes one token if at least one whole token is there, and otherwise returns false without removing anything. Tokens come back continuously at refillPerSecond a second, so after a quarter of a second a rate of 4 adds one token, and an eighth of a second adds half a token. Partial tokens build up across calls and aren't lost, and the bucket never holds more than capacity.
Your code must pass
- Starts full and allows capacity calls at once
- Refuses calls once the bucket is empty
- Refills over time, never above capacity
- Keeps partial tokens between calls