TypeScript / Tested teaching helper
Calculate a bounded retry delay
Cap exponential retry delays and let the caller enforce a total deadline.
TypeScript
export function retryDelayMs(attempt: number, capMs = 8000): number {
const safeAttempt = Number.isFinite(attempt) ? Math.max(0, Math.min(12, Math.floor(attempt))) : 0;
const safeCap = Number.isFinite(capMs) ? Math.max(0, Math.floor(capMs)) : 8000;
return Math.min(safeCap, 250 * 2 ** safeAttempt);
}What matters
This pure function is only a deterministic base delay. In real systems add randomized jitter, a total deadline, a retry budget, and error classification; do not retry authorization failures.
Test these cases
- Attempt 0 → 250 ms
- Attempt 4 → 4000 ms
- Attempt 20 → capped
Sources and limits
This is a reference snippet, not a substitute for reviewing the full vendor API contract, concurrency rules or production threat model. Do not paste secrets into sample code.
This pure helper has runnable Node.js tests in the downloadable educational bundle. Those tests do not verify a full production security system.