Sub topic 6
Retrying with the retry operator
This chapter assumes you can write an Angular service that calls HttpClient, you know what an Observable is, and you have used pipe() with catchError. It covers how the RxJS retry operator works, how to configure it, and where it goes in a pipeline. Backoff, retry policy and interceptors get their own chapters, so this one stays on the operator itself.
What retry does
Some failures are temporary: a dropped connection, a server restarting, a gateway timing out. Sending the same request again often succeeds. The retry operator does this for you.
retry works at the Observable level. When the source Observable emits an error, retry unsubscribes from it and subscribes again. An HttpClient call is a cold Observable, so each subscription sends a new HTTP request. Nothing is sent until someone subscribes, and every resubscription sends another request.
You can see this with plain RxJS. The defer function creates a fresh attempt on each subscription, which is how HttpClient behaves.
import { defer, of, retry, throwError } from 'rxjs';
let attempts = 0;
const source$ = defer(() => {
attempts++;
return attempts < 3
? throwError(() => new Error(`Attempt ${attempts} failed`))
: of('ok');
});
source$.pipe(retry(3)).subscribe({
next: (value) => console.log(value, 'after', attempts, 'attempts'),
error: (err) => console.error('Gave up:', err.message),
});
// Prints: ok after 3 attemptsThe first two attempts fail silently. The subscriber sees only the final result. If all attempts fail, the subscriber receives the last error.
The simplest form: a retry count
Passing a number gives the maximum number of retries.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, retry } 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));
}
}Note the arithmetic. retry(2) means the original attempt plus up to two retries, so at most three requests. This off-by-one is a common source of confusion when you read server logs.
Calling retry() with no argument retries forever. For HTTP requests that is almost never what you want, because a server that is down gets hammered indefinitely and the user sees a spinner that never ends.
The configuration object
retry also accepts an object. It supports three options.
| Option | Type | Meaning |
|---|---|---|
| `count` | `number` | Maximum number of retries. Defaults to `Infinity` when you pass an object without it. |
| `delay` | `number` or `(error, retryCount) => ObservableInput` | Wait before each retry. A number is a fixed delay in milliseconds. A function decides per error. |
| `resetOnSuccess` | `boolean` | Reset the retry counter after the source emits a value. Defaults to `false`. |
The default for count matters. retry({ delay: 1000 }) retries forever, so always set count explicitly.
resetOnSuccess is for streams that emit many values, such as a WebSocket or a polling loop. A single HTTP request emits one value and completes, so you will rarely need it here.
A fixed delay
Retrying immediately is often useless. A server that just returned a 503 needs a moment to recover. A numeric delay adds a pause.
this.http.get<User>('/api/users/1').pipe(
retry({ count: 2, delay: 1000 })
);This waits one second before each retry.
A delay function that decides
The delay function runs each time the source errors. It receives the error and the number of the retry about to happen, starting at 1. It returns an Observable (ObservableInput) that controls what happens next. The behavior depends on what that Observable does:
- If it emits a value,
retryresubscribes to the source. - If it errors, that error goes to the subscriber and retrying stops.
- If it completes without emitting, the whole result completes with no value and no error.
The first behavior lets you wait, using timer. The second lets you stop retrying early, using throwError. The third is a trap, covered in the gotchas below.
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, retry, throwError, timer } from 'rxjs';
export interface User {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class UserLoader {
private http = inject(HttpClient);
load(id: number): Observable<User> {
return this.http.get<User>(`/api/users/${id}`).pipe(
retry({
count: 2,
delay: (error: unknown, retryCount: number) => {
const transient =
error instanceof HttpErrorResponse &&
(error.status === 0 || error.status >= 500);
if (!transient) {
return throwError(() => error);
}
console.warn(`Retry ${retryCount} after status`, (error as HttpErrorResponse).status);
return timer(1000);
},
})
);
}
}A 404 or 400 will not improve by asking again, so the function rethrows it at once and the caller sees the failure after a single request. Network failures (status 0) and 5xx responses get up to two more tries, one second apart. The next chapters build a fuller policy on this idea.
Where retry goes in the pipeline
Operators run in the order you write them in pipe(). This matters because retry only reacts to errors that reach it.
Put retry before catchError:
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 SafeUserService {
private http = inject(HttpClient);
getUser(id: number): Observable<User> {
return this.http.get<User>(`/api/users/${id}`).pipe(
retry({ count: 2, delay: 500 }),
catchError((error: HttpErrorResponse) =>
throwError(() => new Error(`Failed after retries: ${error.status}`))
)
);
}
}The request is retried first. Only if every attempt fails does catchError see the final error and convert it for the caller.
If you reverse the order and catchError returns a fallback value instead of rethrowing, the error never reaches retry:
this.http.get<User[]>('/api/users').pipe(
catchError(() => of([] as User[])), // swallows the error
retry(2) // never triggers
);This pipeline sends exactly one request. Whenever catchError recovers with a normal value, downstream retry has nothing to retry.
Gotchas
- Every subscriber triggers its own requests. Two subscriptions to the same cold Observable send two requests, and each retries independently. With
asyncin a template plus a manualsubscribe, you can double your traffic. - A completing delay Observable ends the stream silently. If your
delayfunction returnsEMPTY, or an Observable likeof(...).pipe(filter(() => false)), the result completes with no value and no error. The component may show an empty state instead of an error. ReturnthrowErrorto stop with an error. - Retrying hides failures. A request that fails twice and then succeeds looks healthy to the user, but it still costs time. Log retries (as the example above does with
console.warn) so you can see flaky endpoints. - Retry multiplies side effects. Retrying a POST that creates an order can create two orders if the first request reached the server but the response was lost. The next chapter covers which methods are safe to retry.
- Retries delay the error. With three retries and a one-second delay, the user waits at least three seconds before seeing any error. Keep the total waiting time in mind when choosing
countanddelay.
Summary of the working model
HttpClientreturns a cold Observable. Each subscription sends one request.retrycatches an error from the source and subscribes again, up tocounttimes.retry(n)allowsn + 1total attempts.- A
delayfunction can wait withtimeror abort withthrowError. - Place
retrybeforecatchErrorso the error reaches it.
Exercise
A service pipeline is written as this.http.get<Item[]>('/api/items').pipe(catchError(() => of([] as Item[])), retry(3)). The server returns 503 on every request. How many HTTP requests are sent, and why? What single change makes the pipeline send four requests before giving up with an empty list?
Show answer
Exactly one request is sent. catchError runs first and replaces the error with a normal value (of([])), so retry never sees an error and never resubscribes. Swapping the order to .pipe(retry(3), catchError(() => of([] as Item[]))) sends four requests (the original plus three retries), and then returns the empty list once all of them fail.