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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Distinguish retryable server errors from client errors so you never hammer a request that will always fail.
- 2Exponential backoff spaces out retries to give a struggling upstream time to recover instead of piling on.
- 3Convert exhausted retries into a clean domain exception so callers see a meaningful failure, not a raw Axios error.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/resilient-payment-retries-in-nestjs-explained-typescript-aca0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.