0 day streak
javascript / expert
Snippet

Advanced Error Recovery with Exponential Backoff

Implementing exponential backoff is a best practice for handling transient network failures. Instead of retrying immediately, the delay increases exponentially with each attempt, preventing the client from overwhelming a struggling server.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
import { timer, throwError } from 'rxjs';
import { retry, mergeMap } from 'rxjs/operators';
const retryStrategy = (maxRetries: number = 3) => retry({
count: maxRetries,
delay: (error, retryCount) => {
console.warn(`Retry attempt ${retryCount}...`);
return timer(Math.pow(2, retryCount) * 1000);
}
});
this.http.get('/api/data').pipe(retryStrategy()).subscribe();
angular
Breakdown
1
retry({ count, delay })
The retry operator configuration that specifies how many times and when to re-subscribe to the source.
2
Math.pow(2, retryCount) * 1000
Calculates the exponential delay (2s, 4s, 8s, etc.) based on the current attempt number.
3
timer(...)
Creates an observable that waits for the calculated duration before triggering the next retry attempt.