Sub topic 8
Exponential backoff with the retry delay option
This chapter assumes you know TypeScript, Angular services, RxJS pipe(), and how to make requests with HttpClient. You should also have met the retry operator and the idea of retrying only safe, transient failures.
Why a fixed retry is not enough
retry(3) resubscribes immediately after each failure. If a server is overloaded, three instant retries add load at the moment it can least handle it. Many clients doing the same thing at once make the problem worse.
Exponential backoff doubles the wait after each failed attempt. The server gets time to recover, and clients spread their retries out.
The delay option
retry accepts a configuration object. Its delay property can be a function that receives the error and the retry count. It returns an Observable, and retry resubscribes to the source when that Observable emits.
retryCountstarts at 1 for the first retry.timer(ms)emits once aftermsmilliseconds, so it works as a pause.- If the function returns an Observable that errors,
retrystops and passes that error on. - When
countis used up, the last source error is emitted.
A backoff helper
Keep the delay math in a small pure function. A pure function is easy to test and reuse. The cap stops the wait from growing without limit.
export function backoff(retryCount: number, baseMs = 500, maxMs = 8000): number {
return Math.min(2 ** (retryCount - 1) * baseMs, maxMs);
}With the defaults, retries 1 to 5 wait 500, 1000, 2000, 4000 and 8000 ms.
Using it in a service
This service retries a GET request up to four times. It retries only the statuses that are worth retrying and fails at once for anything else.
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, retry, throwError, timer } from 'rxjs';
export interface Report {
id: number;
title: string;
}
const RETRYABLE = new Set([0, 408, 429, 500, 502, 503, 504]);
export function backoff(retryCount: number, baseMs = 500, maxMs = 8000): number {
return Math.min(2 ** (retryCount - 1) * baseMs, maxMs);
}
@Injectable({ providedIn: 'root' })
export class ReportService {
private http = inject(HttpClient);
getReports(): Observable<Report[]> {
return this.http.get<Report[]>('/api/reports').pipe(
retry({
count: 4,
delay: (error: unknown, retryCount: number) => {
if (!(error instanceof HttpErrorResponse) || !RETRYABLE.has(error.status)) {
return throwError(() => error);
}
return timer(backoff(retryCount));
},
})
);
}
}The throwError branch is what keeps a 404 or 400 from being retried. Repeating a request that is wrong will never make it right.
Adding jitter
If 1,000 clients all fail at the same moment, they all retry at 500 ms, then all at 1000 ms. This creates synchronized waves. Jitter adds randomness to break them up. A common form is "full jitter": wait a random time between 0 and the computed delay.
import { timer } from 'rxjs';
export function jitteredTimer(retryCount: number) {
const ceiling = Math.min(2 ** (retryCount - 1) * 500, 8000);
return timer(Math.random() * ceiling);
}Pass jitteredTimer(retryCount) where the example above calls timer(backoff(retryCount)).
Common mistakes
- Treating
retryCountas zero-based. The first retry is 1, so2 ** retryCountskips the base delay. - Having no cap. Without a maximum, a high
countcan leave users waiting for minutes. - Retrying every error. Check the status before you return a
timer. - Forgetting the total wait. Four retries with this formula add 7.5 seconds before the final error appears, so show a loading state or a "retrying" message.
Exercise
A request uses retry({ count: 4, delay: (e, n) => timer(2 * (n - 1) 1000) }) with no cap, and every attempt fails with a 503. How long does the code wait in total before the error reaches the caller, ignoring request time?
Show answer
The waits are 1000, 2000, 4000 and 8000 ms for retries 1 to 4, so 15,000 ms (15 seconds) in total. After the fourth retry fails, retry emits the last error with no further wait.