typescript 47 lines · 7 steps

Exponential backoff retries in Angular

An Angular service retries failing HTTP requests with growing, jittered delays — but only for errors worth retrying.

Explained by highlit
1import { HttpClient } from '@angular/common/http';
2import { Injectable } from '@angular/core';
3import { Observable, throwError, timer } from 'rxjs';
4import { mergeMap, retryWhen } from 'rxjs/operators';
5 
6interface RetryConfig {
7 maxRetries: number;
8 baseDelayMs: number;
9 maxDelayMs: number;
10}
11 
12@Injectable({ providedIn: 'root' })
13export class PricingApiService {
14 private readonly config: RetryConfig = {
15 maxRetries: 4,
16 baseDelayMs: 300,
17 maxDelayMs: 8000,
18 };
19 
20 constructor(private readonly http: HttpClient) {}
21 
22 getQuote(symbol: string): Observable<Quote> {
23 return this.http
24 .get<Quote>(`/api/quotes/${symbol}`)
25 .pipe(retryWhen((errors) => this.backoffStrategy(errors)));
26 }
27 
28 private backoffStrategy(errors: Observable<any>): Observable<number> {
29 return errors.pipe(
30 mergeMap((error, index) => {
31 const attempt = index + 1;
32 const retriable = error.status >= 500 || error.status === 0;
33 
34 if (!retriable || attempt > this.config.maxRetries) {
35 return throwError(() => error);
36 }
37 
38 const backoff = Math.min(
39 this.config.baseDelayMs * 2 ** index,
40 this.config.maxDelayMs,
41 );
42 const jitter = Math.random() * this.config.baseDelayMs;
43 return timer(backoff + jitter);
44 }),
45 );
46 }
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Retry only transient failures — server errors and network drops — and let client errors fail fast.
  2. 2Exponential backoff with a cap prevents retries from hammering a struggling backend.
  3. 3Adding random jitter spreads concurrent retries so clients don't all reconnect in sync.

Related explainers

typescript
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { ApiProperty } from '@nestjs/swagger';

Wiring validation and Swagger docs in NestJS

validation openapi decorators
Intermediate 8 steps
typescript
import { Component, Input } from '@angular/core';
 
interface Order {
  id: string;

How Angular ICU plurals localize an order summary

i18n pluralization standalone-component
Intermediate 8 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, catchError, concatMap, finalize } from 'rxjs';
import { DataSource, QueryRunner } from 'typeorm';
 

Wrapping requests in a transaction with NestJS

interceptors transactions rxjs
Advanced 7 steps
typescript
type CsvColumn<T> = {
  header: string;
  value: (row: T) => string | number | boolean | null | undefined;
};

Building a type-safe CSV writer in TypeScript

generics serialization escaping
Intermediate 7 steps
typescript
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js';
 
export interface NormalizedPhone {
  e164: string;

Normalizing phone numbers to E.164 in TypeScript

validation normalization error-handling
Intermediate 7 steps
go
func UploadChunk(c *gin.Context) {
	uploadID := c.Param("uploadID")
	if !validUploadID.MatchString(uploadID) {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid upload id"})

Resumable chunked uploads in Gin

file-upload content-range streaming
Advanced 9 steps

Share this explainer

Here's the card — post it anywhere.

Exponential backoff retries in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code