The Gatekeeper lets through about refill_per_second requests per second, but forgives a short burst. A counter that resets every second would let twice the limit through around a reset (with a limit of 5: five just before it, five just after), so it keeps a bucket of tokens instead.
Build TokenBucket(capacity, refill_per_second):
- The bucket holds at most
capacitytokens and starts full. - Tokens drip in steadily:
refill_per_second / 1000of a token per millisecond, so part-tokens build up. A full bucket stays full. allow(t: int) -> bool: a request attmilliseconds. With at least one whole token, take one and returnTrue; otherwise returnFalse.
t never decreases; requests can share a t.
b = TokenBucket(5, 5) # 5 tokens, refilled at 5 per second: one every 200 ms
b.allow(0) # True (4 left)
b.allow(0) # True (3 left)
b.allow(0) # True
b.allow(0) # True
b.allow(0) # True (a burst of 5: the bucket is empty)
b.allow(0) # False
b.allow(100) # False (half a token has dripped in)
b.allow(200) # True (a whole token now; it's used up)
b.allow(200) # False
b.allow(9000) # True (refilled, but never above 5: 4 left)
g = TokenBucket(1, 3) # one token every 333.33... ms
g.allow(0) # True
g.allow(333) # False (333 ms bring 0.999 of a token)
g.allow(334) # True (1.002 tokens)
capacity and refill_per_second are in 1..10^6; 0 <= t <= 10^9.
⭐ Bonus: a speed test with 300,000 calls earns a star if each call is O(1), however far apart they are.
Show hint
don't drip tokens in one by one: on each call, work out how much dripped in since the last one. Counting in thousandths of a token keeps everything whole.