Sub topic 9
Leaky bucket: smoothing output to a constant rate
This chapter assumes you have read the token bucket chapter. You should be comfortable with Python classes, time.monotonic(), and the idea that a limiter either accepts or rejects a request. Threads and queues appear in one example, but you only need the basics.
The working model
Picture a bucket with a hole in the bottom. Requests pour in at the top and add water. Water leaks out of the hole at a constant rate. If a request would make the bucket overflow, it is dropped or delayed.
The model has two parameters:
- Capacity: how much the bucket can hold.
- Leak rate: how fast the bucket drains, in requests per second.
The name covers two implementations that behave differently. Many tutorials mix them up, so keep them apart.
| Variant | What the bucket holds | When full | Output pattern |
|---|---|---|---|
| Meter | A numeric water level | Reject the request | Bursts pass straight through until the level is full |
| Queue (shaper) | The requests themselves | Reject the new request | Requests leave at exactly the leak rate |
Variant 1: leaky bucket as a meter
The meter keeps one number, the water level. It does not store requests. On each call it lowers the level by the time elapsed multiplied by the leak rate, never going below zero. Then it checks whether the new request fits.
import time
class LeakyBucketMeter:
"""Single-process leaky bucket meter. Not thread-safe."""
def __init__(self, capacity, leak_rate):
self.capacity = capacity # maximum water level
self.leak_rate = leak_rate # units drained per second
self.level = 0.0
self.last = None
def allow(self, cost=1, now=None):
now = time.monotonic() if now is None else now
if self.last is not None:
leaked = (now - self.last) * self.leak_rate
self.level = max(0.0, self.level - leaked)
self.last = now
if self.level + cost <= self.capacity:
self.level += cost
return True
return False
bucket = LeakyBucketMeter(capacity=3, leak_rate=1)
print([bucket.allow(now=0.0) for _ in range(4)]) # True, True, True, False
print(bucket.allow(now=1.0)) # one unit leaked: TrueCompare this with the token bucket. A token bucket with capacity C and refill rate r holds C - level tokens. Both accept and reject the same requests. The meter is the token bucket seen upside down: one counts free space, the other counts used space. If you have already built a token bucket, you do not need this variant.
Variant 2: leaky bucket as a queue
The queue variant is the one that earns the name "smoothing". Accepted requests wait in a FIFO queue, and a worker releases one every 1 / rate seconds. The backend sees a steady stream no matter how spiky the arrivals are.
import queue
import threading
import time
class LeakyBucketQueue:
"""Releases queued items to `handler` at a constant rate."""
def __init__(self, capacity, rate, handler):
self.queue = queue.Queue(maxsize=capacity)
self.interval = 1.0 / rate
self.handler = handler
self._stop = threading.Event()
self._worker = threading.Thread(target=self._drain, daemon=True)
self._worker.start()
def submit(self, item):
try:
self.queue.put_nowait(item)
return True
except queue.Full:
return False
def _drain(self):
next_slot = time.monotonic()
while not self._stop.is_set():
try:
item = self.queue.get(timeout=0.1)
except queue.Empty:
continue
slot = max(next_slot, time.monotonic())
delay = slot - time.monotonic()
if delay > 0 and self._stop.wait(delay):
break
self.handler(item)
next_slot = slot + self.interval
def stop(self):
self._stop.set()
self._worker.join()
start = time.monotonic()
shaper = LeakyBucketQueue(
capacity=3,
rate=5,
handler=lambda i: print(f"released {i} at {time.monotonic() - start:.2f}s"),
)
accepted = [shaper.submit(i) for i in range(8)]
print(accepted)
time.sleep(1.0)
shaper.stop()Eight requests arrive in a burst. Three or four are accepted. The worker may already have taken the first one off the queue, so the exact count varies. The rest are rejected immediately. The accepted ones are released about 0.2 seconds apart. The code schedules each release from the previous slot, not from "now plus interval". That keeps handler run time from lowering the real rate. Using max(next_slot, now) also prevents a catch-up burst after an idle period.
What the queue variant costs and buys
The queue variant gives the backend a predictable load. That suits calls to a fragile downstream system, a third-party API with a strict per-second limit, or network traffic shaping, which is where the algorithm came from.
It also has three costs:
- Added latency. A request accepted into a full bucket waits up to
capacity / rateseconds. With capacity 100 and rate 10 per second, that is 10 seconds. A caller may have timed out by then. - Stale work. Old requests can sit ahead of fresh ones. If freshness matters, the queue is the wrong tool.
- Memory and state. The queue stores whole requests, not one number. Sharing it across servers is much harder than sharing a counter.
For these reasons, a queue-based leaky bucket usually belongs where you control the sender, such as a background job dispatcher or an outbound API client. It rarely belongs on the inbound edge of a synchronous API, where rejecting quickly with a 429 is kinder than making the caller wait.
Meter or token bucket?
If you reject instead of delay, the meter and the token bucket are the same algorithm with different bookkeeping. The practical difference is mostly vocabulary. Teams that say "leaky bucket" for an API limiter often mean the meter. Those who emphasize "constant output rate" mean the queue. When someone proposes a leaky bucket in a design review, ask which one they mean.
Neither variant is a good fit when you need to count requests over an exact window. For that, use a sliding window.
Common errors
- Treating the meter as a shaper. A meter lets a burst through at full speed until the bucket fills. The backend still sees the spike. Only the queue variant flattens it.
- An unbounded queue. Without a capacity, overload turns into growing memory and growing latency instead of rejections. Always set
maxsize. - Sleeping a fixed interval after the handler.
handler(item); sleep(interval)gives a rate of1 / (interval + handler_time). Schedule against absolute slots, as the example does. - Using
time.time()for the leak calculation. A wall clock can jump backward or forward when the clock is adjusted. Use a monotonic clock within one process. Across nodes, see the clock chapter later in this tutorial. - Forgetting locks.
LeakyBucketMeterreads and writeslevelandlastin separate steps. Two threads can both pass the capacity check. Add a lock in a threaded server, or use the atomic approach from the distributed chapters. - Never evicting idle keys. A meter per user leaves one entry for every user that has ever called. Expire entries once the level reaches zero.
Exercises
Exercise
A LeakyBucketMeter has capacity 10 and leak rate 2 per second. It starts empty, and 10 requests arrive at time 0. All are accepted. How many more requests can be accepted at time 3 seconds, assuming none arrived in between?
Show answer
6. The level was 10. After 3 seconds it has leaked 3 × 2 = 6 units, so the level is 4. The bucket has room for 10 − 4 = 6 more requests.
Exercise
A queue-based leaky bucket has capacity 50 and a leak rate of 10 requests per second. What is the longest a request can wait in the queue before release, and why might that be a problem for an inbound API?
Show answer
About 5 seconds (capacity / rate = 50 / 10). A client with a shorter timeout gives up while its request is still queued, and the server then does work for nobody. For inbound APIs, rejecting quickly with a 429 is usually better, so the meter variant or a token bucket fits more often.