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 throttling and quota enforcement for different subscription tiers (free, pro, enterprise) so higher tiers get higher throughput and burst capacity while preventing abuse. Discuss where enforcement happens (API gateway vs service), storing counters or tokens, metering, overage handling, and reporting to customers.
Sample Answer
The idea in plain words
Two different limits are needed, and tiers set both. A rate limit caps speed (requests per second) and protects the system from spikes; a quota caps volume over a long period (requests per month) and protects the business model. A burst is how many requests may arrive at once before the rate limit bites. Free, pro and enterprise differ in all three numbers. When a limit is hit, the API answers with HTTP status 429 Too Many Requests (the standard "slow down" status) and usually a Retry-After header, which tells the client how many seconds to wait before trying again. A third dimension, cost, matters when some calls are far more expensive than others (an AI model call versus a metadata read): count the quota in cost units, not in raw requests.
My recommendation: the API gateway (the front door that authenticates and applies policies to every request) enforces the cheap, uniform checks early: identify the key, look up its plan, apply the per-key rate limit and the quota check. The service enforces anything that needs knowledge of the work: per-endpoint cost, concurrency caps for expensive operations and priority shedding. Counters live in a shared low-latency store (Redis-style: an in-memory key-value database), while the authoritative usage record for billing and customer reports lives in a durable metering pipeline (the flow that records every billable request as an event, stores it durably and totals it for invoices and dashboards).
Start with the plan table, the gateway checks and the counters; overage handling, abuse controls, reporting and failure modes build on them.
Plan table (assumed numbers for illustration)
| Free | Pro | Enterprise | |
|---|---|---|---|
| Sustained rate | 5 requests/s | 50 requests/s | 500 requests/s |
| Burst (bucket size) | 10 | 200 | 2,000 |
| Monthly quota | 10,000 | 5,000,000 | 200,000,000 (committed) |
| At quota exhaustion | Hard stop, 429 | Overage billed | Alert people, no automatic cut |
| Priority under overload | Lowest | Middle | Highest |
Units in the table: rates are per second, burst is a count of requests, quotas are per 30-day month, and cost units (below) are a weight per call. "Committed" means the customer has contractually agreed to pay for that volume whether or not they use it. The two limits answer different questions, and the arithmetic shows why you need both. A 30-day month has 30 x 86,400 = 2,592,000 seconds. A Free key running at its full 5 requests/s for the month would make 5 x 2,592,000 = 12,960,000 requests, far above its 10,000 quota; the quota is what binds, and the key reaches it after 10,000 / 5 = 2,000 seconds (about 33 minutes) of flat-out use. Pro reaches 5,000,000 after 5,000,000 / 50 = 100,000 seconds (about 27.8 hours). Enterprise reaches 200,000,000 after 200,000,000 / 500 = 400,000 seconds (about 4.6 days). Without the rate limit, a Pro customer could also send all 5,000,000 in a few minutes, which the system may not survive even though the quota allows it.
Enforcement: where and how
Gateway (every request):
- Authenticate the API key and resolve it to an account and plan (cached for a short time, such as 60 seconds, so plan changes take effect quickly).
- Rate check with a token bucket per key. A token bucket is a counter of tokens that refills at a fixed speed up to a maximum: each request takes one token, an empty bucket means refusal, the maximum (capacity) is the burst and the refill speed is the sustained rate. Here capacity = burst and refill = sustained rate. Free: a key sending 12 requests at the same instant gets the first 10 through and 2 refused; the next token arrives after 1 / 5 = 0.2 seconds, and since
Retry-Aftertakes whole seconds the response saysRetry-After: 1. - Quota check against the period counter.
- Emit a usage event.
Service (where cost is known):
- Weighted cost: a standard call costs 1 unit and an expensive-model call costs 20 (assumed). The monthly quota is counted in these units, so 10,000 Free units allow only 10,000 / 20 = 500 expensive calls, which protects the costly resource from a cheap-looking quota. The gateway bucket in step 2 counts requests, not units, because its job is to shield the gateway from spikes; charging a 20-unit call against a Free bucket of capacity 10 would mean a Free key could never make one. To limit how fast expensive calls arrive, use the concurrency cap below or a second, smaller bucket on that endpoint.
- A concurrency cap per account for expensive operations (requests in flight at once), because rate alone does not bound load when each call is slow.
Counters and storage.
- Rate state: one small record per key, updated by one atomic operation (one step that no other request can interleave with: in Redis, a small Lua script, which Redis runs as a single uninterrupted unit, or a single built-in atomic command) so two gateway nodes never read stale state. Cost: a network round trip per request. To cut it, each node can hold a local bucket for the key and reconcile with the shared store periodically, accepting a small overshoot.
- Quota state: a counter per
(account, period), for example the keyquota:acct42:2025-06, incremented atomically. If each gateway node counts locally and flushes (sends its accumulated count to the shared counter) once per second, the other nodes cannot see that last second of traffic. The rate limit lets a Free key through at most its burst plus one second of refill in any second, 10 + 5 = 15 requests, so the count that is not yet visible to the other nodes is bounded by about 15 requests, which is 0.15 percent of a 10,000 quota and acceptable. A node that crashes before its flush loses at most the same amount. Enterprise commits are billed from the durable record, not from the fast counter. - Quota reset. Put the period in the key (calendar month in UTC, or the account's anniversary day, decided in the contract). A new month is a new key, the old key expires after a few days, and nothing needs a midnight job that could fail. State the reset instant in every response so customers are not surprised.
- Metering. Each request writes an event (
account,key,endpoint,cost,status, time) to a queue and from there to durable storage and analytics. Billing and dashboards read this ledger; the fast counters can be rebuilt from it if Redis loses state.
Overage and abuse
- Free: hard stop with 429 and a quota-specific error type, plus an upgrade link in the body.
- Pro: allow overage and bill it. With an assumed overage price of 2 dollars per 1,000 requests, 5,200,000 requests in a month is 200,000 over, which is 200,000 / 1,000 x 2 = 400 dollars. Offer a spend cap the customer sets themselves, because surprise bills cause disputes.
- Enterprise: alert the account owner at 80 percent and 100 percent of the commit and let a human decide; cutting off a contracted customer automatically is usually a worse failure than the overage.
- Noisy neighbour (one tenant's traffic slowing everyone else down on shared capacity): per-key limits stop one key, but a customer can create many keys, so also apply the limit per account, and keep a per-account concurrency cap. Behind that, protect shared capacity with load shedding (deliberately refusing some work so the rest still succeeds): when the system is overloaded, reject the lowest priority tier first and reserve a floor of capacity for Enterprise, so a Free flood cannot starve it.
- Penalties: a client that keeps hammering after 429s ignores
Retry-After. Escalate: after, say, 10 refused requests within a minute, block the key for 1 minute, then 5, then 15, and log it. Keep the penalty short and automatic to avoid locking out a legitimate integration with a bug. - Account farming (many free signups to get many free quotas): per-IP signup limits, email verification and a per-organisation view.
Reporting to customers
- Headers on every response: the limit, what remains and when it resets (the
X-RateLimit-*convention), so clients can pace themselves. - A usage endpoint and a dashboard showing quota used and remaining, the reset date, requests per endpoint, and the count of 429s, read from the metering ledger (it may lag a few minutes, which the dashboard should say).
- Email alerts at 80 and 100 percent of quota.
- Self-service upgrade: changing the plan updates the account record; the gateway's plan cache expires within its 60-second time to live (TTL: how long a cached entry is kept before it must be looked up again), and the new burst and rate apply on the next bucket refresh. Decide whether to keep the current month's used count (usually yes) and grant the new quota pro-rated or in full.
Failure modes and what would change the design
- The counter store is down. Decide per tier between fail open (when the check cannot run, allow the request) and fail closed (refuse it). Fail open for paid tiers (allow, rely on the ledger for billing) and keep a coarse local limit so a store outage does not become an unlimited-traffic outage; failing closed for everyone would turn a limiter outage into a full API outage.
- Plan lookup is stale. A downgrade can take up to the 60-second cache time to apply, which is acceptable; state it.
- If every call costs about the same and there is one region, a plain gateway bucket plus a monthly counter is enough and the service-level cost layer can be dropped.
- If the product is multi-region, a single global monthly counter becomes a cross-region hot spot (one key that every region updates, so it is slow and contended); allocate each region a share of the quota and rebalance, or count regionally and reconcile in the ledger.
Common mistakes
- Using one number for both rate and quota.
- Counting every request as 1 unit when one endpoint is 20 times the cost.
- Resetting quotas with a cron job that can silently miss.
- Letting each key, not each account, carry the limit.
- Billing from the fast counter instead of the durable ledger.
- Returning a bare 429 without a reason or reset time.
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.
Describe trade-offs between enforcing rate limits per API key, per user account, per IP, and per resource. For a public API used by both businesses (server-to-server) and end-users, which combinations would you enforce and why? Consider shared API keys, NAT, privacy, and billing implications.
Sample Answer
The idea in plain words
A rate limit is only as fair as the identity it counts against. Count against something too coarse and one bad caller punishes a crowd; count against something too fine and one abuser simply makes more identities. So the choice is a stack: the most specific identity you can trust for each kind of traffic, with coarse limits as backstops (a backstop is a broad limit that catches whatever the finer limits miss). I would limit by API key for server-to-server customers (and bill on it), by user inside the key for traffic from end users, by IP only for requests that have no identity yet (pre-authentication traffic, sent before the caller has proved who it is), and by resource for operations that are expensive or contended.
What each dimension is good and bad at
| Counted against | Protects against | Fails when | Billing and privacy |
|---|---|---|---|
| API key (a secret string that identifies the calling application or customer) | One customer overloading the service | A key shared by many end users or leaked and used by strangers | The natural billing unit: plan, quota, invoice |
| User account (authenticated person) | One person hogging a customer's allowance | Free accounts are cheap to create in bulk | Personal identifier; keep counters short-lived |
| IP address | Anonymous floods, credential stuffing (trying many leaked username and password pairs) before login | NAT (network address translation: many devices sharing one public IP) punishes innocent users; attackers rotate IPs; spoofed headers | An IP address can be personal data under the privacy laws of some countries and regions (jurisdictions), so confirm with privacy counsel; never a billing basis |
| Resource or endpoint (for example "export", or one record) | Expensive operations and hot spots no matter who calls | Over-tight limits that hurt normal use | Can carry its own price (a cost per call) |
Recommendation for a public API with both business and end-user callers
- Server-to-server business customers: key by API key, which maps to a plan (a per-minute rate limit plus a monthly quota). Issue one key per service or environment so that a noisy batch job cannot starve a customer's checkout service, and so a leaked key can be revoked alone.
- End users of a customer's application: apply two layers, the application's key limit (so one app cannot swamp the platform) and a per-user limit inside it (so one user cannot use up the application's whole allowance).
- Anonymous and pre-authentication traffic (login, signup, password reset): key by IP, with a limit high enough for shared addresses, plus a strict per-account limit on the login itself.
- Resource limits for costly operations, such as 10 exports per hour per account, and a cap on writes to one record.
- A global backstop so no combination of the above can exhaust the service.
A request must pass every applicable layer; the response reports the limit that bound it, so callers can tell which one to fix.
Which identity for which credential
- API key: identifies an application or customer. Key by the key's id (never the secret text in logs). Watch for one key used from an unusual spread of source addresses, a sign it is shared or leaked.
- OAuth access token (OAuth is a standard where a user authorises an application, which receives a token): the token identifies a user and an application. Key by user id and client id, not by the token string, otherwise a client that refreshes its token gets a fresh allowance each time.
- JWT (JSON Web Token, a signed token carrying claims such as the user id
sub, the subject, meaning the user, andclient_id, the application they signed in through): key on claims only after the signature is verified, which means the limiter must run after authentication. An unverified claim can be forged to impersonate someone else's allowance. - Anonymous: IP, with the strictest ceilings and the fewest endpoints.
Worked cases (all numbers assumed)
NAT false positive. An office of 200 employees reaches the API through one public address. A pre-authentication limit of 100 requests per minute per IP leaves 100 / 200 = 0.5 requests per person per minute, so the company is locked out. Raising it to 2,000 per minute gives 2,000 / 200 = 10 per person but also hands a single attacker at that address 2,000 per minute. Resolve it by keeping IP limits only where no identity exists, and moving every authenticated call to key and user limits where NAT is irrelevant. For IPv6, an address is 128 bits long and the /64 prefix is its first 64 bits; one customer is commonly given a whole /64, which holds 2^64 addresses, so an attacker can cheaply switch among billions of addresses inside it. Count the /64 prefix as one identity, so rotating inside the block does not earn a fresh allowance.
Shared key. A mobile app ships one API key to 50,000 users, and the plan allows 600 requests per minute for the key. That is 600 / 50,000 = 0.012 requests per user per minute on average, so a key-level limit alone is meaningless for users: either one heavy user starves the rest or the key is exhausted constantly. The per-user layer, keyed on the signed-in user, fixes it. Such a key is not a secret, so never treat it as proof of identity.
Spoofed forwarding header. A proxy adds the address it saw to X-Forwarded-For (a de facto header: widely used by convention without being formally standardised; Forwarded in RFC 7239 is the standardised form). Illustrative: an attacker at 192.0.2.50 sends X-Forwarded-For: 198.51.100.77; the trusted load balancer appends its peer, so the application receives X-Forwarded-For: 198.51.100.77, 192.0.2.50. If the application reads the leftmost entry it counts the attacker as 198.51.100.77, which the attacker can change on every request to dodge the limit or to get a victim's address blocked. With exactly one trusted proxy, the real client is the rightmost entry, 192.0.2.50. With two trusted proxies in a row it is the second from the right: illustratively, the first proxy appends 192.0.2.50, the second appends the first proxy's address 203.0.113.10, and the application sees X-Forwarded-For: 198.51.100.77, 192.0.2.50, 203.0.113.10, while its own network peer is the second proxy and is not in the header. Walking from the right, skip the entry that is your own first proxy (203.0.113.10); the next entry, 192.0.2.50, is the client address as seen by your outermost proxy and the last one you can trust. Count only entries added by proxies you operate.
Billing, privacy and shared credentials
- Keep billing meters separate from rate-limit counters. Limit counters are approximate and expire in a minute; invoices need durable counts of successful requests. State the policy that refused (429) requests are not billed.
- A customer who resells your API to its own customers should receive sub-keys, so its customers are limited and metered separately.
- For privacy, keep IP-keyed counters only for the length of the window, preferably as a salted hash (a one-way scramble of the address with a secret random value mixed in, so the stored value cannot be turned back into the address by trying every possible address) or a truncated prefix, and avoid logging them.
Common mistakes
- Using IP alone for a public API.
- Trusting the leftmost
X-Forwarded-Forentry. - Keying on the token string instead of the user id.
- Letting a single shared key stand for thousands of people.
That is every published Rate Limiting, Throttling and Quota Management question for Solutions Architect so far. Browse the other topics in this category, or practice this one interactively.