Learning pathsPricingChecking sign-in…
GUIDED PRACTICE

Rate Limiter

Design an admission control service that limits requests by a documented identity and time policy.

Clarify this prompt before choosing components

Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.

Ask the interviewerWhy the answer changes the design
Limit requests, weighted work or bytes, and by which identity?Define the key and unit before selecting a counter.
Fixed window, sliding limit or allowed bursts?Algorithm choice changes the user-visible guarantee.
Strict global enforcement or bounded regional overshoot?Partition behavior and fail-open/fail-closed policy require an explicit contract.

Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.

Rate Limiter: Understand the building blocks

Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.

Rate Limiter: Quick vocabulary

TermMeaning and role in this exercise
API: Application Programming InterfaceThe contract for requests, responses and errors between components. An API route does not itself enforce every business invariant.

Rate Limiter: Token bucket and fixed window

What it means: A token bucket refills permission units over time up to a burst capacity; admission spends request cost atomically. A fixed window counts requests in a fixed interval.

Why this problem needs it: The quota needs a precise time and burst meaning.

How to use it: Scope state to the actual quota identity, calculate refill with a declared clock, and perform refill-plus-spend as one atomic decision.

Example in this design: Four tokens plus one second at 2/s gives six; a cost-four request leaves two.

When it fits: Use a token bucket for sustained rate plus permitted bursts; fixed windows fit simpler interval quotas.

Alternative and limits: Independent local budgets can exceed a strict global quota. Window boundaries permit a burst across adjacent windows unless the policy explicitly handles it.

Rate Limiter: Compare-and-set (CAS) and optimistic concurrency

What it means: A conditional write changes state only if an expected version or value still matches. The comparison and write share one atomic boundary.

Why this problem needs it: Concurrent admissions must spend one shared budget atomically.

How to use it: Carry the version read by the caller; atomically compare, mutate and advance it. On conflict, re-read or reject under the business policy.

Example in this design: Two cost-four requests cannot both spend those six tokens.

When it fits: Useful when concurrent requests must not silently overwrite the same owned state.

Alternative and limits: Row locks or a serial owner can simplify highly contended updates. A read followed by an unconditional write is not CAS.

Rate Limiter: Cache-aside, Redis and time to live (TTL)

What it means: A cache keeps reusable copies for faster reads. Cache-aside checks the cache, loads an authoritative source on a miss, then fills it. TTL is the declared entry lifetime.

Why this problem needs it: Redis is an optional shared fast state owner, not merely a cached counter.

How to use it: Key by the correct tenant/object/version, retain an absolute freshness deadline, bound entry size, and apply the stated invalidation or version-fence policy. Redis is one possible in-memory implementation.

Example in this design: An atomic script can refill and spend a scoped bucket; eviction/outage still needs a declared policy.

When it fits: Useful when repeated eligible reads justify memory and the tolerated staleness is explicit.

Alternative and limits: Direct indexed database reads may suffice. A cache is not automatically durable authority; shorter TTL does not prove immediate revocation.

Interview scope and guarantees

Enforce per-user, per-tenant, and endpoint quotas with explicit burst behavior. Decide whether quotas are strict globally or approximate across regions. Return a useful retry hint without consuming unbounded memory for attacker-generated identities.

Capacity worksheet

Assume 100,000 requests/s and 2 million active bucket keys. At 100 bytes of logical state per key, raw state is 200 MB; allocator and replication overhead raise it. A network round trip to a central limiter can dominate a fast API, so distinguish edge protection from strict business quotas.

Concrete API contract

Contract / pseudocode
checkAndConsume {principal,policy,cost,requestId?} -> {allowed,remaining,retryAfter}
HTTP 429 for exceeded client quota
HTTP 503 for service overload when retry is appropriate
Policy versions are distributed separately from counters.

Data model and access paths

Contract / pseudocode
bucket(principal,policy,tokens,last_refill,policy_version)
policy(id,capacity,refill_rate,scope,fail_behavior)
lease(region,policy,allocated_tokens,expires_at) for regional token allocation

Evolve a solution and explain each change

Three architecture decisions for Rate Limiter, including the pressure each introduces.
Three architecture decisions for Rate Limiter, including the pressure each introduces.
Read the diagram

One atomic bucket / Refill tokens from elapsed time and deduct the request cost atomically. / Independent workers with separate buckets multiply the allowance.; Share authority / Route a key to a shared owner or atomic store operation; calculate retry time. / That authority adds latency and can become unavailable.; Choose partition behavior / Use bounded local allocations or fail-open/fail-closed according to the protected resource. / Approximate availability spends a stated overshoot budget.

Open original
Rate Limiter · architecture decisions
Three architecture decisions for Rate Limiter, including the pressure each introduces.

Three architecture decisions for Rate Limiter, including the pressure each introduces.

Step 1: One atomic bucket

Refill tokens from elapsed time and deduct the request cost atomically. Independent workers with separate buckets multiply the allowance.

Step 2: Share authority

Route a key to a shared owner or atomic store operation; calculate retry time. That authority adds latency and can become unavailable.

Step 3: Choose partition behavior

Use bounded local allocations or fail-open/fail-closed according to the protected resource. Approximate availability spends a stated overshoot budget.

Responsibility overview

Connected responsibilities for Rate Limiter. Trace the authoritative and derived paths separately.
Connected responsibilities for Rate Limiter. Trace the authoritative and derived paths separately.
Read the diagram

Caller to Admission API: request with cost; Admission API to Bucket store: atomic token deduction; Operator to Policy loader: change policy; Policy loader to Admission API: refresh policy; Admission API to Local token lease: bounded local allocation; Policy loader to Local token lease: allocate token budget

Open original
Rate Limiter · connected architecture
Connected responsibilities for Rate Limiter. Trace the authoritative and derived paths separately.

Connected responsibilities for Rate Limiter. Trace the authoritative and derived paths separately.

Worked end-to-end scenario

A tenant has capacity 100 and refill rate 10 tokens/s. After a burst consumes all tokens, a one-token request 50 ms later has only 0.5 token available and is rejected. At 100 ms it can succeed. Four API replicas must not each mint 100 tokens for that tenant. Put refill and consumption in one atomic operation on the tenant key or assign bounded local token leases. If the shared store fails, an expensive payment endpoint may reject while a low-risk read endpoint permits limited traffic. Explain the policy by endpoint rather than calling every outage fail-open.

Why these access paths matter

Key by the actual limiting dimension: tenant, endpoint, user, IP, or a defined combination. IP-only limits penalize shared networks and miss rotating clients. Use server time or monotonic elapsed-time handling consistently; clamp negative elapsed time. TTL removes idle bucket records but must not reset an active account’s quota unexpectedly.

Build the baseline first

Rate Limiter: baseline request paths.
Rate Limiter · working baseline
Read the diagram

Request → identity and policy → atomic bucket update; Allowed → backend; denied → retry hint; Idle bucket → expiry → bounded state cleanup

Open original
Rate Limiter · working baseline
Rate Limiter: baseline request paths.

Rate Limiter · working baseline

  1. Request → identity and policy → atomic bucket update.
  2. Allowed → backend; denied → retry hint.
  3. Idle bucket → expiry → bounded state cleanup.

Evolve the design under load

Rate Limiter: additional scaling and recovery paths.
Rate Limiter · scale and recovery paths
Read the diagram

Edge local bucket → coarse abuse protection; Regional token leases → bounded global allocation; Strict quota path → authoritative conditional consumption

Open original
Rate Limiter · scale and recovery paths
Rate Limiter: additional scaling and recovery paths.

Rate Limiter · scale and recovery paths

  1. Edge local bucket → coarse abuse protection.
  2. Regional token leases → bounded global allocation.
  3. Strict quota path → authoritative conditional consumption.

Defend the hardest decision

A token bucket with capacity 20 and refill 5/s allows a burst of 20 then about 5/s sustained. At each atomic check, compute min(capacity, oldTokens + elapsed × rate), then subtract request cost only if enough tokens remain. A read followed by a separate write is unsafe under concurrency. Fixed windows are simpler but allow two bursts around a boundary; sliding logs are more exact but store more events.

Failure and recovery analysis

If Redis fails, fail-open may protect availability but violate a paid quota; fail-closed may break critical user requests. Define this per policy, not globally. Independent regional limits can overshoot a global quota. Token allocations make the overshoot or unused capacity explicit, while strict central coordination increases latency and reduces partition availability.

Security and privacy boundary

Use verified identity and tenant boundaries; trusting a client-supplied user header makes per-user limits bypassable.

Interview follow-ups with reasoning

Question: How do retries affect billing quotas?

Show answer and explanation

Answer: Decide whether a repeated operation consumes another unit and store deduplication only where required.

Question: How do you prevent key explosion?

Show answer and explanation

Answer: Normalize identities and expire idle buckets.

Question: How do weighted operations work?

Show answer and explanation

Answer: Consume tokens proportional to bounded estimated cost.

Operate and verify the design

Allowed/denied rates by policy, decision latency, key cardinality and fail-open usage.

Partition regional limiters and quantify the maximum permitted overshoot under the chosen allocation policy.

A second scenario to test transfer

A bucket holds 20 tokens and refills at 5/s. A request costs 3 tokens. An atomic operation refills according to elapsed server time, subtracts 3, and returns the remaining budget. Two concurrent requests cannot both spend the same final tokens. A regional lease of 10 tokens can serve locally, but the global contract must account for those reserved tokens.

One tenant sends through three regions, each with a local cache of the same 100/minute quota. What violation is possible, and how could leased tokens bound it?

Show answer and explanation

Answer: Independent local counters may each admit 100, allowing roughly 300. A coordinator can lease disjoint portions whose total does not exceed 100, with unused tokens temporarily stranded. Alternatively coordinate each decision centrally at higher latency. State the exact guarantee and how leases expire or return.

Compare alternatives

AlgorithmBoundary behaviorCost
Fixed windowCan burst at rolloverLow state and computation
Sliding logPrecise recent countPer-request timestamp state
Token bucketControlled burst + average rateAtomic refill state
Regional leasesLower coordination latencyBudget may be unevenly spent

A design-changing exercise

A token bucket with 100 capacity and 10/s refill permits 100 instant requests. Is that a bug?

Show answer and explanation

Answer: No, it is the configured burst allowance. Use a different algorithm or lower capacity if the downstream resource cannot tolerate that burst.

Design workshop: one atomic decision

Core scope is tenant/API-key admission with weighted request costs; abuse detection and billing are separate. Assume a two-millisecond local decision budget, bounded bursts and an explicit outage policy per route. A financial write fails closed or uses a genuinely reserved local budget; a public read may fail open with a measured overload allowance.

A token bucket has capacity B, refill rate r tokens/s, balance t and last timestamp. Compute t_new=min(B,t+r×max(0,now−last)). Admit only if t_new≥cost, then subtract cost. If rejected, retry delay is (cost−t_new)/r for positive r. Reject cost>B as an unsatisfiable policy, rather than returning an endless retry loop. The entire read/refill/check/debit/write occurs on one authority.

lua
-- Teaching Lua sketch; validate policy arguments before calling.
local tm = redis.call('TIME')
local now = tonumber(tm[1]) + tonumber(tm[2]) / 1000000
local state = redis.call('HMGET', KEYS[1], 'tokens', 'last')
local cap, rate, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local old = tonumber(state[1]) or cap
local last = tonumber(state[2]) or now
local effective = math.max(now, last)
local tokens = math.min(cap, old + (effective-last)*rate)
local allowed = tokens >= cost and cost <= cap
if allowed then tokens = tokens-cost end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'last', effective)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap/rate*1000)+1000)
return {allowed and 1 or 0, math.floor(tokens*1000)}

This sketch assumes positive refill and bounded integer-scaled return values; handle zero-rate policies separately. Expiring idle state is safe only once elapsed time would have refilled the bucket. Redis atomicity protects concurrent commands, but an asynchronously promoted replica can lose prior debits. Decide whether that small overshoot is permitted; if not, choose stronger durable quota authority rather than claiming Lua removes failover loss.

Token bucket with B=20, r=5/s, cost=3. 0 seconds / 20 / Admit; balance 17; 0 seconds again / 17 / Admit; balance 14; After total 6 requests at t=0 / 5 before sixth / Admit; balance 2; Seventh at t=0 / 2 / Reject; retry after 0.2 seconds; At t=0.2 / 3 / Admit; balance 0
Token bucket with B=20, r=5/s, cost=3.
Read the diagram

Time / Balance before decision / Outcome; 0 seconds / 20 / Admit; balance 17; 0 seconds again / 17 / Admit; balance 14; After total 6 requests at t=0 / 5 before sixth / Admit; balance 2; Seventh at t=0 / 2 / Reject; retry after 0.2 seconds; At t=0.2 / 3 / Admit; balance 0

Open original
Token bucket with B=20, r=5/s, cost=3
Token bucket with B=20, r=5/s, cost=3. 0 seconds / 20 / Admit; balance 17; 0 seconds again / 17 / Admit; balance 14; After total 6 requests at t=0 / 5 before sixth / Admit; balance 2; Seventh at t=0 / 2 / Reject; retry after 0.2 seconds; At t=0.2 / 3 / Admit; balance 0

Token bucket with B=20, r=5/s, cost=3.

Fixed windows can admit 100 requests just before a boundary and another 100 just after it. A sliding log removes timestamps older than the window and counts exactly within that definition but stores per-request state. Sliding counters approximate the previous/current windows and need a stated boundary error. A token bucket controls long-run rate and a burst of B; it is not exactly a rolling-window count.

For global 100/minute admission, allocate disjoint window-scoped budgets: region A 40, B 35, C 25. The durable coordinator deducts leased tokens when issuing them. Regions never replenish independently; a disconnected region can spend only its remaining lease. Do not reissue an expired region's unreported tokens within the same accounting window: expiry does not prove the old owner did not spend them. Return unused tokens only through an atomic close with a fenced owner, or strand them until window reset.

Lease issuance preserves a global budget. Region A to Quota coordinator: Lease 40 for window W and epoch E; Quota coordinator to Quota coordinator: Deduct 40 from unallocated 100; persist lease; Region B to Quota coordinator: Lease 35; unallocated becomes 25; Client to Region A: Spend one local token under W/E; Region A to Quota coordinator: Disconnect: no new budget until authority reachable; Quota coordinator to Region B: Never reissue A's uncertain 40 in window W
Lease issuance preserves a global budget.
Read the diagram

Lease 40 for window W and epoch E; Deduct 40 from unallocated 100; persist lease; Lease 35; unallocated becomes 25; Spend one local token under W/E; Disconnect: no new budget until authority reachable; Never reissue A's uncertain 40 in window W

Open original
Lease issuance preserves a global budget
Lease issuance preserves a global budget. Region A to Quota coordinator: Lease 40 for window W and epoch E; Quota coordinator to Quota coordinator: Deduct 40 from unallocated 100; persist lease; Region B to Quota coordinator: Lease 35; unallocated becomes 25; Client to Region A: Spend one local token under W/E; Region A to Quota coordinator: Disconnect: no new budget until authority reachable; Quota coordinator to Region B: Never reissue A's uncertain 40 in window W

Lease issuance preserves a global budget.

Hierarchical limits require tenant, route and user budgets. To guarantee all-or-none spending, place their state at the same owner and evaluate them in one atomic script/transaction; Redis Cluster keys must share a hash slot for a multi-key script. Otherwise describe conservative partial spending or a reservation protocol. At one million active keys and an illustrative 160 bytes/key, state alone is 160 MB before replication and allocator overhead. Watch decision latency, policy misses, rejected cost, lease utilization and overshoot separately.

Exercise: A loses contact after spending an unknown part of its 40-token lease. Can the coordinator issue 40 replacement tokens to B?

Show answer and explanation

Answer: No within the same window without proving the remaining budget and fencing A. That could admit 140. Stranding uncertain tokens preserves the hard limit at the cost of availability.

Redis atomic rate limiting supports the read/decide/update primitive; the lease protocol here is an application design.

Requirement trace and verification

RequirementImplementing design blockVerification link
R1 — Complete the primary user journey within the stated scope.P01–P04; P09–P10.V1 — Exercise the successful journey and the excluded/boundary case stated in the scope.
R2 — Preserve the problem's authoritative data invariant under concurrency.P05–P06; P11–P12; DD1.V2 — Run the race/replay case below and assert the invariant at the durable authority.
R3 — Meet the declared scale and API behavior without unbounded work.P05–P08; P13–P14; relevant overload deep dives.V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity.
R4 — Recover from the named failure without losing or duplicating the user-visible outcome.P15–P16; deep dives; Operations contract.V4 — Race concurrent consumes at the final token, skew clocks, update rules, and disconnect storage; observed behavior must match the documented policy.

Operational contract

AreaDecision and signals
SLIsDecision p99; allow/deny ratio by policy; bucket cardinality; quota-store errors; fail-open usage.
Overload limitsBound bucket TTL/cardinality, per-key work, local token leases, rule-cache age, and storage concurrency.
RecoveryRestore from rule authority; advance rule versions; apply explicit per-operation fail-open/closed policy during outage.
Access controlsAuthenticate rule changes and bind buckets to trusted principal/scope; prevent caller-controlled quota identity.
Dominant costAtomic storage operations on hot keys and replication of quota state.

Senior-level interviewer follow-ups

Question: What happens to an already approved request if the rate-limit store becomes unavailable?

Show answer and explanation

Answer: Choose and document fail-open or fail-closed by endpoint risk, then bound the fallback with a local emergency budget. Do not present the fallback as globally exact.

Question: How do you prevent region failover from doubling a tenant's quota?

Show answer and explanation

Answer: Use a single quota owner or issue conservative, bounded regional token leases from a global budget. Transfer unused capacity with fencing and accept the consistency/availability trade-off explicitly.

A 60-second design answer

I would define the identity, window, burst behavior, and failure policy before choosing an algorithm. A token bucket updated atomically at the quota owner gives a clear refill and consume decision; hierarchical limits protect both tenant and service. Regional leases can improve availability but must be bounded to avoid double spending. I would observe denials, latency, clock skew, and fallback usage.

Redis API Gateway

Technical references

Redis atomic rate limiting.

PostgreSQL transaction isolation and concurrent updates.

Calculate the token decision atomically

A token bucket has capacity 10, refill 2 tokens/s, and starts full. Spend 7 at t=0: balance 3. At t=1, refill to 5; a request costing 6 is denied. Refill and spend occur in one authoritative atomic operation using a declared time source, with refill capped at capacity.

Contract / pseudocode
t=0: tokens 10 -> spend 7 -> 3
t=1: min(10,3+2)=5
cost 6 -> reject; tokens remain 5
t=0: tokens 10 -> spend 7 -> 3; t=1: min(10,3+2)=5; cost 6 -> reject; tokens remain 5
Calculate the token decision atomically
Read the diagram

t=0: tokens 10 -> spend 7 -> 3; t=1: min(10,3+2)=5; cost 6 -> reject; tokens remain 5

Open original
Calculate the token decision atomically
t=0: tokens 10 -> spend 7 -> 3; t=1: min(10,3+2)=5; cost 6 -> reject; tokens remain 5

Calculate the token decision atomically

Fixed windows can permit a boundary burst from two adjacent allowances. Sliding logs retain individual timestamps and cost memory; sliding counters approximate recent use; token buckets permit bounded bursts while enforcing an average budget. Define user/API/IP scope from trusted context. IP alone can punish shared networks or be spoofed through an untrusted forwarded header.

For a global 100/s limit, two regions each allowing 100/s can permit 200/s. Use a shared owner or fenced sub-budgets with explicit approximation and fail-open/closed policy. Version rules and expire old allowances carefully. Return meaningful 429 guidance, but reserve strong denial for the service's failure/admission contract.

Show answer and explanation

Answer: The last request fails with five tokens, not zero. Denial must not silently spend six unless a different accounting policy is explicitly specified.

Decision review: Rate Limiter

Rate Limiter: What it is

A rate limiter admits or rejects a scoped operation according to a declared budget, time model and request cost.

Rate Limiter: Why it is needed

Finite dependencies need protection and fair access; an admission decision must be atomic when requests share a quota.

Rate Limiter: When to use it

Use a shared authority for a strict aggregate quota. Local budgets can protect availability only with an explicit bound on their combined overshoot.

Rate Limiter: How to use it

For a token bucket, atomically compute elapsed refill, cap at capacity and spend the request cost. Define the clock, identity scope, retry semantics and error response; synchronize the state change rather than merely reading a counter.

Rate Limiter: Compare an alternative

A fixed window is simpler but allows a boundary burst. A token bucket models a refill rate and burst capacity. Neither should be selected without the product meaning of a counted attempt.

Rate Limiter: Worked decision exercise

The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.

A bucket has 4 tokens, capacity 10 and refill 2/s. After one second it has 6. Two simultaneous requests cost 4 each: one leaves 2, the other is rejected. A limit of 10 per fixed window could allow 20 around a boundary.

Rate Limiter: Tokens 4 + one second at 2/s = 6; Atomic request A spends 4: remaining 2; Concurrent request B costs 4: reject; Three local 10/s budgets can total 30/s
Rate Limiter: a concrete state and recovery trace under the exercise assumptions.
Read the diagram

Tokens 4 + one second at 2/s = 6; Atomic request A spends 4: remaining 2; Concurrent request B costs 4: reject; Three local 10/s budgets can total 30/s

Open original
Rate Limiter: worked example
Rate Limiter: Tokens 4 + one second at 2/s = 6; Atomic request A spends 4: remaining 2; Concurrent request B costs 4: reject; Three local 10/s budgets can total 30/s

Rate Limiter: a concrete state and recovery trace under the exercise assumptions.

If three regional emergency limiters each allow 10/s, does the original global 10/s rule still hold?

Show answer and explanation

Answer: Not by those independent limits: their total can reach 30/s. Either divide a bounded emergency allocation, coordinate the strict decision, or explicitly weaken the policy. Decide whether a retried admission reuses a decision ID or represents a newly counted attempt.

Rate Limiter: Check the design

Observe rejects by scope, decision latency, quota overshoot and limiter-outage policy. A reject should not trigger an immediate unbounded retry storm.

Screenshot variant: A local token-bucket library

Clarify whether the budget is per API key, user, IP or endpoint, and whether a burst is allowed. For one process use a token bucket with capacity C and refill rate r tokens/second. For each (caller,endpoint) keep tokens and last-refill time; use a monotonic clock so wall-clock corrections do not create credit. Validate that C and r are positive, and use bounded key storage with safe idle eviction.

Contract / pseudocode
allow(key, now_monotonic):
  atomically within this process for key:
    elapsed = max(0, now_monotonic - last_refill)
    tokens = min(capacity, tokens + elapsed * refill_per_second)
    last_refill = now_monotonic
    if tokens >= 1:
      tokens -= 1
      return allowed
    return denied, retry_after = (1 - tokens) / refill_per_second

The word atomically means a lock, single-thread ownership or equivalent synchronization around both refill and consume. Do not make the check and decrement independent thread-safe operations; that still permits races. A library API can return {allowed, remaining, retryAfterSeconds} and its HTTP adapter maps denial to 429 with an appropriate retry hint.

With C=5 and r=2/s, the first five immediate requests succeed. The sixth is denied with 0.5 seconds of required refill. After 0.25 seconds only half a token exists, so it still fails. After a long idle period, credit is capped at five rather than growing without limit. Test two threads competing for the final token, idle eviction and a clock that does not advance.

This contract is process-local. Four independent application instances each configured for 100/s can permit roughly 400/s collectively, plus configured bursts. A shared global limit requires coordinated state or assigned sub-budgets; the existing distributed lesson explains that extension. Restarting the local process restores its initial bucket state, so document whether that burst reset is acceptable.

Show answer and explanation

Answer: Local enforcement is a good first solution when the requirement is genuinely one process. Monitor accepted/rejected counts and key-map size. On overload, do not allocate an unbounded new bucket for every attacker-supplied key; cap cardinality and expire only safely idle entries.

Deep dive: policy changes must not mint fresh quota

The existing lesson covers an atomic token bucket and shared authority, while its screenshot variant covers a single-process library. This workshop extends them to weighted costs, multiple policy dimensions, retry meaning, state eviction, configuration rollout and partition behavior. A rate decision protects admitted work; it is not proof that the downstream business action completed, and it cannot turn an unsafe retry into an authorized duplicate action.

Define the unit and the charging boundary

Contract choiceMeaningConsequence for retries
Attempt-basedEvery admitted attempt spends its declared costNetwork retries can spend again; state this to callers
Logical-admission basedOne scoped operation/fingerprint has a saved admitted resultAccepted retry resolves that result within its horizon
Completion/billing basedCharge according to a separately defined outcomeNeeds its own reservation/settlement evidence, not just a bucket decrement

Use positive bounded costs in declared units. An endpoint costing three units cannot consume one merely because it is one HTTP request. Bind policy, tenant/caller/resource scope and operation meaning on logical retries; do not trust a client to choose a cheaper cost or another tenant's key. If a prior admitted result is returned again, it cannot authorize multiple independent downstream executions. Couple the business action to its own idempotency/permit-consumption contract.

A denied request may be retried when eligibility changes. This exercise saves admitted logical outcomes but does not permanently cache a denial under the operation key. Rechecking later may allow it after refill. Another API can define a distinct immutable decision-request identity, but must distinguish retrieving an old denial from requesting a new admission decision. A Retry-After estimate is not a reservation of future credit; competing traffic can spend it first.

Refill and all required debits share one decision

Contract / pseudocode
bucket(policy_id, subject, generation, capacity, rate, tokens, last_refill)
admission(scope, operation_key, fingerprint, policy_evidence, cost, result)
policy(version, cost_rule, required_dimensions, partition_behavior)

Under one chosen monotonic/authority time policy, calculate tokens=min(capacity,tokens+rate*elapsed), then compare/subtract the full cost atomically. Protect against backward time and cap long-idle credit. Numeric precision and rounding rules must preserve the units; an implementation should not repeatedly round fractional credit upward and invent tokens.

If tenant and per-user budgets must both admit, check/refill both and debit both in one supported transaction/authority boundary or use an explicitly safe allocation/reservation protocol. Independently decrementing the tenant before discovering the user is exhausted burns tenant credit on a denied operation. Two-phase partial decisions with naive refunds can duplicate credit after retries. If scopes span shards, choose co-location, conservative sub-budgets or a declared approximate/compensated policy; do not claim the local atomic script covers arbitrary cross-shard keys.

A strict token bucket of capacity C and rate r bounds admitted cost over a time interval T by at most C+rT under its stated initial-state/time assumptions. A fixed-window counter has different boundary bursts; configuring both with the same average number does not make their burst contract identical. Multiple independent buckets multiply permitted capacity unless a global authority/allocation policy constrains them.

Roll out a new policy without resetting the bucket full

At time t, the old bucket has one token, capacity five and its refill checkpoint. A policy lowers capacity to two. Settle refill to t under the old policy, carry the resulting credit clamped to the new capacity, then apply the new rate from t. Do not reset the new bucket to two simply because configuration version changed. If the product intentionally grants credit, record it as an explicit policy action with an identity and budget.

Rate policy recovery: bucket has one token under capacity five; policy lowers capacity to two; carry one token rather than refill to two; request cost two is denied; one cost-one request may still be admitted
Configuration version is not a source of free tokens.
Read the diagram

Bucket has one token under capacity five → Policy lowers capacity to two → Carry one token; do not reset to two → A request costing two units is denied → One cost-one request may still be admitted

Open original
Rate Limiter: recovery decision
Rate policy recovery: bucket has one token under capacity five; policy lowers capacity to two; carry one token rather than refill to two; request cost two is denied; one cost-one request may still be admitted

Configuration version is not a source of free tokens.

For old/new clients, the service chooses current trusted cost/rules at the admission boundary. An identical previously admitted operation can resolve its historical receipt without debiting again; it does not receive a new current-policy allowance. Bind accepted fingerprint/meaning and keep enough policy evidence to explain the decision. Non-equivalent payload changes conflict rather than inheriting old admission.

Evicting an empty active bucket and recreating it full mints quota. Retire bucket state only when the declared refill/identity horizon makes recreation equivalent, or recover the remaining balance under a safe authority. Initializing unknown state as empty is conservative but changes availability. Bucket state and accepted-admission receipts may have different retention requirements. Cap attacker-created key cardinality while refusing unsafe resets; bounded memory is not permission to discard active enforcement state.

Choose failure behavior for the protected resource

A shared limiter unavailable during a network partition can fail closed, use still-valid bounded allocations or deliberately fail open under the endpoint's risk policy. A fail-open decision means the original hard quota is no longer enforced; report it as a degraded strategy rather than claiming both strict global limits and unlimited availability. The protected downstream service still needs concurrency, queue and byte budgets even if admission was allowed.

If a strict global allowance is split among regions, rates and burst capacities must fit the total contract, and grant transfer cannot double-spend old valid allocation. State grant validity/clock uncertainty or enforce revocation at a trusted receiver; lack of contact alone does not prove the old grant stopped. Configuration rollout, limiter restarts and failover all need to preserve or conservatively invalidate enforcement state without resetting every node's burst credit.

Limiter assessment: follow the credit and the effect

Question: A policy changes capacity from five to two while one token remains. Should the new bucket start with two tokens automatically?

Show answer and explanation

Answer: No under this policy. Settle elapsed refill at the boundary, then carry credit clamped to the new capacity and use the new rate afterward. A separate explicit grant is different.

Question: Tenant debit succeeded, but the user bucket denied. Is the denied operation's partial debit acceptable under an all-dimensions atomic contract?

Show answer and explanation

Answer: No. Validate all required budgets and commit debits/admission together, or declare a different safe distributed protocol. Blind retry/refund can otherwise lose or duplicate credit.

Question: A logical admission retry returns the saved allowed result. Does that authorize running a non-idempotent downstream operation twice?

Show answer and explanation

Answer: No. Admission receipt resolution and business execution are separate boundaries. Reuse the original business identity or consume the original permit under an enforcing downstream contract.

Score one point for trusted weighted units/charging semantics, atomic required-dimension debit, logical retry versus effect identity, policy/eviction state conservation and honest partition/global-allocation behavior. Compare Transactions and Isolation and Reliability and Overload Control before turning one local bucket into a global service.

22:00Self-guided practice timer
The timer resets when you leave this page. Save your design separately.
Your challenge

One tenant sends through three regions, each with a local cache of the same 100/minute quota. What violation is possible, and how could leased tokens bound it?

Your design draft

Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.

Read study notes

Self-review checklist

Self-guided practice. Automated AI feedback and code execution are not connected.