Rate-Limiting Algorithms
Definition
Token bucket
- In plain English
- A token bucket adds tokens at a steady rate up to a maximum, and each request spends one token, allowing short bursts.
- Think of it like
- It is like an arcade card topped up with one credit a minute, holding at most ten.
Leaky bucket
- In plain English
- A leaky bucket queues requests and lets them out at a fixed steady rate.
- Think of it like
- It is like a funnel that drips water out evenly however fast you pour.
Why it exists
A script spends its full allowance at 10:00:59, then again at 10:01:00. A per-minute limit still allows a sharp burst.
Your counting rule decides whether bursts pass, wait, or fail. Choose it for the work you need to protect.
How it works
Fixed window
- In plain English
- A fixed window counts requests per clock interval, such as per calendar minute, and resets at the boundary.
- Think of it like
- Like a daily allowance that refills at midnight.
Sliding window
- In plain English
- A sliding window counts requests in the last N seconds from right now, so there is no reset edge to exploit.
- Think of it like
- Like counting the cars that passed in the last 60 seconds at any moment.
| Algorithm | Bursts | Smooth output | Memory and edge |
|---|---|---|---|
| Token bucket | Up to saved tokens | No | One balance and timestamp per key |
| Leaky bucket | Wait in a bounded queue | Yes | Queued requests; reject when full |
| Fixed window | Full quota near each boundary | No | One counter; boundary burst |
| Sliding window | Up to quota in any rolling interval | No | Exact logs store timestamps; approximations use less memory |
Tokens refill a bucket capped at ten, and each request is allowed only when it can spend a token.
package main
import (
"fmt"
"time"
)
type bucket struct {
tokens, capacity, rate float64
last time.Time
}
func (b *bucket) allow(now time.Time) bool {
elapsed := max(0, now.Sub(b.last).Seconds())
b.tokens = min(b.capacity, b.tokens+elapsed*b.rate)
b.last = now
if b.tokens < 1 {
return false
}
b.tokens--
return true
}
func main() {
now := time.Unix(0, 0)
b := bucket{2, 2, 1, now}
fmt.Println(b.allow(now), b.allow(now), b.allow(now))
fmt.Println(b.allow(now.Add(time.Second)))
}- 100 requests at 10:00:59 plus 100 at 10:01:00 gives 200 within two seconds.
- A rolling 60-second count rejects the second batch until earlier requests leave the window.
Examples
Allow a short booking burst
Booking opens at 09:00 with ten tokens per user and a refill rate of one token per second.
User clicks spend tokens from a ten-token bucket; empty buckets reject requests before the booking API.
A full bucket permits ten immediate requests. After that, one second without spending restores one token, up to ten.
The insight
Token buckets allow short bursts without unlimited sustained traffic.
Close the reset gap
A script sends 200 redemption requests across a fixed minute boundary.
10:00:59 100 requests accepted in window one
10:01:00 100 requests accepted in window two
Rolling 60-second limit: second batch rejectedAn exact sliding window counts the first batch during the next 60 seconds. Counting allowance does not decide whether a redemption itself is valid.
The insight
Fixed windows have an exploitable edge.
Smooth tunnel exits
Buses reconnect after leaving a tunnel and upload many position updates together.
A bounded leaky-bucket queue releases 20 updates per second to the map service. Reject or combine updates when the queue fills.
A queue of 100 updates takes five seconds to drain if no more arrive. For live positions, replacing older updates may be better.
The insight
Leaky buckets smooth output but can add waiting time.
Trade-offs
Pros
- Token buckets permit bounded bursts.
- Leaky buckets smooth output.
- Sliding windows remove reset edges.
Cons
- Exact sliding logs cost memory.
- Shared counting adds delay.
- Queued work can become stale.
Use when
- An API needs a burst allowance.
- A downstream service needs steady input.
Avoid when
- Exact logs add cost without useful protection.
- An unbounded queue would hide overload.
Quick check
Takeaways
- Token buckets allow short bursts with a steady refill rate.
- Leaky buckets smooth output.
- Sliding windows close the fixed-window boundary gap.