Sub topic 11
Adding request timeouts
This chapter assumes you can write a basic HttpClient service and read an HttpErrorResponse. It also assumes you know catchError, the retry operator, and functional interceptors from the earlier chapters. You will add a time limit to requests, decide what error a timeout should produce, and place the timeout correctly relative to retries.
Why HttpClient needs a timeout
HttpClient has no timeout option. If the server accepts a connection and never answers, the Observable stays open until the browser gives up. Browsers can wait for minutes, and some never abort at all. The user sees a spinner and nothing else.
A timeout is a deadline you set yourself. If no response arrives before the deadline, you cancel the request and report a failure. That failure can then flow into your existing catchError and retry logic.
RxJS provides this through the timeout operator. It does not know anything about HTTP. It watches an Observable and errors if the Observable is silent for too long.
The timeout operator
The simplest use passes a number of milliseconds:
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, timeout } from 'rxjs';
export interface Report {
id: number;
title: string;
}
@Injectable({ providedIn: 'root' })
export class ReportService {
private http = inject(HttpClient);
getReport(id: number): Observable<Report> {
return this.http.get<Report>(`/api/reports/${id}`).pipe(timeout(5000));
}
}If no value arrives within 5000 ms, the operator does two things:
- It unsubscribes from the source. For
HttpClient, unsubscribing aborts the underlying request, so the browser stops waiting for it. - It sends a
TimeoutErrorto the error channel.
TimeoutError comes from RxJS. It is not an HttpErrorResponse, and it has no status property. This matters a great deal, as the next sections show.
The configuration form
timeout also accepts an object. These are the options you will use most:
| Option | Meaning |
|---|---|
| `first` | Maximum wait for the first emitted value. |
| `each` | Maximum wait between emitted values, restarted after every value. |
| `with` | A factory that returns the Observable to switch to when time runs out, instead of throwing `TimeoutError`. |
timeout(5000) is the same as timeout({ each: 5000 }). A plain request emits one HttpResponse and completes, so first and each behave identically there.
They differ when you use reportProgress: true or observe: 'events'. The stream then emits many progress events. With each, the deadline works as an idle timeout. A large upload that keeps making progress is allowed to finish, and a stalled one is cut off. With first, only the wait for the first event is limited.
Choosing the error a timeout produces
You have two reasonable options, and the choice affects the rest of your error handling.
Option 1: keep TimeoutError
Leave the default and recognize it in catchError:
import { HttpErrorResponse } from '@angular/common/http';
import { catchError, throwError, TimeoutError } from 'rxjs';
// inside a service method
catchError((error: unknown) => {
if (error instanceof TimeoutError) {
return throwError(() => new Error('The server took too long to respond.'));
}
if (error instanceof HttpErrorResponse && error.status === 0) {
return throwError(() => new Error('Network error. Check your connection.'));
}
return throwError(() => new Error('Request failed.'));
})This is honest about what happened. The drawback is that every error handler must now deal with two error types, TimeoutError and HttpErrorResponse.
Option 2: convert it to an HttpErrorResponse
Use the with option to produce an HttpErrorResponse with status 408 (Request Timeout). Downstream code then sees one error type. The retry interceptor from the previous chapter already lists 408 as retryable, so timeouts are retried without any change to it.
The cost is that the response is synthetic. The server never sent a 408, and your code invented it. Do not read that status as proof of what the server did. A comment or a custom statusText makes the origin clear.
Option 2 works well in an interceptor, which is where the rest of this chapter puts it.
A timeout interceptor
A timeout applies to nearly every request, so it fits an interceptor. A default limit covers the whole application, and individual requests can override it through an HttpContext. An HttpContextToken carries a typed value from the call site to the interceptor.
import {
HttpContextToken,
HttpErrorResponse,
HttpInterceptorFn,
} from '@angular/common/http';
import { throwError, timeout } from 'rxjs';
export const REQUEST_TIMEOUT_MS = new HttpContextToken<number>(() => 10_000);
export const timeoutInterceptor: HttpInterceptorFn = (req, next) => {
const limit = req.context.get(REQUEST_TIMEOUT_MS);
return next(req).pipe(
timeout({
each: limit,
with: () =>
throwError(
() =>
new HttpErrorResponse({
status: 408,
statusText: `Client timeout after ${limit} ms`,
url: req.urlWithParams,
})
)
})
);
};The token's default of 10 seconds applies when a request sets nothing. A slow endpoint can raise its own limit at the call site:
import { HttpClient, HttpContext } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { REQUEST_TIMEOUT_MS } from './timeout.interceptor';
@Injectable({ providedIn: 'root' })
export class ExportService {
private http = inject(HttpClient);
downloadExport() {
return this.http.get('/api/export', {
responseType: 'blob',
context: new HttpContext().set(REQUEST_TIMEOUT_MS, 60_000),
});
}
}Where the timeout sits relative to retry
The order of entries in withInterceptors changes what the timeout means. The first interceptor in the array is the outermost. Each interceptor wraps everything after it.
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { retryInterceptor } from './retry.interceptor';
import { timeoutInterceptor } from './timeout.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([retryInterceptor, timeoutInterceptor])),
],
};Here retryInterceptor wraps timeoutInterceptor. Each retry resubscribes to next(req), which includes the timeout, so every attempt gets a fresh 10-second limit. With three retries, the worst case is four attempts of 10 seconds each, plus the backoff delays.
Swap the order and the timeout wraps the retries. The limit then covers all attempts and all backoff waits together.
| Order in the array | What the limit measures | Worst-case total wait |
|---|---|---|
| `[retryInterceptor, timeoutInterceptor]` | Each attempt separately | About attempts times limit, plus delays |
| `[timeoutInterceptor, retryInterceptor]` | The whole operation | The limit, no matter how many retries run |
Use a per-attempt timeout when you want to give a slow server several chances. Use a total timeout when the user-facing deadline matters most, such as a search box that must answer within a few seconds.
Timeouts and unsafe methods
The same reasoning applies to the error message. "The request timed out" does not mean "the request failed". For writes, tell the user the outcome is unknown and offer a way to check, such as reloading the list.
Common mistakes
- Putting
timeoutaftercatchError. The timeout then watches the already-recovered stream and never sees the slow request. PlacetimeoutbeforecatchErrorand beforeretryin the pipe. - Assuming the retry interceptor retries
TimeoutError. The interceptor from earlier rethrows anything that is not anHttpErrorResponse. If you keep the rawTimeoutError(option 1), it is never retried. Either convert it to a 408 or extend the retry check. - Setting one limit for every endpoint. Uploads, exports, and report generation need longer limits than a profile lookup. Use the context token for these.
- Confusing a client timeout with a 504. A 504 Gateway Timeout comes from a proxy or load balancer, and it arrives as a real response. It is a server-side failure, and your own 408 is a client-side decision. Log them separately if you monitor failures.
Testing a timeout
Time-based code is slow to test in real time. Angular's fakeAsync and tick move a virtual clock forward instantly, and the RxJS timeout operator runs on that clock.
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import {
HttpClient,
HttpContext,
HttpErrorResponse,
provideHttpClient,
withInterceptors,
} from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { REQUEST_TIMEOUT_MS, timeoutInterceptor } from './timeout.interceptor';
describe('timeoutInterceptor', () => {
let http: HttpClient;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([timeoutInterceptor])),
provideHttpClientTesting(),
],
});
http = TestBed.inject(HttpClient);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => httpMock.verify({ ignoreCancelled: true }));
it('fails with status 408 and cancels the request', fakeAsync(() => {
let status = 0;
http
.get('/api/slow', { context: new HttpContext().set(REQUEST_TIMEOUT_MS, 1000) })
.subscribe({ error: (e: HttpErrorResponse) => (status = e.status) });
const req = httpMock.expectOne('/api/slow');
tick(999);
expect(status).toBe(0);
tick(1);
expect(status).toBe(408);
expect(req.cancelled).toBe(true);
}));
});The test never flushes the request, so the mock backend behaves like a server that does not answer. The check at 999 ms confirms the limit is not hit early, and req.cancelled confirms the request was aborted. verify needs ignoreCancelled: true here. Without it, the cancelled request counts as outstanding.
Summary
HttpClienthas no built-in timeout. Add one with the RxJStimeoutoperator.- A timeout unsubscribes, which aborts the request, and raises
TimeoutError. - Convert
TimeoutErrorto a 408HttpErrorResponsewithwithif you want one error type and automatic retry. - Interceptor order decides whether the limit applies per attempt or to the whole operation.
- A timeout does not undo server work, so be careful with writes.
Exercise
Your app config is withInterceptors([timeoutInterceptor, retryInterceptor]), the timeout limit is 4 seconds, and the retry interceptor allows 3 retries with delays of 500 ms, 1 s and 2 s. A GET request hits a server that never responds. When does the caller receive an error, and how many attempts were made? What changes if you swap the two interceptors?
Show answer
The timeout interceptor is outermost, so its 4-second limit covers all attempts and all backoff delays. The first attempt hangs for the full 4 seconds, and the timeout fires and unsubscribes before any retry can start. The caller gets the 408 error after 4 seconds, and only one attempt was made. If the order is swapped to [retryInterceptor, timeoutInterceptor], each attempt gets its own 4-second limit. Each timeout becomes a 408, which is retryable. That gives four attempts of 4 seconds each plus 0.5 s, 1 s and 2 s of delay, so the error arrives after about 19.5 seconds.