Sub topic 7
Deciding What Is Safe to Retry
This chapter assumes you can already make requests with HttpClient, read an HttpErrorResponse, and use pipe() with catchError and retry. Here you decide which failures to retry and which to pass straight to the caller.
Why retrying needs a policy
The retry operator resubscribes to the source Observable when it errors. For HttpClient, resubscribing sends the request again. The operator does not know whether sending it again is a good idea. If you write retry(3) on every call, you get three bad outcomes:
- A
404or400is retried three times and fails each time, because the request itself is wrong. - A
POSTthat created an order is retried after a timeout, and the server creates a second order. - Every client retries at once after an outage, which adds load to a server that is already struggling.
A retry policy is the rule that separates failures worth another attempt from failures that are not. It rests on two independent questions:
- Is the failure transient? Could the same request succeed a moment later?
- Is the request safe to repeat? If the first attempt partly or fully succeeded, does a second attempt cause harm?
A request is retried only when both answers are yes.
Question 1: is the failure transient?
Use the status code on the HttpErrorResponse to decide. The table groups the common cases.
| Status | Meaning | Retry? | Reason |
|---|---|---|---|
| 0 | No response received (offline, DNS failure, connection reset, CORS block) | Usually | Often a short network problem. A CORS failure never recovers, so a retry limit matters. |
| 400, 422 | Request is invalid | No | The same body will be rejected again. |
| 401, 403 | Not authenticated or not allowed | No | A retry cannot fix credentials. See the chapter on refreshing a 401. |
| 404 | Resource does not exist | No | Retrying cannot create it. |
| 408 | Server timed out waiting for the request | Yes | Usually a slow connection. |
| 429 | Too many requests | Yes, with care | Wait at least as long as the `Retry-After` header says. |
| 500 | Server error | Sometimes | Can be a bug that repeats every time. Keep the attempt count low. |
| 502, 503, 504 | Gateway or availability problem | Yes | Typical during restarts and brief overloads. |
The set {0, 408, 429, 500, 502, 503, 504} is a reasonable default. It is a starting point. Your own API may use 409 for a temporary lock, or return 500 for validation bugs, and the policy should reflect that.
Question 2: is the request safe to repeat?
A method is idempotent if sending it several times has the same effect on the server as sending it once. HTTP defines which methods should behave this way.
| Method | Idempotent by definition | Safe to retry automatically |
|---|---|---|
| GET, HEAD, OPTIONS | Yes (they only read) | Yes |
| PUT | Yes (replaces a resource with the given state) | Usually |
| DELETE | Yes (the resource is gone after one or many calls) | Usually |
| POST | No | No, unless you add an idempotency key |
| PATCH | Not guaranteed | No, unless you know your API's semantics |
"By definition" is a convention, and the server can break it. A PUT that appends to a list, or a DELETE that removes "the oldest item," is not idempotent in practice. Check what your API actually does before you trust the method name.
The ambiguity of a lost response
The hard case is a failure where you cannot tell whether the server did the work. Suppose you POST a payment and the connection drops after the server processed it. You see status 0 or 504, and the charge exists. Retrying charges the customer twice.
For this reason, a failed POST that returns status 0 should not be retried by default. The status tells you the response was lost. It does not tell you the request was.
Idempotency keys
Many APIs let a client make a POST safe to repeat. The client generates a unique value, such as a UUID, and sends it in a header, commonly Idempotency-Key. The server stores the result under that key. A second request with the same key returns the stored result instead of repeating the work.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
export interface Order {
id: number;
total: number;
}
@Injectable({ providedIn: 'root' })
export class OrderService {
private http = inject(HttpClient);
createOrder(total: number): Observable<Order> {
// Generate the key once per user action, not once per attempt.
const key = crypto.randomUUID();
return this.http.post<Order>(
'/api/orders',
{ total },
{ headers: { 'Idempotency-Key': key } }
);
}
}The key is created when createOrder is called, and the headers are part of the HttpRequest object. When retry resubscribes, the same request is sent with the same key. That is the property you need. Only use this pattern if your server supports it, because a header the server ignores gives no protection.
Writing the policy as a function
Keep the policy in one pure function so you can test it without any HTTP at all. It takes the request and the error, and returns a boolean.
import { HttpErrorResponse, HttpRequest } from '@angular/common/http';
const TRANSIENT_STATUSES = new Set([0, 408, 429, 500, 502, 503, 504]);
const IDEMPOTENT_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
export function isRetryable(
req: HttpRequest<unknown>,
error: HttpErrorResponse
): boolean {
if (!TRANSIENT_STATUSES.has(error.status)) {
return false;
}
if (IDEMPOTENT_METHODS.has(req.method)) {
return true;
}
return req.headers.has('Idempotency-Key');
}
export function delayFor(error: HttpErrorResponse, retryCount: number): number {
const retryAfter = Number(error.headers.get('Retry-After'));
if (error.status === 429 && Number.isFinite(retryAfter) && retryAfter > 0) {
return retryAfter * 1000;
}
return 2 ** (retryCount - 1) * 500;
}delayFor honors Retry-After when the value is a number of seconds. The header can also contain an HTTP date. Number turns a date into NaN, so the code falls back to exponential backoff in that case. Add date parsing if your server sends dates.
The interceptor then applies the policy:
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { retry, throwError, timer } from 'rxjs';
import { delayFor, isRetryable } from './retry-policy';
export const retryInterceptor: HttpInterceptorFn = (req, next) =>
next(req).pipe(
retry({
count: 3,
delay: (error: unknown, retryCount: number) => {
if (!(error instanceof HttpErrorResponse) || !isRetryable(req, error)) {
return throwError(() => error);
}
return timer(delayFor(error, retryCount));
},
})
);When the delay function returns an Observable that errors, retry stops and passes that error downstream. When it returns timer(...), retry waits for the timer to emit and then resubscribes. The count is the maximum number of retries, so a request can be sent up to four times in total.
Edge cases and gotchas
- Non-HTTP errors. An error thrown by code in the pipeline, such as a mapping function that throws, is not an
HttpErrorResponse. Retrying it repeats the same bug. Theinstanceofcheck keeps these out. - Timeouts. The RxJS
timeoutoperator throws aTimeoutError, which is not anHttpErrorResponse. If you placetimeoutupstream ofretry, the policy above will not retry it. Decide deliberately whether a timeout counts as transient, and for non-idempotent methods the answer is still no. - Side effects inside the pipe. A
tapupstream ofretryruns again on every attempt. Logging or analytics there will fire several times for one user action. - Stacked retries. If an interceptor retries three times and a component also uses
retry(3), one failure produces up to sixteen requests. Put the policy in one place. - Retry storms. Without a delay, or with a fixed delay, many clients retry at the same moment. Backoff spreads the load. Adding random jitter spreads it further.
- The user is waiting. Three retries with 500 ms, 1 s and 2 s delays add 3.5 seconds before the user sees an error. Show a loading state, and keep the total short for interactive actions.
Summary of the decision
Retry only when the failure is an HttpErrorResponse with a transient status, the request is idempotent or carries an idempotency key, and attempts remain. Cap the count, delay between attempts, honor Retry-After, and keep the policy in a single interceptor.
Exercise
A client sends POST /api/comments with no idempotency header. The request fails with status 504. Should the retry interceptor in this chapter retry it, and why?
Show answer
No. 504 is in the transient set, but POST is not in the idempotent methods set and the request has no Idempotency-Key header, so isRetryable returns false and the error is rethrown. The 504 means the response was lost or the upstream timed out, so the comment may already exist, and a retry could create a duplicate.
Exercise
A GET request returns status 429 with the header Retry-After: 10 on the first failure. What delay does delayFor return, and what does it return for a 503 on the second retry?
Show answer
For the 429, delayFor returns 10000 ms, because the status is 429 and Retry-After parses to a positive number of seconds. For a 503 on the second retry, it returns 2 * (2 - 1) 500 = 1000 ms from the exponential backoff.
Exercise
A component calls this.http.get(url).pipe(retry(2)) and the app also registers retryInterceptor with count: 3. If the server always returns 503, how many requests are sent for one call?
Show answer
Twelve. The interceptor sends up to 4 requests per subscription (1 initial and 3 retries). The component's retry(2) resubscribes twice after the first failure, giving 3 subscriptions, and 3 × 4 = 12. This is why the retry policy should live in only one place.