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

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