BackendPublished: February 23, 20247 min read
NestJS: HttpService retry configuration
How to build safe and explicit HTTP retry logic in NestJS using RxJS and proper error handling.

When an external API fails intermittently, smart retries can remove temporary errors without adding unnecessary complexity.
The idea is straightforward: retry only recoverable errors, log attempts, and fail fast on unrecoverable cases.
1) Install dependencies
bash
npm i --save @nestjs/axios axios2) Inject HttpService
ts
@Injectable()
export class CarsService {
constructor(private readonly httpService: HttpService) {}
public findAll() {
return this.httpService.get("http://localhost:3000/cars");
}
}3) Define a domain error
ts
class CarsApiError extends Error {
constructor(message: string, public readonly status: number) {
super(message);
}
}4) Apply retry with explicit rules
ts
const response$ = this.httpService.get("http://localhost:3000/cars").pipe(
map((response) => {
if (response.status === HttpStatus.OK) {
return response.data;
}
throw new CarsApiError("Cars API error", response.status);
}),
retry({
count: retryCount,
delay: (error, retryAttempt) => {
if (error instanceof CarsApiError && error.status >= 500) {
this.logger.warn(`Retry attempt: ${retryAttempt}`);
return timer(retryDelay);
}
throw error;
},
}),
catchError((error) => {
this.logger.error(error);
throw error;
}),
);Retry does not mean hiding errors: it means handling transient failures differently from structural ones.
With this setup you get explicit, configurable and production-observable retry behavior.