Create a rate limiter based on the Token Bucket method that remains correct when several threads invoke it simultaneously.
Implement:
allow(now: float, cost: int = 1) -> bool
At logical timestamp now, attempt to deduct cost tokens. Produce True when the bucket contains enough tokens; otherwise produce False.
Logical timestamps are supplied to make evaluation deterministic:
capacity refill_rate, where capacity is the maximum number of tokens the bucket can hold and refill_rate is the number of tokens replenished each second.m, the count of operations.m lines has the form ALLOW now cost.Write one result per ALLOW operation: either true or false.
1 <= capacity <= 10^90 < refill_rate <= 10^91 <= m <= 200000now appear in non-decreasing order.Input:
4 2
5
ALLOW 0 2
ALLOW 0 2
ALLOW 0 1
ALLOW 1 2
ALLOW 1 1
Output:
true
true
false
true
false
The bucket begins with four tokens. The first two requests consume all four at time zero, so the next request is denied. By time one, two tokens have been restored; the request costing two succeeds, leaving no token for the final request.