Highlights

Contents

Part V
05

Token bucket

We separate a sustained replenishment rate from a permitted burst. A saved allowance lets a quiet user act quickly without granting unlimited long-term work. We will refill lazily, debit atomically, derive the burst bound, and handle weighted costs and clock changes.

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 17Tokens represent spendable allowance

A viewer was idle, then opens several score pages together. A token bucket stores a bounded allowance that replenishes with time. Each admitted request spends tokens; capacity limits how much allowance an idle user can save.

The illustrative Heron bucket holds at most 100 tokens and refills at 100 divided by 60 tokens per second. A cost-one request requires at least one token. The algorithm can admit a short burst from saved allowance while enforcing a sustained refill rate across a long interval. Capacity and refill rate are different policy parameters.

b′=min⁡(B,b+rΔt).b'=\min(B,b+r\Delta t).

Read this as available tokens b′b' equal the smaller of bucket capacity BB and old balance bb plus refill rate rr times elapsed time Δt\Delta t. A request of cost cc is admitted only if b′≥cb'\ge c, then the new balance becomes b′−cb'-c.

A TOKEN BUCKET SAVES BURST ALLOWANCE AND REFILLS AT A BOUNDED RATEA TOKEN BUCKET SAVES BURST ALLOWANCE AND REFILLS AT A BOUNDED RATErefill rate rbalance never exceeds capacity Brequest costs tokensenough: debit and admittoo few: preserve balance
Figure 12.18Lazy token-bucket update. The complete refill-and-debit procedure needs atomic ownership per subject.

#Section 18The full intermediate token trace

Start with 100 tokens at illustrative time zero. A burst costing 80 leaves 20. After 6 seconds, refill adds 6 times 100 divided by 60, or 10 tokens, so the balance becomes 30. A request group costing 15 leaves 15.

An immediate group costing 20 cannot pass. It lacks 5 tokens, and refill rate is 100 divided by 60, so the minimum modeled wait is 5 divided by that rate, or 3 seconds. Concurrent spend can make the actual future decision different; the wait is advice rather than a reservation.

A 100-TOKEN BUCKET: SPEND 80, WAIT 6 S (+10), SPEND 15, THEN COST 20 MUST WAIT 3 SA 100-TOKEN BUCKET: SPEND 80, WAIT 6 S (+10), SPEND 15, THEN COST 20 MUST WAIT 3 S100start20spend 8030wait 6 s+1015spend 1515cost 20?short 5refill 100/60 tokens/s; every debit is serialized
Figure 12.19Illustrative costs and times at a refill of 100/60 tokens per second. Every debit is serialized.
NEED 20, HAVE 15: SHORT 5 TOKENS ÷ 1.666666/S = 3 SNEED 20, HAVE 15: SHORT 5 TOKENS ÷ 1.666666/S = 3 S15 of 100cost 205 ÷ (100/60) = 3 sa rejection spends nothing; another caller may use the refill first
Figure 12.20Refill-only advice. Another request may spend the newly refilled allowance before this caller returns.

Do not set the balance negative in this policing variant. A virtual-time or debt variant can have different semantics, but it must bound debt and waiting. Name which construction you use before interpreting a negative stored number.

#Section 19The burst-plus-rate bound

The bucket begins with at most BB tokens. During an interval of duration Δt\Delta t, refill contributes at most rΔtr\Delta t more. Therefore the admitted cost in that interval cannot exceed the initial saved allowance plus added allowance, under one correctly serialized bucket and its clock assumptions.

C(Δt)≤B+rΔt.C(\Delta t)\le B+r\Delta t.

Read this as admitted cost CC over duration Δt\Delta t is at most capacity BB plus refill rate rr times the duration. For capacity 100 and 60 seconds at refill 100 divided by 60, the upper accounting bound is 200 tokens. Arrival placement and the endpoint convention affect whether the bound is reached exactly.

IN ANY 60 S A 100-TOKEN BUCKET CAN ADMIT UP TO 100 SAVED + 100 REFILLED = 200IN ANY 60 S A 100-TOKEN BUCKET CAN ADMIT UP TO 100 SAVED + 100 REFILLED = 200saved: 100+refill: 100/60 × 60 = 100=≤ 200C(Δt) ≤ B + rΔt; not the same promise as "100 in any minute"
Figure 12.21Illustrative burst-plus-rate bound. It is different from an exact 100-admission trailing-window contract.

Refill under a cap can discard credit when the bucket is full, making actual admitted cost lower. This does not invalidate the bound. The proof also exposes the distributed failure risk: creating independent fresh buckets gives each replica its own BB, and restoring a stale balance can recreate already-spent credit.

#Section 20Weighted cost and time monotonicity

One cheap score read can cost one token while a conversion costs more. For an illustrative upload cost rule of one token per 100,000,000 bytes, a 5,000,000,000-byte upload costs 50 tokens. This is an assigned policy unit, not a claim that CPU cost scales exactly with byte size.

For costs 20, 30, and 50 with no refill, the total is 100 and exhausts the full bucket. Another cost-one request would bring the total to 101 and must be rejected. Validate that each cost is positive and within policy range. Negative or malformed cost must never create allowance.

WEIGHTED COSTS 20 + 30 + 50 EMPTY THE 100-TOKEN BUCKET; THE NEXT COST-1 CALL IS REFUSEDWEIGHTED COSTS 20 + 30 + 50 EMPTY THE 100-TOKEN BUCKET; THE NEXT COST-1 CALL IS REFUSEDsearch 20export 30transcode 50+1 → 101cost belongs inside the atomic comparison, validated positive and in range
Figure 12.22Illustrative assigned costs. Resource-specific measurements should inform a production weighting rule.

Clock rollback must not add negative refill or move retained time backward. Use nonnegative elapsed time and retain a nondecreasing accounting timestamp. Across replicas, one authoritative time source or explicit skew bounds are needed. Process-local monotonic clocks are excellent for elapsed local waits but cannot be copied blindly as a shared epoch.