Part 3 · Blueprint 11
Rate Limiting Algorithms: Token Bucket to Sliding Window
14 min reading · Sources · Editorial review pending
Locally correct counters can collectively exceed a shared quota.
Page details
Published date · Last edited:
Draft edition. Editorial review and supplementary reading recommendations are still being completed.
Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Back-of-Envelope Capacity Estimation, Load Balancing & API Gateways.
Sixty-second mental model
Problem: Locally correct counters can collectively exceed a shared quota.
Use: Define the allowed burst and synchronization cost.
Design boundary: Define admission by identity, resource and time. Token buckets allow bounded bursts; fixed windows permit boundary bursts; sliding windows track a different history/cost trade-off. Distributed counters need an atomic update rule.
Layer 1 · Intuition
Hypothetical scenario: Northwind is designing rate limiting. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one admission means and which component owns the quota policy.
Think of a gate spending admission tickets. Separate the requester from quota policy, then identify the retained evidence needed after failure.
- Authority
- The entitled state owner.
- Invariant
- A rule preserved across concurrency and failures.
- Rate limiting
- Enforcing an admission policy over a defined rate or quota. Analogy: A gate admitting only the allowed pace of visitors.
- Token bucket
- An admission model replenishing bounded tokens that requests consume. Analogy: A jar refilled steadily, with each visitor spending a token.
Architecture and worked reasoning
Design boundary: Define admission by identity, resource and time. Token buckets allow bounded bursts; fixed windows permit boundary bursts; sliding windows track a different history/cost trade-off. Distributed counters need an atomic update rule.
Responsibilities on the request path
Workload and limiting resource
Hypothetical bucket capacity is 20 tokens with refill of 5 tokens/s. An idle bucket admits 20 immediate unit-cost requests; after two seconds without other requests it can admit 10 more. A fixed 20-request window can admit 20 just before a boundary and 20 just after, which is 40 near the boundary, not the same burst contract.
Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.
Mutation or publication path
- Authenticate the limiting identity.
- Atomically replenish and spend tokens.
- Reject excess work before expensive downstream effects.
Observation and recovery path
- Inspect per-identity budget and global overload.
- Return retry guidance consistent with the policy.
- Keep administrative resets separate from ordinary requests.
Failure that changes the decision
Hypothetical scenario: Each of four API nodes independently allows 20 requests/s for one account. The effective account rate becomes 80 requests/s. Use shared authority or explicitly allocated sub-budgets.
Attempt this decision before reading the explanation
Should a limiter fail open when its state service is unavailable?
The answer depends on the protected resource and abuse consequences. A bounded preallocated local budget may preserve useful work, but unlimited fail-open can remove the only protection during an outage.
Supporting mechanism analysis
Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.
Hypothetical scenario. One Northwind tenant repeatedly requests different uncached products. The requests are valid, yet other tenants wait. Dev places a counter in each application worker. Priya adds another worker and asks what happened to the tenant’s total allowance.
Dev: “Then the allowance must name both the caller and the scope of enforcement.”
Define the charged unit, burst allowance and failure policy before choosing the limiter implementation. Distinguish a caller’s allowed demand from measured safe service capacity. The selected bucket exercise is a separate admission model, not a capacity claim about the original workers.
That changes the aggregate allowance when requests reach several workers. Decide whether the intended scope is local, regional or shared before interpreting the number.
This makes fairness and overload goals reviewable. Then calculate the selected burst and decide what to do if the enforcement service cannot answer.
Rate limiting controls how much work a caller may introduce over time. It can support fair access, abuse resistance or a commercial allowance. Those purposes may need different limits. A daily account quota does not necessarily protect a database against a short burst, while a per-second request limit does not settle monthly billing.
The charged unit matters. A catalogue lookup, a search scanning many candidates and a large media transformation are not necessarily equal-cost operations. Northwind can assign a declared cost class or enforce separate endpoint limits, provided the policy is understandable and tied to actual resource observations. Counting only successful responses would let rejected or expensive failing requests consume unaccounted work.
Place an inexpensive coarse defense before costly parsing or authentication when appropriate, then apply the authenticated tenant policy once trustworthy identity is available. A user-controlled tenant header cannot establish the account to charge. An IP-only policy also needs explicit treatment for shared networks and changing addresses.
A token bucket has a maximum balance and a refill rate. An admitted request consumes its declared token cost. Elapsed time replenishes the balance up to the maximum. A full bucket permits a short burst; the refill rate bounds the continuing allowance under the chosen model. It does not directly bound simultaneous in-flight work.
Northwind proposes one authoritative Redis decision per tenant and operation class, using an atomic server-side transition for elapsed-time refill, cap, comparison and deduction. Separate reads and writes of the balance would leave a race between concurrent callers. The design must also choose a trustworthy time basis and handle backward clock movement conservatively.
Hypothetical scenario. Choose a token bucket holding ten tokens and refilling at two tokens per second. Starting full, a one-second interval can spend at most 10 + 2 × 1 = 12 tokens under the ideal continuous-refill model. This is a selected burst envelope, not a measured service capacity.
A distributed limiter needs an atomic refill-and-spend decision for each policy identity. Per-process buckets multiply the allowance unless the policy explicitly allocates sub-budgets. Fixed windows can admit bursts across a boundary; sliding logs retain more event state; token buckets express a burst plus sustained rate. Compare actual boundary behavior rather than choosing by algorithm name alone.
During a limiter-store outage, decide whether traffic fails closed, uses preallocated local grants or proceeds under an explicitly weaker policy. A local grant must be bounded and not double-issued if a process restarts. Tenant, operation class and resource cost belong in the key; identical request counts can impose very different inference or query work.
Hypothetical worked example. Choose a bucket capacity of ten tokens, a refill rate of two tokens per second and one token per request. Start full and select twelve simultaneous requests, with no elapsed refill between them. Ten are admitted and 12 − 10 = 2 are limited. The accepted burst does not prove ten requests can execute simultaneously within a latency target.
After three idle seconds, the empty bucket gains 3 × 2 = 6 tokens. A subsequent seven-request burst admits six and limits 7 − 6 = 1. If instead the bucket were idle long enough to earn more than ten, its balance would still cap at ten. Unused allowance does not grow without bound in this model.
Now place a full independent ten-token bucket in each of three processes while claiming a global ten-request burst. Their combined immediate allowance becomes 3 × 10 = 30 requests. That is a different policy. A deliberately partitioned allocation could divide rights among processes, but the allocation and rebalancing rules must preserve the aggregate bound.
A fixed-window counter limits events within named time windows. It is simple, but traffic concentrated on either side of a boundary can create a short burst larger than one window’s allowance. A sliding log can examine actual recent events, at a storage and coordination cost. Approximate sliding counters trade precision for a smaller state representation.
A leaky-bucket queue can smooth departures when waiting is allowed; a policing interpretation can reject arrivals that exceed the selected envelope. Explain whether Northwind delays work or rejects it. Waiting consumes memory and the caller’s deadline, so moving excess traffic into a queue is not a free implementation of fairness.
Do not select an algorithm solely because it appears in an interview diagram. State which burst is acceptable, whether callers can wait and how much enforcement precision is required. Different endpoints can justify different answers while sharing the same tenant identity system.
For an illustrative state subtotal, choose an eight-byte timestamp for each retained admission. A full ten-entry sliding log uses 10 × 8 = 80 timestamp bytes per active identity. For 1,000 active identities that is 1,000 × 80 = 80,000 bytes. A selected fixed-window representation with one eight-byte window identifier and one eight-byte count uses 8 + 8 = 16 bytes per identity, or 16,000 bytes for the same cohort. Both exclude keys, allocation, expiry indexes, replicas and transport. These are logical representations, not measured Redis footprints.
Failing open preserves admission while losing the shared bound. Failing closed preserves the bound at the cost of rejecting useful work. A bounded local emergency allowance is another explicit policy, but its aggregate exposure depends on the number of processes and allocated rights. Document which operations receive which policy and why.
Layer 3 · Internals
Trade-offs and limits
| Approach | Provides | Requires |
|---|---|---|
| Token bucket | Expresses a sustained rate with a bounded burst allowance. | A distributed implementation still needs a state-sharing contract. |
| Sliding-window accounting | Can track a chosen recent interval more directly. | Exact event histories and approximate counters have different memory and boundary behavior. |
Recovery decision
Hypothetical scenario: Each of four API nodes independently allows 20 requests/s for one account. The effective account rate becomes 80 requests/s. Use shared authority or explicitly allocated sub-budgets.
The answer depends on the protected resource and abuse consequences. A bounded preallocated local budget may preserve useful work, but unlimited fail-open can remove the only protection during an outage.
Write your design before revealing the review
Should a limiter fail open when its state service is unavailable?
Drafts and self-review are stored only in this browser. They are separate from reading completion.
Compare your decision
The answer depends on the protected resource and abuse consequences. A bounded preallocated local budget may preserve useful work, but unlimited fail-open can remove the only protection during an outage.
Each of four API nodes independently allows 20 requests/s for one account. The effective account rate becomes 80 requests/s. Use shared authority or explicitly allocated sub-budgets.
Check your understanding
Should a limiter fail open when its state service is unavailable?
The answer depends on the protected resource and abuse consequences. A bounded preallocated local budget may preserve useful work, but unlimited fail-open can remove the only protection during an outage.
How would you recover from this failure: Each of four API nodes independently allows 20 requests/s for one account. The effective account rate becomes 80 requests/s. Use shared authority or explicitly allocated sub-budgets.
Start with the exact boundary that failed. Authenticate the limiting identity. Atomically replenish and spend tokens. Reject excess work before expensive downstream effects. Then recover evidence through the observation path: Inspect per-identity budget and global overload. Return retry guidance consistent with the policy. Keep administrative resets separate from ordinary requests. Preserve the distinction between a confirmed state change and an unavailable response.
Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?
Hypothetical bucket capacity is 20 tokens with refill of 5 tokens/s. An idle bucket admits 20 immediate unit-cost requests; after two seconds without other requests it can admit 10 more. A fixed 20-request window can admit 20 just before a boundary and 20 just after, which is 40 near the boundary, not the same burst contract. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Define admission by identity, resource and time. Token buckets allow bounded bursts; fixed windows permit boundary bursts; sliding windows track a different history/cost trade-off. Distributed counters need an atomic update rule.
Which component in this topology could be removed from a smaller first deployment?
Client identity, Policy lookup, Bucket authority, Accepted work name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Authenticate the limiting identity.
What evidence must a caller have before relying on the observation path?
Inspect per-identity budget and global overload. Return retry guidance consistent with the policy. Keep administrative resets separate from ordinary requests. The answer depends on the protected resource and abuse consequences. A bounded preallocated local budget may preserve useful work, but unlimited fail-open can remove the only protection during an outage.
45-minute interview rubric
- 00–05: scope admission and quota policy.
- 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
- 12–28: draw quota policy, numbered writes and reads.
- 28–40: challenge recovery: Define the allowed burst and synchronization cost.
- 40–45: defend tenant_id placement, observations and remaining assumptions.
Go deeper
- INCR | Docs · Primary document · redis.io. Define the allowed burst and synchronization cost. Verified 2026-10-26.
- RFC 6585: Additional HTTP Status Codes · Primary document · www.rfc-editor.org. Define the allowed burst and synchronization cost. Verified 2026-10-26.
Decision log
Define the allowed burst and synchronization cost.
Preserve admission identity and quota policy ownership.
Revisit changed workload, observations or recovery objectives.