
When an external API fails intermittently, smart retries can remove temporary errors without blowing up complexity. Applied blindly, though, they hide real problems and can make an outage worse.
The idea is straightforward: retry only recoverable errors, log every attempt, and fail fast on unrecoverable ones.
There is one detail that is easy to miss: by default, axios rejects every response that is not 2xx. That means checking response.status inside a map is useless for deciding whether to retry, because a 503 never gets there. Let's go step by step.
1) Install dependencies
RxJS already ships with NestJS, so you only need the HTTP module and axios.
npm i @nestjs/axios axios2) Register HttpModule with a timeout
import { Module } from "@nestjs/common";
import { HttpModule } from "@nestjs/axios";
import { CarsService } from "./cars.service";
@Module({
imports: [HttpModule.register({ timeout: 5000 })],
providers: [CarsService],
})
export class CarsModule {}Without a timeout, a request that hangs never fails and therefore is never retried. With one, axios aborts the request and returns an error with no response.
3) Define a domain error
export class CarsApiError extends Error {
constructor(
message: string,
public readonly status?: number,
) {
super(message);
}
}This is what the rest of your application will see once retries run out, without depending on axios.
4) Decide what is worth retrying
import { AxiosError } from "axios";
export function isRetryable(error: unknown): boolean {
if (!(error instanceof AxiosError)) {
return false;
}
if (!error.response) {
return true;
}
return error.response.status >= 500;
}Retry when there is no response at all (timeout, refused connection, DNS problems) or when the server answers with a 5xx. A 4xx means the problem is in the request itself: sending it again won't fix it.
5) Apply retry with exponential backoff
import { HttpService } from "@nestjs/axios";
import { Injectable, Logger } from "@nestjs/common";
import { catchError, map, retry, throwError, timer } from "rxjs";
import { CarsApiError } from "./cars-api.error";
import { isRetryable } from "./is-retryable";
const RETRY_COUNT = 3;
const RETRY_DELAY_MS = 500;
@Injectable()
export class CarsService {
private readonly logger = new Logger(CarsService.name);
constructor(private readonly httpService: HttpService) {}
public findAll() {
return this.httpService.get("http://localhost:3000/cars").pipe(
map((response) => response.data),
retry({
count: RETRY_COUNT,
delay: (error, attempt) => {
if (!isRetryable(error)) {
return throwError(() => error);
}
const wait = RETRY_DELAY_MS * 2 ** (attempt - 1);
this.logger.warn(`Retry ${attempt}/${RETRY_COUNT} in ${wait} ms`);
return timer(wait);
},
}),
catchError((error) => {
this.logger.error(`Cars API failed: ${error.message}`);
return throwError(
() => new CarsApiError("Cars API error", error.response?.status),
);
}),
);
}
}Each wait doubles the previous one (500, 1000 and 2000 ms) so you don't hammer an API that is already struggling. Note that count: 3 means up to three retries, which is four requests in total.
Retry does not mean hiding errors: it means handling transient failures differently from structural ones.
To see what each strategy changes, here is a simulation: pick one, stretch the outage and compare. Requests saved and recovery time don't always move in the same direction.
Saves far more, but clients that failed together come back together. The waves drag recovery out.
- Requests that end well
- 98.2%
- Extra load generated
- +55%
- Recovery after the outage
- 16 s
No strategy is free. Picking one depends on what hurts more: losing requests or prolonging the outage.
Simplified model: 60 req/s, 100 req/s capacity, up to 5 attempts, and throughput that falls under overload.
Before shipping it to production
- Retry only idempotent operations. Repeating a POST can duplicate a payment or an order, unless the API supports idempotency keys.
- Work out the worst case: with a 5 s timeout, four attempts and 3.5 s of waiting, a call can take over 23 s to fail.
- Add some randomness (jitter) to the wait if many clients may retry at the same time.
- On a 429, honor the Retry-After header instead of using a fixed wait.
With this setup you get explicit, configurable and production-observable retry behavior. To try it out, spin up a test server that returns 503 a couple of times and then 200, and check in the logs that the expected retries happen.