💻
CODE SNIPPET — Sunday, Aug 9JavaScript: Retry with Exponential Backoff & JitterEvery API call fails sometimes. Here's a zero-dependency retry utility with AWS-style full jitter that works in Node.js 18+ and browsers:
async function retryWithBackoff(fn, options = {}) {
const { maxRetries = 3, baseDelay = 1000, maxDelay = 30000 } = options;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (err) {
if (attempt === maxRetries) throw err;
// Full jitter: random delay up to min(base * 2^attempt, max)
const delay = Math.random() * Math.min(baseDelay * 2 ** attempt, maxDelay);
await new Promise(r => setTimeout(r, delay));
}
}
}
// Usage:
const data = await retryWithBackoff(async () =>
fetch('https://api.example.com/data').then(r => {
if (!r.ok) throw new Error(r.status);
return r.json();
})
);
Why full jitter? Pure exponential backoff causes thundering herds when many clients retry simultaneously. Jitter spreads retries out randomly, reducing server load spikes.
💡 Pro tip: Add a
Retry-After header check and respect it — most well-designed APIs tell you exactly how long to wait before retrying. Bookmark this — you'll use it in every project. 📌