Sub topic 6
Retrying with the retry operator
This chapter assumes you can write a service that calls HttpClient, you know what pipe() does, and you have seen catchError and HttpErrorResponse in the earlier chapters. Here you add the RxJS retry operator so a failed request is sent again before the caller sees an error.
Why retry works with HttpClient
An HttpClient call returns a cold Observable. Nothing is sent until someone subscribes, and each subscription sends its own request. The retry operator uses this. When the source emits an error, retry unsubscribes and subscribes again, which sends a fresh HTTP request.
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, catchError, retry, throwError } from 'rxjs';
export interface User {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class UserService {
private http = inject(HttpClient);
getUser(id: number): Observable<User> {
return this.http.get<User>(`/api/users/${id}`).pipe(
retry(2),
catchError((error: HttpErrorResponse) =>
throwError(() => new Error(`Request failed with status ${error.status}`))
)
);
}
}retry(2) means two retries after the first attempt, so at most three requests are sent. If the third attempt also fails, the error passes to the next operator.
The component never sees the two failures. It receives only the final result.
Operator order matters
Put retry before catchError. catchError replaces the error with a new Observable or a different error. If it comes first, retry has nothing to retry, because the failure was already converted.
// Wrong: catchError handles the error first, so retry never sees it
this.http.get<User>(url).pipe(catchError(handle), retry(2));
// Right: retry sees the raw error, catchError handles the final one
this.http.get<User>(url).pipe(retry(2), catchError(handle));Retrying only some errors
A bare retry(2) retries every error. A 404 or a 400 will fail the same way each time, so retrying wastes requests and delays the error message. The object form accepts a delay function that runs on each error. It returns an Observable. When that Observable emits, retry resubscribes. When it errors, the retrying stops and that error is passed on.
import { HttpErrorResponse } from '@angular/common/http';
import { of, retry, throwError } from 'rxjs';
const isTransient = (error: unknown): boolean =>
error instanceof HttpErrorResponse &&
(error.status === 0 || error.status >= 500);
// Used inside a pipe():
retry({
count: 2,
delay: (error: unknown) =>
isTransient(error) ? of(null) : throwError(() => error),
});Here of(null) emits at once, so the retry happens with no pause. The next chapters cover how to decide what is safe to retry and how to add a growing delay.
Common errors
- Retrying non-idempotent requests. A POST that creates an order may have succeeded on the server even though the response was lost. Retrying can create a duplicate. Start with GET requests.
- Expecting
retry(3)to mean three attempts. It means one attempt plus three retries. - Retrying without a limit.
retry()with no argument retries forever and can flood a struggling server. - Retrying with no delay. Instant retries often hit the same outage. Use a delay for anything beyond a quick demonstration.
Exercise
A service calls this.http.get(url).pipe(catchError(handle), retry(3)). The server returns 503 on every call. How many requests are sent, and how do you fix the pipe so retrying happens?
Show answer
One request is sent. catchError converts the 503 into a new result before retry sees it, so there is nothing to retry. Swap the order to pipe(retry(3), catchError(handle)). Then the server receives 4 requests (1 attempt plus 3 retries) before handle runs.