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.
Implement a rate-limited wrapper in JavaScript:
function rateLimit(fn, maxCalls, perMilliseconds)
The wrapper should return a function that ensures fn is invoked at most maxCalls times per perMilliseconds window. Calls beyond the limit must be queued and executed as capacity becomes available. Preserve this and arguments for fn. Provide a browser-friendly implementation and discuss trade-offs between sliding-window and token-bucket approaches.
Sample Answer
The idea in plain words
The wrapper must remember when the last few calls started (a short log of start times, which is the simplest form of a "sliding window": the span of the most recent perMilliseconds, moving forward with the clock). When a new call arrives and fewer than maxCalls started inside the last perMilliseconds, run it now; otherwise put it in a first-in-first-out queue (a line where the earliest waiter goes first) and set one timer for the moment the oldest recorded start falls out of the window. Because a queued call cannot return its result synchronously, the wrapper returns a Promise (an object that later delivers the result or the error), so callers use await or .then.
Design decisions
- State:
starts, the start times of the latest calls (at mostmaxCallsof them), andqueue, the waiting calls. Each queued item storesthis, the arguments, and theresolve/rejectfunctions of its Promise. - Preserving
thisand arguments: the returned function is a regularfunction(an arrow function would not receive the caller'sthis), collects...args, and later runsfn.apply(job.self, job.args). - One timer, not one per call: when the queue is non-empty and the window is full, schedule a single
drainforstarts[0] + perMilliseconds - now, the moment the oldest start expires.drainre-reads the clock, so if a browser fires the timer late (background tabs can delay timers) the queue simply drains late, never early. - Clock:
performance.now()is a monotonic clock (it does not jump when the user changes the system time, unlikeDate.now()). The code takes an optionalenvobject so a test can supply a simulated clock and timer. - Errors: if
fnthrows or returns a rejected Promise, only that call's Promise rejects; the queue keeps draining.
The listing contains the function and a deterministic test: 7 calls at time 0 with maxCalls = 3 and perMilliseconds = 1000, then an 8th call after a long idle gap. The assertions fail if the function is changed to admit a fourth call per window.
const assert = require("node:assert");
// Sliding-window limiter: at most maxCalls invocations start in any
// perMilliseconds span. Extra calls wait in a FIFO queue.
// env is optional and lets a test replace the clock and the timer.
function rateLimit(fn, maxCalls, perMilliseconds, env = {}) {
if (!Number.isInteger(maxCalls) || maxCalls < 1) {
throw new RangeError("maxCalls must be a positive integer");
}
if (!(perMilliseconds > 0)) {
throw new RangeError("perMilliseconds must be positive");
}
const now = env.now || (() => performance.now()); // monotonic in browsers and Node
const schedule = env.setTimeout || ((f, ms) => setTimeout(f, ms));
const starts = []; // start times of the latest calls, oldest first (length <= maxCalls)
const queue = []; // waiting calls: { self, args, resolve, reject }
let timerPending = false;
function drain() {
timerPending = false;
const t = now();
while (starts.length > 0 && starts[0] <= t - perMilliseconds) starts.shift();
while (queue.length > 0 && starts.length < maxCalls) {
const job = queue.shift();
starts.push(t);
try {
job.resolve(fn.apply(job.self, job.args)); // keeps this and arguments
} catch (err) {
job.reject(err);
}
}
if (queue.length > 0 && !timerPending) {
timerPending = true;
schedule(drain, starts[0] + perMilliseconds - t); // when the oldest start expires
}
}
return function limited(...args) {
return new Promise((resolve, reject) => {
queue.push({ self: this, args, resolve, reject });
if (!timerPending) drain();
});
};
}
// Test harness: simulated time, no real waiting.
function makeFakeTime() {
const f = { t: 0, timers: [] };
f.env = {
now: () => f.t,
setTimeout: (cb, ms) => {
f.timers.push({ at: f.t + ms, cb });
f.timers.sort((a, b) => a.at - b.at);
},
};
f.runAll = () => {
while (f.timers.length > 0) {
const next = f.timers.shift();
f.t = next.at;
next.cb();
}
};
return f;
}
async function main() {
const fake = makeFakeTime();
const log = [];
const api = {
name: "api",
send(x) { log.push([fake.t, this.name, x]); return x * 10; },
};
api.send = rateLimit(api.send, 3, 1000, fake.env);
const results = [1, 2, 3, 4, 5, 6, 7].map((x) => api.send(x)); // 7 calls at t = 0
fake.runAll();
fake.t = 4500; // idle for a while: no leftover debt
const late = api.send(8);
fake.runAll();
console.log("start times (ms):", log.map((e) => e[0]).join(" "));
console.log("this preserved:", log.every((e) => e[1] === "api"));
console.log("resolved values:", (await Promise.all([...results, late])).join(" "));
assert.deepStrictEqual(log.map((e) => e[0]), [0, 0, 0, 1000, 1000, 1000, 2000, 4500]);
assert.deepStrictEqual(log.map((e) => e[2]), [1, 2, 3, 4, 5, 6, 7, 8]); // FIFO order
// For every start, at most 3 starts fall in the window (start - 1000, start].
for (const [s] of log) {
assert.ok(log.filter(([u]) => u > s - 1000 && u <= s).length <= 3);
}
console.log("assertions passed");
}
main();
Expected output (simulated time, so the same on every run):
start times (ms): 0 0 0 1000 1000 1000 2000 4500
this preserved: true
resolved values: 10 20 30 40 50 60 70 80
assertions passed
Reading the output: calls 1 to 3 start at 0; calls 4 to 6 wait until the first start expires at 0 + 1000 = 1000 ms; call 7 waits until those three starts expire at 1000 + 1000 = 2000 ms; call 8 arrives at 4500 ms when nothing is recent and starts immediately. In every 1000 ms window at most 3 calls start, this is the original object (api), and results come back in call order (10 to 80).
Sliding window versus token bucket
| Sliding window (as implemented) | Token bucket | |
|---|---|---|
| Rule | At most maxCalls starts in any span of perMilliseconds | Capacity C tokens, one token refilled every perMilliseconds / maxCalls ms; a call spends a token |
| State | Up to maxCalls timestamps | Two numbers (tokens, last refill time) |
| Burst | maxCalls at once, then a pause | Same burst if C = maxCalls, but then it refills continuously |
| Smoothing | Calls bunch up at window expiry (1000, 1000, 1000 above) | Spreads waiting calls evenly |
| Guarantee | Hard cap per window: no span that counts only one of its ends holds more than maxCalls starts | At most C + (rate x T) in any span of length T: the capacity plus the tokens that refill during T |
Using the same 7 calls: a token bucket with C = 3 and a refill of 3 tokens per 1000 ms adds one token every 1000 / 3 = 333.3 ms, so calls 4 to 7 start at 333.3, 666.7, 1000 and 1333.3 ms. The last of the seven starts at 1333.3 ms instead of 2000 ms, which means the queue empties sooner. The price is a weaker per-span cap. Counting both ends of a 1000 ms span, the bucket can admit 3 + 3 = 6 starts (at 0, 0, 0, 333.3, 666.7 and 1000 ms), and even counting only one end it can admit 5 (after a quiet period, starts at 1, 1, 1, 334.3 and 667.7 ms), where the window version never puts more than 3 in a span that counts one end. So: if the other side states a hard "N per window" limit and counts strictly, use the sliding window; if you are smoothing UI work or the other side measures an average rate, the token bucket drains faster and needs less memory.
Browser-specific points
- Each tab has its own limiter instance. Several tabs, or several workers, each get their own allowance, so a server-wide limit needs a shared coordinator (one place that all tabs ask before calling: for example a service worker, a script the browser runs in the background for the whole site, or messages sent between tabs with a
BroadcastChannel, a browser feature for tabs of the same site to talk to each other) or enforcement on the server. - An unbounded queue is a memory leak if callers outpace the rate; offer a maximum queue length and reject or drop the oldest when it is hit, and expose a way to cancel pending items when a component unmounts (is removed from the page, so nobody is waiting for its result any more).
- Client-side limiting is a courtesy and a cost saver. The server still enforces its own limit and may answer 429 (Too Many Requests, the standard "slow down" status), often with a
Retry-Afterheader saying how many seconds to wait; the wrapper does not replace handling that response.
Running the code
node rate_limit_demo.js
Node.js 24 (node:assert and the global performance). The rateLimit function itself uses only performance.now, setTimeout and Promises, so it runs unchanged in a browser module; the require line and the test are Node-only.
Your application depends on a third-party analytics API that enforces rate limits, and a dashboard calls it on every page load. How would you design the data access pattern so users still get useful data when limits are hit? Cover caching, batching and fallbacks.
Sample Answer
The idea in plain words
A rate limit is a cap a provider puts on how many requests your key may make per period; past it you get 429 Too Many Requests (RFC 6585), often with a Retry-After header saying how long to wait. If every dashboard page load calls the provider directly, your traffic is set by how many people open the page, which you do not control. The fix is to cut that link: users read from your own store, and a small controlled component refreshes that store from the provider at a rate you choose. The user-facing request never waits on, or fails because of, the provider's limit.
Assumptions for the worked example
These are assumptions, not facts about any real provider.
- The provider allows 60 requests per minute for our one API key, shared by all our customers (tenants).
- We serve 50 tenants, each dashboard has 12 widgets, and the provider has an endpoint that returns up to 4 widgets' metrics in one call, so a full refresh of one tenant is 12/4=3 calls.
- The provider's data changes at most every 15 minutes.
- Peak traffic is 200 dashboard page loads per minute across all tenants.
What the naive design costs
Calling the provider per widget per page load: 200×12=2400 calls per minute, and 2400/60=40, so the key is asked for 40 times what it may give. Most widgets fail at peak, and retries make it worse.
The design, in the order a request travels
- Browser to your dashboard API only. The page never calls the provider. It reads the latest stored values for the tenant.
- Cache lookup (an in-memory store such as Redis, plus a durable copy in your own database). Each entry holds the data, the time it was fetched (
as_of), and a freshness time-to-live (TTL, how long the entry counts as fresh). Add a random 10 percent to each TTL so entries for different tenants do not all expire in the same second. - On a miss or an expired entry, one refresh per key. Concurrent requests for the same tenant wait on a single in-flight refresh instead of each calling the provider (called request coalescing or single-flight: one real fetch, many waiting callers; the trace below counts it). Without it, 30 users opening the same dashboard at once make 30 identical calls.
- Batching. Fetch the 4-widgets-per-call group, so a tenant refresh is 3 calls rather than 12.
- A shared outbound limiter in front of the provider. All instances of your service take permits from one token bucket (a counter of permits that refills at a steady rate, where an empty bucket means wait). Size it below the provider's cap: 80 percent of 60 is 48 calls per minute, which is 0.8 per second, with a capacity of 6 so one tenant refresh (3 calls) goes straight through. The 12 calls per minute you leave unused is room for retries and manual refreshes.
- React to a 429 anyway. Honor
Retry-After, pause the whole outbound limiter for that long, and use a circuit breaker (a switch that stops calls to a failing dependency for a cooling-off period) so a provider incident does not turn into a flood of retries. For example (assumed settings), after 5 refused or failed calls in a row the breaker opens for 30 seconds, during which every dashboard read is served from the cache with zero provider calls; then one trial call goes out, and the breaker closes if it succeeds. - Refresh by schedule, not by demand, for tenants who have had a viewer recently, and have a viewer's request only mark a cold tenant as wanted.
Budget arithmetic with the numbers above
The calls per minute needed to keep every tenant fresh is tenants×calls per refresh÷TTL in minutes.
| Design | Calculation | Calls per minute | Fits 48? |
|---|---|---|---|
| Per-widget, TTL 5 min | 50 x 12 / 5 | 120 | no |
| Per-widget, TTL 15 min | 50 x 12 / 15 | 40 | yes, little headroom |
| Batched, TTL 5 min | 50 x 3 / 5 | 30 | yes, 18 spare |
| Batched, TTL 15 min | 50 x 3 / 15 | 10 | yes, 38 spare |
Recommendation: batched with a 5 minute TTL (30 calls per minute). It is well inside the 48 call ceiling, and since the provider's data changes at most every 15 minutes, a 5 minute TTL keeps data about 5 minutes behind the provider at worst (a little more with the TTL jitter and the refresh time). If the data were hourly, a 15 minute TTL would be the better choice and would free budget for more tenants. Page loads then cost zero provider calls: 200 loads per minute are 200 cache reads.
Starting with an empty cache, warming all tenants takes 50×3=150 calls, and 150/48=3.125 minutes at the limiter's rate, so order the warm-up by who has a viewer now.
Tracing the outbound limiter and single-flight
Four tenants ask for a refresh at the same instant, each needing 3 calls, against the bucket of capacity 6 and 0.8 tokens per second (one token every 1.25 seconds). The program also counts provider calls when 30 viewers open one tenant's dashboard together.
# Outbound limiter from the design: capacity 6, refill 0.8 tokens per second.
# Integer micro-tokens and milliseconds, simulated time only.
TOKEN = 1_000_000
CAP, RATE_PER_MS = 6 * TOKEN, 800 # 0.8 tokens/s = 800 micro-tokens per ms
class Limiter:
def __init__(self):
self.tokens, self.last = CAP, 0
def acquire(self, asked_at):
"""Return the time (ms) at which a call asked for at asked_at may go out."""
now = max(asked_at, self.last)
self.tokens = min(CAP, self.tokens + (now - self.last) * RATE_PER_MS)
self.last = now
if self.tokens < TOKEN:
wait = -(-(TOKEN - self.tokens) // RATE_PER_MS) # ceiling division
self.last += wait
self.tokens += wait * RATE_PER_MS
self.tokens -= TOKEN
return self.last
lim = Limiter()
for tenant in ("t1", "t2", "t3", "t4"): # all four ask at time 0
print(tenant, "3 calls go out at ms:", [lim.acquire(0) for _ in range(3)])
# Single-flight: viewers who arrive while a refresh is in flight share it.
in_flight, provider_calls = {}, 0
def get_dashboard(tenant):
global provider_calls
if tenant not in in_flight: # first viewer starts the refresh
in_flight[tenant] = True
provider_calls += 3 # 3 batched calls per refresh
return "waits on the shared refresh"
for _ in range(30):
get_dashboard("t1")
print("30 viewers of one tenant at once -> provider calls:", provider_calls, "(without single-flight:", 30 * 3, ")")
Output:
t1 3 calls go out at ms: [0, 0, 0]
t2 3 calls go out at ms: [0, 0, 0]
t3 3 calls go out at ms: [1250, 2500, 3750]
t4 3 calls go out at ms: [5000, 6250, 7500]
30 viewers of one tenant at once -> provider calls: 3 (without single-flight: 90 )
Reading it: the bucket starts with its 6 tokens, so tenant t1 (3 calls) and tenant t2 (3 calls) go out at once and leave it empty, which is why a capacity of 6 lets one tenant refresh straight through and a second one right behind it. Tenant t3 then waits for tokens that arrive every 1.25 s, so its calls go out at 1250, 2500 and 3750 ms, and t4 follows at 5000, 6250 and 7500 ms. Even a burst of four tenants therefore never sends more than the bucket allows, and the last one finishes in 7.5 seconds. In the second test, the first viewer starts the refresh and the other 29 find it already in flight, so the provider sees 3 calls instead of 30 x 3 = 90.
Fallbacks when limits are hit
Walk down this ladder; each step is a worse but still useful answer.
- Fresh cache entry: serve it.
- Stale entry: serve it and say so. The HTTP caching extensions
stale-while-revalidateandstale-if-error(RFC 5861) describe the same idea at the HTTP layer: serve old data while refreshing, or when the origin errors. For example,Cache-Control: max-age=300, stale-if-error=21600says a response is fresh for 5 minutes and may still be served for up to 6 hours past that if the origin returns an error. Allow stale data up to a limit that matches the business (for example 6 hours), and show "data as of 14:05" in the widget. - Your own snapshot store (the last good daily or hourly rollup) for a tenant whose cache has been evicted.
- Per-widget empty state with a short explanation and a retry time, never a blank page or a spinner that never ends. Widgets fail independently.
An illustrative response from your own dashboard API during a provider throttle (field names are this design's, not a standard):
{
"tenant": "t-17",
"widgets": [
{"id": "signups", "value": 412, "as_of": "2026-03-02T14:05:00Z", "stale": true},
{"id": "funnel", "value": null, "state": "unavailable", "retry_after_s": 120}
]
}
The HTTP status is 200 because the dashboard did produce a useful answer; the staleness is in the payload where the UI can use it. A provider 429 is not forwarded to the browser, since the user cannot act on it.
Trade-offs and mistakes
- Fresher data costs budget linearly. Halving the TTL doubles the calls per minute. Pick the TTL from how fast the provider's data actually changes, not from a feeling.
- Per-user live refresh buttons are a leak in the design. Route them through the same limiter, allow one per tenant per minute, and show the cooldown.
- Caching per user instead of per tenant multiplies provider calls by the number of users for identical data.
- Retrying inside the request path makes the user wait out the provider's limit. Retry in the background.
- Letting each service instance rate-limit itself gives N times the intended rate. The limiter must be shared, or each instance given 48/N calls per minute.
- Caching errors forever. Cache a failure for a short time only (for example 30 seconds) so a recovered provider is used again.
- If the provider offers webhooks (HTTP calls it makes to you when data changes), use them to refresh entries and keep polling only as a safety net.
As a platform owner, design SDK features and primitives that surface rate limit information and help client applications behave politely. Include automatic backoff strategies, callbacks or events developers can subscribe to, transparent retries for idempotent calls, and a small diagnostics API to inspect current quotas. Explain language-specific considerations for concurrency.
Sample Answer
The idea in plain words
An SDK (software development kit, the client library customers install to call your API) is the place where rate limits are either handled politely or turned into outages. If every SDK retries instantly on a 429 (HTTP "Too Many Requests"), the SDKs together become a retry storm that makes the overload worse. So as platform owner I would build the polite behaviour INTO the SDK by default, make it observable, and let developers turn parts of it off. The central idea: the SDK reads what the server says (Retry-After, remaining quota), waits that long plus a little random delay, retries only when retrying is safe, and gives up cleanly before it wastes the caller's time.
The five pieces
- Rate-limit state parsed from every response:
Retry-After(seconds or an HTTP date) and, if the API sends them,X-RateLimit-Limit/Remaining/Reset(a common convention, not a standard). Stored per credential, because limits belong to a key or account, not to a client object. - Retry policy. Retry on 429 for every method (the next section says why that is safe), and on 503, other 5xx responses, timeouts and connection errors only for calls that are safe to repeat. Wait time: if
Retry-Afterexists use it, plus a small random addition; otherwise exponential backoff with full jitter: wait a random time between 0 andmin(cap, base x 2^k)for retry numberk(0-based). Jitter (randomness) matters because thousands of clients that failed together would otherwise retry together. A retry limit caps the number of retries for one call (a count) and an overall deadline (time), so a call cannot spin forever; a separate retry budget, described below, caps retries across all calls. - Client-side pacing. A shared token bucket per credential per process, filled from the server's stated limit, so concurrent calls queue briefly instead of all being fired and rejected. The server's 429 stays the source of truth; local pacing only avoids wasteful rejections.
- Events (callbacks).
onRateLimited,onRetry,onQuotaLow(threshold), each receiving a small object: endpoint, attempt number, wait milliseconds, scope, remaining. Callbacks must not block or throw into the request path: the SDK catches and logs their errors, and never runs them while holding its internal lock. - Diagnostics API.
client.rateLimits.snapshot()returns, from the latest responses,limit,remaining,resetsInSeconds,observedAt,queuedCalls,retriesLastMinute,throttledUntil. Support engineers can then ask a customer for one printed object instead of guessing.
Safe retries: which calls may be repeated
- A 429 is retried for every method, but only because I own the server and can promise that a 429 is returned BEFORE any side effect. State that promise in the docs. A third-party API without that promise needs the stricter rule below.
- After a timeout or a 5xx, the SDK cannot know whether the server did the work. Repeating is safe only for idempotent calls (repeating gives the same end state: GET, PUT, DELETE) or when the caller supplied an idempotency key (a unique value sent with the request so the server returns the first result instead of acting twice). So
POSTwithout a key is not retried after a timeout; with a key it is, and the SDK reuses the SAME key on every attempt. An SDK should generate a key for unsafe calls if the API supports one.
Worked example (assumed settings: base 500 ms, cap 8000 ms, 5 retries, deadline 20 s)
Delay ceiling per retry, min(8000, 500 x 2^k):
- k = 0: 500, k = 1: 1000, k = 2: 2000, k = 3: 4000, k = 4: 8000 (500 x 16 = 8000 reaches the cap).
- Each real delay is a random value between 0 and its ceiling; the worst case if every draw is the maximum is
500 + 1000 + 2000 + 4000 + 8000 = 15,500ms, under the 20 s deadline.
Trace 1: POST /orders with key k-123 gets 429 with Retry-After: 3. The SDK waits 3000 ms plus up to 10% random addition (assumption), 0 to 300 ms, resends with the same key, and receives 201. The caller saw one slower call and the onRetry event fired once.
Trace 2: a 429 with Retry-After: 30 arrives when the remaining deadline is 20 s. Sleeping 30 s would overrun the deadline, so the SDK fails immediately with a RateLimitError carrying retryAfter = 30 instead of sleeping uselessly.
Trace 3: a POST with no idempotency key times out. The SDK does not retry (the order may exist) and raises a timeout error that says so.
The herd effect, by arithmetic: 1,000 clients told Retry-After: 3 that all retry exactly at 3.000 s send 1,000 requests in the same instant. Spread over a 300 ms addition they arrive at about 1000 / 300 = 3.3 per millisecond on average.
Retries multiply load: a call with up to 5 retries can send 6 requests, up to 6 times the offered load during an overload. So add the retry budget: allow retries only while they are at most about 10% of recent requests per client (an assumption to tune); with 100 calls in the window that is at most 10 retries, after which calls fail fast. The program below runs the arithmetic: 100 calls that are all refused send 600 requests without a budget and 110 with it.
The SDK primitives as code
A small Python sketch of the four primitives the card names: the event registry, the wait decision from the traces, the retry budget, and the diagnostics snapshot. It uses plain functions and a fixed worst case (the server answers 429 to everything), so the output is exact.
from dataclasses import dataclass, asdict
# 1. Events: a callback that raises can never break the request path.
class Events:
def __init__(self):
self.handlers = {}
def on(self, name, fn):
self.handlers.setdefault(name, []).append(fn)
def emit(self, name, **info):
for fn in self.handlers.get(name, []):
try:
fn(info)
except Exception as exc: # swallow and log, never raise into the call
print(f" (callback for {name} raised {type(exc).__name__}; ignored)")
events = Events()
events.on("retry", lambda e: print(f" onRetry: attempt {e['attempt']}, wait {e['wait_ms']} ms"))
events.on("retry", lambda e: 1 / 0) # a broken subscriber
# 2. The wait decision from the worked traces (assumed deadline 20 s).
def next_step(retry_after_s, elapsed_ms, deadline_ms=20000):
wait_ms = retry_after_s * 1000
if elapsed_ms + wait_ms > deadline_ms:
return "fail now with RateLimitError(retry_after=%d)" % retry_after_s
events.emit("retry", attempt=1, wait_ms=wait_ms)
return f"sleep {wait_ms} ms then retry"
print("Retry-After 3 at 0 ms ->", next_step(3, 0))
print("Retry-After 30 at 0 ms ->", next_step(30, 0))
# 3. Retry budget: a retry is allowed only if retries, counting this one, stay at or under 10% of calls started.
class RetryBudget:
def __init__(self, ratio):
self.ratio, self.calls, self.retries = ratio, 0, 0
def may_retry(self):
if self.retries + 1 <= self.ratio * self.calls:
self.retries += 1
return True
return False
def overload(calls, max_retries, budget=None):
"""Every request is answered 429. Count the requests the server receives."""
sent = 0
for _ in range(calls):
sent += 1 # first attempt
if budget:
budget.calls += 1
for _ in range(max_retries):
if budget is None or budget.may_retry():
sent += 1
else:
break
return sent
print("100 calls, 5 retries each, no budget:", overload(100, 5), "requests sent")
print("100 calls, 5 retries each, 10% budget:", overload(100, 5, RetryBudget(0.10)), "requests sent")
# 4. Diagnostics snapshot (the same fields the card names, in snake_case here;
# observed_at and throttled_until are seconds on one simulated clock).
@dataclass
class Snapshot:
limit: int
remaining: int
resets_in_seconds: int
observed_at: float
queued_calls: int
retries_last_minute: int
throttled_until: float
print(asdict(Snapshot(100, 0, 7, 0.0, 3, 12, 7.0)))
Output:
onRetry: attempt 1, wait 3000 ms
(callback for retry raised ZeroDivisionError; ignored)
Retry-After 3 at 0 ms -> sleep 3000 ms then retry
Retry-After 30 at 0 ms -> fail now with RateLimitError(retry_after=30)
100 calls, 5 retries each, no budget: 600 requests sent
100 calls, 5 retries each, 10% budget: 110 requests sent
{'limit': 100, 'remaining': 0, 'resets_in_seconds': 7, 'observed_at': 0.0, 'queued_calls': 3, 'retries_last_minute': 12, 'throttled_until': 7.0}
Reading it: the first two lines are Trace 1 and Trace 2. For Retry-After 3 the SDK sleeps 3000 ms; the onRetry subscriber prints, and the broken second subscriber raises ZeroDivisionError which the registry swallows, so the call still proceeds. For Retry-After 30 the wait would overrun the 20 s deadline, so the SDK fails at once. The two overload lines tie the budget to the amplification: 100 calls with up to 5 retries each send 100 x 6 = 600 requests when every attempt is refused; with the retry budget set to 10 percent the same 100 calls send 100 first attempts plus at most 10 retries, 110 requests, so the SDK adds 10 percent to the offered load instead of 500 percent. The last line is the shape of the diagnostics object a support engineer asks a customer to print: observed at 0.0 s, 7 seconds until the window resets, so throttled until 7.0 s.
Language-specific concurrency
The same three questions apply in every language: where does the shared limiter state live, what can block while waiting, and how is a waiting call cancelled. Each bullet answers them for one language, so read the ones that match the SDKs you ship.
- JavaScript (Node, browsers): single-threaded event loop (one thread that runs callbacks as events arrive), so shared limiter state needs no lock, but waiting must be non-blocking (
setTimeoutin a Promise) and cancellable withAbortSignal. Separate worker threads or processes do not share state. - Python: with threads, guard the bucket and counters with a lock (the global interpreter lock, which lets only one thread run Python code at a time, does not make a read-modify-write atomic); in
asyncio(Python's built-in library for cooperative, single-thread concurrency) useasyncio.sleepand nevertime.sleep, which would freeze every task; offer both sync and async clients. - Go: take a
context.Context(Go's standard value that carries a deadline and a cancel signal down the call chain) on every call, let one goroutine (a lightweight thread run by Go's runtime) or a mutex own the state, and use timers instead of one sleeping goroutine per waiter. - Java: use thread-safe collections or atomics, and never sleep on a shared executor or event-loop thread (it starves other requests: they wait because no thread is free); schedule retries with a scheduled executor (a thread pool that runs tasks after a delay) or
CompletableFuture(Java's object for a result that arrives later) delayed execution. - Across processes: one process cannot see another's pacing. Say so in the docs, and let the server's 429 handle the rest, or let users configure a per-process share of the limit.
Defaults and trade-offs
Transparent retries on by default for 429 and for safe calls, a short default deadline, events and diagnostics on, and a single switch to disable retries (some callers want to fail fast and manage their own queue). What would flip a default: a latency-critical interactive path wants a small deadline and no queued waiting, while a batch job wants the opposite.
Common mistakes
Retrying instantly without jitter; ignoring Retry-After; retrying non-idempotent calls without a key; unbounded retries; one limiter per client object when a process creates many; running user callbacks inside a lock; sleeping on a thread another request needs.
Define client retry and backoff guidance for your public API. Include: which status codes are safe to retry, how to treat idempotent vs non-idempotent operations, suggested backoff algorithm (exponential backoff with jitter), maximum retry attempts, and how to document this for SDKs and developer docs.
Sample Answer
The idea in plain words
A retry is sending the same request again after a failure. Retries turn short glitches into non-events, but done carelessly they double the load on a service that is already struggling and can run a non-repeatable action twice (charging a card twice). Good guidance answers four questions for every client: should this failure be retried at all, is it safe to repeat this operation, how long to wait, and when to give up. The answer to the third question is exponential backoff with jitter: wait longer after each failure (backoff), and randomise the wait (jitter) so many clients do not all return at the same instant.
1. Which failures to retry
| Outcome | Retry? | Reason |
|---|---|---|
| Connection refused or reset, DNS failure, timeout before any response | Yes, if the operation is safe to repeat (section 2) | Usually transient |
| 408 Request Timeout | Yes | Server gave up waiting for the request |
| 429 Too Many Requests | Yes, after Retry-After | Client-rate problem that clears with time |
| 500 Internal Server Error | Cautiously, a small number of times | May be a bug that repeats, may be a transient fault |
| 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout | Yes | Upstream or capacity trouble, often brief |
| 400, 404, 405, 409, 410, 422 | No | The request is wrong or the state conflicts; repeating it unchanged gives the same answer |
| 401 | Once, after refreshing the credential | Expired token is the one case where a retry can differ |
| 403 | No | Authenticated but not permitted |
The principle: retry only when a second identical attempt has a real chance of a different result.
2. Idempotent versus non-idempotent operations
An operation is idempotent when doing it twice has the same effect as doing it once. By HTTP definition (RFC 9110) GET, HEAD, PUT, DELETE, OPTIONS and TRACE are idempotent; POST and PATCH are not guaranteed to be. The danger is the ambiguous failure: a POST times out and the client cannot know whether the server created the order before the connection broke.
- For idempotent methods, retry freely under the policy below.
- For POST and PATCH, retry only if the API supports an idempotency key: a unique value the client generates once per logical operation and sends on every attempt (commonly in an
Idempotency-Keyheader, which is an IETF draft, not yet a final standard). The server stores the result under that key for some period and returns the stored result on a repeat instead of acting again. The SDK must generate the key before the first attempt and reuse the same key on every retry; a new key per attempt defeats the purpose. - Without a key, retry a POST only when the failure proves the server never processed it (connection refused, or a 429 or 503 returned before any work), and otherwise surface the error to the caller.
3. Backoff algorithm
Use exponential backoff with full jitter. For retry number n counting from 0, with base delay b and cap c, wait a random time drawn uniformly between 0 and an upper bound:
upper(n)=min(c,b⋅2n),wait(n)=uniform(0, upper(n))If the response has Retry-After, wait at least that long: wait=max(Retry-After, wait(n)). The server knows its recovery time better than the client does.
Recommended defaults, stated as assumptions to tune: base b = 0.5 seconds, cap c = 30 seconds, at most 4 retries (5 attempts in total) and an overall deadline per logical call.
Worked schedule with those defaults. The upper bounds are 0.5⋅2n for n = 0 to 3:
| Retry | Upper bound (s) | Expected wait with full jitter (s) |
|---|---|---|
| 1 (n = 0) | 0.5 x 1 = 0.5 | 0.25 |
| 2 (n = 1) | 0.5 x 2 = 1 | 0.5 |
| 3 (n = 2) | 0.5 x 4 = 2 | 1 |
| 4 (n = 3) | 0.5 x 8 = 4 | 2 |
The worst case total wait is 0.5 + 1 + 2 + 4 = 7.5 seconds, and the expected total is half of that, 3.75 seconds (the expected value of a uniform draw is half its upper bound). The cap of 30 seconds is never reached with only 4 retries; it matters only if you allow more. Add the time each attempt takes (for example up to a per-attempt timeout of 5 seconds) to find the worst case end to end: 5 attempts x 5 s + 7.5 s = 32.5 seconds, so a caller needs an overall deadline at least that long or the client should fail sooner.
Why jitter. Suppose 1,000 clients fail at the same moment and the outage lasts, so every retry fails too. With plain exponential backoff all 1,000 return together at each step: a spike of 1,000 requests at the same instant, four times. With full jitter, the 1,000 first retries are spread over the 0.5-second bound, about 1,000 / 0.5 = 2,000 per second on average; the second retries over 1 second, 1,000 / 1 = 1,000 per second; the third over 2 seconds, 1,000 / 2 = 500 per second; the fourth over 4 seconds, 1,000 / 4 = 250 per second. These are averages, and later rounds overlap earlier ones in time, but the load arrives as a smeared stream instead of repeated spikes, and the peak rate falls with every round.
4. Limits that protect the server
- Maximum attempts: 3 to 5 total attempts. More rarely helps; a fault that lasts longer is better handled by a circuit breaker (a component that stops calls for a while after repeated failures).
- Overall deadline: a time budget for the whole logical call, shared by all attempts. Stop retrying when the next wait would exceed it, including when
Retry-Afteris longer than what is left. - Retry budget: cap retries to a fraction of normal traffic (say retries at most 10 percent of requests over a recent window, an assumed figure to tune) so an outage cannot multiply load.
- Retry only at one layer. If a browser, an SDK and a service each make 3 attempts, one user action becomes 3 x 3 x 3 = 27 calls to the bottom service. Document which layer owns retries.
5. How to document it for SDKs and developer docs
- Publish the table in section 1 as the official list of retryable outcomes, plus a sentence for network errors.
- State the algorithm, defaults (base, cap, attempts, deadline) and that
Retry-Afteris honoured, with the formula above. - State per operation whether it is idempotent and which POST endpoints accept an
Idempotency-Key, and for how long the server remembers a key. - Say that SDKs retry by default only for idempotent operations and for keyed POSTs, that every default is configurable, and that retries are logged with the attempt number and the request ID.
- Give a short pseudocode example and a "what you will see" example (429 with
Retry-After: 23, client waits at least 23 seconds). - Provide a test mode or a documented way to trigger a 429 and a 503 so integrators can test their handling.
Common mistakes
- Retrying 4xx errors that cannot change, such as 400 or 404.
- Retrying a POST without an idempotency key after a timeout and creating duplicates.
- Backoff without jitter, which synchronises clients.
- Ignoring
Retry-After. - Retrying at every layer, multiplying load.
- No overall deadline, so a user waits minutes.
Describe the token bucket rate limiting algorithm: explain the key parameters (capacity and refill rate), how it enforces throughput while allowing bursts, and how it differs behaviorally from leaky bucket and fixed-window approaches. Provide a short example of when token bucket is preferable.
Sample Answer
The idea in plain words
Rate limiting means capping how many requests a caller may make over time so one caller cannot starve the others (use up the shared capacity until the rest get little or none of it). A token bucket does this with a simple picture: a bucket holds tokens, every request must take a token out, and tokens drip back in at a fixed speed. If the bucket is empty the request is refused (an HTTP API answers 429 Too Many Requests). The bucket's size allows a burst (many requests at once), and the drip speed fixes the long-run average. That pairing, "short spikes are fine, the average is capped", is why the algorithm is so common.
The two parameters and the formula
- Capacity B: the most tokens the bucket can hold. It is the largest burst a caller can send after being idle.
- Refill rate r: tokens added per second. It is the sustained throughput (steady requests per second the caller can keep up forever).
State per caller is just two numbers: tokens and last (the time of the last update). Nothing runs on a timer. On each request the limiter refills lazily ("lazy refill" means computing the refill when a request arrives instead of adding tokens every tick):
tokens_now = min(B, tokens_before + (now - last) * r)
if tokens_now >= cost: tokens_now = tokens_now - cost, allow
else: deny
last = now
cost is 1 for a plain request and can be larger for expensive calls. Two consequences follow. In any interval of T seconds starting from a full bucket, at most B + r*T tokens can be spent. And an empty bucket needs B / r seconds to refill completely.
Worked trace (assumed numbers: B = 10, r = 2 tokens per second)
- At t = 0 the bucket is full with 10 tokens. Ten requests arrive in the same instant: all ten are allowed, tokens drop to 0. An eleventh at t = 0 is denied.
- At t = 1.5 s the bucket holds 0 + 1.5 * 2 = 3 tokens. Three requests are allowed and a fourth is denied.
- The caller then goes quiet. After 10 idle seconds the formula gives min(10, 0 + 10 * 2) = min(10, 20) = 10: the bucket is back to full, never above B.
- Over any 60 seconds starting from a full bucket the caller can spend at most 10 + 2 * 60 = 130 tokens, and the steady rate is 2 * 60 = 120 per minute. The extra 10 is the burst allowance.
Full refill from empty takes B / r = 10 / 2 = 5 seconds.
How it differs from leaky bucket and fixed window
Take the same limit in all three, an average of 2 requests per second.
| Algorithm | What it does with a burst of 10 arriving at once | Behaviour at a boundary |
|---|---|---|
| Token bucket (B = 10, r = 2) | Serves all 10 immediately, then refuses until tokens return | Cannot exceed B + r*T in any interval |
| Leaky bucket as a queue (holds 10 waiting requests, one leaves every 0.5 s) | Accepts them but releases them at 0.5, 1.0, ..., 5.0 s, so the last waits 5.0 s; extra arrivals while the queue is full are dropped | Output is smooth at 2 per second |
| Fixed window (20 requests per 10 s window, counter resets each window) | Serves them if the window has room | Up to 2x the limit across a window edge |
The fixed-window edge case with numbers: 20 requests at t = 9.9 s fill the first window (counter 20 of 20), then the counter resets at t = 10 s and 20 more at t = 10.1 s are allowed. That is 40 requests in 0.2 s while the stated limit is 20 per 10 s. The token bucket under the same pattern allows at most B + r*T = 10 + 2 * 0.2 = 10.4 tokens in that 0.2 s, so 10 whole requests.
The behavioural summary: token bucket lets bursts through at full speed and caps the average; leaky bucket (queue form) removes bursts by delaying them and adds waiting time; fixed window is the cheapest (one counter) but lets a double burst through at the edge.
Per-tenant quotas and state that expires by itself
Different plans are just different (B, r) pairs, for example a free plan with B = 20, r = 1 per second and a paid plan with B = 200, r = 10 per second (assumed plans). The key is the tenant or API key.
You do not need a central database of every tenant's bucket or a cleanup job. A bucket that has been idle for B / r seconds is full again, and a missing bucket is created full, so deleting an idle bucket changes nothing a caller can observe. So store (tokens, last) under the key with a time-to-live (TTL, an automatic expiry) of about B / r seconds after each update: 20 / 1 = 20 s for the free plan and 200 / 10 = 20 s for the paid one. An in-process map with eviction of full buckets does the same job. This equivalence holds only if new keys start full; if you want new keys to start empty, the TTL trick no longer applies.
When to prefer token bucket
Choose it when clients are naturally bursty but bounded: a browser page that fires 8 parallel API calls on load and then sits idle for a minute is the standard case. With B = 10 and r = 2 the page loads at full speed, and a script hammering the API is held to 2 per second. Fixed window would punish an unlucky page load that lands just after a counter fills; a leaky-bucket queue would make the page wait for its own calls. Prefer a leaky bucket when a fragile downstream (a legacy system that can only take 2 calls per second, with no tolerance for spikes) needs perfectly even input.
Common mistakes
- Confusing capacity with rate: B = 10 does not mean 10 per second, it means 10 stored at most.
- Forgetting the cap
min(B, ...), so a long-idle caller accumulates an unbounded burst. - Using wall-clock time that can jump backwards (when an administrator or time-sync service sets the date) instead of a monotonic clock, which only ever moves forward and is meant for measuring elapsed time.
- Letting a request with cost larger than B wait forever: it can never succeed, so reject it outright.
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.