| | |

RxJS 11 ๐ŸŸฃ Error Handling & Resilience โ€” Recovering gracefully with catchError, retry with exponential backoff, and finalize

โฑ๏ธ Estimated read: 15 min | |

RxJS streams fail. A network request times out, a JSON parse throws, a downstream operator hits an unexpected null. When an error reaches the subscriber without being handled, the subscription tears down and the error propagates to the global handler โ€” or crashes the application. RxJS provides three core operators for resilience: catchError intercepts the error and returns a recovery observable, retry re-subscribes to the source a configurable number of times, and finalize runs cleanup logic whether the stream completes normally or terminates with an error. Together they form the error-handling vocabulary every RxJS developer uses daily.

This chapter covers the catchError operator for recovery strategies, the retry operator with exponential backoff for transient failures, and the finalize operator for guaranteed cleanup. The sections that follow walk through each operator in isolation, then show how they compose into a resilient pipeline that handles network instability, rate limiting, and resource disposal without leaking subscriptions or swallowing errors silently.

Key point: catchError returns a new observable to replace the failed stream, retry re-subscribes to the source with configurable delay and count, and finalize executes a callback on both completion and error โ€” the three operators cover recovery, retry, and cleanup respectively.


Why Error Handling & Resilience exists

The uncaught error terminates the stream.
When an operator throws and no catchError sits upstream, the observable errors out, the subscription ends, and any downstream operators never run. A single failed HTTP request kills the entire pipeline unless the error is caught and transformed into a continuation.

The transient failure succeeds on retry.
Network blips, temporary rate limits, and momentary backend unavailability are not permanent errors. Re-subscribing to the same source after a short delay often succeeds, but a naive immediate retry hammers the server and worsens the problem. Exponential backoff spaces attempts and adds jitter to avoid thundering herds.

The resource must be released.
Subscriptions, WebSocket connections, file handles, and loading indicators need deterministic cleanup. A finally block in synchronous code runs on both return and throw; finalize is the observable equivalent โ€” it runs when the stream completes, errors, or is unsubscribed.

The error context matters for recovery.
Not all errors are equal. A 401 Unauthorized means refresh the token and retry. A 404 Not Found means show a fallback. A 500 Internal Server Error means retry with backoff. catchError receives the error and the source observable, letting the handler decide based on type, status code, or custom properties.

The composition order changes behavior.
catchError before retry catches the error and never lets retry see it. retry before catchError retries the source, then catches if all retries exhaust. The order is a design decision: retry-then-recover for transient failures, recover-then-retry for fallback chains that themselves might fail.


a. The catchError operator โ€” Recovery strategies

catchError intercepts an error notification from the source, executes a handler function, and returns a new observable that becomes the continuation of the stream. The handler receives the error and the source observable, enabling both recovery and conditional retry logic.

import { of, throwError } from "rxjs";
import { catchError, map } from "rxjs/operators";

// Basic recovery: return a fallback value
of(1, 2, 3).pipe(
  map((x) => {
    if (x === 2) throw new Error("Boom");
    return x * 2;
  }),
  catchError((err) => of("fallback")) // โ† recovery observable
).subscribe(console.log); // 2, "fallback", 6

The recovery observable can be any observable โ€” a static value with of, a new HTTP request, a cached result, or an empty completion with EMPTY. The stream continues normally after the recovery observable completes.

import { of, EMPTY, timer } from "rxjs";
import { catchError, switchMap } from "rxjs/operators";

// Recovery with a new request: retry once with a different endpoint
function fetchWithFallback<T>(primary: string, fallback: string) {
  return fetch(primary).pipe(
    catchError((err) => {
      console.warn("Primary failed, trying fallback:", err.message);
      return fetch(fallback); // โ† new observable replaces the failed one
    })
  );
}

The handler also receives the source observable, enabling the “retry with modified parameters” pattern โ€” but retry is the dedicated operator for that (see section b).

import { of } from "rxjs";
import { catchError, tap } from "rxjs/operators";

// Accessing the source for conditional logic
of(1, 2, 3).pipe(
  tap((x) => { if (x === 2) throw new Error("Skip 2"); }),
  catchError((err, source$) => {
    // source$ is the original observable โ€” can re-subscribe selectively
    return source$.pipe(
      // but this re-runs the whole pipeline including the tap!
    );
  })
);

Key distinction: catchError catches errors from upstream operators only. Errors thrown inside the catchError handler itself propagate downstream uncaught โ€” wrap the handler body in a try/catch or nest another catchError if the recovery logic can fail.


b. The retry operator โ€” Exponential backoff for transient failures

retry re-subscribes to the source observable when it errors, up to a configurable count. The simple form retry(3) retries immediately three times. The advanced form retry({ count, delay, resetOnSuccess }) accepts a delay function that receives the retry attempt number and returns a timer observable โ€” this is where exponential backoff lives.

import { interval } from "rxjs";
import { retry, take, map } from "rxjs/operators";

// Immediate retry โ€” hammers the source on failure
interval(100).pipe(
  take(3),
  map((x) => { if (x === 1) throw new Error("Transient"); return x; }),
  retry(3) // retries immediately 3 times
).subscribe({
  next: console.log,
  error: (e) => console.error("Exhausted:", e.message)
});

Exponential backoff uses the delay option. The function receives the attempt index (starting at 0) and returns an observable that emits when the next retry should occur. timer(ms) is the standard building block.

import { ajax } from "rxjs/ajax";
import { retry, catchError } from "rxjs/operators";
import { timer, of } from "rxjs";

// Exponential backoff: 1s, 2s, 4s, 8s... with jitter
ajax.getJSON("/api/data").pipe(
  retry({
    count: 5,
    delay: (attempt, error) => {
      const baseDelay = 1000 * Math.pow(2, attempt); // 1000, 2000, 4000...
      const jitter = Math.random() * 300;            // ยฑ0-300ms
      return timer(baseDelay + jitter);
    },
  }),
  catchError((err) => of({ fallback: true, error: err.message }))
).subscribe(console.log);

The resetOnSuccess: true option (default) resets the attempt counter when the source emits a value. This matters for long-lived streams like WebSocket message handlers โ€” a successful message means the connection is healthy, so the next error starts counting from zero again.

import { webSocket } from "rxjs/webSocket";
import { retry } from "rxjs/operators";

// WebSocket with retry that resets on each message
const socket$ = webSocket("wss://api.example.com/feed").pipe(
  retry({
    count: 10,
    delay: (attempt) => timer(1000 * Math.pow(2, attempt)),
    resetOnSuccess: true // โ† each message resets the counter
  })
);

Conditional retry โ€” only retry on specific errors โ€” combines retry with a predicate inside catchError, or uses the retry delay function to return EMPTY (which completes without retrying) for non-retryable errors.

import { ajax } from "rxjs/ajax";
import { retry, catchError } from "rxjs/operators";
import { timer, of, EMPTY } from "rxjs";

ajax.getJSON("/api/data").pipe(
  retry({
    count: 3,
    delay: (attempt, error) => {
      // Only retry on network errors or 5xx
      if (error.name === "AjaxError" && error.status >= 500) {
        return timer(1000 * Math.pow(2, attempt));
      }
      // Non-retryable: complete the delay with EMPTY โ†’ no retry
      return EMPTY;
    },
  }),
  catchError((err) => of({ error: err.message }))
).subscribe(console.log);

c. The finalize operator โ€” Guaranteed cleanup

finalize registers a callback that runs when the observable completes, errors, or is unsubscribed. It is the observable equivalent of finally โ€” use it for loading indicators, connection cleanup, analytics flush, or any side effect that must happen exactly once per subscription.

import { interval } from "rxjs";
import { finalize, take } from "rxjs/operators";

// Runs on completion
interval(100).pipe(
  take(3),
  finalize(() => console.log("Cleanup: completed"))
).subscribe({
  next: console.log,
  complete: () => console.log("Done")
});
// Output: 0, 1, 2, "Done", "Cleanup: completed"

The callback runs on error too โ€” the error propagates after finalize finishes.

import { throwError } from "rxjs";
import { finalize } from "rxjs/operators";

// Runs on error
throwError(() => new Error("Boom")).pipe(
  finalize(() => console.log("Cleanup: errored"))
).subscribe({
  error: (e) => console.error("Caught:", e.message)
});
// Output: "Cleanup: errored", "Caught: Boom"

The callback runs on unsubscribe โ€” this is critical for resource disposal.

import { interval } from "rxjs";
import { finalize, take } from "rxjs/operators";

// Runs on unsubscribe
const sub = interval(100).pipe(
  finalize(() => console.log("Cleanup: unsubscribed"))
).subscribe(console.log);

setTimeout(() => sub.unsubscribe(), 250);
// Output: 0, 1, "Cleanup: unsubscribed"

Multiple finalize operators stack โ€” each runs in order, and all run regardless of how the stream terminates. This allows modular cleanup: one for the spinner, one for the WebSocket, one for the analytics.

import { ajax } from "rxjs/ajax";
import { finalize, catchError } from "rxjs/operators";
import { of } from "rxjs";

function fetchWithLoading(url: string) {
  showSpinner();
  return ajax.getJSON(url).pipe(
    finalize(() => hideSpinner()),           // โ† always hides spinner
    catchError((err) => {
      logError(err);
      return of(null);
    }),
    finalize(() => analytics.flush())        // โ† always flushes analytics
  );
}

The callback receives no arguments. It cannot access the value, error, or subscription. If you need the error for logging, catch it first, log, then re-throw โ€” or use tap with finalize for the cleanup.

import { throwError } from "rxjs";
import { tap, finalize } from "rxjs/operators";

throwError(() => new Error("Boom")).pipe(
  tap({
    error: (err) => logError(err), // โ† access error here
  }),
  finalize(() => cleanup())        // โ† cleanup runs after
).subscribe({
  error: (e) => console.error(e)
});

Complete Example Session

// ============================================
// PART 1: BASIC CATCHERROR RECOVERY
// ============================================
import { of, throwError, timer, EMPTY } from "rxjs";
import { catchError, retry, finalize, map, tap } from "rxjs/operators";

function fetchUser(id: number) {
  return of({ id, name: "Alice" }).pipe(
    map((user) => {
      if (user.id === 404) throw new Error("Not found");
      return user;
    }),
    catchError((err) => {
      console.warn("Fetch failed, returning guest:", err.message);
      return of({ id: 0, name: "Guest" }); // recovery observable
    })
  );
}

// ============================================
// PART 2: RETRY WITH EXPONENTIAL BACKOFF
// ============================================
function fetchWithRetry<T>(url: string, maxRetries = 3) {
  return fetch(url).pipe(
    retry({
      count: maxRetries,
      delay: (attempt) => {
        const base = 1000 * Math.pow(2, attempt); // 1s, 2s, 4s
        const jitter = Math.random() * 200;
        return timer(base + jitter);
      },
      resetOnSuccess: true,
    }),
    catchError((err) => {
      console.error("All retries exhausted:", err.message);
      return EMPTY; // complete silently
    })
  );
}

// ============================================
// PART 3: FINALIZE FOR SPINNER CLEANUP
// ============================================
function fetchWithLoading<T>(source: () => import("rxjs").Observable<T>) {
  const start = Date.now();
  showSpinner();
  return source().pipe(
    finalize(() => {
      hideSpinner();
      console.log(`Request took ${Date.now() - start}ms`);
    })
  );
}

function showSpinner() { console.log("๐Ÿ”„ Loading..."); }
function hideSpinner() { console.log("โœ… Done"); }

// ============================================
// PART 4: CONDITIONAL RETRY ON 5XX ONLY
// ============================================
function fetchApi<T>(url: string) {
  return fetch(url).pipe(
    retry({
      count: 5,
      delay: (attempt, error) => {
        const isRetryable = error?.status >= 500 || error?.name === "TypeError"; // network error
        if (!isRetryable) return EMPTY;
        return timer(1000 * Math.pow(2, attempt));
      },
    })
  );
}

// ============================================
// PART 5: COMPOSED RESILIENT PIPELINE
// ============================================
function resilientFetch<T>(url: string, fallback: T) {
  let attempt = 0;
  return fetch(url).pipe(
    tap(() => attempt = 0), // reset on success
    retry({
      count: 3,
      delay: () => timer(1000 * Math.pow(2, attempt++)),
      resetOnSuccess: true,
    }),
    catchError((err) => {
      console.warn("Failed after retries, using fallback:", err.message);
      return of(fallback);
    }),
    finalize(() => {
      console.log("Pipeline terminated");
    })
  );
}

// ============================================
// PART 6: WEBSOCKET RECONNECT PATTERN
// ============================================
function createReconnectingSocket(url: string) {
  return webSocket(url).pipe(
    retry({
      count: Infinity,
      delay: (attempt) => timer(Math.min(1000 * Math.pow(2, attempt), 30000)),
      resetOnSuccess: true,
    }),
    catchError((err) => {
      console.error("WebSocket failed permanently:", err);
      return EMPTY;
    }),
    finalize(() => console.log("Socket closed"))
  );
}

// ============================================
// PART 7: MULTIPLE FINALIZE STACKING
// ============================================
function trackedFetch<T>(url: string) {
  analytics.track("fetch_start", { url });
  return fetch(url).pipe(
    finalize(() => analytics.track("fetch_end", { url })),
    catchError((err) => {
      analytics.track("fetch_error", { url, error: err.message });
      return of(null);
    }),
    finalize(() => analytics.flush())
  );
}

// ============================================
// PART 8: RETRY WITH CUSTOM ERROR CLASS
// ============================================
class TransientError extends Error {
  constructor(public readonly retryAfter: number) {
    super("Transient");
    this.name = "TransientError";
  }
}

function fetchWithCustomRetry<T>(url: string) {
  return fetch(url).pipe(
    catchError((err) => {
      if (err instanceof TransientError) {
        return timer(err.retryAfter).pipe(
          switchMap(() => fetch(url)) // retry once after server-suggested delay
        );
      }
      return throwError(() => err);
    })
  );
}

// ============================================
// PART 9: UNSUBSCRIBE CLEANUP VERIFICATION
// ============================================
function verifyCleanup() {
  let cleaned = false;
  const sub = of(1, 2, 3).pipe(
    finalize(() => { cleaned = true; })
  ).subscribe();

  sub.unsubscribe();
  console.assert(cleaned === true, "finalize must run on unsubscribe");
}

// ============================================
// PART 10: COMPLETE RESILIENT SERVICE
// ============================================
class ApiService {
  private baseUrl = "/api";

  get<T>(endpoint: string, fallback: T) {
    return fetch(`${this.baseUrl}${endpoint}`).pipe(
      retry({
        count: 3,
        delay: (attempt) => timer(500 * Math.pow(2, attempt)),
        resetOnSuccess: true,
      }),
      catchError((err) => {
        if (err.status === 401) return this.refreshToken().pipe(switchMap(() => this.get(endpoint, fallback)));
        return of(fallback);
      }),
      finalize(() => this.requestCount++)
    );
  }

  private refreshToken() { return of("new-token"); }
  private requestCount = 0;
}

The parts covered basic recovery, exponential backoff, spinner cleanup, conditional retry, composed pipeline, WebSocket reconnect, stacked finalize, custom error retry, unsubscribe verification, and a complete service class.


Quick Reference

catchError Recovery Options

Recovery ObservableUse Case
of(fallbackValue)Static fallback value
of(null)Null placeholder
EMPTYSilent completion
throwError(() => err)Re-throw after logging
newRequest$Alternative request
cached$Stale cache fallback

retry Configuration

OptionTypeDefaultDescription
countnumberInfinityMax retry attempts
delay(attempt, error) => Observable0Timer before next retry
resetOnSuccessbooleantrueReset counter on next emission

finalize Execution Triggers

TriggerRuns finalize?
completeYes
errorYes
unsubscribeYes
subscription never startsNo

Common Backoff Formulas

FormulaSequence (ms)Use Case
1000 * 2^attempt1000, 2000, 4000, 8000Standard exponential
1000 * attempt^21000, 4000, 9000, 16000Polynomial backoff
Math.min(1000 * 2^attempt, 30000)Capped at 30sMax delay bound
base + Math.random() * jitterยฑ jitterThundering herd prevention

Best Practices

โœ… Do This:

// Catch specific errors, recover with fallback
catchError((err) => err.status === 404 ? of(defaultUser) : throwError(() => err)) // โœ…

// Exponential backoff with jitter
retry({ count: 3, delay: (i) => timer(1000 * 2**i + Math.random()*200) })           // โœ…

// Finalize for guaranteed cleanup
finalize(() => { hideSpinner(); connection.close(); })                                 // โœ…

// Reset retry counter on success for long-lived streams
retry({ count: 10, delay: backoff, resetOnSuccess: true })                             // โœ…

// Conditional retry: only on network/5xx
delay: (_, err) => err.status >= 500 ? timer(backoff) : EMPTY                          // โœ…

โŒ Don’t Do This:

// Catch everything, swallow errors silently
catchError(() => of(null))                                                             // โŒ

// Immediate retry hammers the server
retry(5)                                                                               // โŒ

// Forget finalize โ€” spinner stays forever on error
catchError(() => of(fallback)) // no finalize                                          // โŒ

// Retry non-retryable errors (4xx)
retry({ count: 3, delay: () => timer(1000) }) // retries 400, 401, 404                // โŒ

// Access error in finalize โ€” impossible
finalize((err) => log(err)) // err is undefined                                        // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Spinner never hidesfinalize missing after catchErrorAdd finalize(hideSpinner) after catchError
Infinite retry loopretry({ count: Infinity }) on permanent errorLimit count, or conditional delay returning EMPTY
Error swallowedcatchError(() => of(fallback)) without loggingLog inside catchError before returning fallback
Retry counter never resetsresetOnSuccess: false on WebSocketSet resetOnSuccess: true for message streams
Cleanup runs twiceTwo subscriptions to same finalize-wrapped observableEach subscription gets its own finalize โ€” expected
Jitter missingtimer(1000 * 2^attempt) without randomnessAdd + Math.random() * 200 to delay
Recovery observable errorscatchError handler throwsWrap handler in try/catch or nest catchError
Wrong order: catch before retrycatchError consumes error, retry never sees itPlace retry before catchError for retry-then-recover

Real-World Examples

1. HTTP with fallback

fetch("/api/user").pipe(catchError(() => of(defaultUser)));

2. Exponential backoff

retry({ count: 5, delay: (i) => timer(1000 * 2**i + Math.random()*300) });

3. Spinner cleanup

pipe(finalize(() => hideSpinner()));

4. Conditional retry on 5xx

retry({ delay: (_, e) => e.status >= 500 ? timer(backoff) : EMPTY });

5. WebSocket reconnect

webSocket(url).pipe(retry({ count: Infinity, delay: backoff, resetOnSuccess: true }));

6. Token refresh on 401

catchError((e) => e.status === 401 ? refreshToken().pipe(switchMap(() => retryRequest())) : throwError(() => e));

7. Cache fallback

catchError(() => cache.get(key));

8. Analytics flush

pipe(finalize(() => analytics.flush()));

9. Unsubscribe cleanup

pipe(finalize(() => ws.close()));

10. Silent completion on failure

catchError(() => EMPTY);

Visual

The Three Operators in a Pipeline

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  SOURCE                                                         โ”‚
โ”‚    โ”‚                                                            โ”‚
โ”‚    โ–ผ                                                            โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                   โ”‚
โ”‚  โ”‚ retry   โ”‚โ”€โ”€โ”€โ”€โ–บโ”‚catchErrorโ”‚โ”€โ”€โ”€โ”€โ–บโ”‚ finalizeโ”‚                   โ”‚
โ”‚  โ”‚(backoff)โ”‚     โ”‚(recover) โ”‚     โ”‚(cleanup)โ”‚                   โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                   โ”‚
โ”‚    โ”‚                                                            โ”‚
โ”‚    โ–ผ                                                            โ”‚
โ”‚  SUBSCRIBER                                                     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Retry-Then-Recover vs Recover-Then-Retry

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  RETRY THEN RECOVER (transient failures)                        โ”‚
โ”‚  source โ”€โ”€โ–บ retry(3) โ”€โ”€โ–บ catchError(fallback) โ”€โ”€โ–บ subscriber    โ”‚
โ”‚         โ”‚           โ”‚                                            โ”‚
โ”‚         โ”‚           โ””โ”€ only runs if ALL retries fail            โ”‚
โ”‚         โ””โ”€ retries the SOURCE observable                        โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  RECOVER THEN RETRY (fallback chain)                            โ”‚
โ”‚  source โ”€โ”€โ–บ catchError(altSource) โ”€โ”€โ–บ retry(2) โ”€โ”€โ–บ subscriber   โ”‚
โ”‚         โ”‚           โ”‚                                            โ”‚
โ”‚         โ”‚           โ””โ”€ retries the FALLBACK observable          โ”‚
โ”‚         โ””โ”€ tries fallback immediately on first error            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Exponential Backoff Timeline

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  ATTEMPT 0: error โ”€โ”€โ”€โ”€โ–บ wait 1.0s โ”€โ”€โ–บ retry                     โ”‚
โ”‚  ATTEMPT 1: error โ”€โ”€โ”€โ”€โ–บ wait 2.1s โ”€โ”€โ–บ retry                     โ”‚
โ”‚  ATTEMPT 2: error โ”€โ”€โ”€โ”€โ–บ wait 4.3s โ”€โ”€โ–บ retry                     โ”‚
โ”‚  ATTEMPT 3: error โ”€โ”€โ”€โ”€โ–บ wait 8.0s โ”€โ”€โ–บ retry                     โ”‚
โ”‚  ATTEMPT 4: success โ”€โ”€โ–บ emit value โ”€โ”€โ–บ reset counter            โ”‚
โ”‚                                                                  โ”‚
โ”‚  Jitter (ยฑ0-300ms) prevents synchronized retries                โ”‚
โ”‚  across multiple clients (thundering herd)                      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Finalize Execution Points

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  COMPLETION PATH                                                โ”‚
โ”‚  source โ”€โ”€โ–บ next โ”€โ”€โ–บ next โ”€โ”€โ–บ complete โ”€โ”€โ–บ finalize()           โ”‚
โ”‚                                                                  โ”‚
โ”‚  ERROR PATH                                                     โ”‚
โ”‚  source โ”€โ”€โ–บ next โ”€โ”€โ–บ error โ”€โ”€โ–บ finalize() โ”€โ”€โ–บ subscriber.error  โ”‚
โ”‚                                                                  โ”‚
โ”‚  UNSUBSCRIBE PATH                                               โ”‚
โ”‚  source โ”€โ”€โ–บ next โ”€โ”€โ–บ unsubscribe() โ”€โ”€โ–บ finalize()               โ”‚
โ”‚                                                                  โ”‚
โ”‚  finalize ALWAYS runs (if subscription started)                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Recovery operatorcatchError
Retry operatorretry
Cleanup operatorfinalize
Backoff strategyExponential with jitter
Retry conditionNetwork errors, 5xx status
Reset behaviorresetOnSuccess: true
Fallback typesof(value), EMPTY, new request
Execution triggersComplete, error, unsubscribe

Key takeaways:

  • catchError replaces the failed stream with a recovery observable. The handler receives the error and the source, returning any observable โ€” a fallback value, a new request, EMPTY for silent completion, or a re-thrown error. Place it after retry for retry-then-recover, or before for recover-then-retry.
  • retry re-subscribes to the source on error. The delay option accepts a function returning a timer observable, enabling exponential backoff with jitter. resetOnSuccess: true resets the attempt counter on each emission โ€” essential for WebSocket and long-lived streams. Return EMPTY from delay to skip retry for non-retryable errors.
  • finalize runs on every termination path. Complete, error, and unsubscribe all invoke the callback exactly once per subscription. Stack multiple finalize operators for modular cleanup (spinner, connection, analytics). The callback receives no arguments โ€” use tap before finalize if you need the error or value.
  • Composition order determines semantics. retry โ†’ catchError means “retry the source, then fall back.” catchError โ†’ retry means “fall back, then retry the fallback.” The former handles transient source failures; the latter handles fallback chains that might themselves fail.
  • Conditional retry prevents hammering on client errors. Check error.status or error.name inside the delay function. Return EMPTY for 4xx errors โ€” they won’t succeed on retry. Only retry network errors (TypeError), timeouts, and 5xx server errors.

Remember: Resilience in RxJS is a three-part contract: retry for transient failures with exponential backoff, catchError for recovery with context-aware fallbacks, and finalize for guaranteed resource disposal. The order retry โ†’ catchError โ†’ finalize covers the vast majority of real-world scenarios โ€” network requests that blip, WebSockets that reconnect, and UI indicators that must always clear. Treat every subscription as a resource that needs cleanup, and every error as a decision point: retry, recover, or propagate.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!