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.
You want to A/B test a stricter rate limit policy on a small percentage of users. Design the experiment: selection criteria, instrumentation, metrics to measure (churn, errors, support tickets, system load), rollout plan, rollback criteria, and how to interpret correlated signals like recent marketing events.
Sample Answer
The idea in plain words
An A/B test (a controlled experiment) gives a random part of your users the new thing (here a stricter rate limit, a cap on requests per period) and the rest the old thing, then compares what happens to each group at the same time. Randomization is what lets you say the difference was caused by the limit and not by something else that happened that week, such as a marketing push. A rate limit is an unusual thing to test, for three reasons that shape the whole design. Most accounts never reach either limit, so the change touches few of them. The outcome you fear most (customers leaving) is slow and rare. And system load is shared by everyone, so the two groups cannot be separated on it. The plan below is built around those three facts.
Step 1: define the hypothesis and the unit
Hypothesis (example): reducing the default limit from 100 to 60 requests per minute lowers load and cost without a meaningful rise in failures, tickets or churn (customers cancelling). The numbers are an example; the method is the point.
Randomize by account, not by request or user, because the limit belongs to the account's key and several people at one customer share it. Assign deterministically, with a hash of the account id and an experiment name, so an account always sees the same limit. New accounts get their arm from the same hash when they are created, and the stricter limit applies to them only after the 14-day exclusion in Step 2. Record the assignment so it can be audited.
Step 2: selection criteria
- Eligible: self-serve accounts on standard plans.
- Excluded: accounts with a contractual limit or SLA, accounts in their first 14 days (still integrating), and accounts under an open support escalation.
- Stratify (randomize within groups) by plan and by usage band, so treatment and control have the same mix of heavy and light users. For example, if 10 percent of eligible accounts are heavy users, randomize heavy and light accounts separately so each arm gets about 10 percent heavy rather than leaving it to chance.
- Start small: 5 percent of eligible accounts treated, with a same-size control group.
Step 3: shadow mode first, and define who is actually affected
A guardrail metric is one that must not get worse, even though it is not the goal; it can stop the test but it does not decide it. Before anyone is limited, run the new limit in shadow mode: compute, for every account in both groups, whether a request would have been refused under the new limit, without refusing it. This gives an "affected" flag defined identically for treatment and control.
Assumed numbers: 20,000 eligible accounts, so 1,000 treated and 1,000 control. Suppose shadow data shows 6 percent of accounts would exceed the new limit in a normal week. Then 0.06×1,000=60 accounts per group are actually affected. Comparing whole groups dilutes any effect by a factor of 1,000/60≈16.7, so the main comparison is affected-treated against affected-control (60 against 60), with the whole-group comparison reported as a check.
Step 4: instrumentation
Log for every request: account id, experiment arm, applicable limit, decision (allowed, refused, would-have-been-refused), endpoint, response code and latency. Log the client's behaviour after a 429 (whether it waited the Retry-After time or retried at once). Tag support tickets with the account id and a topic so limit-related ones can be counted by arm. Check the sample ratio, the share of accounts that land in each arm compared with the share you assigned. With 1,000 treated and 1,000 control assigned, logs that show 1,000 treated accounts but only 850 control accounts mean the assignment or the logging is broken, and the results cannot be trusted until that is explained.
Step 5: metrics
| Role | Metric | Why |
|---|---|---|
| Primary | Successful-request ratio of affected accounts, and the share of their work completed after a 429 | Fast and sensitive; shows whether integrations survive |
| Customer health | 429 count per affected account; weekly active API accounts; accounts that stop calling | Early sign of breakage |
| Support | Limit-related tickets per affected account | Direct cost to the business |
| Churn | Cancellations over 30 and 60 days | Slow, so a guardrail read later, not a decision metric |
| System load | Admitted requests per second and cost per account | Savings measure |
Why churn cannot decide this. Assume a baseline of 3 percent monthly churn, so p=0.03 is the baseline churn rate in the control group. Two choices fix how sure the test must be. The significance level of 5 percent (two-sided, meaning a difference in either direction counts) caps the chance of declaring an effect when there is none at 5 percent. The power of 80 percent is the chance of detecting a real difference of the size you care about. The constant 2.8 combines the two: it is 1.96+0.84, where 1.96 is the standard normal value that leaves 2.5 percent in each tail and 0.84 is the value that gives 80 percent power. With those choices the smallest difference detectable is about 2.8×2p(1−p)/n, where n is the group size. For 1,000 accounts per group that is 2.8×2×0.03×0.97/1000≈2.1 percentage points; for the 60 affected accounts per group it is about 8.7 points. To detect a 1-point change (d=0.01) solve the same formula for n:
n=d22.82×2p(1−p)=0.00017.84×0.0582=0.00010.4563≈4,563
affected accounts per group. At 6 percent affected that means roughly 4,563/0.06=76,050 accounts per group, far more than exist. So decide on fast, sensitive metrics, and read the churn trend as a guardrail. With only 60 affected accounts per group, a person can also read each affected account's tickets and usage directly.
System load is shared. Treated accounts are only a small slice of traffic, so load measured on the platform will not differ between arms. Measure per-account request volume and cost, then extrapolate to full rollout (for example, the reduction in admitted requests per affected account times the number of accounts that would be affected).
Step 6: rollout plan
- Shadow mode only, two weeks (covers two weekly cycles).
- Treat 1 percent for one week to check logging and the 429 message.
- Treat 5 percent for at least two weeks.
- If the pre-agreed guardrails hold, 25 percent for two weeks, then 50 percent, then everyone.
- Announce the change in the changelog and developer portal before step 3, and make the 429 response say what the limit is and where to request more.
Each stage runs a minimum duration, not "until the number looks good": stopping a test the moment a metric looks favourable inflates false positives.
Step 7: rollback criteria, written before the test
Illustrative thresholds, to be agreed by the team in advance:
- Successful-request ratio of affected-treated falls more than 2 percentage points below affected-control for two days running.
- Limit-related tickets from treated accounts at three times the control rate, once there are at least five tickets.
- Any escalation from a customer with a contract, or any severity incident traced to the limit.
Rollback is a configuration flag keyed to the experiment: setting it restores the old limit for everyone in minutes without a deploy. Test the flag before the experiment starts.
Step 8: interpreting correlated signals such as a marketing event
Suppose a campaign starts in week two and traffic and signups jump. A before/after comparison is ruined by it, which is exactly why you compare treatment with control over the same weeks: both groups see the campaign. Remaining care is needed:
- Mix shift (the population changes composition over time): the campaign adds new accounts. They enter the test only after their 14-day exclusion, so they show up in its later weeks, and the same hash gives them an arm, so the arms stay balanced. They behave unlike older accounts, so report results separately for accounts created before and during the campaign.
- Interaction (the effect differs between kinds of account): a stricter limit may hurt new accounts more than established ones. Treat that as a hypothesis to follow up, not a finding, since it is one of several subgroup looks.
- Load: the campaign raises platform load, so do not read a rise in platform load as an effect of the limit.
- Tickets: campaign signups create tickets of every kind. Compare limit-related tickets by arm, not the total.
- If the campaign is only in one region and assignment was not stratified by region, check balance by region before trusting the comparison.
Common mistakes
- Randomizing requests or users instead of accounts.
- Comparing before and after instead of treatment and control.
- Judging by churn at a sample size that cannot see it.
- Diluting a result by including accounts that never reach the limit.
- No notice to customers, and no way to undo the change quickly.
You are the senior engineer deciding whether to invest in stricter automated rate limiting or invest the same effort into better documentation and SDKs that reduce accidental abuse. Outline how you would evaluate ROI, measure risk, involve stakeholders, and produce a prioritized rollout plan with short-term, medium-term, and long-term actions.
Sample Answer
The short answer
A rate limit is a rule that caps how many requests one caller (usually one API key) may send in a time window, and the server enforces it by answering HTTP 429 Too Many Requests once the cap is hit. Documentation and an SDK (software development kit, the client library you ship so customers do not hand-write HTTP calls) work the other way: they make it less likely that a well-meaning customer sends too many requests in the first place.
These are not substitutes. Docs and SDKs only change the behaviour of customers who read them and use them. A limiter changes the outcome for everyone, including customers who never read anything and the rare caller who is deliberately abusive. So my recommendation is to do both, in a fixed order: measure what the "abuse" actually is, ship the cheap education and visibility first, run the stricter limit in report-only mode before it blocks anyone, and then enforce it gradually. The ROI (return on investment) question is really "which share of our incidents is accidental, and how much of that can an SDK realistically remove?"
How I would evaluate it, in order
1. Classify the problem before choosing the fix. Pull the last quarter of incidents and the top offending keys, and label each as accidental or deliberate. Accidental means a bug or a naive client: a retry loop with no waiting between attempts, polling every second for something that changes hourly, fetching one record at a time instead of in pages. Deliberate means scraping or bulk extraction. The split decides everything: an SDK can fix the first kind and cannot touch the second.
2. Estimate the benefit of each option with the same formula. Expected incidents avoided per quarter = incidents per quarter x share the option can reach x effectiveness on that share. Then divide by effort so the two options are comparable.
3. Measure risk, which is mostly the risk of hurting good customers. Replay the last 30 days of request logs against the proposed limit offline and count which keys would have been throttled. That count is the false-positive risk, and it costs no customer anything to measure.
4. Involve the people who will feel the change (listed below), then sequence the work.
Worked scenario (every input is an assumption for illustration, not a fact about any real company)
Assumed starting facts: 400 paying API customers; 10 incidents last quarter where one key's traffic degraded service for others; each incident cost 12 engineer-hours of on-call and clean-up; the limiter work is estimated at 6 engineer-weeks and the SDK plus docs work at 8 engineer-weeks, at 40 hours per week.
Step 1, classification of the 10 incidents (assumed result of reviewing them): 6 retry loops without backoff, 2 over-aggressive polling, 2 deliberate bulk scraping. Accidental share = (6 + 2) / 10 = 8/10 = 0.8.
Step 2, benefit of the stricter limiter. It sits in front of every caller, so reach = 1.0. Assume it contains the blast radius (stops one key from degrading others) in 80% of incidents, effectiveness 0.8. Avoided = 10 x 1.0 x 0.8 = 8 incidents per quarter. Per engineer-week of effort: 8 / 6 = 1.33.
Step 3, benefit of SDK plus docs. Reach is the accidental share (0.8) times the share of traffic that actually runs through the new SDK after six months, which I assume is 0.5, so reach = 0.8 x 0.5 = 0.4. Assume the SDK's built-in backoff removes 70% of those incidents, effectiveness 0.7. Avoided = 10 x 0.4 x 0.7 = 2.8 incidents per quarter. Per engineer-week: 2.8 / 8 = 0.35.
Step 4, payback in the same unit (engineer-hours). Limiter: 6 x 40 = 240 hours of effort, saving 8 x 12 = 96 hours per quarter, payback 240 / 96 = 2.5 quarters. SDK and docs: 8 x 40 = 320 hours, saving 2.8 x 12 = 33.6 hours per quarter, payback 320 / 33.6 = about 9.5 quarters. On on-call hours alone the limiter wins clearly. The SDK's real value is not in these hours: it is in the customer-side numbers (fewer 429s seen by honest customers, fewer support tickets, faster first successful call), which is why I would not drop it.
Step 5, the risk replay. Assume replaying 30 days of logs against a proposed limit of 600 requests per minute per key shows 22 of 400 keys exceeding it at least once: 22 / 400 = 5.5% of customers. Reading those 22, assume 17 are buggy loops or polling and 5 are legitimate batch jobs. So 5 / 400 = 1.25% of customers are real false positives. Those 5 get contacted before enforcement and are offered a higher plan limit or a larger burst allowance.
Reading the numbers together: the limiter is the better first dollar for protecting the platform; the replay shows it would hurt about 1 customer in 80 if switched on blindly; and an SDK that backs off on 429 is what makes the limiter rarely felt. A limiter without a well-behaved client also has a hidden problem: a client that retries instantly on 429 keeps hammering the limiter, so rejection cost still lands on your servers.
Who to involve and what each owns
- Support: forecasts ticket volume and owns the customer-facing wording of the 429 body.
- Account managers or customer success: know which large customers have bulk jobs and which contracts promise specific limits.
- Sales and legal: any contract or published plan that states a limit or an SLA (service-level agreement, the availability and performance promise to customers) constrains what can change and how much notice is owed.
- SRE (site reliability engineering) and the platform team: capacity numbers, where the limiter runs, and the on-call impact.
- Developer relations or docs: the limits page, backoff guidance, SDK release notes.
- Finance: only if breaches trigger service credits or if limits are tied to paid tiers.
Outcome metrics (the scoreboard I would agree on up front)
- Share of responses that are 429, per plan, and the share of 429s that are followed by another request within one second (a direct measure of naive retry loops).
- Incidents per quarter attributed to a single key degrading others (the headline number).
- Rate-limit-tagged support tickets per week.
- SDK share of total traffic, read from a client identifier header the SDK sends.
- Customer health: churn or downgrades among customers who were throttled, compared with those who were not.
- Time to first successful call for new customers (an education metric).
Prioritized rollout
Short term (days 0 to 30), cheap, reversible, no customer blocked:
- Do the incident classification and the 30-day replay from steps 1 and 5.
- Publish a limits page: the current limits per plan, what a 429 looks like, and how to wait correctly. Make sure every 429 carries a Retry-After header (RFC 9110: seconds to wait, or a date) so clients have an instruction instead of a guess. The RateLimit header fields that advertise remaining quota are an IETF draft rather than a finished standard, and X-RateLimit-* is a common convention, so say in the docs exactly which ones you send.
- Turn on the new limit in report-only mode: log "would have throttled" with the key, but still allow the request.
Medium term (days 30 to 90), enforce softly:
- Release the SDK change: honour Retry-After, use exponential backoff with jitter (a random wait that grows after each failure so many clients do not retry in lockstep), page through large lists, and send a client-version header.
- Contact the 22 replay offenders by name: fix guidance for the 17, a higher limit or burst for the 5.
- Start enforcement for the plan tier with the fewest false positives, with a warning header for one cycle before the first rejection.
Long term (day 90 onward), make it a system:
- Enforce per-plan limits and quotas everywhere, with a self-service dashboard of usage against limit.
- Set a deprecation date for old SDK versions that retry badly.
- Review the limits quarterly against the scoreboard; consider adaptive limits only if the data shows fixed ones cause pain.
Decision triggers, so the plan is not a wish: if the replay shows more than about 5% of customers would be legitimately blocked, raise the limit or add burst before enforcing rather than after; if by day 90 the SDK carries under about 30% of traffic, do not wait for adoption, continue enforcing and put effort into the docs and the 429 body instead. These thresholds are illustrations I chose for this scenario; set yours from your own replay and contracts.
Trade-offs and common mistakes
- Treating it as either-or. The limiter is the guarantee, the SDK is the courtesy; a platform needs the guarantee.
- Enforcing before measuring. Without a replay you learn your false-positive rate from angry customers.
- Counting only on-call hours. They understate value (customer trust, credits) and can make education look worse than it is, as the payback figures above show.
- Ignoring what the limit does to retries. A strict limit with a clients-retry-immediately SDK makes load worse; ship backoff and Retry-After handling together with enforcement.
- Using one global number. Limits per plan and per endpoint cost (a search call costs more than a lookup) cause fewer false positives than one flat figure.
- Forgetting the deliberate 20%. In the scenario, 2 of 10 incidents are deliberate; no amount of documentation affects them, so the limiter must exist regardless.
Consider implementing rate limiting for a public API that experiences bursty traffic. Compare enforcing rate limits at the client SDK level versus at the API gateway (server-side). Discuss trade-offs in enforcement correctness, user experience during bursts, ability to prevent abuse, developer burden, measurement accuracy, and operational complexity. Propose a combined approach and explain how you would monitor and evolve it.
Sample Answer
The idea in plain words
A client SDK (software development kit, the library you give customers to call your API) can count and pace its own requests, and an API gateway (the server-side front door every request passes through) can count and reject them. The key difference is trust: you control the gateway, you do not control what runs on the customer's machine. Anyone can skip your SDK and call the API with curl, so a client-side limit can never be the protection. It is a courtesy that makes bursts smoother. The gateway is the authority. The best design uses both: the gateway enforces, and the SDK reads what the gateway says and paces itself so it rarely hits the limit.
Comparison on the six dimensions asked
| Dimension | Client SDK limit | Gateway limit |
|---|---|---|
| Enforcement correctness | Not enforceable: bypassable, each process counts alone, restarts reset it | Authoritative; all callers counted in one place |
| User experience in a burst | Can queue and smooth, so the caller sees a short delay instead of an error | Rejects with 429 once the burst allowance is spent |
| Abuse prevention | None against a bad actor | The only real defence |
| Developer burden | A library per language to build, test, version and get customers to upgrade | One implementation, but customers must handle 429 |
| Measurement accuracy | Sees only its own process; undercounts a customer running many instances | Sees true totals per key |
| Operational complexity | Many SDK versions in the wild, slow to change | Central config, changed in minutes, but a shared component that must scale |
The combined approach I would ship
- Gateway: a token bucket per API key. The bucket has capacity B (burst) and refill r tokens per second (sustained rate), and a request spends one token. Bursty traffic is the reason to use it: it admits a burst up to B and then enforces r. Reject with 429 (the HTTP status "Too Many Requests") plus
Retry-After(a header giving the seconds to wait before retrying), and send rate limit headers on every response so the client knows its remaining budget. - SDK: on a response, read the limit headers and keep a small local token bucket seeded from them. Queue requests that would exceed the budget instead of sending them, retry 429s after
Retry-After(or, if it is absent, use exponential backoff with jitter: waits that grow, for example 0.5 s, 1 s, 2 s, each randomised so many clients do not retry at the same instant), and cap retries. The server's numbers drive the SDK, so the limit is never hard-coded in the library and changing the plan does not need an SDK release. - The SDK never enforces a stricter limit than the gateway. It paces to the numbers the gateway reports and no lower, so a mismatch (clock drift, or several processes sharing one key) shows up as a gateway 429 that the SDK retries, and never as an SDK that throttles a customer below what they paid for.
What the SDK reads
The widely used (but not standardised) X-RateLimit-* headers are what the SDK reads. An illustrative refusal for the plan below, where one token returns every 0.6 s so the wait rounds up to 1 whole second:
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 1
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1
Content-Length: 78
{"error":"rate_limited","detail":"Limit of 100 requests per minute exceeded."}
Read it line by line: X-RateLimit-Limit: 100 is the plan's requests per minute, so the SDK sets its refill to 100/60≈1.667 tokens per second; X-RateLimit-Remaining: 0 means start the local bucket empty (on a success response showing 17, it would start with 17 tokens); Retry-After: 1 and X-RateLimit-Reset: 1 (seconds until a request is allowed again, as documented for this API) say to pause 1 second. Header names and meanings vary between APIs, so an SDK follows the API's documentation.
Worked example (assumed numbers)
Plan: 100 requests per minute, so r=100/60≈1.667 tokens per second, with burst capacity B=20. A customer's job fires 50 requests at time 0.
- Gateway only: the bucket is full with 20 tokens, so 20 requests are admitted and 50−20=30 are rejected with 429. The customer's code sees 30 errors and must deal with them.
- Gateway plus SDK (one process, nothing else using the key): the SDK sends 20 immediately, queues the other 30, and releases them as tokens return at 1.667 per second. Draining 30 takes 30/1.667=18 seconds (30×0.6, since one token takes 0.6 s). No errors reach the caller, all 50 requests succeed, and the last one finishes about 18 seconds after the first.
The trade-off is visible: the SDK turns errors into delay, which is better for a batch job and may be worse for an interactive call. So the SDK exposes a setting for maximum queue wait, after which it returns the error.
Monitoring and evolving it
Measure at the gateway: 429 rate per key and per SDK version (from a User-Agent or an SDK version header the SDK sets), the share of requests that arrive when the bucket is under 10% full, and retry volume (a rising ratio of retries to first attempts means clients are not pacing). Alert on a sudden jump in 429s for one key (a bug or an attack) and on keys that sit near the limit for days (a candidate for a plan upgrade conversation, which is where a product manager gets signal). Evolve by changing the bucket parameters centrally and letting SDKs adapt via the headers, shipping SDK improvements gradually behind a feature flag (a setting that turns a behaviour on or off without a new release; default off, then on), and keeping a kill switch (a flag that disables the feature at once). The kill switch works through a server hint: a field in a response or in a small configuration document the SDK fetches periodically, defined by the API owner, that tells the SDK to stop its own pacing and just send requests, so a buggy SDK can be turned off remotely.
Failure modes to plan for: an SDK bug that retries without backoff (it multiplies load at the worst time), customers on old SDK versions, and several SDK processes sharing one key, each pacing as if it were alone, which still sums above the limit and is caught only by the gateway.
Common mistakes
Hard-coding the limit in the SDK, treating the SDK limit as security, retrying every error not only 429, and having no metric for which SDK versions generate rejections.
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 a developer portal and documentation features to help API consumers understand and handle limits. Include real-time usage dashboards, examples for handling 429, SDKs with built-in retries, a quota simulator, changelogs, and support pathways. Explain how these tools reduce support load and improve onboarding.
Sample Answer
The idea in plain words
People contact support about limits for three reasons: they do not know what the limits are, they cannot see how close they are, and they do not know what to do when a request is refused. A developer portal is the product surface that answers those three questions before anyone has to ask. A rate limit is a cap on requests per period; the refusal is 429 Too Many Requests (RFC 6585), usually with a Retry-After header (RFC 9110) saying how many seconds to wait. The portal's job is to show usage against the cap, teach the correct reaction to a 429, let a developer test a plan before shipping it, announce changes in advance, and give a clear route to a human when self-service is not enough.
Start from the tickets, not the features
Before designing, list why developers actually write in, and map each reason to a feature. The figures here are assumptions chosen to show the method, not measurements: 1,000 active API keys, 60 limit-related tickets a month, each taking about 15 minutes of support time, split by the shares in the table. A real team would take the shares from its own ticket history.
| Ticket reason (assumed share) | Tickets | Feature that answers it |
|---|---|---|
| "Why am I getting 429s?" (50 percent) | 30 | Usage dashboard, 429 guide, request ID lookup |
| "How do I get a higher limit?" (30 percent) | 18 | Plan page and in-portal increase request |
| "What are the limits?" (20 percent) | 12 | Limits table in docs, quota simulator |
Baseline load: 60×15=900 minutes, which is 15 hours a month. A target such as halving the first row would save 15×15=225 minutes (3.75 hours); it is a hypothesis to test with the measures at the end, not a result.
The features
1. Real-time usage dashboard. Per key and per endpoint: requests in the current window against the limit, time to reset, 429 count over time, and the top endpoints by usage. Feed it from the same counters the gateway enforces with, so what the developer sees is what is enforced; say how fresh it is ("updated every 60 seconds"). Add alerts at 80 and 100 percent of quota by email or by webhook (an HTTP request the platform sends to a URL the developer registers, so their own system is told without polling), so the first notice is not a failure. The 80 percent alert leaves time to act (with a limit of 100 per minute it fires when 80 have been used); the 100 percent alert says the limit has been reached.
What the developer sees, as an illustrative mock-up of one key's dashboard (the numbers are made up and consistent with a limit of 100 requests per minute):
| Endpoint | Requests this minute | Limit | Resets in | 429s in the last hour |
|---|---|---|---|---|
/v1/orders | 82 | 100 | 18 s | 0 |
/v1/search | 100 | 100 | 12 s | 14 |
A banner under the table reads "Data updated 40 seconds ago". "Real-time" here means close enough to the gateway's own counters that the developer can act on it, and the freshness is shown rather than implied. The second row is the one that explains a developer's 429s: it is at 100 percent with a recent history of refusals. The first row is at 82 percent, so its 80 percent alert has already fired. To investigate one failure, the developer pastes the request ID from the error into a lookup box and sees, for example (illustrative): request req_7f3a, endpoint /v1/search, decision rate_limited, remaining 0, window resets in 12 s, which is exactly the information support would otherwise ask for.
2. Examples of handling a 429. Show the actual response and the rules for reacting. An illustrative response for a limit of 100 requests per minute (the X-RateLimit-* names are a widespread convention, not a standard; the IETF RateLimit header fields are still a draft):
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Content-Length: 126
Retry-After: 12
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 12
{"error":{"code":"rate_limited","message":"Limit of 100 requests per minute exceeded for this key.","retry_after_seconds":12}}
Retry-After: 12 means wait 12 seconds before retrying. X-RateLimit-Reset: 12 is, by this API's own definition, the seconds until the window resets. The body repeats the wait in a machine-readable field, and the Content-Length of 126 is the byte length of that body.
The rules the page teaches:
- Never retry immediately. Wait at least
Retry-After. - If the header is missing, use exponential backoff with full jitter: the ceiling on the wait doubles with each failed attempt, and the actual wait is a random time between 0 and that ceiling, min(cap,base×2n) seconds for the nth retry. With base 1 second and cap 60 seconds the ceilings are 2, 4, 8, 16, 32, 60 seconds for retries 1 to 6 (since 26=64 is capped at 60). Jitter prevents many clients retrying at the same instant. One sample draw (random seed 7) shows actual waits, which are never above the ceiling and average half of it over many draws:
import random
random.seed(7)
base, cap = 1, 60
print("retry ceiling sample wait")
for n in range(1, 7):
ceiling = min(cap, base * 2 ** n)
wait = random.uniform(0, ceiling)
print("%5d %7d %9.1f s" % (n, ceiling, wait))
Output:
retry ceiling sample wait
1 2 0.6 s
2 4 0.6 s
3 8 5.2 s
4 16 1.2 s
5 32 17.1 s
6 60 21.9 s
Run it with Python 3.12 (standard library only).
3. Cap the number of retries and the total time spent, then report the failure.
4. Retry a POST only when it carries an idempotency key, a unique value the client generates for one logical operation and sends with the request, so the server can recognise a repeat of the same operation and return the original result instead of creating a duplicate (for example a second order). Without one, a retry after a timeout may repeat a charge or an order that actually succeeded.
5. Reduce demand: batch, cache, and spread work over time instead of just retrying.
3. SDKs with built-in retries. Ship the rules above as defaults: retry on 429 and 503 only, honor Retry-After, add jitter, cap attempts, set an overall deadline, and send an idempotency key automatically on unsafe methods. Expose settings (max retries, hooks that log each retry) and a note in the docs that turning retries off is supported. Developers who use the SDK then handle limits correctly without reading the guide, which removes a whole class of tickets.
4. Quota simulator. A page where a developer enters the planned traffic (burst size, steady rate, endpoints) and sees predicted outcomes against their plan's limit. The limit is modelled as a token bucket: a bucket that holds up to a capacity of tokens and gains tokens at a steady refill rate; each request spends one token, and a request that finds the bucket empty is refused with a 429. The capacity sets the largest burst and the refill rate sets the long-run speed. Example for a plan with a bucket capacity of 10 tokens refilling at 2 per second: a planned burst of 30 requests admits the first 10 and rejects 20. To send all 30 without rejection the client must pace: the missing 20 tokens refill in 20/2=10 seconds. The simulator turns "your limit is 2 per second" into "your batch job needs 10 seconds extra". Offer a sandbox key with a deliberately low limit, so a developer can see a real 429 and test their handler before production.
5. Changelog and notice. Treat limits as part of the contract. Publish every limit change with an effective date and a machine-readable feed. Set a notice policy for decreases (for example 30 days; the length is a business decision) and tell affected keys directly, using usage data to find the ones that would have hit the new limit.
6. Support pathways. Escalate in tiers. Error responses carry a stable error code that links to its docs page and a request ID the developer can paste into a ticket, so support can find the exact call. The dashboard has a "request higher limit" form pre-filled with the key's recent usage, and an auto-approval rule for small increases. A human channel remains for large or unusual requests, and the status page shows incidents that look like limit problems.
How this reduces support load and improves onboarding
Each feature removes a question: the dashboard answers "am I near the limit", the 429 guide and SDK answer "what do I do", the simulator answers "will my plan fit", the changelog answers "what changed", and the request form moves an increase from a thread of emails to a form with the evidence attached. For onboarding, the measurable path is signup, first successful call, first 429 handled correctly, then production traffic; the sandbox and SDK shorten it.
Measure it
Ticket rate per 1,000 active keys, share of 429 tickets answered by a link to the docs, time to first successful call, share of keys that hit 100 percent of quota without having received the 80 percent alert, share of clients that retry correctly (waiting at least the Retry-After value), and time to resolve an increase request. Compare before and after for the same cohort size, and read ticket categories again after each release.
Mistakes
- A dashboard that disagrees with the gateway (different counters, different window) creates more tickets than it saves.
- Docs that give a limit as "100 requests" without the window (per second, minute, day) or the scope (per key, per IP, per endpoint).
- An SDK that retries every failure, including 4xx errors that will never succeed.
- Changing limits without notice and finding out from the support queue.
That is every published Rate Limiting, Throttling and Quota Management question for Technical Product Manager so far. Browse the other topics in this category, or practice this one interactively.