Highlights

Contents

Part VI
06

Leaky bucket

We make output smoother instead of merely deciding whether arrivals fit a saved allowance. Waiting can absorb a burst, but it also consumes resources and user time. We will separate policing from shaping, calculate drain time, bound a queue, and compare all five algorithms.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Rate limitingrequirements2Fixed window counter3Sliding window log4Sliding window counter5Token bucket6Leaky bucket7Distributed limiting withRedis8Case study: the completelimiter

#Section 21Leaky-bucket shaping

A downstream media service wants evenly paced jobs even when uploads arrive in a burst. A leaky bucket models work leaving at a controlled rate. In a queue-based shaping construction, arrivals join a bounded queue and the scheduler releases them at that rate.

A shaper delays work to change its departure timing. A policer admits or rejects work against a rule without promising queued departure. Both names sometimes appear beside leaky-bucket descriptions, so state whether your design really retains waiting requests or merely checks a virtual schedule.

SHAPING TURNS A BURST INTO PACED DEPARTURESSHAPING TURNS A BURST INTO PACED DEPARTURESbursty arrivalsjobjobjobbounded queuepaced releaseacceptance and departure happen at different times
Figure 12.23Queue-based shaping. A rejected arrival never enters the queue; a retained one consumes waiting resources.

At Heron’s illustrative rate of 100 requests per 60 seconds, draining a queue of 100 with no new arrivals takes 60 seconds in the continuous-rate model. That delay would be unacceptable for a 500-millisecond interactive score request. The same algorithm can be useful for background work with a different deadline contract.

#Section 22Queue state and waiting time

The shaping queue contains 20 equal-cost jobs ahead of a new request. At a modeled release rate of 100 divided by 60 jobs per second, waiting for those jobs to leave takes 20 divided by that rate, or 12 seconds. This is the queue delay before the new job’s own processing.

Wqueue=q/r.W_{\text{queue}}=q/r.

Read this as the deterministic modeled waiting time equals queued cost qq ahead of the request divided by release rate rr. Unequal jobs use queued cost in consistent units rather than raw job count. Worker execution and scheduling overhead can add further delay.

A LEAKY QUEUE WITH 20 AHEAD, RELEASING 100/60 PER SECOND: 12 S BEFORE WORK EVEN STARTSA LEAKY QUEUE WITH 20 AHEAD, RELEASING 100/60 PER SECOND: 12 S BEFORE WORK EVEN STARTSyouwait = 20 ÷ (100/60) = 12 sprocessing time is extra; admitted can still mean late
Figure 12.24Continuous-rate queue model. Discrete releases and execution time change exact completion timing.

If the expected departure is later than the request deadline, reject before retaining it. Otherwise a shaper can become a warehouse of expired work. Cancellation must remove or mark queued work without accidentally refunding another request or double releasing the same item.

#Section 23Virtual schedules and bounded debt

Instead of a physical queue, a limiter can keep a virtual next-available time. An arrival reserves a slice of future rate, then receives a delay or rejection according to the policy. This can implement a leaky-bucket-like meter without storing every waiting payload.

An illustrative debt of 30 cost units at a refill or service rate of 100 divided by 60 corresponds to 18 seconds of future service. If the maximum permitted delay is shorter, reject that reservation. The service must decide who actually schedules the deferred effect; merely returning a delay does not ensure the client follows it.

30 UNITS OF RESERVED DEBT AT 100/60 PER SECOND = 18 S OF FUTURE SERVICE30 UNITS OF RESERVED DEBT AT 100/60 PER SECOND = 18 S OF FUTURE SERVICEdebt 30 units = 18 smax delay 15 s (illustrative)051015202530 sover the limit: reject the reservation; the state still needs one atomic owner
Figure 12.25Virtual accounting exercise. It does not retain a payload or promise client compliance.

Distributed scheduler ownership is a separate problem. Two workers that interpret the same reserved time can execute a job twice unless queue or command identity controls execution. Rate accounting must not be mistaken for an exactly-once effect guarantee.

#Section 24Comparing the five choices

Heron’s exact user rule favors the sliding log if its recent-history cost fits the workload. A burst-capable public read policy can favor a token bucket. A background dispatch path can favor a bounded shaper. Fixed windows and sliding counters are inexpensive when their boundary or approximation semantics are acceptable.

Property Fixed window Sliding log Sliding counter Token bucket Leaky shaping
Stored history bucket count recent events recent buckets balance and time queue or virtual time
Moving-window exactness no yes, with atomic rule approximation different contract different contract
Burst behavior boundary burst interval bound estimate-dependent saved allowance delayed output
Main cost low state per-event state approximation error clock and atomic debit waiting and scheduling
Rejection basis bucket full recent log full estimated count insufficient tokens queue or delay bound
FOUR ALGORITHMS, FOUR DIFFERENT THINGS THEY PRESERVEFOUR ALGORITHMS, FOUR DIFFERENT THINGS THEY PRESERVEfixed / counter42cheap stateboundary burst or estimatesliding logexact recent arrivalsmemory per eventtoken bucketburst plus steady ratesaved allowanceleaky shapingpaced outputcallers wait
Figure 12.26Policy comparison. These are mechanisms rather than benchmark rankings.

Do not choose by memorized slogans such as token buckets are always best. State which behavior the consumer needs and which failure it must tolerate. The next part examines the shared atomic state on which every distributed implementation depends.