Feature · ~40 min
Rate limiter: allow bursts
The API gateway limits each API key with FixedWindowLimiter (src/limiter.py): a fixed number of calls per minute. Customers on the paid plan complain that a batch job sending 40 requests at once gets most of them rejected, although they stay far under their per-minute budget on average.
Implement TokenBucket in src/limiter.py and give the pro plan one in src/policy.py:
TokenBucket(rate, capacity, clock=None): each key has a bucket that starts full withcapacitytokens and refills atratetokens per second, never abovecapacity.rateandcapacitymust be positive, otherwiseValueError. Without a clock it usesSystemClock.allow(key, cost=1)takescosttokens and returnsTruewhen the bucket holds at least that many; otherwise it takes nothing and returnsFalse. Acostabovecapacitycan never succeed: raiseValueError.retry_after(key, cost=1)returns the seconds untilallow(key, cost)would succeed (0if it would now) without taking anything. SameValueErrorrule.- Keys are independent. Tokens may be fractional.
limiter_for('pro')returns a bucket refilled at the plan's per-minute rate (600 a minute is 10 a second) holding up to 50 tokens. Thefreeplan keeps its fixed window; unknown plans raiseValueError.
Use FakeClock from src/clock.py in tests instead of sleeping. A hidden suite checks the behaviour above; you only see how many of its tests pass.