Belajar
← All lessons

How retries and backoff work

Retry a flaky call

Client
Orders API

retry.js

async function callWithRetry(url, maxAttempts = 4) {  for (let attempt = 1; ; attempt++) {    try {      const res = await fetchWithTimeout(url, 2000);      if (res.ok) return res;      throw new HttpError(res.status);    } catch (err) {      if (attempt === maxAttempts) throw err;      const delay = 1000 * 2 ** (attempt - 1);      await sleep(delay); // 1s, 2s, 4s    }  }}

Sixty clients retry at once and jitter spreads them out

Failure rate
Base delay
Max attempts
JitterOffFull jitter
Calls the service gets, every 250ms

backoff.js

function delayFor(attempt, { base, jitter }) {  const cap = base * 2 ** (attempt - 1);  if (!jitter) return cap; // everyone waits the same  return Math.random() * cap; // full jitter} for (let attempt = 1; attempt <= maxAttempts; attempt++) {  const res = await call();  if (res.ok) return res;  await sleep(delayFor(attempt, opts));}throw new Error("gave up");

Retry only what can work a 400 fails every time

The service answers503Timeout429400401
Response
If the client keeps trying

should-retry.js

function shouldRetry(err) {  if (err.name === "TimeoutError") return true;  const s = err.status;  if (s === 429) return true; // wait for Retry-After  if (s >= 500) return true;  // the server is having trouble  return false; // 4xx: the request itself is wrong}

Retry a payment safely with an idempotency key

Shop app
Network
Payments
Ledger

checkout.js

// one key per payment, sent again on every retryconst key = crypto.randomUUID();await callWithRetry("/charges", {  method: "POST",  headers: { "Idempotency-Key": key },  body: JSON.stringify({ amount: 2000 }),});

server.js

app.post("/charges", async (req, res) => {  const key = req.get("Idempotency-Key");  const seen = key && (await saved.get(key));  if (seen) return res.status(201).json(seen);  const charge = await db.charges.insert(req.body);  if (key) await saved.put(key, charge);  res.status(201).json(charge);});

Topics

Next: How webhooks work

Open lesson