Skip to article content
FrontendXLesson 07 / 20

Errors, retries, timeouts and graceful degradation

Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.

intermediate · about 45 minutes · 5 exercises

  • Predict
  • Explain
  • Implement
  • Test

What you will be able to do

#
  • Classify model API failures into retryable and non-retryable classes with a stated first response for each.
  • Implement deterministic exponential backoff with a retry budget and trace attempts and delays for a scripted failure sequence.
  • Explain why timeout retries require idempotency and choose an honest fallback when the budget is exhausted.

Overview

#

A failure taxonomy before any retry code

Model API calls fail in distinguishable ways, and the correct response differs by class:

Failure classExampleRetryable?First response
Rate limiting429Yes, after backoffSlow down, respect the window
Server faults5xxYes, after backoffRetry with a budget
Transporttimeout, connection resetYes, with careRetry only if idempotent
Bad request400 validationNoFix the request
Auth401, 403NoFix credentials or permissions
Policy stopcontent filterNo (same input)Change the input or refuse gracefully
Bad outputunparseable JSONSpecialBounded repair, lesson 5

Writing the taxonomy down is the engineering act. Teams that skip it end up retrying 400s in a loop or treating a rate-limit storm as a bug in their own code.

Backoff with a bounded budget

Exponential backoff waits longer after each failure: base, base times 2, base times 4. A retry budget caps total attempts so a persistent outage produces a clean failure, not an infinite loop. This course uses deterministic doubling with no jitter so exercises are hand-traceable; production systems add random jitter to keep many clients from retrying in synchronized waves.

snippet.javascript
function retryWithBackoff(fn, opts) {
  const maxAttempts = opts.maxAttempts;
  const baseDelayMs = opts.baseDelayMs;
  const delays = [];
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const outcome = fn();
    if (outcome.ok) {
      return { ok: true, value: outcome.value, attempts: attempt, delays };
    }
    if (!classifyError(outcome.error).retryable) {
      return { ok: false, error: outcome.error, attempts: attempt, delays };
    }
    if (attempt < maxAttempts) {
      delays.push(baseDelayMs * Math.pow(2, attempt - 1));
    }
  }
  return { ok: false, error: "exhausted", attempts: maxAttempts, delays };
}

With a scripted client whose calls fail with rate_limited twice and then succeed, retryWithBackoff(fn, { maxAttempts: 3, baseDelayMs: 100 }) returns ok with attempts 3 and delays 100 then 200. Trace it: attempt 1 fails, delay 100; attempt 2 fails, delay 200; attempt 3 succeeds.

Timeouts and idempotency

A timeout means your client gave up waiting. It does not mean the server did no work: the request may have completed after you stopped listening. Retrying a non-idempotent operation (charge a card, send an email, create a record) can therefore do the work twice. The defenses are boring and effective: pass an idempotency key so the server can deduplicate, or design the operation so running it twice is harmless, or make the retry a human decision. This is the same reasoning that motivates approval gates in lesson 11.

Graceful degradation is a product feature

When the budget is exhausted, the feature still owes the user an answer. Decide the fallback deliberately: queue and retry later, serve cached content, present a clear "this feature is unavailable" state, or route to a human. What you must not do is hide the failure behind a plausible-looking canned response that the user cannot distinguish from a real answer. Degradation honesty is part of the honesty themes this course keeps returning to: uncertainty labeled as uncertainty (lesson 14), retrieval gaps answered with abstention (lesson 9), and outages surfaced as outages.

Rate limits are a shared resource

A 429 tells you the pool is exhausted, not that your request was wrong. Respect the window the error reports, spread load with concurrency limits, and remember that retries amplify load precisely when the system is least able to absorb it. Under sustained pressure, fail fast toward your fallback instead of piling retries onto an overloaded upstream.

Continue with ai-engineering-embeddings-and-similarity, the first retrieval lesson. Lesson ai-engineering-bounded-agents applies retry budgets inside agent loops.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Implement

    Implement retryWithBackoff(fn, opts) where fn returns { ok, value } on success or { ok: false, error } on failure. Retry only errors that classifyError marks retryable, delay baseDelayMs * 2^(attempt-1) between attempts, and stop after maxAttempts. Return { ok, value?, error?, attempts, delays }.

    starter.javascript
    function classifyError(kind) {
      // Provided: rate_limited, server_error, timeout, network -> retryable.
      // invalid_request, unauthorized, not_found, content_filtered -> not.
      // Unknown -> not retryable.
      const retryable = ["rate_limited", "server_error", "timeout", "network"];
      return { retryable: retryable.includes(kind) };
    }
    
    function retryWithBackoff(fn, opts) {
      // fn returns { ok: true, value } or { ok: false, error }.
      // opts: { maxAttempts, baseDelayMs }.
      // Retry only retryable errors; delay baseDelayMs * 2^(attempt-1)
      // between attempts; record delays in order.
    }

    Reveal the reference answer
    reference.javascript
    function classifyError(kind) {
      const retryable = ["rate_limited", "server_error", "timeout", "network"];
      return { retryable: retryable.includes(kind) };
    }
    
    function retryWithBackoff(fn, opts) {
      const delays = [];
      for (let attempt = 1; attempt <= opts.maxAttempts; attempt++) {
        const outcome = fn();
        if (outcome.ok) {
          return { ok: true, value: outcome.value, attempts: attempt, delays };
        }
        if (!classifyError(outcome.error).retryable) {
          return { ok: false, error: outcome.error, attempts: attempt, delays };
        }
        if (attempt < opts.maxAttempts) {
          delays.push(opts.baseDelayMs * Math.pow(2, attempt - 1));
        }
      }
      return { ok: false, error: "exhausted", attempts: opts.maxAttempts, delays };
    }
    
    function scriptedClient() {
      const script = ["rate_limited", "rate_limited", "ok"];
      let i = 0;
      return () => {
        const kind = script[i];
        i += 1;
        return kind === "ok" ? { ok: true, value: "done" } : { ok: false, error: kind };
      };
    }
    
    const result = retryWithBackoff(scriptedClient(), { maxAttempts: 3, baseDelayMs: 100 });
    console.log(JSON.stringify(result));

    Authored expected output: {"ok":true,"value":"done","attempts":3,"delays":[100,200]}

    The scripted client fails twice with rate_limited and succeeds on the third call. Delays double: 100 then 200. Making delays explicit data keeps the retry logic testable without timers.

  2. Exercise 2Predict

    With the same two-failures-then-success script but maxAttempts 2, predict the exact object retryWithBackoff returns.

    starter.javascript
    function classifyError(kind) {
      const retryable = ["rate_limited", "server_error", "timeout", "network"];
      return { retryable: retryable.includes(kind) };
    }
    
    function retryWithBackoff(fn, opts) {
      const delays = [];
      for (let attempt = 1; attempt <= opts.maxAttempts; attempt++) {
        const outcome = fn();
        if (outcome.ok) {
          return { ok: true, value: outcome.value, attempts: attempt, delays };
        }
        if (!classifyError(outcome.error).retryable) {
          return { ok: false, error: outcome.error, attempts: attempt, delays };
        }
        if (attempt < opts.maxAttempts) {
          delays.push(opts.baseDelayMs * Math.pow(2, attempt - 1));
        }
      }
      return { ok: false, error: "exhausted", attempts: opts.maxAttempts, delays };
    }
    
    function scriptedClient() {
      const script = ["rate_limited", "rate_limited", "ok"];
      let i = 0;
      return () => {
        const kind = script[i];
        i += 1;
        return kind === "ok" ? { ok: true, value: "done" } : { ok: false, error: kind };
      };
    }
    
    const result = retryWithBackoff(scriptedClient(), { maxAttempts: 2, baseDelayMs: 100 });
    console.log(JSON.stringify(result));

    Reveal the reference answer
    reference.javascript
    // Predicted output:
    //
    // {"ok":false,"error":"exhausted","attempts":2,"delays":[100]}
    //
    // Trace: attempt 1 fails with rate_limited (retryable), so delay 100 is
    // recorded. Attempt 2 fails too; the budget of 2 is now spent, so the
    // loop exits and returns the "exhausted" sentinel with attempts 2 and
    // delays [100]. The third scripted success is never consumed.

    Authored expected output: {"ok":false,"error":"exhausted","attempts":2,"delays":[100]}

    Attempt 1 fails with a retryable error, delay 100 is recorded, attempt 2 fails, the budget is spent, and the loop returns the exhausted sentinel with attempts 2 and one recorded delay.

  3. Exercise 3Implement

    Implement classifyError(kind) returning { retryable } for these kinds: rate_limited, server_error, timeout and network are retryable; invalid_request, unauthorized, not_found and content_filtered are not. Unknown kinds must default to non-retryable.

    starter.javascript
    function classifyError(kind) {
      // rate_limited, server_error, timeout, network -> { retryable: true }
      // invalid_request, unauthorized, not_found, content_filtered -> { retryable: false }
      // anything else -> { retryable: false }
    }

    Reveal the reference answer
    reference.javascript
    function classifyError(kind) {
      const retryable = ["rate_limited", "server_error", "timeout", "network"];
      return { retryable: retryable.includes(kind) };
    }
    
    console.log(String(classifyError("server_error").retryable));
    console.log(String(classifyError("invalid_request").retryable));

    Authored expected output: true false

    classifyError("server_error").retryable is true and classifyError("invalid_request").retryable is false. Defaulting unknown kinds to non-retryable is the safe direction: retrying an unrecognized failure can amplify an incident.

  4. Exercise 4Test

    Write assertions for a permanently rate-limited client with maxAttempts 3: the result is not ok, attempts equals 3, and delays equals [100, 200]. Then assert a non-retryable error stops immediately with attempts 1 and no delays.

    starter.javascript
    function check(label, condition) {
      console.log(condition ? "PASS" : "FAIL");
    }
    
    // Write six assertions:
    // 1. A client that always fails with rate_limited, maxAttempts 3,
    //    baseDelayMs 100: result.ok === false.
    // 2. Same client: result.attempts === 3.
    // 3. Same client: result.delays deep-equals [100, 200].
    // 4. A client that fails once with invalid_request: result.ok === false.
    // 5. Same client: result.attempts === 1.
    // 6. Same client: result.delays deep-equals [].

    Reveal the reference answer
    reference.javascript
    function check(label, condition) {
      console.log(condition ? "PASS" : "FAIL");
    }
    
    function makeClient(script) {
      let i = 0;
      return () => {
        const kind = script[i];
        i += 1;
        return kind === "ok" ? { ok: true, value: "done" } : { ok: false, error: kind };
      };
    }
    
    const rateLimited = retryWithBackoff(makeClient(["rate_limited", "rate_limited", "rate_limited"]), { maxAttempts: 3, baseDelayMs: 100 });
    check("budget exhausted is not ok", rateLimited.ok === false);
    check("three attempts made", rateLimited.attempts === 3);
    check("delays double", JSON.stringify(rateLimited.delays) === JSON.stringify([100, 200]));
    
    const badRequest = retryWithBackoff(makeClient(["invalid_request", "ok"]), { maxAttempts: 3, baseDelayMs: 100 });
    check("non-retryable is not ok", badRequest.ok === false);
    check("non-retryable stops at one attempt", badRequest.attempts === 1);
    check("non-retryable records no delays", JSON.stringify(badRequest.delays) === JSON.stringify([]));

    Authored expected output: PASS PASS PASS PASS PASS PASS

    The first three assertions pin the budget behavior; the last three pin fail-fast behavior for non-retryable errors. Together they encode the taxonomy as executable expectations for the central verifier to run later.

  5. Exercise 5Explain

    Knowledge check: why does retrying after a timeout require idempotency?

    starter.text
    // Choose the correct option.

    Reveal the reference answer
    reference.text
    A timeout means the client stopped waiting, not that the server did no work. The original request may have completed after the client gave up, so a blind retry can execute side effects twice unless the operation is idempotent or carries a deduplication key.

    Authored expected output: The server may have completed the work, so a retry can duplicate side effects

    Idempotency keys or naturally idempotent designs are prerequisites for retrying any operation with side effects.

Common misconceptions

#
  • Myth: every error deserves a retry. Fact: 4xx validation and auth failures repeat identically; only rate limits, server faults and transport failures are retry candidates.
  • Myth: a timeout means nothing happened. Fact: the server may have completed the work after your client gave up; non-idempotent retries can double side effects.
  • Myth: more retries are always safer. Fact: retries amplify load during outages; a bounded budget plus an explicit fallback is the safer design.

Follow-up practice

#
  • ai-engineering-embeddings-and-similarity
  • ai-engineering-bounded-agents

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.