Sub topic 10
Building a Retry Interceptor
This chapter assumes you can write a catchError handler and use the retry operator on an HttpClient call. It also assumes you know what an HttpErrorResponse is. Here you move the retry policy out of individual services and into one functional interceptor.
Why put retries in an interceptor
If every service calls retry on its own, each one repeats the same rules, and they drift apart over time. A functional interceptor is a function that sees every request and its response stream. Putting the policy there gives you one place to decide what is retried, how often, and how long to wait.
The interceptor
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { retry, throwError, timer } from 'rxjs';
const RETRYABLE_STATUSES = new Set([0, 408, 429, 500, 502, 503, 504]);
export const retryInterceptor: HttpInterceptorFn = (req, next) => {
if (req.method !== 'GET') {
return next(req);
}
return next(req).pipe(
retry({
count: 3,
delay: (error: unknown, retryCount: number) => {
if (!(error instanceof HttpErrorResponse) || !RETRYABLE_STATUSES.has(error.status)) {
return throwError(() => error);
}
return timer(2 ** (retryCount - 1) * 500);
},
})
);
};The function has three parts:
- Method check. Only
GETrequests are retried. AGETis normally safe to repeat. APOSTthat timed out may have already created a record, so a retry could create it twice. - Status check. Status
0means the browser never got a response, for example because the network dropped. The other codes are timeouts (408), rate limiting (429) and temporary server faults (500, 502, 503, 504). A 404 or 400 will fail the same way every time, so retrying only wastes time. - Backoff.
retryCountstarts at 1, so2 ** (retryCount - 1) * 500gives 500 ms, 1000 ms and 2000 ms. Thedelayfunction returns an Observable. The retry happens when that Observable emits. If it errors instead, the error goes straight to the subscriber.
How a request flows
Registering it
Register the interceptor once, and it applies to every HttpClient request in the app:
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { retryInterceptor } from './retry.interceptor';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient(withInterceptors([retryInterceptor]))],
};withInterceptors runs the functions in array order. If you add an auth interceptor later, its position decides whether a retried request gets a fresh token or the original one.
Common mistakes
- Retrying every method. Limit retries to idempotent requests. An idempotent request has the same effect whether you send it once or several times.
- Retrying without a delay. Immediate retries add load to a server that is already struggling. Backoff gives it time to recover.
- Ignoring
Retry-After. On a 429 or 503 the server may tell you how long to wait. This version uses its own schedule, which is fine for a first pass. - Handling the error twice. The interceptor only retries. The
catchErrorin your service still turns the final failure into a message, and it runs only after retries are used up.
Exercise
A user clicks "Save", which sends a POST. The server returns 503. With the interceptor above, how many times is the request sent, and why? How many times would a GET to the same URL be sent if every attempt returned 503?
Show answer
The POST is sent once, because the interceptor passes non-GET requests through without retry, since a repeated POST could create duplicate data. The GET is sent four times: the original attempt plus three retries, waiting 500 ms, 1 s and 2 s between them. After the last failure the 503 error reaches the caller.