Rate Limiting, Throttling and Quota Management Questions
Protecting API capacity and enforcing fair use: rate-limiting algorithms (token bucket, leaky bucket, fixed/sliding window), per-client, per-tenant and hierarchical quotas, throttling responses (429 semantics, Retry-After, limit headers), and tiered plan enforcement. Covers where to enforce limits (gateway vs. service), distributed counters, concurrency limits, client retry with backoff and jitter, and backpressure, load shedding and graceful degradation under load. Excludes gateway configuration generally, API versioning, authentication mechanics, cache design, and billing and payment pipelines.
Design an API platform that enforces rate limits per API key, per user, and per IP at large scale (100k RPS sustained). Explain architecture components, low-latency enforcement strategies (local cache + Redis), storage choices, sharding/hot keys handling, cross-region limits, telemetry, and how to expose limit info to clients.
Sample Answer
The idea in plain words
A rate limiter caps how many requests an identity (an API key, a user, an IP address) may make in a span of time, and answers "too many" with HTTP status 429. At 100k requests per second (RPS) the design question is not the counting algorithm, it is where the count lives. If every request makes a round trip to a shared store such as Redis (an in-memory key-value database), the store becomes the bottleneck and its latency lands on every request. The insight: decide locally from memory, and use the shared store only to hand out and reclaim budget in batches. The store coordinates; the gateway nodes decide.
The numbers that drive the design are the 100k RPS, the 20 nodes and the 1 ms budget; they set the lease arithmetic below. Leases and the fail-open or fail-closed decision are the core; hot-key splitting, cross-region allowances, soft limits and headers extend them.
Requirements to pin down first (assumptions, stated so the numbers below can be checked)
- 100k RPS sustained, peaks of about 2x (200k RPS), 100k tenants, 3 regions, 50 edge points of presence (POPs, the small proxy sites close to users), about 20 gateway nodes per region.
- The limit decision may add at most 1 ms at p95 (the 95th percentile: 95% of requests are at least that fast) (assumption); a Redis round trip inside a region costs about 1 ms (assumption), which is why it cannot sit on every request.
- Three dimensions: per API key (the paying integration), per user (the end person behind the key), per IP (abuse control before anyone is authenticated).
Components and the request path
- Edge POP: terminates TLS (ends the encrypted connection there, so the proxy can read the request) and applies only the cheap, unauthenticated check: a per-IP limit held in the node's own memory. It sits first because nothing else is known about the caller yet, and it keeps floods away from the authentication step.
- Regional gateway: authenticates the key, then applies the per-key and per-user limits. Each node holds token buckets in local memory. A token bucket has capacity B (the burst it allows) and refills at r tokens per second (the sustained rate); a request spends one token or is rejected.
- Limit store: a Redis Cluster per region, sharded by hash of the counter key (each key name is hashed to pick which shard, one of several servers each holding a share of the keys, owns it). It holds the authoritative budget for each key and each tenant.
- Config service: plans, per-route overrides and per-tenant exceptions. It pushes changes to nodes, and nodes cache them, so 100k tenants do not mean 100k config reads per second.
- Telemetry pipeline: nodes emit counters asynchronously (never inline) to a metrics system.
Order of checks: IP, then key, then user, then route. Cheap and unauthenticated first, expensive and specific last.
Low-latency enforcement: leases from the store
Instead of one Redis operation per request, each node asks the store for a lease: a chunk of tokens it may spend locally without further coordination. Worked example for one hot key (all numbers are assumptions chosen to show the arithmetic):
- The key's limit is r=10,000 requests per second spread over N=20 nodes.
- Nodes sync every T=0.1 s. Each sync tops the node's lease up to L=r×T/N=10,000×0.1/20=50 tokens: it asks the store for 50 minus whatever is still unspent, so a node never holds more than 50.
- Store operations: each node syncs 10 times a second, so 20×10=200 operations per second, against 10,000 if every request went to the store. That is 10,000/200=50 times fewer.
- Worst-case slack: every node could be holding an unspent lease of 50 tokens, so 20×50=1,000 tokens, which is 1,000/10,000=10% of one second of the limit. This is the price of the speed: the limit is approximate by at most one lease per node, and the lease size is the knob. A smaller T is more exact and costs more store traffic.
The node starts that top-up in the background before it runs dry (when under about 20% left), so the request path never waits on the store. Because the top-up asks only for the missing amount, the lease stays at or below 50; asking for a full 50 on top of the 10 tokens left would let a node hold 60 and raise the worst case above to 1,200 tokens, 12%. The store side is one atomic step (a Redis Lua script, which Redis runs without interleaving other commands): read the bucket, add elapsed refill, subtract the grant, write back. Atomicity matters because two nodes asking at once must not both receive the last tokens.
Hot keys and sharding
A hot key is one counter that receives a large share of the traffic, for example one tenant sending 20% of all requests. Because a key lives on exactly one shard, it lands on one Redis shard. Leasing already cuts its store load by the 50 times computed in the lease example. If one shard is still too hot, split the counter into k sub-buckets (key#0 to key#k-1), each with rate r/k, and let each node use the sub-bucket chosen by its node id. Detect hot keys with a periodic top-N count of lease requests per key, and split only those. The cost is that a sub-bucket can be full while another is empty, so a hot key is slightly stricter than its stated limit.
Cross-region limits
A strictly global limit means a cross-region round trip, tens of milliseconds, which breaks the budget. Instead give each region an allowance of the global limit and rebalance it every second or so from observed traffic. Example (assumed): global limit 1,000 per second, traffic shares 60%, 30%, 10%, giving allowances 1,000×0.6=600, 300 and 100, which sum to 1,000. Keep a floor (say 5% of the limit) so a quiet region is not starved when its traffic jumps. During a shift, the global total can overshoot for up to one rebalance interval. Reserve strict global counting for the few things that need it, such as a paid monthly quota.
Soft and hard limits, per-route throttles
- Soft limit: crossing it never rejects. It adds a warning header and a metric, and can notify the customer. Hard limit: crossing it returns 429. Example: soft at 80% of the limit, hard at 100%.
- Per-route throttling: give each route a cost in tokens (a read costs 1, a search 5, an export 20) so one bucket protects the expensive routes. Overrides live in the config service.
When the limit store is degraded
The decision per route class is fail open (allow, because rejecting good traffic is worse) or fail closed (reject, because allowing is worse). I would commit to this: fail open with a local fallback for ordinary reads, where each node enforces r/N from its own memory so the aggregate stays near r; fail closed for login, expensive exports and anything abuse-sensitive. The graceful path under a datastore partition: nodes keep spending their last lease, then drop to the local fallback; tenant config stays cached so a config outage does not remove limits; a default plan applies to tenants not yet cached. Alert on every fail-open decision, because an unseen fail-open turns the limiter off.
What clients see
On every response, headers tell clients where they stand. X-RateLimit-* is a long-used convention, not a standard; the IETF (Internet Engineering Task Force, the body that publishes internet standards) HTTP API working group is developing RateLimit-Policy and RateLimit header fields in an Internet-Draft (a working document, not an RFC, whose syntax has changed between versions, so treat the example as one version of a moving draft). A 429 should carry Retry-After (defined in RFC 9110, the HTTP semantics standard), either as delta-seconds (a whole number of seconds to wait) or an HTTP date. The example uses delta-seconds. Illustrative response:
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 22
RateLimit-Policy: "perminute";q=100;w=60
RateLimit: "perminute";r=0;t=22
Content-Length: 70
{"error":"rate_limited","policy":"perminute","retry_after_seconds":22}
The values use the "structured field" format of HTTP headers: a quoted name, then parameters separated by semicolons. q=100;w=60 means a quota of 100 per 60-second window; r=0;t=22 means none left, with an effective window t of 22 seconds (the time within which the client can use no more than r), which for this simple window limiter is the time until it resets. The body is 70 bytes, matching Content-Length. Use seconds-until-reset, not a timestamp, so client clock skew cannot corrupt it.
Telemetry
Per decision: allowed, limited, degraded (fail-open), lease-refill latency, store error rate, top limited keys, and the gap between enforced and configured limits. Alerts: store errors, any sustained fail-open, a tenant limited above a threshold (a bad client or a plan that is too small).
Common mistakes
- One Redis call per request at this scale. Counting with get-then-set instead of an atomic step. Trusting the client IP header without knowing which proxies are allowed to set it. Treating cross-region as exact. No decision for store failure, so the first Redis incident decides it.
Follow-ups to expect
Why local leases rather than a pure local limit? (A pure local limit multiplies by node count and drifts when nodes scale.) How does autoscaling change the lease size? Recompute L as N changes: going from 20 to 40 nodes at the same T=0.1 s gives L=10,000×0.1/40=25 tokens per sync. Nodes holding an old 50-token lease keep it only until it expires (set the expiry near T, so old leases drain within about one sync interval). For up to one interval the worst case is the 20 old leases of 50 plus 20 new leases of 25, 20×50+20×25=1,500 tokens, which is 15% of one second of the limit. Once the old leases expire it settles at 40×25=1,000, the same 10% as before; store operations double to 40×10=400 per second.
Design a hierarchical quota system that supports per-organization, per-team, and per-user quotas with pooling and delegation. Describe enforcement points, data model for quota accounting, how to aggregate usage, how to handle overages and delegation, and how to surface per-entity usage to billing systems.
Sample Answer
The idea in plain words
A quota is an allowance of some resource (API calls, tokens, gigabytes) over a billing period, such as a month. A hierarchical quota arranges allowances as a tree: an organization has a total, the organization divides it among teams, and teams divide theirs among users. The one rule that makes the tree work is that a request must fit at every level on its path to the root: the user's limit, the team's limit and the organization's limit. Pooling means capacity nobody has claimed can be borrowed by any team. Delegation means a node with unused allowance hands part of it to another node. The design question is how to enforce this quickly on every request, account for it exactly enough to bill, and keep the rules (limits, overrides, delegations) manageable.
Requirements to clarify first
- Is the limit hard (reject at the limit) or soft (allow and bill the excess)? Often it differs per resource.
- Per-period (monthly) quotas, or also short-term rate limits? This design covers the period quota; per-second rate limits sit next to it.
- Are limits per service as well (for example calls to service X versus service Y)? Here yes: a limit is keyed by node and resource.
- How exact must billing be (to the unit, or to within a small tolerance)?
Three decisions carry the design: the effective-limit formula, one atomic check across every level on the path, and an append-only usage ledger as the source of truth for billing. The control plane and data plane split, leases, overage handling and the billing pipeline below are how those decisions are made fast, manageable and exact.
Control plane and data plane
Split the system in two, because they have opposite needs.
- Control plane (administrative path): stores nodes, limits, per-service limits, admin overrides and delegations; computes each node's effective limit; publishes changes. Low traffic, needs strong consistency and an audit trail. If it is down, administrators cannot change quotas, but traffic continues.
- Data plane (request path): the gateways or services that check and consume quota on every request. High traffic, needs microsecond-to-millisecond decisions and must keep working when the control plane is unreachable, using cached limits and pre-granted allowances.
The effective limit of a node for a resource is:
effective=base allocation+active overrides+delegated in−delegated out
Data model
| Table | Key fields | Purpose |
|---|---|---|
quota_node | id, parent_id, kind (org, team, user), path | The tree. A stored path of ancestor ids makes "all ancestors of this user" one lookup. |
quota_limit | node_id, resource (service and unit), period, base_allocation, reserved_min, ceiling, overage_mode (hard, soft, grace) | One row per node per resource. |
quota_override | node_id, resource, extra_units, expires_at, reason, created_by | Admin overrides with expiry and an audit trail. |
quota_delegation | from_node, to_node, resource, units, expires_at | Delegations. |
usage_event | event_id (unique), node path, resource, units, timestamp | Append-only ledger, the source of truth for billing. The unique event_id makes retries idempotent. |
usage_rollup | node_id, resource, period_start, units | Aggregates, one per node and period. |
Enforcement on the request path
For a request of cost c from user u in team t in organization o, admit only if all three hold, then consume at all three levels in one atomic step (one indivisible operation that no other request can interleave with: for example a single Lua script, a short program in the Lua language that Redis runs as one uninterruptible unit, or one database transaction on the path). Atomicity matters: if the user counter is incremented and then the organization check fails, usage leaks.
- User: u.used+c≤u.effective
- Team: t.used+c≤t.effective, or the excess is borrowed from the pool and the pool has enough
- Organization: o.used+c≤o.effective (plus any allowed overage)
The pool is whatever the organization has not allocated: pool=o.effective−∑team allocations−borrowed.
To avoid calling a central store per request, each gateway holds a lease: a chunk of units reserved from the central counter (for example 100 units), spent locally, and renewed when it falls below 20 percent. Because a lease is carved out of the remaining balance, strict limits are never overshot; the cost is stranded capacity (units reserved in a lease but sitting unused where other gateways cannot spend them, at most gateways x lease size). For small quotas use small leases or central checks. For soft limits, plain asynchronous local counters are enough and the overshoot is bounded by what arrives between synchronisations.
Worked example (assumed numbers)
Organization limit: 10,000 units per month. Team allocations: A 4,000, B 3,000, C 1,000, total 8,000, so the pool is 10,000−8,000=2,000. Users in A are each capped at 1,500.
- Borrowing. Late in the month A has used 3,950 and user u2 has used 1,400. u2 sends a request of cost 100. User check: 1,400+100=1,500≤1,500, pass. Team check: 3,950+100=4,050>4,000, excess 50. The pool holds 2,000, so 50 is borrowed and the pool becomes 1,950. Organization (assume 7,200 used): 7,200+100=7,300≤10,000, pass. Admitted.
- Delegation limits. Team A tries to delegate 500 of its own units to B. The most a node can delegate is its allocation minus what it has used and borrowed. A has used 4,050 against 4,000, so nothing remains and the request is refused. This stops delegation being used to hide overuse.
- Delegation that works. C has used 200 of 1,000, so it can delegate up to 1,000−200=800. C delegates 600 to A until month end. A's effective limit becomes 4,000+600=4,600 and C's becomes 1,000−600=400. A's 4,050 now fits inside its own allocation, so the borrowed 50 returns to the pool (2,000 again). Organization total allocation is unchanged.
- Overage and billing. Suppose the month ends with every team at its allocation, A 1,800 units above its original 4,000 and B 1,200 above its 3,000, with no delegation. Organization usage is 8,000+1,800+1,200=11,000, so 1,000 units exceed the limit. With a soft limit and an assumed overage price of USD 2 per 1,000 units, the charge is 1,000/1,000×2=USD 2.00. Attribute it to teams in proportion to their units above allocation: A 1,800/3,000=60%, so USD 1.20; B 40 percent, so USD 0.80. The parts sum to USD 2.00.
Overages, notifications and overrides
- Overage modes per resource: hard (reject with 429 and a clear reason), soft (allow, bill the excess), and grace (allow a bounded excess, for example 10 percent for 24 hours, then hard). Thresholds at 80 and 100 percent notify the team and organization admins.
- Admin overrides raise a limit temporarily with an expiry, a reason and an actor recorded. Cap the sum of overrides unless the override is itself a purchase. An expired override is removed by the control plane publishing the new effective limit, not by a cleanup job alone, so enforcement does not depend on a cron.
- Per-service limits are extra rows for the same node (resource = service plus unit), checked in the same atomic step. A request must pass the service limit and the shared total.
Aggregating usage and surfacing it to billing
- Every consumed request appends a
usage_eventwith a unique event id, the node path, resource and units. - A stream processor (a program that reads a continuous flow of events and updates its results as they arrive) rolls events up per leaf, then up each ancestor using the stored path, into
usage_rollup. - A reconciliation job (a scheduled comparison of two records of the same thing, with a rule for which one wins) compares the data plane's counters with the ledger rollups and corrects drift (lost increments after a crash, for example). The ledger wins.
- At period close, billing reads the rollups per node and resource, plus delegations and overrides in force, after a watermark delay (a deliberate wait after the period ends so that late-arriving events are included; for example 24 hours). Late events after close become an adjustment on the next invoice.
- The invoice is issued to the organization with a per-team and per-user breakdown (showback means showing who used what; chargeback means billing that amount to the team).
Leases and the usage rollup, with numbers
Two small programs-in-one trace the parts the worked example above does not: a lease being spent and renewed, what a lease strands when the balance is low, and how ledger events roll up the tree.
# Leases: gateways spend from a local chunk carved out of the central balance.
class Central:
def __init__(self, balance):
self.balance = balance
def grant(self, want):
got = min(want, self.balance) # a partial grant when little is left
self.balance -= got
return got
class Gateway:
LEASE, RENEW_BELOW = 100, 20 # lease size; renew when under 20 percent
def __init__(self, name, central):
self.name, self.central = name, central
self.units = central.grant(self.LEASE)
def spend(self, cost):
if self.units < cost:
self.units += self.central.grant(self.LEASE) # try one renewal
if self.units < cost:
return False
self.units -= cost
if self.units < self.RENEW_BELOW:
self.units += self.central.grant(self.LEASE)
return True
print("-- plenty left: central balance 1000, 3 gateways")
c = Central(1000)
gws = [Gateway(f"g{i}", c) for i in (1, 2, 3)]
print("after the first leases: central", c.balance, [g.units for g in gws])
for _ in range(17):
gws[0].spend(5) # g1 spends 17 x 5 = 85 units
print("g1 spent 85 and renewed: central", c.balance, "leases", [g.units for g in gws])
print("-- little left: central balance 150")
c = Central(150)
g1, g2, g3 = (Gateway(n, c) for n in ("g1", "g2", "g3"))
print("leases", [g1.units, g2.units, g3.units], "central", c.balance)
print("g3 request of 5 units admitted:", g3.spend(5))
print("units sitting unused in other gateways' leases:", g1.units + g2.units)
# Usage ledger and rollup: event_id makes retries idempotent.
print("-- rollup")
events = [("e1", "o/A/u1", 100), ("e2", "o/A/u2", 50), ("e3", "o/B/u3", 70),
("e2", "o/A/u2", 50), ("e4", "o/A/u1", 30)] # e2 arrives twice (a retry)
seen, rollup = set(), {}
for eid, path, units in events:
if eid in seen:
continue
seen.add(eid)
parts = path.split("/")
for i in range(1, len(parts) + 1): # leaf and every ancestor
node = "/".join(parts[:i])
rollup[node] = rollup.get(node, 0) + units
for node in sorted(rollup):
print(f"{node:8s} {rollup[node]}")
unique_total = 100 + 50 + 70 + 30
assert rollup["o"] == unique_total
print("organization total equals the sum of unique events:", unique_total)
Output:
-- plenty left: central balance 1000, 3 gateways
after the first leases: central 700 [100, 100, 100]
g1 spent 85 and renewed: central 600 leases [115, 100, 100]
-- little left: central balance 150
leases [100, 50, 0] central 0
g3 request of 5 units admitted: False
units sitting unused in other gateways' leases: 150
-- rollup
o 250
o/A 180
o/A/u1 130
o/A/u2 50
o/B 70
o/B/u3 70
organization total equals the sum of unique events: 250
Reading it. With a central balance of 1,000 and a lease of 100, three gateways take 300 and leave 700. Gateway g1 then spends 85 units in 17 requests of 5; when its lease falls to 15, below the 20 percent mark, it renews, so it ends with 115 and the central balance drops to 600. Nothing was checked centrally for those 17 requests. In the low-balance case only 150 units remain: g1 receives 100, g2 receives the last 50 and g3 receives nothing. A request of 5 units at g3 is refused even though g1 and g2 still hold 150 unspent units between them, which is stranded capacity; this is why small quotas use small leases or central checks. In the rollup, event e2 arrives twice, as a retry would deliver it, and the unique event id lets the ledger count it once: user u1 has 100 + 30 = 130, team A has 130 + 50 = 180, and the organization total of 250 equals the sum of the four unique events.
Trade-offs and mistakes
- Counting only at the leaf makes team and organization checks a read-time sum over many rows. Maintain counters at every level.
- Non-atomic multi-level checks over-admit under concurrency.
- Sum of user caps greater than the team allocation is fine and common (it is overcommit: promising more in total than exists, because not everyone uses their full share at once), but state it so users know the team limit binds first.
- Central counter on the hot path adds latency and a single point of failure. Leases fix it at the price of stranded capacity.
- Failure policy when the control plane or counter store is unreachable must be chosen per resource: fail closed (reject when the check cannot be made) for expensive or billed operations, or fail open (admit) with a conservative local cap for cheap ones.
Your ingestion API runs in two regions behind a global load balancer and enforces 1,000 requests per minute per tenant across both. The counter store in one region becomes unreachable. What should the limiter do, how does the answer differ for a login endpoint and a read endpoint, and how do you keep latency low while synchronising counts?
Sample Answer
The idea in plain words
When the shared counter is unreachable, the limiter must still answer every request, and it has three choices: fail open (admit everything), fail closed (refuse everything), or degrade (fall back to a rougher local rule). The right choice depends on what a wrong answer costs. Letting a few extra reads through costs some capacity. Letting extra password guesses through costs security. Refusing legitimate traffic because a helper broke turns a small fault into an outage. So the limiter is not given one global policy; each endpoint gets its own, decided in advance.
Detect the failure without hurting latency
Give every call to the counter store a tight timeout, assumed 20 ms, and wrap it in a circuit breaker (a switch that stops calling a failing dependency for a while). Assume it opens after 5 consecutive failures and probes again after 5 seconds. Without it every request would wait up to 20 ms for a dead store. With it only the first 5 requests pay, 5 x 20 ms = 100 ms in total, and every later request goes straight to the fallback. A single probe request tests the store after 5 seconds; if it answers, calls resume.
The three choices, on numbers
Assumption: tenant limit 1,000 per minute across both regions. Region B's store is unreachable from B's instances; region A's store works. The tenant offers 900 requests per minute in A and 300 in B, 1,200 in total, 200 over the limit. Last known split of its traffic: 75% in A, 25% in B.
| Policy while the store is down | Admitted in A | Admitted in B | Total | Versus limit 1,000 |
|---|---|---|---|---|
| Fail open in B, A unaware | 900 | 300 | 1,200 | 200 over |
| Fail closed in B | 900 | 0 | 900 | 100 under, 300 legitimate requests refused |
| Local slice in B only (25% of 1,000 = 250), A unaware | 900 | 250 | 1,150 | 150 over |
| Local slices in both (A tightens to 75% = 750 once it sees B's sync going stale; B uses 250) | 750 | 250 | 1,000 | exactly at the limit, 200 refused |
Why A is unaware in the first rows: A's counter holds only A's traffic. A can tighten only if it notices that B's sync has gone stale, which is why the sync carries a heartbeat (a periodic "still alive" message).
Inside B, the instances cannot see one another's in-process counters. With 4 instances, each gets 250 / 4 = 62.5, rounded down to 62, so the region admits at most 248. If the load balancer sends one instance 150 of the tenant's requests, it refuses 150 - 62 = 88 although other instances have spare budget. That unevenness is the cost of having no shared state.
Read endpoint
Fail open, with a seatbelt. Reads only consume capacity, and other protections (concurrency limits, which cap how many requests run at the same moment; autoscaling, which adds servers automatically as load rises; and load shedding, which is deliberately dropping excess work under overload) still bound the damage. Refusing reads because the limiter's store is down would punish tenants who did nothing wrong. The seatbelt is a generous local cap, for instance 3x the normal per-instance share, so a runaway client is still stopped.
Login endpoint
Never fail open. The limit protects against password guessing and credential stuffing (trying leaked username and password pairs), so a failed limiter must not mean unlimited attempts. Also key it by account and source address, not by tenant. Assume a limit of 5 failed attempts per minute per account. Fall back to a strict in-process rule: with 4 instances, ceil(5 / 4) = 2 attempts per instance gives at most 4 x 2 = 8 attempts per minute per account if the guesses are spread across all instances, against 5 normally. That is looser by 3 attempts but bounded; fail-open would be unbounded. A legitimate user who mistypes twice on one instance is blocked for the rest of the minute, which is the price. Add a step-up (a captcha or a short delay) for repeated failures during the outage.
Keeping latency low while synchronising
The request path decides only from local state; the cross-region work is asynchronous. Each region increments its own counter, and a background sender ships changed counts to the other region about once per second (staleness T = 1 s, assumed). The overshoot while healthy is bounded by what the other region admits during T. With 900 per minute in A (15 per second) and 300 per minute in B (5 per second), both regions together can admit at most (15 + 5) x 1 s = 20 extra requests, 20 / 1,000 = 2%, before they see each other's counts. A synchronous call across regions (assumed 80 ms) on every request would break any tight latency budget.
Recovery
When the store returns, replay what was admitted during the outage into it as increments, so the window is accurate again. If the total now exceeds 1,000, refuse until the window rolls over. Do not drain region B from the global load balancer merely because its limiter store failed; the fault is in a helper, and moving all traffic would add load elsewhere.
Decision summary
| Endpoint | Store down | Why |
|---|---|---|
| Read | Fail open with a generous local cap | A wrong answer costs capacity, which other layers protect |
| Login | Strict local limit, never open | A wrong answer costs security |
| Ingestion (the stated 1,000 per minute) | Local slice, tighten the other region when its sync goes stale | Keeps the total near the contract without refusing everyone |
Common mistakes
- One global "fail open" or "fail closed" for every endpoint.
- Waiting for the dead store on every request instead of tripping a breaker.
- Forgetting that the healthy region needs to know the other one is silent.
Design tenant isolation and per-tenant rate-limiting for a multi-tenant SaaS platform where tenants are billed based on usage. Discuss per-tenant quotas, burst handling, metering and billing accuracy, noisy neighbor mitigation, shared resource scheduling, and how to attribute cost and usage accurately for billing reconciliation.
Sample Answer
The idea in plain words
A multi-tenant platform serves many customers (tenants) from the same servers. Two things must hold: one tenant's heavy use must not slow the others (tenant isolation, and the tenant that does it is the noisy neighbor), and the usage you bill for must be right. The key insight is that these are two separate systems with different accuracy needs. The limiter protects capacity right now, so it must be fast and may be approximate. The meter produces the numbers on an invoice, so it must be exact, durable and safe against duplicates. Billing from the limiter's counters is the classic mistake. If time is short, lead with three ideas: keep the limiter and the meter separate, give each tenant a token bucket plus a concurrency cap, and deduplicate usage events by ID.
Method: what to clarify, then the design
Clarify first (these change the design): what is billed (requests, or work such as compute time or rows read), whether a quota is a hard stop or a soft limit with overage charges, what tiers exist, whether tenants run synchronous calls (a person waits) or batch jobs, and how late a usage record may arrive before an invoice closes.
Request path, in order:
- Identify the tenant from the authenticated credential (an API key or token claim), never from a field the client can set freely, or one tenant can spend another's allowance.
- Rate limit at the gateway (the entry point that sees every request): a per-tenant token bucket, a counter that refills at a steady rate and allows a burst up to its capacity.
- Schedule shared resources fairly behind the gateway (concurrency caps and weighted queues, below). A weighted queue serves several queues in proportion to their weights, so a weight-4 tenant is served about four times as often as a weight-1 tenant.
- Emit a usage event for each billable outcome, to a durable log, with a unique event ID.
- Aggregate and invoice from deduplicated events, then reconcile against independent records.
Per-tenant quotas and burst handling
Two different limits do two different jobs. A rate limit (requests per second) protects the platform; a quota (units per month) is the commercial entitlement.
Assumed plan (illustrative): sustained rate 100 requests per second, burst capacity 200, included quota 5,000,000 units per month, overage price 0.40 USD per 1,000 units.
- Burst: the bucket starts full at 200 tokens and refills at 100 per second. A tenant sends 300 requests in one instant: 200 are accepted, 100 are rejected. One token takes 1/100 = 0.01 s to refill, and
Retry-Aftercarries whole seconds, so the rejected calls are told 1. - Quota: a tenant that uses 5,300,000 units pays for 300,000 units over quota, which is 300 thousands at 0.40 USD each, 120 USD. A hard quota would instead answer 429 once the 5,000,000 is gone; choose hard for free tiers (no unbounded cost to you) and soft with overage for paid tiers (an invoice is better than an outage for the customer).
- Cost-weighted limits: if a read costs 1 unit and a report-generation call costs 25, a limit of 100 units per second allows 100 reads or 4 reports per second (100 / 25 = 4). Count units of work, not requests, when requests differ in cost.
An illustrative rejection (RFC 6585 defines 429; Retry-After is in RFC 9110; the body follows RFC 9457 problem details, a standard JSON error format served as application/problem+json):
HTTP/1.1 429 Too Many Requests
Retry-After: 1
Content-Type: application/problem+json
Content-Length: 124
{"type":"about:blank","title":"Too Many Requests","status":429,"detail":"Tenant rate limit exceeded. Retry after 1 second."}
Content-Length: 124 is the byte length of that body. Rejected requests are not metered or billed.
Noisy-neighbor mitigation and shared resource scheduling
Rate limits alone do not isolate: 20 tenants each within their limit can still exceed total capacity, and one slow tenant query can hold workers. Layer these:
- Per-tenant concurrency caps: at most N requests of one tenant in flight, so a slow tenant cannot take every worker.
- Weighted fair sharing of a pool: each tenant is assured a minimum share proportional to its weight, and capacity that a tenant leaves idle is lent to busy tenants (work-conserving).
- Bulkheads (named after the sealed compartments of a ship, which keep a leak in one from sinking the rest): separate pools for expensive operations, so reports cannot starve the interactive API.
Worked share (assumed pool of 56 workers, weights by tier: A=4, B=2, C=1, D=1, total weight 8). Minimum shares are 56 x 4/8 = 28, 14, 7, 7 (sum 56). If D is idle, its 7 are lent to the busy tenants in the ratio 4:2:1 (sum 7), so the extra is 4, 2, 1. Busy tenants then get A=32, B=16, C=8, total 56. When D returns it takes its 7 back; nobody was ever below their minimum.
Throttle or queue?
Reject with 429 when a person is waiting and a queue would only convert the problem into a timeout. Queue when the work is asynchronous (batch, exports) and delay is acceptable. A queue must be bounded and per tenant. Size it from the wait you can afford: if a tenant's work drains at 100 per second and its clients time out at 2 seconds, the queue depth should not exceed 100 x 2 = 200, otherwise the last queued requests will have been abandoned by the time they run.
Sharding tenant state
Keep each tenant's limiter state on exactly one shard (one of several store servers that each own part of the data), chosen by hashing the tenant ID (run a hash function on the ID and take the remainder after dividing by the number of shards, so the same tenant always lands on the same shard). That way updating it is a single atomic operation, one step that nothing can interleave with (an increment or a short server-side script). The weakness is a very hot tenant, whose shard takes every request. Example (assumed): ordinary tenants put 1,000 requests per second on a shard, and a tenant sending 4,000 requests per second lands entirely on one shard, which then sees 1,000+4,000=5,000, five times its neighbours. A common remedy is token leasing: each gateway node takes a batch of tokens from the central counter and spends them locally. With batches of 10 tokens and a tenant at 100 requests per second, central calls fall from 100 per second to 10 per second (100 / 10); for the 4,000-per-second tenant above they fall from 4,000 to 4,000/10=400 per second. The cost: tokens held by an idle node are stranded. With 4 nodes holding up to 10 each, at most 40 tokens, which is 40 / 200 = 20% of the burst capacity, can be out of use. Tokens already leased are deducted centrally, so the total never exceeds the limit.
Metering and billing accuracy
- Meter at the point the outcome is known and only billable outcomes (for example successful responses). 429s and platform errors are not billed.
- Every usage event carries
event_id(use the gateway-generated request ID),tenant_id,plan,units, and the event time (when the request happened, not when it was processed). - Delivery from the event log to the aggregator is at-least-once (the log retries until the event is stored, so an event may arrive twice but is not dropped in transit), so the aggregator deduplicates by
event_id. At-least-once says nothing about an event that never reached the log, for example when the gateway crashed after answering and before emitting it; reconciliation below exists to catch that case. - Late events: close an invoice period only after a grace window, for example 24 hours (an assumption), and bill later arrivals on the next invoice as an adjustment.
- Keep the billing counters separate from the limiter's counters. The limiter can lose a few counts on a failover (the switch to a standby copy when the primary fails); the meter cannot.
Cost and usage attribution, and reconciliation
Propagate the tenant ID on every internal call (a request header, or trace baggage: key-value context that distributed tracing carries along with a request across services), so downstream services can emit their own units (database rows read, compute milliseconds) tagged with the tenant. Shared costs with no tenant tag, such as a shared database cluster, are allocated by each tenant's share of the weighted units.
Reconciliation compares independent records: the gateway access log is the record of what happened, the deduplicated meter is the record of what will be billed, and the invoice is derived from the meter. Worked example (assumed numbers): for one day the gateway log shows 1,000,000 billable successes for a tenant. The event stream delivered 1,000,180 events: 300 are duplicates and 120 never reached the log (the emitter crashed after serving those requests), since 1,000,000 - 120 + 300 = 1,000,180. After deduplication the meter holds 1,000,000 - 120 = 999,880 events. The gap is 120 events, 120 / 1,000,000 = 0.012%, which at 0.40 USD per 1,000 units is 120 / 1,000 x 0.40 = 0.048 USD of under-billing. A check that fires on any gap above a small tolerance catches it, and the missing IDs found by diffing the gateway log against the meter are replayed.
Judgment
I would enforce the per-tenant rate limit at the gateway, put concurrency caps and weighted queues in front of the shared pool, and build the meter as a separate event pipeline. Use a hard quota on the free tier and a soft quota with overage on paid tiers. If one tenant is large enough that sharding does not help, give it a dedicated pool of workers with the same code path rather than a separate deployment.
Common mistakes
- Billing from limiter counters, which are approximate and reset.
- Taking the tenant from a client-supplied header.
- A per-tenant rate limit with no concurrency cap, so a few slow requests hold every worker.
- Unbounded queues, which hide overload until every request times out.
- Counting requests when the cost per request varies widely.
Design a distributed rate limiter using Redis clusters for a global API. Discuss algorithm choices (fixed-window with distributed counters, sliding window with sorted sets, token bucket), atomicity (Lua scripts), fairness, latency trade-offs, how to shard keys, and strategies to handle network partitions and clock skew.
Sample Answer
The idea in plain words
A distributed rate limiter enforces one limit across many gateway or application servers by keeping the counters in a shared store instead of in each server's memory. Redis is an in-memory key-value database. Redis Cluster is a set of Redis servers that split the keyspace (all key names) into 16,384 hash slots, buckets that a key name is hashed into, and spread the slots across shards (servers that each own a share of the data); each key lives on exactly one shard, plus its replicas (live copies kept for failover). Two problems follow. Correctness: many servers update the same counter at once, so each update must be atomic (indivisible). Cost: a network round trip to the store on every request adds latency and load, so for a global API (several regions) you must decide how much exactness to trade for speed. The core of a first design is the algorithm choice, the atomic script and the regional split; the sharding, lease, failover and skew notes refine it. My recommendation: a token bucket per key, stored as one small hash and updated by a Lua script in a Redis shard in the same region as the gateway; the global limit split across regions as allocated shares; on store failure fall back to a conservative local limit.
Algorithm choice
| Algorithm | State per key | Atomic update | Use here |
|---|---|---|---|
| Fixed window counter | 1 integer | INCR (add 1 to a number, atomically) is atomic; set the expiry (a time to live, TTL, after which Redis deletes the key) when the result is 1, or use a script so a crash between the two cannot leave a key without a TTL | Coarse abuse limits (per IP per minute). Weakness: up to 2 x L requests can pass across a window boundary |
| Sliding window with sorted set | Up to L timestamps | Needs a script (read, trim, add) | Small exact limits such as login attempts. Memory grows with L |
| Token bucket | 2 numbers (tokens, last update) | Needs a script (read, refill, spend, write) | Per-key API limits: constant memory, explicit burst, easy Retry-After |
The script and its behaviour
Redis runs a Lua script (a small program sent with the EVAL command) as one uninterrupted step, so two gateways cannot read the same old token count. The script below keeps tokens as integer milli-tokens (1 token = 1,000), so for a whole number of tokens per second the refill elapsed_ms x rate is exact integer arithmetic with no floating-point rounding; otherwise a value like 0.999999999 can wrongly deny a request that should pass. A rate that is not a whole number of tokens per second (100 per minute is about 1.67 per second) makes the product fractional, so express it as a whole number per second or choose a finer unit than 1,000 per token. It also ignores a caller whose clock is behind (max(0, now - ts)) and expires an idle bucket after the time it would take to refill completely, because a full bucket is identical to a new one.
-- KEYS[1] = hash holding one bucket
-- ARGV[1] = now in ms, ARGV[2] = refill in tokens per second,
-- ARGV[3] = capacity in tokens, ARGV[4] = cost of this request in tokens
-- Tokens are stored as integer milli-tokens (1 token = 1000), so for a whole
-- number of tokens per second the refill is exact: elapsed_ms * rate.
local now = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cap = tonumber(ARGV[3]) * 1000
local cost = tonumber(ARGV[4]) * 1000
local s = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(s[1])
local ts = tonumber(s[2])
if tokens == nil then
tokens = cap
ts = now
end
local elapsed = math.max(0, now - ts) -- a caller with an older clock adds nothing
tokens = math.min(cap, tokens + elapsed * rate)
local allowed = 0
local wait_ms = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
else
wait_ms = math.ceil((cost - tokens) / rate)
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', math.max(ts, now))
-- once the bucket would be full again it equals a new one, so let it expire
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate) + 1000)
return {allowed, math.floor(tokens / 1000), wait_ms}
Reading the script line by line: HMGET reads the two stored fields (tokens, ts, the time of the last update) from the hash; a missing hash means a new client, so it starts with a full bucket. elapsed is the time since the last update, never negative. The refill line adds elapsed x rate and caps the total at cap. If the bucket holds at least cost it subtracts the cost and sets allowed = 1; otherwise it computes how many milliseconds the missing tokens take to refill. HSET writes the new balance and timestamp back, PEXPIRE sets the idle expiry, and the script returns whether the request passed, the whole tokens left and the wait.
The program below is a line-by-line Python translation of the script (the Lua itself runs inside Redis; the translation lets you check the logic on its own). A plain dictionary stands in for the Redis hash, so HMGET becomes a lookup, HSET an assignment and PEXPIRE a returned expiry time. It replays a burst, then 800 random requests, and compares every reply with an independent reference that uses exact fractions of whole tokens instead of milli-token integers. A last test removes the clock clamp to show that the check can fail.
import math
import random
from fractions import Fraction
RATE, CAP = 5, 10 # 5 tokens per second, the bucket holds 10
def script(store, key, now, cost_tokens=1, clamp=True):
"""Step for step the Lua script. store maps key -> (milli-tokens, timestamp in ms)."""
cap, cost = CAP * 1000, cost_tokens * 1000
state = store.get(key) # HMGET key tokens ts
tokens, ts = state if state else (cap, now)
elapsed = now - ts
if clamp:
elapsed = max(0, elapsed) # a caller with an older clock adds nothing
tokens = min(cap, tokens + elapsed * RATE) # ms x tokens/s = milli-tokens
allowed, wait_ms = 0, 0
if tokens >= cost:
tokens -= cost
allowed = 1
else:
wait_ms = math.ceil((cost - tokens) / RATE)
store[key] = (tokens, max(ts, now)) # HSET key tokens ts
ttl_ms = math.ceil(cap / RATE) + 1000 # PEXPIRE key ttl_ms
return [allowed, math.floor(tokens / 1000), wait_ms], ttl_ms
class Reference:
"""Independent version: exact fractions of whole tokens, no milli-token integers."""
def __init__(self):
self.tokens, self.ts = Fraction(CAP), None
def check(self, now, cost=1):
if self.ts is None:
self.ts = now
self.tokens = min(Fraction(CAP), self.tokens + Fraction(max(0, now - self.ts) * RATE, 1000))
self.ts = max(self.ts, now)
if self.tokens >= cost:
self.tokens -= cost
return [1, math.floor(self.tokens), 0]
return [0, math.floor(self.tokens), math.ceil((cost - self.tokens) * 1000 / RATE)]
store, ref = {}, Reference()
print("burst of 12 at t=0 (capacity 10, 5 tokens/s): [allowed, tokens_left, wait_ms]")
for i in range(12):
got, ttl = script(store, "demo", 0)
assert got == ref.check(0)
if i in (0, 9, 10, 11):
print("request", i + 1, got)
got199, _ = script(store, "demo", 199)
got200, _ = script(store, "demo", 200)
print("t=199:", got199, " t=200:", got200)
print("idle expiry set on every call:", ttl, "ms (capacity / rate + 1 s)")
rng = random.Random(5)
stores, refs = {}, {k: Reference() for k in "xyz"}
t = mism = 0
for i in range(800):
t += rng.choice([0, 0, 5, 20, 100, 300])
k, cost = rng.choice("xyz"), rng.choice([1, 1, 1, 3])
mism += script(stores, k, t, cost)[0] != refs[k].check(t, cost)
print("random trace: 800 requests, 3 keys, costs 1 or 3, mismatches:", mism)
for label, clamp in (("with clamp", True), ("without clamp", False)):
store, ref = {}, Reference()
for _ in range(10):
script(store, "skew", 1000, clamp=clamp)
ref.check(1000)
behind = script(store, "skew", 200, clamp=clamp)[0]
exp_behind = ref.check(200)
ahead = script(store, "skew", 1400, clamp=clamp)[0]
exp_ahead = ref.check(1400)
print(f"{label}: behind by 800 ms (now=200): {behind}, expected {exp_behind}; "
f"ahead by 400 ms (now=1400): {ahead}, expected {exp_ahead}")
Output:
burst of 12 at t=0 (capacity 10, 5 tokens/s): [allowed, tokens_left, wait_ms]
request 1 [1, 9, 0]
request 10 [1, 0, 0]
request 11 [0, 0, 200]
request 12 [0, 0, 200]
t=199: [0, 0, 1] t=200: [1, 0, 0]
idle expiry set on every call: 3000 ms (capacity / rate + 1 s)
random trace: 800 requests, 3 keys, costs 1 or 3, mismatches: 0
with clamp: behind by 800 ms (now=200): [0, 0, 200], expected [0, 0, 200]; ahead by 400 ms (now=1400): [1, 1, 0], expected [1, 1, 0]
without clamp: behind by 800 ms (now=200): [0, -4, 1000], expected [0, 0, 200]; ahead by 400 ms (now=1400): [0, -2, 600], expected [1, 1, 0]
Reading it: capacity 10 and 5 tokens per second. Twelve requests at t = 0 pass 10 and refuse 2; the refused ones are told to wait ceil(1000 / 5) = 200 ms, because one token (1,000 milli-tokens) is needed at 5 milli-tokens per ms. At t = 199 the refill is 199 x 5 = 995 milli-tokens, 5 short, so the wait is 1 ms; at t = 200 it is exactly 1,000 and the request passes. The idle expiry is capacity / rate + 1 s = 10,000 / 5 + 1,000 = 3,000 ms. The random trace (800 requests, 3 keys, costs of 1 or 3 tokens) matched the reference every time. In the skew test a caller whose clock is 800 ms behind gets no refill and one whose clock is 400 ms ahead gets 400 x 5 = 2,000 milli-tokens (2 tokens), spends 1 and leaves 1. Without the max(0, ...) clamp the same calls disagree with the reference (a negative balance and a wrong wait), so the check can fail. The comparison covers one rate, one capacity, supplied timestamps and no concurrency; it does not cover Redis itself, failover, replication lag or simultaneous callers.
Sharding keys
- Name keys by what you limit:
rl:{tenant42}:search. In Redis Cluster, only the text inside{...}is hashed to a slot, so all of one tenant's keys land on one shard and a script can touch several of them (every key in one script call must be in the same slot). - Spread load by having many keys (per tenant, per API key). The dangerous key is a single global counter such as "50,000 requests per second for the whole API": it is one key on one shard and becomes a hot spot. Split it into N sub-buckets (
rl:{global:3}) with each gateway using one, each holding 1/N of the rate, or use leases (below). - Do not use cross-key transactions for limits; they do not scale across slots.
Latency and fewer round trips
Assumed figures for illustration: a round trip to a Redis in the same region costs well under a millisecond, while a trip to another region costs tens of milliseconds. A global API therefore keeps one Redis Cluster per region and enforces the limit locally, and the global allowance is split into regional shares (for example 1,000 requests per second as 400, 300 and 300 for three regions, which sum to 1,000), rebalanced periodically from observed traffic. A customer who spreads traffic evenly across regions is limited exactly; a customer who sends everything to one region is limited to that region's share, so choose shares and rebalancing rules to match the contract.
To cut round trips, a gateway can take a lease (a block of allowance handed out for a short time): ask the store for a block of tokens (say 10) and spend them locally. With 25 requests/s on a gateway this means 25 / 10 = 2.5 store calls per second instead of 25, 10 times fewer. The cost is accuracy: the tokens are removed from the shared bucket when leased, so the long-run rate stays correct, but tokens held and then spent in a rush can exceed the rate briefly. With 4 gateways and leases of 10, at most 4 x 10 = 40 tokens can be outstanding at once, so give leases a short expiry (about a second, an assumed value) and size leases against the burst you can tolerate.
Fairness
Per-key buckets give each client its own allowance, so one client cannot consume another's. A shared global limit does not by itself guarantee that: a heavy client can take the whole global bucket. Put per-tenant limits underneath the global one, and when the system is overloaded shed load by priority instead of first come, first served.
Network partitions, failures and clock skew
- Store unreachable or slow. Give the limiter call a short timeout (a few milliseconds, assumed) and a circuit breaker (a rule that stops calling a failing dependency for a while, so each request does not wait for the timeout). Then pick a fallback per endpoint: fail open (when the check cannot run, allow the request) to a local limit of roughly (global limit / number of gateways) for ordinary reads, so an outage of the limiter does not become an outage of the API; fail closed (refuse the request) for expensive or abuse-prone endpoints such as login or paid model calls. State the decision, because the alternatives differ in cost: failing open risks extra load, failing closed turns a limiter fault into an API outage.
- Partition between regions. Regional shares keep working independently, which is why they are preferred over a single global counter: each region continues within its share and the global total is still bounded by the sum of shares.
- Failover (promoting a replica to replace a failed primary). Replication in Redis is asynchronous (the primary acknowledges a write before the replica has it), so a promoted replica may miss the last few updates and some buckets can roll back to a fuller state. The cost is a bounded extra allowance (at most a bucket's capacity per key), which is usually acceptable for a rate limit, though not for a billing counter.
- Clock skew. If the time comes from the callers, gateways with different clocks disagree. As shown above, a clock ahead by 400 ms hands out 2 extra tokens once at 5 tokens/s, and a clock behind adds nothing. Reading the time from Redis inside the script (
redis.call('TIME')) removes the problem for that shard. The Redis documentation allows this because, since Redis 5.0, scripts replicate by their effects rather than by re-running the script.
Running the code
python token_bucket_model.py
Python 3.12, standard library only (math, random, fractions); the seed and the traces are fixed, so the output is identical on every run.
Common mistakes
- Read-modify-write from the application without a script.
- One global key for a huge limit.
- Cross-region calls on the request path.
- Floating-point token counts that drift.
- No answer for "what if Redis is down?".
- Treating eviction as harmless: if Redis evicts an active client's bucket, that client gets a fresh full bucket.
Unlock Full Question Bank
Get access to all 9 Rate Limiting, Throttling and Quota Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.