Algorithms¶
A rate such as 100/minute leaves a question open: 100 in which minute? Each
algorithm answers it differently, and the answer decides how bursts are treated.
What each one keeps¶
| Algorithm | State per key | What it allows |
|---|---|---|
SlidingWindow (the default) |
three numbers | About the limit in the period ending now |
FixedWindow |
two numbers | The limit in each window on the clock |
TokenBucket |
two numbers | A burst up to the limit, then a steady refill |
Fixed window. Time is cut into windows one period long, aligned to the clock, and each window allows the limit. It is exact per window and the easiest to explain to the people calling your API: the count resets at a known moment.
Sliding window. It keeps the count for the current fixed window and for the one before, and weighs the earlier one by how much of it still overlaps a period ending now. Ten seconds into a minute, the earlier minute still counts for five sixths. This is an approximation: it assumes the earlier window's requests were spread evenly.
Token bucket. A bucket holds up to limit tokens and gains limit / period
tokens a second. Each unit of cost takes one. A full bucket allows a burst, and
after that traffic is smoothed to the refill rate.
The boundary effect¶
All three use a fixed, small amount of memory per key, and for that reason all three can let through up to twice the limit in a short stretch:
- Fixed window: a full burst at the end of one window, then another at the start of the next.
- Sliding window: the same pattern, but only when the earlier window's requests all came at its very end. With traffic that is spread out it stays close to the limit.
- Token bucket: a full bucket's burst, plus what refills during the period that follows.
Only a record of every request's time avoids this, and that costs memory in proportion to the limit. paceapi does not include one.
What is guaranteed:
- Fixed window and sliding window never exceed the limit within a window aligned to the clock.
- Token bucket never exceeds the limit plus what has refilled, over any stretch of time.
Choosing¶
- Sliding window is the default because it is closest to what people mean by "100 a minute", and it handles a burst at the boundary far better than a fixed window in ordinary traffic.
- Fixed window suits quotas that should reset at a known time.
- Token bucket suits smoothing traffic to a steady rate while still allowing short bursts.
Details that apply to all three¶
- A cost of zero looks at the bucket without using anything.
- A cost larger than the whole limit can never fit. It is denied, and the suggested wait is one full period.
- A forced cost is counted even if it does not fit. Use it when the cost is only known after the work is done. It can leave a token bucket in debt, which the refill repays before anything else fits.
- If the clock moves backwards, nothing refills or resets early.