Retry with Backoff Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Retry with Backoff runs in O(attempts) time and O(1) space, in TypeScript as in every other language.
- ✓The runtime tools are the JavaScript ones. What TypeScript adds is the ability to make retryability part of the ERROR TYPE rather than a runtime string comparison: define a discriminated union of failure kinds, and let the compiler force the retry loop to handle each one, so adding a new failure mode later is a compile error at every decision point rather than a silent fall-through to the retry branch.
- ✓Model the outcome as a discriminated union, success, retryable, permanent, and switch exhaustively with a never-typed default.
- ✓The TypeScript trap: Typing a retry helper as (fn: () => Promise<T>) => Promise<T> makes it look safe while silently permitting non-idempotent operations, and the type system cannot express idempotence, so the guard has to be a naming and review convention, or a branded type you require callers to construct.
- ✓Erased; runtime cost equals the JavaScript version. The classification switch is a few nanoseconds.
What Retry with Backoff actually is
Retry with Backoff in TypeScript: what you actually reach for
TypeScript implementation
export type Outcome<T> =
| { readonly kind: 'ok'; readonly value: T }
| { readonly kind: 'retryable'; readonly error: Error; readonly retryAfterMs?: number }
| { readonly kind: 'permanent'; readonly error: Error };
const fullJitter = (attempt: number, base = 200, cap = 10_000): number =>
Math.random() * Math.min(cap, base * 2 ** attempt);
const sleep = (ms: number) => new Promise<void>(r => setTimeout(r, ms));
/** The caller must classify; the loop cannot guess, and the compiler enforces it. */
export async function withRetry<T>(
op: () => Promise<Outcome<T>>,
attempts = 5,
): Promise<T> {
let last: Error | undefined;
for (let i = 0; i < attempts; i++) {
const out = await op();
switch (out.kind) {
case 'ok':
return out.value;
case 'permanent':
throw out.error; // never retried
case 'retryable':
last = out.error;
await sleep(out.retryAfterMs ?? fullJitter(i));
break;
default: {
const _exhaustive: never = out; // a new kind = COMPILE error
throw new Error(String(_exhaustive));
}
}
}
throw last ?? new Error('retries exhausted');
}
// The type system CANNOT express idempotence. That guard stays a review
// convention or a branded type callers must construct deliberately.Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(attempts)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Retry with Backoff?
The runtime tools are the JavaScript ones. What TypeScript adds is the ability to make retryability part of the ERROR TYPE rather than a runtime string comparison: define a discriminated union of failure kinds, and let the compiler force the retry loop to handle each one, so adding a new failure mode later is a compile error at every decision point rather than a silent fall-through to the retry branch.
What is the most common TypeScript mistake when implementing Retry with Backoff?
Typing a retry helper as (fn: () => Promise<T>) => Promise<T> makes it look safe while silently permitting non-idempotent operations, and the type system cannot express idempotence, so the guard has to be a naming and review convention, or a branded type you require callers to construct. The narrower TypeScript-specific trap is catch binding: caught values are unknown under useUnknownInCatchVariables, and casting to Error to read a code property reintroduces exactly the unchecked assumption the union was meant to remove.
How does Retry with Backoff actually perform in TypeScript?
Erased; runtime cost equals the JavaScript version. The classification switch is a few nanoseconds. The engineering value is that the retry POLICY becomes a single typed function that can be tested in isolation, which is where the correctness of the whole mechanism actually lives. Time complexity is O(attempts) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.