MediumRate LimitingPython 3

Token Budget Ledger

Maintain rolling-window token spend per caller with expiry on every read and write path.

35m2 sample tests3 hidden tests

Track rolling token spend per key with deterministic expiry.

Requirements

  • Define TokenBudget(limit, window_seconds, now).
  • spend(key, tokens) records spend if it fits the current rolling window.
  • Return True when spend is accepted, otherwise False.
  • remaining(key) returns remaining tokens in the current window.
  • Events expire when now() - event_time >= window_seconds.
  • Expired spend must not count on reads or writes.
  • Different keys are independent.

Example

python
1clock = {"t": 0} 2budget = TokenBudget(10, 60, now=lambda: clock["t"]) 3assert budget.spend("org", 7) 4assert budget.remaining("org") == 3 5assert not budget.spend("org", 4)

Constraints

  • Use injected time.
  • Do not allow negative spends.
  • Do not share spend across keys.

Editor
Results
Run sample tests or submit all tests.