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

ruby
class Order
  class InvalidTransition < StandardError; end
 
  TRANSITIONS = {

A state machine for order transitions in Ruby

state-machine data-driven error-handling
Intermediate 8 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';

How a JWT strategy authenticates in NestJS

authentication jwt passport
Intermediate 7 steps
typescript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { catchError, filter, take, switchMap } from 'rxjs/operators';

Refreshing auth tokens in an Angular interceptor

http-interceptor token-refresh rxjs
Advanced 8 steps
rust
use std::cmp::Ordering;
use std::str::FromStr;
 
#[derive(Debug, Clone, PartialEq, Eq)]

Parsing and ordering semantic versions in Rust

parsing trait-implementation ordering
Intermediate 8 steps
javascript
'use client';
 
import { useEffect } from 'react';
import * as Sentry from '@sentry/nextjs';

How a Next.js error boundary recovers

error-boundary error-handling observability
Intermediate 8 steps
ruby
class Registration < ApplicationRecord
  belongs_to :event
 
  validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }

Validating registrations in Rails

validations i18n error-handling
Intermediate 8 steps

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