typescript 43 lines · 8 steps

Resilient payment retries in NestJS

A NestJS service captures a payment over HTTP with exponential backoff, only retrying failures worth retrying.

Explained by highlit
1import { HttpService } from '@nestjs/axios';
2import { Injectable, Logger, ServiceUnavailableException } from '@nestjs/common';
3import { AxiosError } from 'axios';
4import { catchError, firstValueFrom, retry, timer } from 'rxjs';
5 
6interface PaymentIntent {
7 id: string;
8 status: 'succeeded' | 'pending' | 'failed';
9}
10 
11@Injectable()
12export class PaymentGatewayService {
13 private readonly logger = new Logger(PaymentGatewayService.name);
14 
15 constructor(private readonly httpService: HttpService) {}
16 
17 async capture(intentId: string, amount: number): Promise<PaymentIntent> {
18 const request$ = this.httpService
19 .post<PaymentIntent>(`/payment_intents/${intentId}/capture`, { amount })
20 .pipe(
21 retry({
22 count: 3,
23 delay: (error: AxiosError, retryCount) => {
24 if (error.response && error.response.status < 500) {
25 throw error;
26 }
27 const backoff = 2 ** retryCount * 250;
28 this.logger.warn(
29 `Capture ${intentId} failed (${error.code ?? error.response?.status}), retry ${retryCount} in ${backoff}ms`,
30 );
31 return timer(backoff);
32 },
33 }),
34 catchError((error: AxiosError) => {
35 this.logger.error(`Capture ${intentId} exhausted retries`, error.stack);
36 throw new ServiceUnavailableException('Payment gateway unavailable');
37 }),
38 );
39 
40 const { data } = await firstValueFrom(request$);
41 return data;
42 }
43}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Distinguish retryable server errors from client errors so you never hammer a request that will always fail.
  2. 2Exponential backoff spaces out retries to give a struggling upstream time to recover instead of piling on.
  3. 3Convert exhausted retries into a clean domain exception so callers see a meaningful failure, not a raw Axios error.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Resilient payment retries in NestJS — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code