Sub topic 9
Leaky bucket: smoothing output to a constant rate
This chapter assumes you have read the token bucket chapter and can read short Python. The leaky bucket is the mirror image of the token bucket. Instead of letting bursts through, it evens them out.
The model
Picture a bucket with a hole in the bottom. Requests pour in at any speed. Water leaks out at a fixed rate. If the bucket is full, new water spills over, and that spilled water is a rejected request.
Two parameters define it:
- Capacity: how many requests can wait at once.
- Leak rate: how many requests leave per second.
Two ways to implement it
As a queue (a shaper). Requests wait in a FIFO queue, and a worker takes one out every 1 / leak_rate seconds. The backend sees a perfectly even stream. The cost is added latency, because a request may wait behind others.
As a meter. You keep only a number, the water level. It is a counter that drains with time. A request is accepted if it fits under capacity. Nothing is actually delayed, so this is cheap and works like a token bucket seen from the other side.
import time
class LeakyBucket:
"""Meter-style leaky bucket. Not thread-safe."""
def __init__(self, capacity, leak_rate, clock=time.monotonic):
self.capacity = capacity # maximum water level
self.leak_rate = leak_rate # units drained per second
self.clock = clock
self.level = 0.0
self.last = clock()
def allow(self, cost=1):
now = self.clock()
self.level = max(0.0, self.level - (now - self.last) * self.leak_rate)
self.last = now
if self.level + cost <= self.capacity:
self.level += cost
return True
return False
now = [0.0]
bucket = LeakyBucket(capacity=3, leak_rate=1, clock=lambda: now[0])
print([bucket.allow() for _ in range(4)]) # [True, True, True, False]
now[0] = 1.0 # one unit has leaked out
print(bucket.allow(), bucket.allow()) # True FalseThe injected clock lets you test with a fake clock, as a later chapter describes.
Leaky bucket versus token bucket
| Property | Token bucket | Leaky bucket (queue) |
|---|---|---|
| Bursts | Allowed up to capacity | Absorbed, then released evenly |
| Backend load | Can spike to the burst size | Constant |
| Added latency | None | Queue wait |
| Stored state | Tokens and timestamp | Queue, or level and timestamp |
Common errors
- Treating the meter and the queue as the same thing. The meter version rejects or accepts instantly. It does not smooth anything for the backend.
- Leaving the queue unbounded. Without a capacity limit, a flood grows memory and wait times without bound.
- Serving stale requests. A request that waited several seconds in the queue may belong to a client that has already timed out. Drop requests older than a maximum wait.
- Expecting low latency for bursty users. A client sending ten requests at once gets the last one served ten intervals later.
Use a leaky bucket when the downstream system needs a steady rate, such as a payment provider with a strict per-second cap. Use a token bucket when clients may burst and the backend can handle it.
Exercise
A leaky bucket has capacity 5 and a leak rate of 2 per second. It is empty, and 8 requests arrive at the same instant. How many are accepted, and how long until the bucket is empty again?
Show answer
Five are accepted and three are rejected, because the level can't exceed 5. The bucket drains at 2 per second, so it is empty after 5 / 2 = 2.5 seconds.