Skip to content
BytePatterns

Token Bucket Rate Limiter

EasySystem Design#token-bucket#integer-math~15m

Problem

An API gateway limits each client with a token bucket. The bucket holds at most capacity tokens and starts full at time 0. Tokens drip back in continuously at per_second tokens per second, never beyond the capacity, and every request spends one whole token or is rejected. Given the request times in milliseconds, in order, return for each one whether it is allowed. Refills are fractional, so a quarter of a second at 4 tokens per second is exactly one token; avoid floating point so a request exactly on the boundary is never rejected by a rounding error.

Examples

Input:  capacity = 2, per_second = 1, times_ms = [0, 0, 0, 500, 1000, 3000]
Output: [True, True, False, False, True, True]
Why:    the burst of three gets two; half a token at 500 is not enough; the bucket refills after
Input:  capacity = 1, per_second = 4, times_ms = [0, 100, 250, 260]
Output: [True, False, True, False]
Why:    exactly one token is back at 250 ms
Input:  capacity = 3, per_second = 1, times_ms = []
Output: []
Why:    edge case, no traffic

Hints

0 / 3

Stuck on the idea rather than the code? Rate Limiting covers it.