Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Error Retry Logic in JavaScript

Write retry logic in JavaScript: simple retries, exponential backoff, retries with conditions and a RetryHandler class with demos. Explanation and output.

IntermediateJavaScript Error HandlingExample 7 of 10
error-retry-logic.js
1// Method 1: Simple retry
2async function retryOperation(fn, maxRetries = 3) {
3 for (let i = 0; i < maxRetries; i++) {
4 try {
5 return await fn();
6 } catch (error) {
7 if (i === maxRetries - 1) throw error;
8 console.log(`Retry ${i + 1} failed, retrying...`);
9 await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
10 }
11 }
12}
13
14// Method 2: Retry with exponential backoff
15async function retryWithBackoff(fn, maxRetries = 3, baseDelay = 1000) {
16 for (let i = 0; i < maxRetries; i++) {
17 try {
18 return await fn();
19 } catch (error) {
20 if (i === maxRetries - 1) throw error;
21 const delay = baseDelay * Math.pow(2, i);
22 console.log(`Retry ${i + 1} after ${delay}ms`);
23 await new Promise(resolve => setTimeout(resolve, delay));
24 }
25 }
26}
27
28// Method 3: Retry with conditions
29async function retryWithCondition(fn, shouldRetry, maxRetries = 3) {
30 for (let i = 0; i < maxRetries; i++) {
31 try {
32 return await fn();
33 } catch (error) {
34 if (!shouldRetry(error) || i === maxRetries - 1) {
35 throw error;
36 }
37 await new Promise(resolve => setTimeout(resolve, 1000));
38 }
39 }
40}
41
42// Usage
43retryWithCondition(
44 () => fetch('https://api.example.com/data'),
45 (error) => error.message.includes('network') || error.message.includes('timeout'),
46 3
47).catch(error => console.log('Conditional retry gave up:', error.message));
48
49// Method 4: Retry class
50class RetryHandler {
51 constructor(options = {}) {
52 this.maxRetries = options.maxRetries || 3;
53 this.delay = options.delay || 1000;
54 this.backoff = options.backoff || 'exponential';
55 }
56
57 async execute(fn) {
58 for (let i = 0; i < this.maxRetries; i++) {
59 try {
60 return await fn();
61 } catch (error) {
62 if (i === this.maxRetries - 1) throw error;
63
64 const delay = this.calculateDelay(i);
65 await this.wait(delay);
66 }
67 }
68 }
69
70 calculateDelay(attempt) {
71 if (this.backoff === 'exponential') {
72 return this.delay * Math.pow(2, attempt);
73 }
74 return this.delay;
75 }
76
77 wait(ms) {
78 return new Promise(resolve => setTimeout(resolve, ms));
79 }
80}
81
82const retryHandler = new RetryHandler({ maxRetries: 3, delay: 1000 });
83retryHandler.execute(() => fetch('https://api.example.com/data'))
84 .catch(error => console.log('RetryHandler gave up:', error.message));
85
86// Demo: an operation that fails twice, then works
87let attempts = 0;
88function flakyUpload() {
89 attempts++;
90 if (attempts < 3) return Promise.reject(new Error('Server busy'));
91 return Promise.resolve('Uploaded on attempt ' + attempts);
92}
93
94retryWithBackoff(flakyUpload).then(result => console.log(result));

Sample Output

Retry 1 after 1000ms

This line is from the flakyUpload demo. Its first try failed.

Conditional retry gave up: Failed to fetch

The error text has no "network" or "timeout", so shouldRetry says no. Node prints "fetch failed".

RetryHandler gave up: Failed to fetch

Prints after about 3 seconds, after three failed tries with waits of 1000 ms and 2000 ms.

In this one

  • How a retry loop works with await
  • What exponential backoff is and why it helps
  • When not to retry an error
  • Why every retry call needs a .catch

How it works

  1. 1

    Three retry calls start together.

  2. 2

    flakyUpload fails, and backoff waits 1000 ms.

  3. 3

    The conditional retry gives up right away.

  4. 4

    flakyUpload fails again and waits 2000 ms.

  5. 5

    The third try works and prints the result.

  6. 6

    RetryHandler fails three times and gives up.

Edge cases

Retrying errors that never pass

A 400 Bad Request is retried again and again.

Retry only network errors, timeouts and 5xx replies.

Many clients retry together

Everyone retries at the same second and overloads the server.

Add a small random delay, called jitter.

No final catch

The last failure becomes an unhandled rejection.

Always add .catch or await inside try.

What's going on

Some errors fix themselves. A server may be busy for a second, or a phone may lose signal briefly. Retry logic tries the same operation again before giving up. JavaScript async functions and timers make this short to write.

Method 1 loops up to maxRetries times. Each time it awaits fn(). On success it returns the result and the loop ends. On failure it waits and tries again. On the last try it throws, so the caller learns that everything failed.

Method 2 uses exponential backoff. Backoff means waiting longer after each failure. The wait doubles: 1000 ms, then 2000 ms, then 4000 ms. This gives a busy server time to recover, instead of hitting it again right away.

Method 3 retries only when shouldRetry says the error is worth it. A wrong password will never succeed, so retrying it wastes time. In the run, fetch fails with "fetch failed", which does not include "network" or "timeout", so it gives up at once.

Method 4 puts the same idea in a RetryHandler class with options for max tries, delay and backoff type.

Each call has a .catch, so a final failure prints a clear message instead of becoming an unhandled rejection. The flakyUpload demo fails twice with "Server busy" and works on the third try.

The lines interleave because the calls run at the same time. Each one waits on its own timer.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

With base 1000 ms, what is the third backoff wait?

Pick an answer to check it.

Question 2

Why add .catch to a retry call?

Pick an answer to check it.

Questions people ask

How many retries should I use?

Usually 3 to 5. More only makes users wait longer.

Is it safe to retry a payment?

Only if the server ignores duplicates, for example with an idempotency key.

Why does the order of lines mix?

All three calls run at once, each on its own timer.