⚑LearnIT
Engineering Β· Topic 16

πŸ”API Error Handling & Retries

16.1Robust fetch with retries + exponential backoff

async function fetchWithRetry(url, options = {}, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const res = await fetch(url, options);
      // Retry only on transient/server errors, not client errors (4xx)
      if (!res.ok) {
        if (res.status >= 500 && attempt < maxRetries - 1) throw new Error(`HTTP ${res.status}`);
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
      }
      return await res.json();
    } catch (err) {
      if (attempt === maxRetries - 1) throw err;         // out of retries
      const backoff = 1000 * 2 ** attempt;               // 1s, 2s, 4s...
      const jitter = Math.random() * 200;                // avoid thundering herd
      await new Promise((r) => setTimeout(r, backoff + jitter));
    }
  }
}

Principles:

  • Retry only what's retryable. 5xx and network errors: yes. 4xx (bad request, unauthorized, not found): no β€” retrying won't help and can cause harm. 429 (rate limited): retry, but respect Retry-After.
  • Exponential backoff + jitter β€” spreads retries so you don't hammer a recovering server (thundering herd).
  • Idempotency for writes. Retrying a POST can double-charge/double-create. Use idempotency keys so the server dedupes retried writes.
  • Timeouts. Don't wait forever β€” use AbortController with a timeout so a hung request fails fast.
  • User-facing errors. Distinguish "retrying…", "failed, tap to retry", and "you're offline". Show actionable messages, not raw error codes.

16.2Let a library do it

@tanstack/react-query / SWR give you retries, backoff, caching, deduplication, background refetch, and optimistic updates declaratively:

useQuery({
  queryKey: ['tickets'],
  queryFn: fetchTickets,
  retry: 2,
  retryDelay: (i) => Math.min(1000 * 2 ** i, 30000),
  staleTime: 60_000,
});

16.3Error boundaries (for render-time errors, not fetch)

React error boundaries catch errors thrown during rendering of their child tree and show a fallback instead of unmounting the whole app. They do not catch async errors (event handlers, fetch) β€” handle those with try/catch and state.

import { ErrorBoundary } from 'react-error-boundary';
<ErrorBoundary FallbackComponent={ErrorFallback} onReset={() => location.assign('/')}>
  <App />
</ErrorBoundary>

Wrap risky subtrees (a lazy-loaded module, a chart, a third-party widget) so one crash doesn't take down the page. Combine with a monitoring hook (onError) to report to Sentry.

🧠 Quiz: API Error Handling & Retries

2 questions

1'Exponential backoff' for retries means:

2React Error Boundaries catch:

Answered 0/2