Skip to content
jshacks.dev
Async

The RxJS retry Operator Explained With Examples

Learn how the RxJS retry operator resubscribes after an error, how to add delay and backoff with its config object and which failures should never be retried.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, RabbitMQ, Redis and Apache Kafka logos.

Networks fail in boring ways: a dropped packet, a 503 during a deploy, a connection reset. A second attempt a moment later usually works. retry automates that second attempt by resubscribing to the source observable when it errors. It is a few lines of code with a large downside if used carelessly, because an unconditional immediate retry on a struggling server makes the struggle worse. This post explains retry in RxJS 7 with printed output, covers the count form and the config object with delay, shows exponential backoff, explains why the source must be cold and lists the errors that should never be retried.

What it does

retry(count) catches an error from the source, resubscribes to it up to count times, and passes values through as they come. If the source errors again after the retries are used up, that error reaches the subscriber.

JavaScript
import { defer, of, throwError } from "rxjs";
import { retry } from "rxjs/operators";

let attempt = 0;

const flaky$ = defer(() => {
  attempt += 1;
  console.log(`attempt ${attempt}`);
  return attempt < 3 ? throwError(() => new Error("fail")) : of("success");
});

flaky$.pipe(retry(3)).subscribe({
  next: (v) => console.log("value", v),
  error: (e) => console.log("error", e.message),
});
Text
attempt 1
attempt 2
attempt 3
value success

Two failures, then success on the third attempt. retry(3) means up to three retries after the first try, so up to four attempts in total. When the budget runs out, the last error is delivered.

JavaScript
import { throwError } from "rxjs";
import { retry } from "rxjs/operators";

throwError(() => new Error("always fails"))
  .pipe(retry(2))
  .subscribe({ error: (e) => console.log("gave up:", e.message) });
Text
gave up: always fails

The source must be cold

retry resubscribes. If the source is cold, each subscription starts the work again, which is what you want. If the source is a promise wrapped with from, it does not restart: the promise is already settled, and every resubscription sees the same rejection immediately.

JavaScript
import { defer, from } from "rxjs";
import { retry } from "rxjs/operators";

let calls = 0;
const request = () => {
  calls += 1;
  return Promise.reject(new Error(`call ${calls}`));
};

// wrong: the promise is created once
from(request())
  .pipe(retry(2))
  .subscribe({ error: (e) => console.log("wrong:", e.message, "calls", calls) });

calls = 0;

// right: defer creates a new promise per subscription
defer(() => request())
  .pipe(retry(2))
  .subscribe({ error: (e) => console.log("right:", e.message, "calls", calls) });
Text
wrong: call 1 calls 1
right: call 3 calls 3

Always use defer for promise-based work. HTTP clients that return cold observables, such as Angular's HttpClient, restart correctly.

Delay between attempts

Retrying instantly hammers a failing service. RxJS 7 added a config object with a delay option, which takes a number of milliseconds or a function.

JavaScript
import { defer, of, throwError } from "rxjs";
import { retry } from "rxjs/operators";

let n = 0;
const start = Date.now();

defer(() => {
  n += 1;
  return n < 3 ? throwError(() => new Error("down")) : of("up");
})
  .pipe(retry({ count: 3, delay: 100 }))
  .subscribe((v) => {
    const waited = Math.round((Date.now() - start) / 100) * 100;
    console.log(v, `after about ${waited} ms`);
  });
Text
up after about 200 ms

Two failures, two waits of 100 ms. The measured figure varies with the timer, which is why the code rounds it.

Exponential backoff

When delay is a function, it receives the error and the retry count, and returns an observable. The retry happens when that observable emits. A timer with a growing duration gives exponential backoff.

JavaScript
import { defer, throwError, timer } from "rxjs";
import { retry } from "rxjs/operators";

let tries = 0;

defer(() => {
  tries += 1;
  console.log(`try ${tries}`);
  return throwError(() => new Error("down"));
})
  .pipe(
    retry({
      count: 3,
      delay: (error, retryCount) => {
        const wait = 100 * 2 ** (retryCount - 1);
        console.log(`waiting ${wait} ms`);
        return timer(wait);
      },
    })
  )
  .subscribe({ error: (e) => console.log("failed:", e.message) });
Text
try 1
waiting 100 ms
try 2
waiting 200 ms
try 3
waiting 400 ms
try 4
failed: down

retryCount starts at 1 for the first retry. Real systems add jitter, a random fraction of the wait, so that many clients do not retry in lockstep. Replace the wait with wait + Math.random() * 100 and the shape is the same.

Retrying only some errors

Not every failure deserves a retry. A 404 or a validation error will fail the same way every time. The delay function can rethrow to stop retrying.

JavaScript
import { defer, throwError, timer } from "rxjs";
import { retry } from "rxjs/operators";

let calls = 0;

defer(() => {
  calls += 1;
  return throwError(() => ({ status: calls === 1 ? 503 : 404 }));
})
  .pipe(
    retry({
      count: 5,
      delay: (error) =>
        error.status >= 500 ? timer(10) : throwError(() => error),
    })
  )
  .subscribe({ error: (e) => console.log("stopped at", e.status, "after", calls, "calls") });
Text
stopped at 404 after 2 calls

The first failure was a 503, so it was retried. The second was a 404, which the selector turned into an immediate error. The delay function is the place to make that decision, and reading error.status there keeps the policy in one spot.

Resetting the count

By default the count includes consecutive failures only if you set resetOnSuccess. For a long-lived source that emits successfully between failures, a global budget would be used up over time. Setting resetOnSuccess: true makes each success start the budget again.

JavaScript
import { defer, of, throwError, concat } from "rxjs";
import { retry, take } from "rxjs/operators";

let run = 0;

defer(() => {
  run += 1;
  return concat(of(`ok ${run}`), throwError(() => new Error("blip")));
})
  .pipe(retry({ count: 1, resetOnSuccess: true }), take(4))
  .subscribe({
    next: (v) => console.log(v),
    error: () => console.log("error"),
  });
Text
ok 1
ok 2
ok 3
ok 4

Each attempt emits a value before failing, so every retry follows a success and the budget resets. The take(4) ends the otherwise endless stream. Without resetOnSuccess, the output would stop after ok 2 with an error, because the single retry would already be spent.

retry versus retryWhen

Before RxJS 7, retryWhen was the way to add delay. It is deprecated, and the config object above covers its uses with less code. Prefer retry({ delay }).

Common mistakes

Retrying a hot source. A subject or shared stream does not restart work. Retry the cold source that does the work.

Retrying non-idempotent calls blindly. A retried POST that already succeeded server-side may create a duplicate. Use idempotency keys, or retry only reads.

No delay. Immediate retries add load at the worst moment. Always wait, and add jitter for many clients.

No limit. retry() with no count retries forever. Give it a count, or a time-bound via takeUntil.

Retrying client errors. 4xx responses are unlikely to change on a second attempt. Rethrow them in delay.

Choosing a retry policy

A retry policy has three parts: how many times, how long to wait and which errors qualify. The count is a budget, and it should be small. Three or four attempts cover the transient failures that actually resolve themselves, such as a connection reset or a brief deployment gap. Beyond that, you are no longer retrying a blip, you are hammering a service that is down, and the user is staring at a spinner. The wait should grow, because a service that failed once is likely to fail again immediately, and giving it breathing room is the whole point of backoff. And the qualifying errors should be a short list: network failures, timeouts and server errors in the 5xx range, plus the specific 429 and 503 responses that tell you to try again later.

When a server sends a Retry-After header with a 429 or 503 response, honor it. It is more accurate than any delay you can compute on the client. The delay function receives the error, so it can read the header from the error object and return a timer of that length.

Retrying the right layer

Retrying a whole pipeline repeats work that did not fail. If a stream first loads a configuration, then fetches a list, then fetches details for each item, a failure in the third step should not trigger the first two again. Put the retry operator on the smallest observable that can fail independently, which is usually the single HTTP call. A retry on the outer stream is the blunt option, and it can multiply the load on services that were healthy. Keep an eye on stacked retries too: if a client retries three times and the gateway in front of it also retries three times, one user action can produce nine requests against a struggling backend.

Observing retries in production

A retry that succeeds silently hides a degraded dependency. Log each retry with the error, the attempt number and the delay, or emit a metric, so that a rising retry rate shows up before users complain. The delay function is a convenient place for that, since it runs once per retry and already has the error and the count in hand.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.