Networking8 min read
Designing an API Client with Automatic Failover
Timeouts, retries with jittered backoff, circuit breakers and endpoint failover — composed as small policies instead of one tangled fetch wrapper.
Every decentralized app depends on infrastructure it doesn't fully control: public RPCs, indexers, gateways. They're usually fine. When they aren't, the difference between "the app is down" and "the app got a little slower" is how the client behaves.
This article builds a resilient client out of small, composable policies.
Start with what can go wrong
A request can fail in distinguishable ways, and each deserves a different response:
| Failure | Example | Right response |
|---|---|---|
| Slow | Node under load | Time out, try again |
| Transient error | 502, connection reset | Retry with backoff |
| Persistent error | Node down for maintenance | Stop hammering it, fail over |
| Client error | 400, invalid params | Don't retry at all |
A single try/catch around fetch treats all of these the same. Policies let us treat them differently.
Policy 1: timeouts
A request without a timeout can hang forever, holding a slot and a spinner. Timeouts are the foundation every other policy builds on.
async function withTimeout<T>(run: (signal: AbortSignal) => Promise<T>, ms: number) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(new TimeoutError(ms)), ms);
try {
return await run(controller.signal);
} finally {
clearTimeout(timer);
}
}Use AbortSignal so the underlying request is actually cancelled, not merely ignored.
Policy 2: retries with jittered backoff
Retrying immediately turns one failure into many. Exponential backoff spaces attempts out; jitter randomizes them so thousands of clients don't retry in lockstep.
function backoff(attempt: number, base = 200, max = 5_000, random = Math.random) {
const ceiling = Math.min(max, base * 2 ** attempt);
return random() * ceiling; // "full jitter"
}Full jitter — a random delay between zero and the exponential ceiling — is simple and spreads load remarkably well.
Only retry what's retryable: timeouts, network errors and 5xx responses. A 400 will fail the same way every time.
Policy 3: circuit breakers
Retries help with blips. They hurt during outages: every request still pays the full timeout before failing. A circuit breaker remembers recent failures per endpoint:
- Closed — requests flow normally. Consecutive failures are counted.
- Open — after N failures, requests are rejected instantly for a cooldown period.
- Half-open — after the cooldown, one trial request is allowed. Success closes the circuit; failure re-opens it.
The breaker turns "every request waits 3 seconds then fails" into "requests skip the broken endpoint immediately".
Policy 4: failover
With breakers in place, failover is straightforward: try endpoints in priority order, skipping any whose breaker is open, and move to the next when retries on the current one are exhausted.
for (const endpoint of endpoints) {
if (breakers.get(endpoint).isOpen(now())) continue;
const result = await tryWithRetries(endpoint);
if (result.ok) return result;
}
throw new ExhaustedError(trace);Compose, don't nest
The key design decision is keeping these as separate, testable policies with injected dependencies — clock, randomness, transport — rather than one 200-line function:
const client = createResilientClient({
endpoints: ["https://rpc-a.example", "https://rpc-b.example"],
transport: fetchTransport,
timeoutMs: 2_000,
maxRetries: 2,
backoff: { baseMs: 200, maxMs: 2_000 },
breaker: { failureThreshold: 3, cooldownMs: 10_000 },
clock: systemClock,
random: Math.random,
});Injecting the clock and randomness means tests can assert exact backoff delays and breaker transitions without real waiting.
Make it observable
A resilient client that silently fails over hides real problems. Emit structured events — attempt started, attempt failed (and why), backoff scheduled, breaker opened, failed over — and route them to logs and metrics. You want to know your primary endpoint is flapping before your users do.