Refill a rate limit with an injected monotonic clock
A token bucket permits a burst while enforcing a longer-term rate. Refill depends on elapsed monotonic time, not wall-clock dates that can jump. The bucket stores its last observation and clamps the number of available tokens to capacity.
This exercise makes the clock an argument, so boundary cases run immediately and repeatably. A backwards timestamp is rejected instead of manufacturing or removing tokens. A single in-memory bucket limits one owner only; several application processes need shared coordination or deliberately partitioned budgets. It should not be advertised as a global rate limit.
capacity=3
available=0.5
elapsed=2
rate=1
print(min(capacity,available+elapsed*rate))Review the design
Injected monotonic time makes refill deterministic. Authentication, tenant-specific quotas and shared state remain separate service responsibilities; a local counter cannot enforce a fleet-wide policy.
Your task
Implement Bucket(capacity,rate,start=0) and allow(now). Start full, refill by elapsed*rate, consume one token if available, return bool. Require capacity>=1, rate>=0 and nondecreasing now.
The explanation opens here once every check passes.