Sub topic 10
Building a retry interceptor
This chapter assumes you can write a basic HttpClient service, you know what catchError and retry do in RxJS, and you have seen a functional interceptor. Here you combine them. You will build one interceptor that retries transient failures for every request, instead of repeating retry in each service.
What the interceptor must decide
A retry interceptor answers three questions for each request:
- Is this request safe to repeat?
- Is this error likely to go away on its own?
- How long should it wait before the next attempt?
The earlier chapters on retry policy and backoff covered the reasoning. Here each answer becomes a few lines of code.
| Question | Decision in this chapter |
|---|---|
| Safe to repeat? | Only `GET` requests |
| Transient error? | Status 0, 408, 429, 500, 502, 503, 504 |
| Delay between attempts | 500 ms, 1 s, 2 s (exponential) |
| Attempts | 3 retries, so 4 requests at most |
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);
},
})
);
};How it works, line by line
An HttpInterceptorFn receives the request (req) and a next function that passes the request to the next interceptor, or to the backend if there is none. It returns an Observable of events.
The first if is the safety check. A non-GET request goes straight through with next(req) and no retry logic. This protects POST requests, which might create a duplicate record if the first attempt reached the server but the response was lost.
For a GET, the interceptor pipes next(req) into retry with a configuration object. count: 3 allows three re-subscriptions after the first failure. Each re-subscription sends a new HTTP request, because an HttpClient Observable is cold. It does nothing until subscribed, and each subscription makes a fresh request.
The delay function runs after each failure and decides what happens next:
- If it returns an Observable that emits,
retryre-subscribes. Returningtimer(ms)therefore means "waitms, then try again". - If it returns an Observable that errors,
retrystops and passes that error downstream. ReturningthrowError(() => error)means "do not retry this one".
The retryCount argument is 1 for the first retry, 2 for the second and 3 for the third. The expression 2 ** (retryCount - 1) * 500 gives 500, 1000 and 2000 ms.
The type guard matters
The error parameter is unknown. Not every error in this stream is an HttpErrorResponse. A bug in a downstream interceptor could throw a plain Error, and you do not want to retry that. The instanceof check rejects anything that is not an HTTP failure before error.status is read.
The component sees none of the failed attempts. It receives either the data or one final error.
Registering the interceptor
Register the interceptor once, in the application config:
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]))],
};Every request made through HttpClient now passes through it. Your service from the catchError chapter does not change. Retries happen inside the interceptor, and catchError in the service runs only after the retries are used up or skipped. That ordering is what you want. The user sees one error message, not three.
Interceptor order
withInterceptors takes an array, and the order of that array matters. Requests flow through the interceptors from first to last. Responses flow back from last to first.
The retry interceptor re-subscribes to next(req). That means it re-runs every interceptor listed after it and the backend call, once per attempt. Interceptors listed before it see the request once and the final outcome once.
This gives you a design choice:
- Put an auth interceptor after the retry interceptor, and each retry gets a freshly attached token.
- Put a logging interceptor before it, and you log one line per logical request.
- Put a logging interceptor after it, and you log one line per attempt, which is better for debugging flaky backends.
provideHttpClient(withInterceptors([loggingInterceptor, retryInterceptor, authInterceptor]));In this array, loggingInterceptor logs once per call, and authInterceptor runs on every attempt.
Edge cases
Status 0 is not always "offline"
A status of 0 means the browser got no HTTP response at all. That covers a dropped connection and a server that is down. It also covers a CORS failure and a request blocked by an extension. Retrying a CORS failure wastes about 3.5 seconds, because it will never succeed. If your API is on the same origin, CORS is unlikely and status 0 is a good retry candidate. If it is cross-origin, consider removing 0 from the set after you confirm your CORS setup is correct.
429 and the Retry-After header
A 429 response means the server is rate limiting you, and it often says how long to wait in a Retry-After header. A fixed backoff ignores that value. Reading it is a reasonable extension. error.headers.get('Retry-After') returns the header as a string or null. Note that the value can be a number of seconds or an HTTP date, so parse it defensively.
Timeouts are not HttpErrorResponse
If you add the RxJS timeout operator, a timeout throws a TimeoutError, not an HttpErrorResponse. The interceptor above rethrows it without retrying, because of the instanceof check. To retry on timeout, either handle TimeoutError explicitly in the delay function, or convert it to a retryable error first. Place timeout inside the retry, so each attempt gets its own time limit.
import { timeout } from 'rxjs';
// Inside the interceptor: each attempt gets its own 5 s limit.
return next(req).pipe(timeout(5000), retry({ /* ... */ }));If you write retry(...) before timeout(...), the timeout covers all attempts together, which is rarely what you want.
Per-request opt-out
Sometimes a specific GET should never retry, for example a health check that must fail fast. Angular's HttpContext carries per-request flags into interceptors:
import { HttpContextToken } from '@angular/common/http';
export const SKIP_RETRY = new HttpContextToken<boolean>(() => false);
// In the interceptor:
// if (req.method !== 'GET' || req.context.get(SKIP_RETRY)) { return next(req); }
// At the call site:
// this.http.get('/api/health', { context: new HttpContext().set(SKIP_RETRY, true) });Total worst-case wait
With three retries the waits add up to 3.5 seconds, plus the time each attempt takes to fail. A request that times out at 5 seconds on every attempt could keep a spinner running for about 23.5 seconds (4 × 5 s plus 3.5 s). Check that number against what your users will tolerate before you raise count.
Testing the interceptor
Test the interceptor through HttpClient, with HttpTestingController standing in for the server. Retry delays use real timers, so use fakeAsync and tick to move time forward without waiting.
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { retryInterceptor } from './retry.interceptor';
describe('retryInterceptor', () => {
let http: HttpClient;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([retryInterceptor])),
provideHttpClientTesting(),
],
});
http = TestBed.inject(HttpClient);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => httpMock.verify());
it('retries a GET after a 503 and returns the later success', fakeAsync(() => {
let result: unknown;
http.get('/api/ping').subscribe((r) => (result = r));
httpMock
.expectOne('/api/ping')
.flush('unavailable', { status: 503, statusText: 'Service Unavailable' });
tick(500);
httpMock.expectOne('/api/ping').flush({ ok: true });
expect(result).toEqual({ ok: true });
}));
it('does not retry a 404', () => {
let status = 0;
http.get('/api/missing').subscribe({ error: (e) => (status = e.status) });
httpMock
.expectOne('/api/missing')
.flush('Not found', { status: 404, statusText: 'Not Found' });
expect(status).toBe(404);
});
it('does not retry a POST', () => {
let status = 0;
http.post('/api/items', {}).subscribe({ error: (e) => (status = e.status) });
httpMock
.expectOne('/api/items')
.flush('Unavailable', { status: 503, statusText: 'Service Unavailable' });
expect(status).toBe(503);
});
});Two details make these tests reliable. First, httpMock.verify() in afterEach fails the test if a request was made that you did not expect, which catches an unwanted retry. Second, tick(500) is needed in the first test because the retry waits 500 ms before sending the second request. Without it, expectOne finds nothing.
Common mistakes
- Retrying every method. A retried
POSTcan create duplicates. Restrict to safe methods, or require an idempotency key. - Retrying 4xx errors. A 400, 401, 403 or 404 will fail the same way each time. Retrying only delays the error message.
- Calling
retry(3)with no delay. The three attempts fire back to back and add load without giving the server time to recover. - Forgetting that
retryre-runs later interceptors. Side effects in interceptors after it, such as incrementing a counter, run once per attempt.
Exercise
A teammate changes the interceptor so that RETRYABLE_STATUSES also includes 401, to "fix expired sessions". Why does this not fix the problem, and what happens to the user?
Show answer
A 401 means the credentials are rejected. Repeating the same request with the same token returns 401 again, so the user waits 3.5 seconds (500 ms + 1 s + 2 s) and then sees the same error. Fixing an expired session needs a token refresh before the retry, which is a separate interceptor concern covered later in this tutorial. 401 should not be in a plain retry list.
Exercise
You place retry(...) before timeout(5000) in the pipe, as in next(req).pipe(retry({ count: 3 }), timeout(5000)). What is the effect compared with putting timeout first?
Show answer
With timeout after retry, the 5 seconds cover the whole sequence of attempts and delays, so a slow first attempt can leave the later retries no time. A TimeoutError also cuts the whole chain short. With timeout first, each attempt gets its own 5 second limit, and retry can handle the failure if you treat the timeout as retryable.