JavaScript Snippet

Retry with Exponential Backoff

Difficulty: Medium

Network calls and flaky integrations need a retry wrapper, but plain retries hammer the same endpoint and amplify outages. Exponential backoff doubles the wait between attempts so transient failures recover fast and persistent failures don't DDoS the upstream. This snippet covers the canonical retry, a jittered version that prevents thundering-herd retries across clients, and a policy-driven variant that lets the caller decide which errors are retryable.

Code Snippets
/

Retry with Exponential Backoff

Retry with Exponential Backoff

Network calls and flaky integrations need a retry wrapper, but plain retries hammer the same endpoint and amplify outages. Exponential backoff doubles the wait between attempts so transient failures recover fast and persistent failures don't DDoS the upstream. This snippet covers the canonical retry, a jittered version that prevents thundering-herd retries across clients, and a policy-driven variant that lets the caller decide which errors are retryable.

JavaScript
Medium
3 snippets
utility
code-template
error-handling
retry-policy

855 views

15

The shape is a for loop with try/catch and a sleep between attempts. Doubling the wait via baseMs * 2 ** attempt gives 100ms, 200ms, 400ms, 800ms, which lets transient blips recover quickly while persistent failures back off enough to not overwhelm upstream. The attempt === retries early break ensures the final attempt does NOT sleep needlessly before throwing. Always rethrow the last error so callers can react to genuine failures; swallowing it turns this from a retry into a silent skip.