← Back to Backend, page 2

backend-0039 · Medium mid

How do the token bucket and leaky bucket algorithms differ, and which one allows bursts?

A token bucket holds up to capacity tokens and refills at a steady rate. Each request takes a token, so a client can burst up to the capacity and then is limited to the refill rate. A leaky bucket (as a queue) accepts requests into a bucket of fixed size and processes them at a constant rate. It smooths output, never bursts, and drops what does not fit. Use a token bucket to allow controlled bursts (most APIs) and a leaky bucket to shape traffic to a steady rate for a downstream system.

Full answer

Token bucket

  • State: tokens (a number) and the last refill time. On a request: add elapsed * rate tokens (up to capacity), then if tokens >= 1 take one and allow, else reject and tell the client how long until the next token (Retry-After = (1 - tokens) / rate).
  • Burst size = capacity, long-term rate = refill rate. Needs only two numbers per client, and no timers (refill lazily).

Leaky bucket

  • Requests enter a queue (the bucket) that has a maximum size. The queue is drained at a constant rate. If the queue is full, new requests are dropped. A variant uses the bucket as a meter and does not queue at all.
  • Output is smooth, which protects a fragile downstream. Added latency for queued requests is the cost.

Choosing

  • Public APIs: token bucket (burst friendly, simple).
  • Calls to a downstream system with a hard rate limit: leaky bucket or a queue with a fixed consumer rate.
  • Often both: a token bucket at the edge and a queue in front of a slow dependency.
javascript
class TokenBucket {
  constructor(capacity, refillPerSecond) { this.capacity = capacity; this.rate = refillPerSecond; this.tokens = capacity; this.last = 0; }
  take(now) {
    this.tokens = Math.min(this.capacity, this.tokens + (now - this.last) * this.rate); this.last = now;
    if (this.tokens >= 1) { this.tokens -= 1; return { allowed: true }; }
    return { allowed: false, retryAfter: Math.ceil((1 - this.tokens) / this.rate) };
  }
}

class LeakyBucket {                                   // a queue that is drained at a constant rate
  constructor(size, leakPerSecond) { this.size = size; this.interval = 1 / leakPerSecond; this.nextFree = 0; this.queued = []; }
  add(now) {
    this.queued = this.queued.filter((t) => t > now);                  // requests already processed leave the bucket
    if (this.queued.length >= this.size) return { accepted: false };
    const processAt = Math.max(now, this.nextFree) + this.interval;
    this.nextFree = processAt; this.queued.push(processAt);
    return { accepted: true, processAt };
  }
}

// 8 requests arrive at t = 0 s, then 3 more at t = 4 s. Capacity 5, rate 1 per second.
const bucket = new TokenBucket(5, 1), leaky = new LeakyBucket(5, 1);
const arrivals = [0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4];
console.log('arrival  token bucket                 leaky bucket (processed at)');
for (const t of arrivals) {
  const a = bucket.take(t), b = leaky.add(t);
  console.log(`t=${t}s     `, (a.allowed ? 'allowed now' : `rejected, retry in ${a.retryAfter}s`).padEnd(28), b.accepted ? `t=${b.processAt}s` : 'dropped');
}

Both limiters get explicit timestamps, so the timeline is exact. The leaky bucket here queues requests and shows when each one is processed. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): arrival token bucket leaky bucket (processed at) t=0s allowed now t=1s t=0s allowed now t=2s t=0s allowed now t=3s t=0s allowed now t=4s t=0s allowed now t=5s t=0s rejected, retry in 1s dropped t=0s rejected, retry in 1s dropped t=0s rejected, retry in 1s dropped t=4s allowed now t=6s t=4s allowed now t=7s t=4s allowed now t=8s

Key points

  • Token bucket: burst up to capacity, then the refill rate.
  • Refill lazily from the elapsed time.
  • Leaky bucket: constant output rate, queue size limit.
  • Retry-After comes from the missing token fraction.
  • Pick by whether bursts are acceptable.

Common mistakes

  • Mixing up which algorithm allows bursts.
  • Refilling with a background timer for every client.
  • Using floating point tokens without clamping to the capacity.
  • Not returning Retry-After.
  • Using one global bucket for all clients.

Follow-ups

  • How would you implement a token bucket in Redis atomically?
  • How do you set capacity and refill rate for a paid plan?
  • What is GCRA?

Tips

  • Say burst versus smooth.
  • Give the refill formula.
  • Name a use case for each.