Rate limiting comes up the moment one noisy client can hurt everyone else. Two algorithms dominate, and the names describe them well: the token bucket and the leaky bucket. They sound interchangeable and behave differently exactly where it matters — at the burst.
A token bucket fills at a steady rate up to a maximum. Each request spends a token; no token, no request. Because the bucket holds a reserve, a client that has been quiet can burst up to the bucket size instantly, then is throttled to the refill rate. That burst tolerance is usually what you want for user-facing APIs.
type Bucket struct {
capacity float64
tokens float64
rate float64 // tokens per second
last time.Time
}
func (b *Bucket) Allow(now time.Time) bool {
elapsed := now.Sub(b.last).Seconds()
b.tokens = min(b.capacity, b.tokens+elapsed*b.rate)
b.last = now
if b.tokens >= 1 {
b.tokens--
return true
}
return false
}
A leaky bucket instead drains at a fixed rate: requests queue and leave at a constant pace regardless of how they arrived. It smooths output completely, which is ideal when the thing downstream (a payment processor, a modem) genuinely cannot go faster than X per second. The cost is latency — a burst waits in the queue rather than passing through.
A rule of thumb: token bucket when you want to allow bursts up to a limit, leaky bucket when you want to forbid them and pace a downstream. For distributed limits across many servers, keep the same token-bucket math but store tokens and last in Redis and update them with a small Lua script so the read-modify-write is atomic.