Volver al blogLeer en EN
BackendPublicado: 23 de febrero de 20247 min lectura

NestJS: configuracion de reintentos con HttpService

Como montar retries claros y seguros en llamadas HTTP dentro de NestJS usando RxJS y control de errores.

Logo de NestJS

Cuando una API externa falla de forma intermitente, aplicar retries de forma inteligente evita errores temporales sin disparar complejidad innecesaria.

La idea es simple: reintentar solo en errores recuperables, registrar intentos y cortar en condiciones no recuperables.

1) Instala dependencias

bash
npm i --save @nestjs/axios axios

2) Inyecta HttpService

ts
@Injectable()
export class CarsService {
  constructor(private readonly httpService: HttpService) {}

  public findAll() {
    return this.httpService.get("http://localhost:3000/cars");
  }
}

3) Define un error de dominio

ts
class CarsApiError extends Error {
  constructor(message: string, public readonly status: number) {
    super(message);
  }
}

4) Aplica retry con reglas claras

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 no significa ocultar errores: significa tratar de forma distinta lo transitorio frente a lo estructural.

Con esta base tienes una configuracion explicita, parametrizable y facil de observar en produccion.