Skip to content

Limit request rates under a declared policy

11 min reading

Work token-bucket/sliding-window examples and explain distributed enforcement limits

Page details

System Design · Operate the system

11 min reading · 24 min with practice

Sources

Published · Last edited:

Prerequisite: Cache data while preserving a freshness contract. For basics, use the independent System Design foundations.

More
20px

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.

Maya: “We want fair browsing, not just valid credentials.”

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.

Whose work is limited, and at which boundary?

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 allows a bounded burst

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.

One scoped admission decision before expensive workRequests acquire authenticated tenant identity and operation cost. One atomic bucket decision either admits work to a separate concurrency boundary or returns a limited response. Independent processes must not each grant the full global allowance.Tenant + actionDeclared costAtomic bucketRefill and deductAdmitted workConcurrency boundOtherwise: explicit limited response
Rate, burst and in-flight capacity are distinct controls.

Put distributed limiting state behind one declared policy

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.

Put distributed limiting state behind one declared policy — selected design evidence
Policy fieldSelected valueMeaning
Bucket identitytenant T / costly searchOne shared allowance
Capacity10 tokensMaximum stored burst
Refill2 tokens/sSustained modeled rate
Refill and spend must form one consistent decision for the selected shared policy.Refill and spend must form one consistent decision for the selected shared policy. Refill by elapsed time to Atomic spend check: cap at bucket capacity; Atomic spend check to Admit or reject: deduct only when admitted.Refill by elapsedtimeAtomic spend checkAdmit or rejectcap at bucket capacitydeduct only when admitted
Refill and spend must form one consistent decision for the selected shared policy. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

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.

Work one burst without averaging it away

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.

Choose the time semantics deliberately

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.

Run the same arrivals through two policies

Hypothetical scenario. Compare a fixed window allowing ten requests per named second with a sliding log allowing ten in the trailing interval (t − 1 second, t]. Ten requests arrive at 0.99 seconds and ten more at 1.01 seconds, with no earlier traffic. A fixed window admits both groups in different windows: 10 + 10 = 20 requests within 1.01 − 0.99 = 0.02 seconds. The sliding log admits the first ten and rejects the next ten because the earlier group remains inside its trailing interval.

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.

A weighted sliding counter stores window counts and estimates how much of the preceding window still matters. It cannot reconstruct the exact burst location inside that window. Choose that approximation only if the admission contract accepts its boundary error. A smoothing queue makes a different promise again: it postpones accepted work and must bound waiting. These comparisons let the tenant policy choose the algorithm; HTTP 429 communicates rejection without selecting one for the server.

Choose behavior when the limiter is unavailable

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.

Retry traffic also needs accounting. A caller rejected by admission should not immediately retry in a tight loop. Publish supported retry guidance without promising that the next attempt will succeed. The server can be under competing demand or a separate concurrency constraint when the caller returns.

In the wild: HTTP exposes a limited outcome

RFC 6585 defines HTTP 429 for excessive request rate and permits retry guidance. It does not prescribe Northwind’s identity model, bucket algorithm or fairness policy. Those remain explicit application decisions. A well-formed status code cannot repair a non-atomic counter.

Scaling the service changes the allowance

Hypothetical failure scenario. The application fleet grows while every process retains a full tenant bucket. A customer who distributes requests across the new processes gains more admitted work, although the advertised tenant allowance never changed. Other tenants now compete with a policy accidentally defined by fleet size.

Use shared enforcement or a deliberate distribution of admission rights. Test the aggregate policy during process replacement and regional failover, including unused rights and disconnected nodes. The limiter’s own key distribution can create hot tenants; its capacity must support decisions without becoming an unbounded new dependency.

Use rate limits alongside capacity controls

Use this mechanism where a named caller’s arrival envelope matters. Add concurrency bounds when slow requests can accumulate, and use deadlines and load shedding to protect already admitted work. A per-tenant bucket alone cannot guarantee the whole fleet has enough capacity when many compliant tenants arrive together.

Keep authorization separate. A caller with available tokens may still lack permission to read a product or perform a reservation. A caller with permission may still exceed an allowance. Returning precise outcomes helps clients respond correctly and helps operators distinguish abuse, scarcity and application errors.

Challenge the proposed mechanism

Three regions each create a full ten-token bucket for one global tenant. Is the original policy preserved?

Reveal the design reasoning

No, unless those grants were allocated within the global budget. Partition allowances deliberately or coordinate spending, and state the availability trade-off. Count retries according to the declared policy rather than accidentally refunding attempted work.

Decision and reconsideration: Choose an enforceable burst and sustained-rate contract. Revisit it when cost, regional placement or outage behavior changes.

Defend the admission contract

  1. Three processes each hold a full ten-token bucket. Is the global burst ten?

    Count all granted rights

    No. The immediate allowance can reach thirty requests. Share the decision or partition rights deliberately before claiming an aggregate ten-request envelope.

  2. Can a request with sufficient tokens skip authorization?

    Keep policy boundaries separate

    No. Admission controls resource use. Authorization controls permission. Identity must be trustworthy for both decisions, and satisfying either does not imply the other.

  3. Does a two-token-per-second refill prevent too many slow requests from remaining active?

    Distinguish rate and occupancy

    No. In-flight work depends on how long requests remain active. A separate concurrency boundary and deadlines are needed when occupancy threatens capacity.

A declared arrival limit does not bound how long accepted requests occupy resources. Page 34 slows a dependency and traces concurrency, queueing and retries against the remaining capacity.

Northwind decision log

Charge a declared unit to authenticated tenant and action identity.
Enforce one aggregate allowance with explicit burst and outage behavior.
Next, bound retries, waiting and concurrent work under overload.

Go deeper: request defenses and rate envelopes