Sub topic 8
Exponential backoff with the retry delay option
This chapter assumes you know how retry resubscribes to a failed Observable, how to decide which errors are safe to retry, and how HttpErrorResponse exposes status. Here you will control the time between attempts, so a struggling server gets room to recover.
Why a fixed wait is not enough
retry(3) resubscribes immediately after each failure. If a server fails because it is overloaded, three instant retries add load at the worst moment. If thousands of clients fail at once and retry at the same instant, they hit the server together again and again.
Exponential backoff doubles the wait after each failure. The early retries are quick, which suits a brief glitch. The later retries are slow, which gives a real outage time to clear.
The delay option
Since RxJS 7.3, retry accepts a configuration object instead of only a number:
retry({
count: 3,
delay: (error: unknown, retryCount: number) => timer(1000),
resetOnSuccess: false,
})countis the maximum number of retries. The default is infinite, so always set it for HTTP calls.delayis either a number of milliseconds or a function that returns an Observable. It is called each time a retry is about to happen.resetOnSuccessresets the retry counter after the source emits a value. It rarely matters for HttpClient, because a request emits once and then completes. It matters for long-lived streams such as WebSockets.
The function form receives the error and retryCount, which starts at 1 for the first retry. The returned Observable is a notifier. When it emits its first value, retry resubscribes to the source. timer(ms) fits well because it emits once after ms milliseconds.
What the notifier can do
The notifier's behavior decides what happens next:
| Notifier behavior | Result |
|---|---|
| Emits a value | `retry` resubscribes to the source |
| Errors, for example `throwError(() => error)` | The stream fails with that error and no retry happens |
| Completes without emitting, for example `EMPTY` | The output stream completes with no value and no error |
The last row is a common mistake. If your delay function returns EMPTY to mean "stop retrying", the subscriber receives no error and no value. Callers waiting for a result will see only a completion. To stop retrying, return throwError(() => error).
How count and retryCount relate
With count: 3, the source runs up to four times: the first attempt and three retries. The delay function is called with retryCount values 1, 2 and 3. After the third retry fails, retry emits that last error without calling delay again.
Computing the exponential delay
The formula used in the retry interceptor from the Topic Spine is:
wait = base * 2 ^ (retryCount - 1)The exponent is retryCount - 1 because the count starts at 1. With a base of 500 ms, the waits are 500 ms, 1 s and 2 s.
The following script runs as shown. It uses defer so each retry re-executes the failing function, and it logs the planned waits.
import { defer, of, retry, throwError, timer } from 'rxjs';
let attempts = 0;
const flaky$ = defer(() => {
attempts++;
console.log(`attempt ${attempts}`);
return attempts < 4
? throwError(() => new Error(`failure ${attempts}`))
: of(`succeeded on attempt ${attempts}`);
});
flaky$
.pipe(
retry({
count: 3,
delay: (error: unknown, retryCount: number) => {
const waitMs = 100 * 2 ** (retryCount - 1);
console.log(`retry ${retryCount} in ${waitMs} ms after`, (error as Error).message);
return timer(waitMs);
},
})
)
.subscribe({
next: (value) => console.log(value),
error: (err) => console.log('gave up:', err.message),
});The run waits 100 ms, 200 ms and 400 ms, then prints succeeded on attempt 4. If you change the threshold to attempts < 10, all three retries fail and the subscriber receives gave up: failure 4.
Capping the delay
Unbounded doubling grows quickly. With a 500 ms base, the sixth retry would wait 16 seconds. Real applications cap the delay and keep the retry count small, since a user will not wait through long backoff.
const waitMs = Math.min(maxMs, baseMs * 2 ** (retryCount - 1));With baseMs = 500 and maxMs = 8000, the schedule is:
| retryCount | Uncapped wait | Capped wait |
|---|---|---|
| 1 | 500 ms | 500 ms |
| 2 | 1000 ms | 1000 ms |
| 3 | 2000 ms | 2000 ms |
| 4 | 4000 ms | 4000 ms |
| 5 | 8000 ms | 8000 ms |
| 6 | 16000 ms | 8000 ms |
For user-facing requests, 2 or 3 retries is usually the limit. Longer schedules suit background work such as sync jobs.
Adding jitter
If many clients fail at the same moment, say during a deploy, plain exponential backoff keeps them synchronized. Each client retries at 500 ms, then at 1.5 s, and so on, so the server sees waves of traffic. Jitter adds randomness so the retries spread out.
The "full jitter" approach picks a random wait between 0 and the capped exponential value:
import { HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError, timer } from 'rxjs';
export interface BackoffOptions {
baseMs: number;
maxMs: number;
random?: () => number;
}
export function backoffDelay(options: BackoffOptions) {
const { baseMs, maxMs, random = Math.random } = options;
return (error: unknown, retryCount: number): Observable<number> => {
const ceiling = Math.min(maxMs, baseMs * 2 ** (retryCount - 1));
const waitMs = Math.floor(random() * ceiling);
return timer(waitMs);
};
}The random parameter defaults to Math.random but can be replaced in tests with a function that returns a fixed value such as 0.5. That makes the schedule deterministic.
You use it in place of the inline function:
retry({ count: 3, delay: backoffDelay({ baseMs: 500, maxMs: 8000 }) })Full jitter can pick a very short wait, even 0 ms, on any attempt. If you want a guaranteed minimum, add it to the random part, for example ceiling / 2 + random() * (ceiling / 2). This variant is often called "equal jitter".
Combining backoff with a retry policy
The delay function is also where you decide whether to retry at all. Returning throwError for a non-retryable error stops the loop at once. This is how the interceptor in the Topic Spine rejects 4xx responses without waiting. You can also honor the server's Retry-After header when it is present:
import { HttpErrorResponse } from '@angular/common/http';
import { throwError, timer } from 'rxjs';
const RETRYABLE = new Set([0, 408, 429, 500, 502, 503, 504]);
export function policyDelay(error: unknown, retryCount: number) {
if (!(error instanceof HttpErrorResponse) || !RETRYABLE.has(error.status)) {
return throwError(() => error);
}
const retryAfter = Number(error.headers.get('Retry-After'));
if (Number.isFinite(retryAfter) && retryAfter > 0) {
return timer(Math.min(retryAfter, 30) * 1000);
}
return timer(Math.min(8000, 500 * 2 ** (retryCount - 1)));
}Retry-After is usually a number of seconds, but the HTTP standard also allows a date. The code above ignores the date form, because Number returns NaN for it, and falls back to backoff. The 30 second cap stops a server from holding the client for an arbitrary time.
Edge cases and gotchas
- Retries are not counted in the timeout. If you apply
timeoutbeforeretry, each attempt gets its own limit. If you apply it after, the limit covers all attempts and all backoff waits together. Place it deliberately. - Unsubscribing cancels the wait. If a component is destroyed during a backoff wait, unsubscribing cancels the
timerand no further request is sent. - Non-idempotent requests. Backoff does not make a POST safe to retry. A request that reached the server and failed on the way back may run twice.
- Total time. Three retries with a 500 ms base add only 3.5 s of waiting, but the requests themselves can be slow. Compute the worst case as request time times attempts plus the waits.
- Testing. Use
fakeAsyncandtick(ms)to advance time, or pass a fixedrandomfunction. Real timers make tests slow.
Summary of the decisions
- Set
countto a small number, usually 2 or 3 for user-facing calls. - Compute the wait as
base * 2 ** (retryCount - 1). - Cap it with
Math.min. - Add jitter when many clients may fail together.
- Return
throwError(() => error)fromdelayto stop retrying on errors that will not improve.
Exercise
A delay function is written as (error, retryCount) => timer(500 * 2 ** retryCount) with count: 3. What waits does it produce, and how should it change to give 500 ms, 1 s and 2 s?
Show answer
Because retryCount starts at 1, the function waits 1000 ms, 2000 ms and 4000 ms. The exponent should be retryCount - 1, giving timer(500 * 2 ** (retryCount - 1)), which waits 500 ms, 1000 ms and 2000 ms.
Exercise
A delay function returns EMPTY for a 400 response, intending to stop retrying. What does the subscriber see, and what should the function return instead?
Show answer
The subscriber sees the stream complete with no value and no error, because a notifier that completes without emitting completes the output. The function should return throwError(() => error) so the caller receives the 400 error.
Exercise
Why is jitter added to exponential backoff, and which parameter makes a jittered schedule testable?
Show answer
Without jitter, clients that failed at the same moment retry at the same moments and hit the server in synchronized waves. Jitter randomizes the waits so retries spread out. Injecting the random function, such as the random option in backoffDelay, lets a test supply a fixed value and get a deterministic schedule.