javascript / expert
Snippet
Resilient Async Streams with Exponential Backoff
When handling flaky network requests, a simple retry is often insufficient. Exponential backoff reduces server strain by increasing the delay between attempts mathematically, ensuring a more stable recovery mechanism.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
import { timer, retry } from 'rxjs';this.http.get('/api/data').pipe(retry({count: 3,delay: (error, retryCount) => {const backoffTime = Math.pow(2, retryCount) * 1000;console.warn(`Retry #${retryCount} in ${backoffTime}ms`);return timer(backoffTime);}})).subscribe();
angular
Breakdown
1
delay: (error, retryCount) => ...
A dynamic delay function that receives the error and the current attempt index.
2
Math.pow(2, retryCount) * 1000
Calculates the wait time exponentially (1s, 2s, 4s, etc.) to prevent thundering herd problems.