System Design Academy

Saving…

Lesson 3 of 10 in Module 50 of 54 lessons complete

Rate-Limiting Algorithms

Module 5, lesson 3Concept12 min

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.
AlgorithmBurstsSmooth outputMemory and edge
Token bucketUp to saved tokensNoOne balance and timestamp per key
Leaky bucketWait in a bounded queueYesQueued requests; reject when full
Fixed windowFull quota near each boundaryNoOne counter; boundary burst
Sliding windowUp to quota in any rolling intervalNoExact 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.

A refill rate and bucket size control different things.

Tokens refill a bucket capped at ten, and each request is allowed only when it can spend a token.

A single caller uses elapsed time to refill; concurrent callers would need synchronized access.
Go
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.

Saved tokens permit a few quick clicks.

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.

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

Which algorithm allows short bursts up to a cap while enforcing an average rate?
What is the weakness of a fixed window?

Takeaways

  • Token buckets allow short bursts with a steady refill rate.
  • Leaky buckets smooth output.
  • Sliding windows close the fixed-window boundary gap.

Try the quick check above whenever you feel ready.

Previous: Rate Limiting — Why and Where