Thuta Learning
API Tutorial
AdvancedWeb DevelopmentIntermediate

Rate Limit & Retry

API TutorialLesson 2535 min

What you'll walk away with

  • Explain how fixed window, sliding window and token bucket limiters differ, including the boundary burst problem of fixed windows
  • Read a 429 Too Many Requests response and its Retry-After header and write client code that waits correctly
  • Implement exponential backoff with jitter and cap retries with an attempt limit and a deadline
  • Explain why a timed-out POST must not be retried without an idempotency key

Explain it simply

Explain it simply

Think of an API as a busy counter at a post office. The clerk can only serve so many people per minute, so there is a rule: take a place in line, and if the line is full, come back in a moment. A rate limit is that rule written down as numbers, such as 100 requests per minute for each API key.

When you go over the number, the server does not crash and it does not ignore you. It answers with status 429 Too Many Requests, usually with a Retry-After header that says how many seconds to wait. Your job as the caller is to read that answer, pause for the stated time and try again, instead of pushing harder against the counter.

Problem → Why → Solution

The problem: an importer that retries instantly

Picture an import script that pulls 1,000 products from an API. Its author assumed that on a 429 you simply call again, so the retry sits straight inside a loop. The first twenty or so calls work. Then the limit is reached and the loop fires hundreds of requests per second at a server that has just said it is busy.

Failing is not the only cost. Depending on the provider, refused requests may still count toward the limit, and a client that keeps hammering can be blocked for a while. When many clients behave this way together, they keep knocking over a server that is trying to recover.

import.js
// Naive importer: no delay, no limit, no way out
async function fetchProduct(id) {
  let res = await fetch("https://api.example.com/v1/products/" + id);
  while (res.status === 429) {
    // retry immediately, forever
    res = await fetch("https://api.example.com/v1/products/" + id);
  }
  return res.json();
}

for (let id = 1; id <= 1000; id++) {
  await fetchProduct(id);
}

Why is this pattern harmful?

The server says "please slow down" and this client hears "ask again". It never reads Retry-After, never waits and never gives up, so it keeps the window full instead of letting it refill. The fix is to wait as long as the server says, compute your own backoff when it says nothing, and cap both the attempts and the total time.

Core concept: how limits count and how they answer

A rate limit is a promise the provider makes to all customers at once: nobody gets to use so much of the shared machine that everyone else slows down. Providers also use limits to control cost, because every request to a paid backend, such as an AI model, costs real money. What gets counted differs from provider to provider. It can be requests per second, requests per day, tokens processed per minute, simultaneous connections, or a quota on one expensive endpoint, and several of these can apply at the same time.

The server needs a counting method, and three are common. A fixed window counts requests inside calendar slots such as each minute and resets at the boundary. A sliding window looks at the last N seconds from the moment of each request, so there is no boundary to exploit. A token bucket refills at a steady rate and lets a client spend saved-up tokens in a burst. The deeper section below compares them side by side.

On the wire the contract is small. A refused request gets status 429 Too Many Requests, and a good provider adds Retry-After, which HTTP defines as either a number of seconds or a calendar date. Headers that report your remaining budget are only a convention, and there is no single standard yet. GitHub sends X-RateLimit-Remaining, other providers use RateLimit-style names, and an IETF draft is working toward one standard, so read your provider's documentation instead of assuming. Some APIs answer 503 Service Unavailable with Retry-After when they are overloaded; treat that the same way.

text
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 30
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0

{"error":"rate_limited","message":"Limit is 100 requests per minute."}

The client has duties of its own.

  • Obey Retry-After. It is the server's instruction, and it beats any delay you computed yourself.
  • When there is no Retry-After, use exponential backoff with jitter: wait a random time up to a ceiling that doubles after every failure, so a crowd of clients does not retry in lockstep.
  • Stop after a maximum number of attempts or a total deadline, then report the failure to your caller.
  • Retrying a refused request is fine, but retry a timed-out POST only with an idempotency key, because the server may already have done the work.
  • Slow yourself down first: a queue or a concurrency limit keeps you under the limit so that 429 stays rare.
Mental model: a bucket the server refills
  1. Client sends a request
  2. Limiter spends a token or count
  3. Empty bucket: 429 + Retry-After
  4. Client waits, then retries

The server refills the bucket on its own schedule, so waiting works and pushing does not.

General pattern: the retry loop

text
for attempt in 1..maxAttempts:
    response = send(request)
    if response.status is not 429 (or 503):
        return response
    if attempt == maxAttempts or deadline passed:
        raise the last response as an error
    delay = Retry-After            # the server's word wins
            or random(0, min(cap, base * 2^(attempt - 1)))
    wait(delay)

This shape works in any language. Retry-After takes priority, backoff with random jitter is the fallback, and the loop is bounded by both an attempt count and a deadline so it can never spin forever.

Example: a token-bucket limiter you can watch

This example starts a mock server with node:http inside the sample and puts a token bucket in front of it. Each bucket holds 3 tokens and refills one per second, with one bucket per API key. Time comes from a fake clock you advance by hand instead of Date.now(), so every run prints exactly the same thing.

Alice sends five requests back to back. The first three pass and the last two get 429. Bob has his own bucket and is unaffected. After the fake clock moves forward two seconds, Alice's bucket has two tokens again and a request succeeds.

token-bucket.mjs
import http from "node:http";

// A fake clock that only moves when we say so, so the demo never depends on real time.
const clock = { seconds: 0 };

class TokenBucket {
  constructor(capacity, refillPerSecond) {
    this.capacity = capacity;
    this.refillPerSecond = refillPerSecond;
    this.tokens = capacity;
    this.lastSeen = clock.seconds;
  }

  take() {
    const elapsed = clock.seconds - this.lastSeen;
    this.tokens = Math.min(this.capacity, this.tokens + elapsed * this.refillPerSecond);
    this.lastSeen = clock.seconds;
    if (this.tokens >= 1) {
      this.tokens -= 1;
      return { allowed: true, remaining: Math.floor(this.tokens) };
    }
    const retryAfter = Math.ceil((1 - this.tokens) / this.refillPerSecond);
    return { allowed: false, retryAfter };
  }
}

const buckets = new Map();
const server = http.createServer((req, res) => {
  const key = req.headers["x-api-key"] ?? "anonymous";
  if (!buckets.has(key)) buckets.set(key, new TokenBucket(3, 1));
  const result = buckets.get(key).take();

  res.setHeader("Content-Type", "application/json");
  res.setHeader("X-RateLimit-Limit", "3");
  if (!result.allowed) {
    res.statusCode = 429;
    res.setHeader("Retry-After", String(result.retryAfter));
    res.end(JSON.stringify({ error: "rate_limited", message: "Too many requests." }));
    return;
  }
  res.setHeader("X-RateLimit-Remaining", String(result.remaining));
  res.end(JSON.stringify({ ok: true }));
});

await new Promise((resolve) => server.listen(0, resolve));
const base = `http://127.0.0.1:${server.address().port}`;

async function call(apiKey, label) {
  const res = await fetch(`${base}/v1/items`, { headers: { "X-API-Key": apiKey } });
  const detail = res.status === 429
    ? `retry-after=${res.headers.get("retry-after")}`
    : `remaining=${res.headers.get("x-ratelimit-remaining")}`;
  console.log(`${label}: ${res.status} ${detail}`);
}

for (let i = 1; i <= 5; i++) await call("alice", `alice #${i}`);
await call("bob", "bob #1");
clock.seconds += 2;
await call("alice", "alice after 2s");
server.close();

Code breakdown

  1. Fake clockconst clock = { seconds: 0 };

    Time lives in a plain object. A test can raise this value to pretend seconds have passed, so nothing really waits and the output stays stable.

  2. Refillthis.tokens = Math.min(this.capacity, this.tokens + elapsed * this.refillPerSecond);

    Tokens are refilled for the seconds that passed since the last request. Math.min stops the bucket from growing past its capacity, so a long idle period never buys an unlimited burst.

  3. Wait timeconst retryAfter = Math.ceil((1 - this.tokens) / this.refillPerSecond);

    This computes how long until one whole token exists and rounds up with ceil. Retry-After is a whole number of seconds, so the wait is always rounded up rather than down.

  4. One bucket per keyif (!buckets.has(key)) buckets.set(key, new TokenBucket(3, 1));

    Every API key gets its own bucket. Alice running dry does not touch Bob's bucket, which is the fairness goal of a rate limit.

  5. 429 responseres.setHeader("Retry-After", String(result.retryAfter));

    A refused response carries status 429 plus Retry-After as a number of seconds. Header values are strings, which is why the number goes through String().

  6. Time passesclock.seconds += 2;

    Advancing the fake clock by 2 gives Alice's bucket two tokens back. The next request spends one, which leaves remaining=1.

You should see
alice #1: 200 remaining=2
alice #2: 200 remaining=1
alice #3: 200 remaining=0
alice #4: 429 retry-after=1
alice #5: 429 retry-after=1
bob #1: 200 remaining=2
alice after 2s: 200 remaining=1

Fixed window, sliding window and token bucket compared

A fixed window is simple and cheap: one counter and the start of the window are enough. The weakness is the boundary. With a limit of 100 per minute, a client can send 100 requests at 12:00:59 and another 100 at 12:01:00, getting 200 through in two seconds. A sliding window removes that seam but has to remember request times, which costs more memory. A token bucket is popular because it allows a controlled burst with very little state.

AlgorithmStrengthWeakness
Fixed windowSimple, least stateUp to double the limit across a boundary
Sliding windowNo seam, preciseStores request times, so more memory
Token bucketAllows bursts, controls the averageTwo numbers to tune: capacity and refill rate

The simulation below uses a 10-second window with a limit of 3 and sends six requests between second 8 and second 11. The fixed window opens a new slot at second 10 and lets all six through, while the sliding window lets only three pass.

windows.mjs
const LIMIT = 3;
const WINDOW = 10; // seconds

function fixedWindow() {
  let windowId = -1;
  let count = 0;
  return (t) => {
    const id = Math.floor(t / WINDOW);
    if (id !== windowId) {
      windowId = id;
      count = 0;
    }
    if (count >= LIMIT) return false;
    count += 1;
    return true;
  };
}

function slidingWindow() {
  let hits = [];
  return (t) => {
    hits = hits.filter((hit) => hit > t - WINDOW);
    if (hits.length >= LIMIT) return false;
    hits.push(t);
    return true;
  };
}

const fixed = fixedWindow();
const sliding = slidingWindow();
console.log("time  fixed  sliding");
for (const t of [8, 8.5, 9, 10, 10.5, 11]) {
  const f = fixed(t) ? "allow" : "deny";
  const s = sliding(t) ? "allow" : "deny";
  console.log(`${String(t).padEnd(5)} ${f.padEnd(6)} ${s}`);
}
text
time  fixed  sliding
8     allow  allow
8.5   allow  allow
9     allow  allow
10    allow  deny
10.5  allow  deny
11    allow  deny

On the client: Retry-After, backoff and idempotency

A good retry helper follows three rules. First, a 429 means the server refused the request before doing any work, so retrying is fine for any method (still check your provider's documentation). Second, in uncertain cases such as a 503 or a network error, retry only idempotent methods such as GET, PUT and DELETE, or requests that carry an Idempotency-Key. Third, use Retry-After when it is present and fall back to backoff with jitter and a growing ceiling when it is not.

In the sample below, sleep and random are injected from outside, so it can record the waits without really waiting. The server simulates a POST /orders that saves the order and then loses the first reply, as if the network dropped. A keyless POST is not retried, because that would create a second order. With a key, the server looks the key up and returns the stored order, so no duplicate appears.

retry-client.mjs
import http from "node:http";

// --- mock server -------------------------------------------------------
let flakyCalls = 0;
const orders = [];
const byKey = new Map();

const server = http.createServer((req, res) => {
  if (req.url === "/flaky") {
    flakyCalls += 1;
    if (flakyCalls === 1) {
      res.writeHead(429, { "Retry-After": "2" }).end();
    } else if (flakyCalls === 2) {
      res.writeHead(503).end();
    } else {
      res.writeHead(200).end("ok");
    }
    return;
  }
  // POST /orders: the order is saved, then the "network" drops the first reply.
  const key = req.headers["idempotency-key"];
  if (key && byKey.has(key)) {
    res.writeHead(200).end(JSON.stringify(byKey.get(key)));
    return;
  }
  const order = { id: orders.length + 1 };
  orders.push(order);
  if (key) byKey.set(key, order);
  res.writeHead(503).end();
});

await new Promise((resolve) => server.listen(0, resolve));
const base = `http://127.0.0.1:${server.address().port}`;

// --- client -------------------------------------------------------------
const IDEMPOTENT = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);

function parseRetryAfter(value) {
  if (value === null) return null;
  if (/^\d+$/.test(value)) return Number(value) * 1000;
  const when = Date.parse(value);
  return Number.isNaN(when) ? null : Math.max(0, when - Date.now());
}

async function fetchWithRetry(url, options, { maxAttempts, sleep, random }) {
  const method = (options.method ?? "GET").toUpperCase();
  const key = options.headers?.["Idempotency-Key"];
  const safeToRepeat = IDEMPOTENT.has(method) || Boolean(key);
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(url, options);
    const refused = res.status === 429; // the server declined before doing any work
    const transient = res.status === 503;
    if (attempt >= maxAttempts || !(refused || (transient && safeToRepeat))) return res;
    const asked = parseRetryAfter(res.headers.get("retry-after"));
    const cap = Math.min(8000, 500 * 2 ** (attempt - 1));
    await sleep(asked ?? Math.floor(random() * cap)); // full jitter when no Retry-After
  }
}

const waits = [];
const policy = { maxAttempts: 4, sleep: async (ms) => waits.push(ms), random: () => 0.5 };

const get = await fetchWithRetry(`${base}/flaky`, {}, policy);
console.log("GET status:", get.status, "waits:", JSON.stringify(waits));

const plain = await fetchWithRetry(`${base}/orders`, { method: "POST" }, policy);
console.log("POST without key:", plain.status, "orders saved:", orders.length);

const post = { method: "POST", headers: { "Idempotency-Key": "checkout-42" } };
const keyed = await fetchWithRetry(`${base}/orders`, post, policy);
console.log("POST with key:", keyed.status, "orders saved:", orders.length);
server.close();
text
GET status: 200 waits: [2000,500]
POST without key: 503 orders saved: 1
POST with key: 200 orders saved: 2

Idempotency-Key is a convention

The Idempotency-Key header is used by providers such as Stripe and is an IETF draft, but not every API supports it. Check your provider's documentation, and when it does not, never retry a timed-out POST blindly: look the resource up with a GET first to see whether it was created.

Slowing yourself down: a concurrency limit

Avoiding a 429 beats handling one. Firing 1,000 requests at once with Promise.all will cross any limit immediately. Feed the work through a few lanes instead, so only two run at a time. In the helper below, two lanes each take a new job only after finishing the previous one, so the number of requests in flight never exceeds two.

map-limit.mjs
async function mapLimit(items, limit, worker) {
  const results = new Array(items.length);
  let next = 0;
  let active = 0;
  let peak = 0;

  async function lane() {
    while (next < items.length) {
      const index = next++;
      active += 1;
      peak = Math.max(peak, active);
      results[index] = await worker(items[index]);
      active -= 1;
    }
  }

  await Promise.all(Array.from({ length: limit }, lane));
  return { results, peak };
}

const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const { results, peak } = await mapLimit([1, 2, 3, 4, 5, 6], 2, async (n) => {
  await pause(5);
  return n * 10;
});
console.log(results, "peak in flight:", peak);
text
[ 10, 20, 30, 40, 50, 60 ] peak in flight: 2

A concurrency limit controls how many requests run at once, but not how many you send per minute in total. For that, many clients also keep their own token bucket and take a token before every request, which is a client-side throttle.

In real projects

Where this shows up in real projects

Cloud and AI providers publish limits per plan and sometimes per model, and those numbers change, so reading them from response headers is safer than hard-coding them. A nightly sync job that fires every request at midnight will hit 429 far more often than one that spreads the same work across the whole day.

When many worker servers share one API key, a limiter inside each process is not enough, so the bucket lives in a shared store such as Redis and every worker takes tokens from it. If you build your own API the same applies: gateways and reverse proxies such as nginx include built-in limiters. Watching the percentage of 429 responses on a dashboard warns you before you hit the ceiling and tells you when a bigger plan is justified. Browsers add a twist, because cross-origin JavaScript cannot see Retry-After unless the server exposes it, which the next lesson on CORS explains.

Common mistakes

Common mistakes

1. Retrying in a tight loop with no delay

while (res.status === 429) { res = await fetch(url); } attacks the server harder. It burns more quota, extends any penalty and stops your own job from finishing. Wait for Retry-After and cap the attempts.

2. Backoff without jitter

If 500 clients all wait exactly 1s, 2s, 4s, they all come back at the same instant and cause another spike, the thundering herd. Spread the delay with random(0, ceiling) so the retries arrive scattered.

3. Assuming Retry-After is always a number

In HTTP, Retry-After can also be a date such as Wed, 21 Oct 2026 07:28:00 GMT. Calling Number(value) on it gives NaN, and a setTimeout with NaN fires immediately. Test for digits first and fall back to Date.parse.

4. Retrying a timed-out POST without a key

A timeout can mean the server never received the request, or that it did the work and the reply got lost. Sending it again may charge a card twice or send two emails, so retry only when an Idempotency-Key is present.

Best practices

Best practices

  • Share one retry helper across the whole app instead of writing a loop at every fetch call site.
  • Pass both sleep and random in as parameters so tests can verify the behaviour without really waiting.
  • Do not rotate API keys or spread traffic over many IP addresses to dodge a limit; that breaks provider rules and can get the account blocked.

Mini challenge

Mini challenge: a fixed window limiter

Build a fixed window limiter in front of a mock server instead of a token bucket. Allow 2 requests per 10-second window, drive time with a fake clock and show the quota coming back when the window changes.

  • A FixedWindowLimiter class whose hit() returns { allowed, remaining } or { allowed: false, retryAfter }
  • Compute the window start with Math.floor(clock.now / windowSeconds) * windowSeconds and reset the count when a new window begins
  • On refusal, retryAfter is the number of seconds left in the current window
  • Make three requests at t=0, move the clock to 10, make one more, and print every result
fixed-window.mjs
import http from "node:http";

const clock = { now: 0 };

class FixedWindowLimiter {
  constructor(limit, windowSeconds) {
    // TODO: remember the limit and window length, plus the current window start and count
  }

  hit() {
    // TODO: begin a new window when clock.now has moved into the next one
    // TODO: count used up? refuse with retryAfter = seconds left in this window
    // TODO: otherwise count the hit and return allowed: true with remaining
  }
}

const limiter = new FixedWindowLimiter(2, 10);
const server = http.createServer((req, res) => {
  // TODO: call limiter.hit(), then answer 200 (with remaining) or 429 (with Retry-After)
});

// TODO: listen on port 0 and call the server three times at t=0
// TODO: move clock.now to 10, call once more, print each line, then close the server

Expected: The program prints: t=0 200 remaining=1 t=0 200 remaining=0 t=0 429 retry-after=10 t=10 200 remaining=1

Show hint

Compare the stored windowStart with the one you just computed to know whether a new window began. retryAfter is windowStart + windowSeconds - clock.now. Print the time from clock.now, never from Date.now().

Show solution
fixed-window.mjs
import http from "node:http";

const clock = { now: 0 };

class FixedWindowLimiter {
  constructor(limit, windowSeconds) {
    this.limit = limit;
    this.windowSeconds = windowSeconds;
    this.windowStart = -1;
    this.count = 0;
  }

  hit() {
    const start = Math.floor(clock.now / this.windowSeconds) * this.windowSeconds;
    if (start !== this.windowStart) {
      this.windowStart = start;
      this.count = 0;
    }
    if (this.count >= this.limit) {
      return { allowed: false, retryAfter: start + this.windowSeconds - clock.now };
    }
    this.count += 1;
    return { allowed: true, remaining: this.limit - this.count };
  }
}

const limiter = new FixedWindowLimiter(2, 10);
const server = http.createServer((req, res) => {
  const verdict = limiter.hit();
  if (verdict.allowed) {
    res.writeHead(200, { "X-Remaining": String(verdict.remaining) }).end("ok");
  } else {
    res.writeHead(429, { "Retry-After": String(verdict.retryAfter) }).end("slow down");
  }
});

await new Promise((resolve) => server.listen(0, resolve));
const url = "http://127.0.0.1:" + server.address().port + "/";

async function ping() {
  const res = await fetch(url);
  const extra = res.status === 200
    ? "remaining=" + res.headers.get("x-remaining")
    : "retry-after=" + res.headers.get("retry-after");
  console.log("t=" + clock.now, res.status, extra);
}

await ping();
await ping();
await ping();
clock.now = 10;
await ping();
server.close();

Quick quiz 1 / 3

A response is 429 with Retry-After: 7, but your backoff formula computed only 2 seconds. What should you do?

Quick quiz 2 / 3

A token bucket has capacity 5 and refills 1 token per second. It is empty after 5 requests at t=0. If requests arrive back to back at t=3, how many pass before the first 429?

Quick quiz 3 / 3

A POST /payments with no Idempotency-Key times out. Why is an automatic resend risky?

What to remember

  • A rate limit counts requests, tokens or concurrency and answers 429 Too Many Requests when exceeded; Retry-After says how long to wait.
  • A fixed window can let double the limit through at a boundary, a sliding window has no seam, and a token bucket allows bursts while controlling the average.
  • X-RateLimit-* and RateLimit-* headers are conventions that differ by provider, so read the documentation.
  • The client obeys Retry-After first, falls back to exponential backoff with jitter, and always has an attempt cap and a deadline.
  • Retrying a refused request is fine, but never retry a timed-out POST without an idempotency key; slow yourself down with a concurrency limit as well.

RFC 9110 — HTTP Semantics — IETF

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Rate Limit & Retry | Thuta Learning