Skip to content
RateStack
API cookbook

Handle rate limits without exploding

Read the burndown header, back off on 429, alert before exhaustion. The two-line client wrapper that solves it.

RTBy RateStack TeamPublishedReviewed
intermediateTypeScript

RateStack returns X-RateLimit-Remaining and X-RateLimit-Reset headers on every response. On 429, it additionally returns Retry-After. The recipe is to back off on 429, log the burndown on every response, and alert when remaining falls below a threshold.

async function ratestackFetch(path: string, init: RequestInit): Promise<Response> {
  for (let attempt = 0; attempt < 5; attempt++) {
    const res = await fetch(path, init);
    if (res.status === 429) {
      const retryAfter = Number(res.headers.get("retry-after") ?? "1");
      await sleep(retryAfter * 1000);
      continue;
    }
    const remaining = Number(res.headers.get("x-ratelimit-remaining") ?? "0");
    if (remaining < 50) metrics.alert("ratestack-rate-limit-low", { remaining });
    return res;
  }
  throw new Error("ratestack: exhausted retries on 429");
}

Production tip: do not retry forever; bound the loop. Exhausted retries should page an operator, not silently drop work.

Handle rate limits without exploding — API cookbook | RateStack