What to send back with a 429: Retry-After, RateLimit headers and telling a rate limit apart from a quota
A 429 on its own tells the client very little. "Too many requests" covers a client that sent three calls in the same second, a client that used its whole month on day 16, and anything in between. What actually decides whether the client recovers on its own is what you put next to the status code: a Retry-After value, maybe a pair of RateLimit fields, and a body that says which limit was hit.
I'm one of the three founders of UsageRail. It gives paid APIs keys for their customers, per-customer rate limits and quotas, and bills usage through the developer's own Stripe account, so I've spent more time on 429s than is probably healthy. How to count requests (token bucket, sliding window and so on) is covered in our guide to API rate limiting. This post is only about the response: what goes in it, and what a client should do with it.
The code is plain Node.js with no dependencies. I ran all of it on Node 26.3; the output further down is from that run.
What the status code promises
RFC 6585 defines 429 in a few sentences. The response "SHOULD include details explaining the condition, and MAY include a Retry-After header indicating how long to wait before making a new request." It also says the spec "does not define how the origin server identifies the user, nor how it counts requests."
So the status code says nothing about why, and nothing about for how long. Two things follow:
- Every 429 you send should carry
Retry-After, unless waiting won't help (more on that below). - The body needs a machine-readable reason. A human-readable sentence is nice, but clients branch on codes, not on English.
Retry-After: send seconds, and round up
RFC 9110 allows two forms: an HTTP date (Retry-After: Fri, 31 Dec 1999 23:59:59 GMT) or a number of seconds (Retry-After: 120). Send seconds. A date only works if the client's clock agrees with yours, and plenty of clients run on machines with drifting clocks. Your client code should still accept both, because other APIs send dates.
Two details are easy to get wrong.
Which limit decides the value. Most plans have more than one limit, say 2 requests per second and 6 per minute. When a request is refused, Retry-After has to be the wait for the slowest limit that refused it. If the per-minute bucket is empty and needs 8 seconds, telling the client "1" because the per-second bucket refills in one second just earns you seven more 429s.
Rounding. Retry-After is a whole number of seconds, and the real wait almost never is. Round up. Here is a per-minute bucket of 6 (one token every 10 seconds), driven by a fake clock. Six requests at 09:00:00 empty it, and a seventh arrives 2.5 seconds later, when the bucket holds a quarter of a token:
at +2.5s: 429 {
'Retry-After': '8',
'RateLimit-Policy': '"per_minute";q=6;w=60',
RateLimit: '"per_minute";r=0;t=8'
}
exact wait: 7.5 s
after 7 s: 429 {"Retry-After":"1","RateLimit-Policy":"\"per_minute\";q=6;w=60","RateLimit":"\"per_minute\";r=0;t=1"}
after 8 s: 200
The exact wait is 7.5 seconds. A server that rounded down would have said 7, and a well-behaved client that waited exactly 7 seconds would have been refused again.
RateLimit-Policy and RateLimit
Retry-After only tells the client about the past: you were refused, come back later. The IETF draft for rate limit headers (draft-ietf-httpapi-ratelimit-headers) adds two fields that let a client slow down before it gets refused. Revision -11, published on May 23, 2026, is still the latest as I write this, and it is still a draft, not an RFC.
RateLimit-Policy: "per_minute";q=6;w=60describes a policy: a quotaqper window ofwseconds.RateLimit: "per_minute";r=0;t=8reports where the client stands now:runits left, andt, the seconds within which it can use no more thanr.
Both are lists, so one header can describe several policies. This is the part of my limiter that builds the headers when a request is refused:
// Refused requests don't take a token. Build the headers from every bucket the plan has.
let retryAfter = 0;
const policy = [];
const current = [];
WINDOWS.forEach((window, i) => {
const bucket = state[i];
if (!bucket) return;
const secondsPerToken = window.seconds / bucket.capacity;
const empty = bucket.tokens < 1;
// Blocked bucket: seconds until it holds one whole token. Others: seconds until full.
// Always round up: a client that waits exactly this long must not get another 429.
const t = Math.ceil((empty ? 1 - bucket.tokens : bucket.capacity - bucket.tokens) * secondsPerToken);
if (empty) retryAfter = Math.max(retryAfter, t);
policy.push(`"${window.name}";q=${bucket.capacity};w=${window.seconds}`);
current.push(`"${window.name}";r=${Math.floor(bucket.tokens)};t=${t}`);
});
return {
ok: false,
status: 429,
headers: { "Retry-After": String(retryAfter), "RateLimit-Policy": policy.join(", "), RateLimit: current.join(", ") },
body: { error: "rate_limited", retry_after: retryAfter },
};
A token bucket doesn't map exactly onto "q per w seconds". I send the bucket size as q and the time to refill it from empty as w. For the bucket that ran out, t is the time until it holds one token again, which is exact. For a bucket that still has tokens there's no exact answer, because it keeps refilling while the client spends. I send the time until it's full, and a client that treats r as "what I can spend right now" stays safe.
A few rules from the draft are worth knowing on both sides:
- When a response has both
Retry-AfterandRateLimit, the client MUST giveRetry-Afterprecedence. On the server side,Retry-AfterSHOULD NOT point earlier than the end of thetwindow. - Malformed
RateLimitfields MUST be ignored. Clients can't assume the next response carries the fields at all. - Servers don't have to send them on every response. You can send them only on 429s, or only when a customer is close to the limit. Sending them on 200s lets clients pace themselves before the first refusal, at the cost of computing them for every request.
One more thing about vocabulary. The draft calls every allocation a "quota", including 2 requests per second, and its quota-exceeded problem type covers any policy. That isn't the same thing as the monthly quota on a pricing page, and the next section is about keeping those two apart.
A rate limit and a quota need different answers
A rate limit is about speed. It recovers by itself in seconds, so retrying is the right move. A quota is about volume over a billing period: 1,000 requests a month on a free plan, for example. Retrying a quota refusal is pointless until the period ends, or until the customer upgrades or buys credits. Clients need to tell the two apart without guessing, so each refusal gets its own status or error code. The codes below are the ones UsageRail's SDK returns; the demo in this post implements the first three rows.
| Situation | Status | Retry-After | Body error |
|---|---|---|---|
| Rate limit hit | 429 | seconds until a token is back | rate_limited |
| Quota used up, plan stops at the limit | 429 | seconds until the period ends | quota_exceeded (the demo adds resets_at) |
| Prepaid credits used up | 402 | none, waiting won't help | insufficient_credits |
| Customer suspended | 403 | none | consumer_suspended |
| The quota service can't be reached and you chose to refuse rather than let requests through | 503 | none, the client's own backoff applies | quota_unavailable |
The 402 needs a word. RFC 9110 lists 402 Payment Required as "reserved for future use". It has never been given precise semantics, but its name says exactly what the client has to do (pay), and that's why I use it for prepaid credits. Some APIs answer the same case with 403 or with a 429 and an error code; whichever you choose, document it.
Should the monthly quota also go into RateLimit-Policy? The draft allows it; one of its examples reports a "day" policy. I leave it out. My quota resets at a fixed moment (the demo uses the start of each UTC calendar month), and the draft itself warns (section 8.5) that a fixed reset time brings every throttled client back at the same moment. A quota refusal gets Retry-After plus resets_at in the body, and the client treats it as a business event, not a retry.
The order of the checks matters too. My server checks the quota before the rate limit. If a customer has used up the month and is also sending too fast, the quota is the refusal they need to hear about; a "wait 1 second" answer would just send them into a loop that ends at the quota anyway.
// Quota first: if both a quota and a rate limit apply, the quota is the one the client needs to hear about.
if (plan.prepaid) {
if (customer.credits < 1) return { ok: false, status: 402, headers: {}, body: { error: "insufficient_credits" } };
} else if (plan.monthlyQuota != null) {
const { start, end } = periodBounds(at);
if ((usage.get(`${customerId}:${start}`) ?? 0) >= plan.monthlyQuota) {
const retryAfter = Math.ceil((end - at) / 1000);
return {
ok: false,
status: 429,
headers: { "Retry-After": String(retryAfter) },
body: { error: "quota_exceeded", retry_after: retryAfter, resets_at: new Date(end).toISOString() },
};
}
}
return checkRate(customerId, plan, at);
Only successful responses use up quota or credits, and a refused request doesn't take a token from the bucket.
The client: retry short waits, stop on long ones
Most retry helpers do "on 429, sleep for Retry-After, try again". Against the quota refusal above, that sleeps for two weeks. The draft says as much in section 8.5.1: a large value "could inhibit clients to contact the server (e.g. similarly to receiving 'Retry-after: 1000000')", and clients should set thresholds they consider reasonable.
My client does three things: it stops at once on refusals that waiting can't fix, it refuses to sleep longer than a cap, and it adds jitter so that clients refused at the same moment don't all return at the same moment.
// Retry-After is either delay-seconds or an HTTP date (RFC 9110, section 10.2.3).
export function parseRetryAfter(value, now = Date.now()) {
if (value == null) return null;
if (/^\d+$/.test(value.trim())) return Number(value.trim());
const date = Date.parse(value);
return Number.isNaN(date) ? null : Math.max(0, Math.ceil((date - now) / 1000));
}
export async function callApi(url, init = {}, { maxWaitSeconds = 30, maxAttempts = 4, onWait = () => {} } = {}) {
for (let attempt = 1; ; attempt++) {
const response = await fetch(url, init);
if (response.status !== 429 && response.status !== 503 && response.status !== 402) return response;
const body = await response.json().catch(() => null);
const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
// Waiting doesn't fix these two. Hand them to the caller right away.
if (response.status === 402) throw new LimitError("payment_required", response, body, retryAfter);
if (body?.error === "quota_exceeded") throw new LimitError("quota_exceeded", response, body, retryAfter);
// An API that doesn't label its 429s still gets caught here: a 12-day Retry-After is not a retry.
if (retryAfter != null && retryAfter > maxWaitSeconds) throw new LimitError("wait_too_long", response, body, retryAfter);
if (attempt >= maxAttempts) throw new LimitError("gave_up", response, body, retryAfter);
// No Retry-After: fall back to exponential backoff. Add jitter either way so clients don't return in lockstep.
const baseMs = retryAfter != null ? retryAfter * 1000 : 2 ** (attempt - 1) * 1000;
const waitMs = baseMs + Math.floor(Math.random() * 250);
onWait({ attempt, status: response.status, retryAfter, rateLimit: parseRateLimit(response.headers.get("ratelimit")), waitMs });
await sleep(waitMs);
}
}
The two helpers it uses are short. LimitError carries the kind of refusal, the body and the Retry-After value. parseRateLimit reads the simple form of the RateLimit field shown above and returns null for anything it doesn't understand, as the draft requires. It is not a full Structured Fields parser, which is fine for logging and pacing but not for a library you publish.
export class LimitError extends Error {
constructor(kind, response, body, retryAfter) {
super(`${kind} (HTTP ${response.status})`);
this.kind = kind; // "quota_exceeded" | "payment_required" | "wait_too_long" | "gave_up"
this.status = response.status;
this.body = body;
this.retryAfter = retryAfter; // seconds, or null
}
}
export function parseRateLimit(value) {
if (!value) return null;
const policies = {};
for (const item of value.split(",")) {
const match = /^\s*"([^"]+)"((?:;[a-z]+=\d+)*)\s*$/.exec(item);
if (!match) return null;
const params = Object.fromEntries([...match[2].matchAll(/;([a-z]+)=(\d+)/g)].map(([, k, v]) => [k, Number(v)]));
if (params.r == null) return null;
policies[match[1]] = params;
}
return policies;
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
The maxWaitSeconds check is the one that protects you from APIs that don't label their refusals: you can't know why their 429 came with a two-week Retry-After, but you know you shouldn't sleep through it.
Running it
To try it, I put the limiter behind a 30-line node:http server that reads an x-api-key header, and wrote a script that sends requests at it with plain fetch and with callApi. The test server gives customer alice a free plan with 2 requests per second, 6 per minute and 8 per month, and customer bob one prepaid credit. First, three raw requests from alice in a row:
+0.0s 200 {"hello":"alice"}
+0.0s 200 {"hello":"alice"}
+0.0s 429 {"error":"rate_limited","retry_after":1}
retry-after: 1
ratelimit-policy: "per_second";q=2;w=1, "per_minute";q=6;w=60
ratelimit: "per_second";r=0;t=1, "per_minute";r=4;t=20
Then the same customer through callApi, one call after another until something stops it:
+0.0s call 1: 429, Retry-After 1, RateLimit {"per_second":{"r":0,"t":1},"per_minute":{"r":4,"t":20}}, waiting 1062 ms
+1.1s call 1: 200 {"hello":"alice"}
+1.1s call 2: 200 {"hello":"alice"}
+1.1s call 3: 429, Retry-After 1, RateLimit {"per_second":{"r":0,"t":1},"per_minute":{"r":2,"t":39}}, waiting 1054 ms
+2.1s call 3: 200 {"hello":"alice"}
+2.1s call 4: 200 {"hello":"alice"}
+2.1s call 5: 429, Retry-After 8, RateLimit {"per_second":{"r":0,"t":1},"per_minute":{"r":0,"t":8}}, waiting 8214 ms
+10.4s call 5: 200 {"hello":"alice"}
+10.4s call 6: 429, Retry-After 10, RateLimit {"per_second":{"r":1,"t":1},"per_minute":{"r":0,"t":10}}, waiting 10119 ms
+20.5s call 6: 200 {"hello":"alice"}
+20.5s call 7: stopped, quota_exceeded, Retry-After 1237094, body {"error":"quota_exceeded","retry_after":1237094,"resets_at":"2026-12-01T00:00:00.000Z"}
Call 5 is the case from earlier: both buckets are empty, the per-second one needs 1 second and the per-minute one needs 8, so Retry-After is 8. By call 7, alice has eight successful requests this month, so the quota is used up: Retry-After is 1,237,094 seconds (about 14 days, since I ran this on November 17), and the client stops instead of sleeping.
Bob, with one prepaid credit:
+20.5s call 1: 200 {"hello":"bob"}
+20.5s call 2: stopped, payment_required, Retry-After null, body {"error":"insufficient_credits"}
A short checklist
For the server:
- Every 429 carries
Retry-Afterin whole seconds, rounded up, taken from the slowest limit that refused the request. - The body has an error code that separates
rate_limitedfromquota_exceeded. Quota refusals also say when the period resets. RateLimit-PolicyandRateLimitare optional extras. If you send them, keep them consistent withRetry-After.- Refusals that money fixes, not time, get a status without
Retry-After(402 for credits in my case).
For the client:
- Accept both forms of
Retry-After. - Never sleep longer than a cap you chose. Past the cap, surface the error to whoever can act on it.
- Add jitter to every wait.
What UsageRail's SDK sends
Since this is the code path I work on every day: UsageRail's SDK runs inside your API process and handles keys, limits and usage-based billing for APIs. Its refusals follow the table above. Rate limit refusals are 429 rate_limited with Retry-After plus RateLimit-Policy and RateLimit from draft -11, sent only on refusals. A plan that stops at its quota answers 429 quota_exceeded, with Retry-After set to the seconds left in the period, and prepaid plans answer 402 insufficient_credits when credits run out. Our docs tell clients to rely on Retry-After first, because the draft can still rename its fields before it becomes an RFC; it already has a few times.
If you handle 429s differently, especially on the client side, I'd like to hear how in the comments.
Super Lede
All rights reserved