GenClass is open source.Star on GitHub

How to fix race conditions in Angular and RxJS.

An Angular race condition happens when a user action sends a request while an earlier one is still running and the code lets both run: a double click places two orders, or a slow, older search response replaces newer results. The fix is the RxJS operator that decides what happens to the overlap: exhaustMap ignores repeat clicks, switchMap cancels the older request and concatMap queues saves in order. mergeMap runs them all at once, which is safe only when order does not matter.

Which RxJS operator fixes which race

In RxJS, a flattening operator turns each click or keystroke into an HttpClient request. The four below differ only in what happens when a new value arrives during a request.

What each RxJS flattening operator does with an overlapping request
OperatorA new value arrives during a requestUse it for
exhaustMapIgnored until the current request completes. DocsSubmit and payment buttons
switchMapThe current request is canceled (HttpClient aborts it) and the new one starts. DocsSearch boxes and filters
concatMapQueued, then sent when the current request completes. DocsSaves to the same record
mergeMapSent at once, next to the current one; the responses land in any order. DocsIndependent requests, such as one upload per file

A subscribe() inside another subscribe() behaves like mergeMap: every request runs and the last response to arrive wins. Replace the nested subscription with the operator that fits the case.

A double click sends two requests: exhaustMap

Send the clicks into a Subject and let exhaustMap start the POST. Clicks that arrive while it runs are ignored, so a double click sends one POST. The disabled button shows the user that the click counted, and exhaustMap still ignores a second click that lands before the button re-renders.

import { Component, inject, input, signal } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
import { EMPTY, Subject, catchError, exhaustMap, finalize } from "rxjs";

@Component({
  selector: "app-place-order",
  template: `
    <button (click)="clicks.next()" [disabled]="saving()">
      Place order
    </button>
    @if (placed()) { <p>Order placed.</p> }
  `,
})
export class PlaceOrder {
  cartId = input.required<string>();
  protected clicks = new Subject<void>();
  protected saving = signal(false);
  protected placed = signal(false);
  private http = inject(HttpClient);

  constructor() {
    this.clicks.pipe(
      exhaustMap(() => {
        this.saving.set(true);
        const body = { cartId: this.cartId() };
        return this.http.post("/api/orders", body).pipe(
          catchError(() => EMPTY), // tell the user; keep listening
          finalize(() => this.saving.set(false)),
        );
      }),
      takeUntilDestroyed(),
    ).subscribe(() => this.placed.set(true));
  }
}

Catch errors inside the inner pipe. If a failed POST reaches the outer stream, the subscription ends and later clicks send nothing.

exhaustMap only guards clicks on this button. A retry after a timeout or a second tab can still send the same order twice, so give each order an idempotency key that the server checks. The duplicate submissions guide covers the server side.

The request for "ang" is slow, the one for "angular" is fast, and the older answer lands last, so the list shows results for text the user already changed. Pipe the input's valueChanges through three operators:

import { Component, inject } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { FormControl, ReactiveFormsModule } from "@angular/forms";
import { toSignal } from "@angular/core/rxjs-interop";
import {
  catchError, debounceTime, distinctUntilChanged, of, switchMap,
} from "rxjs";

type Item = { id: number; name: string };

@Component({
  selector: "app-search",
  imports: [ReactiveFormsModule],
  template: `
    <input [formControl]="query" placeholder="Search">
    @for (item of results(); track item.id) {
      <p>{{ item.name }}</p>
    }
  `,
})
export class Search {
  private http = inject(HttpClient);
  protected query = new FormControl("", { nonNullable: true });
  protected results = toSignal(
    this.query.valueChanges.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((q) =>
        this.http
          .get<Item[]>("/api/search", { params: { q } })
          .pipe(catchError(() => of([]))),
      ),
    ),
    { initialValue: [] },
  );
}

debounceTime(300) waits until typing pauses for 300 ms and passes on only the latest text. distinctUntilChanged() drops a value equal to the one before it, for example when a letter is typed and deleted within the pause. switchMap keeps only the newest request: when a new term arrives, it unsubscribes from the running one, which HttpClient then aborts (Angular docs), so the old response never reaches the list. The catchError sits inside, so one failed search does not end the stream.

Debounce alone does not fix the race. It sends fewer requests, but if the user pauses after "ang" and again after "angular", the two requests can still overlap and the older one can land last. The same pattern fits a filter or a route parameter. Out-of-order responses explains the bug outside Angular, and the race condition simulator lets you change the timing and watch it happen.

Saves that must stay in order: concatMap

Two quick edits to the same record can put two PUT requests in flight at once. With mergeMap the server may finish the older one last and keep it. concatMap sends one save, waits for it to complete, then sends the next, so the server gets the edits in the order they were made.

import { Injectable, inject } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { EMPTY, Subject, catchError, concatMap } from "rxjs";

type Note = { id: string; text: string };

@Injectable({ providedIn: "root" })
export class NoteSaver {
  private http = inject(HttpClient);
  private edits = new Subject<Note>();

  constructor() {
    this.edits.pipe(
      concatMap((note) =>
        this.http.put(`/api/notes/${note.id}`, note).pipe(
          catchError(() => EMPTY), // report it; the queue goes on
        ),
      ),
    ).subscribe();
  }

  save(note: Note) {
    this.edits.next(note);
  }
}

switchMap is wrong here too. It aborts the older PUT in the browser, but a request that already reached the server can still be saved, perhaps after the newer one, and the page never learns how it ended. The queue lives in a root service, so a waiting save survives when its component is destroyed.

The RxJS docs warn that concatMap buffers values without limit when they arrive faster than the requests complete. For autosave, put debounceTime in front of it so one pause in typing sends one save. Lost edits and autosave covers the rest of that bug.

When mergeMap is the right choice

Use mergeMap when the requests are independent and their order does not matter, such as uploading several files. Its second argument caps how many run at once; the default is no limit (RxJS docs).

uploadAll(files: File[]) {
  // at most three uploads at a time
  return from(files).pipe(
    mergeMap((file) => this.http.post("/api/files", file), 3),
  );
}

If two of the responses can write to the same data, pick one of the other three operators.

Cleanup, and requests sent twice

takeUntilDestroyed() completes a stream when the component, directive or service that created it is destroyed. It has been stable since Angular 19 (API docs) and does the same job as the older takeUntil(this.destroy$) pattern. Call it in a constructor or a field initializer, where Angular can inject the DestroyRef, or pass a DestroyRef in. toSignal and the async pipe clean up on their own.

HttpClient observables are cold: each subscription sends its own request, so an observable used by two async pipes goes to the server twice. Subscribe once, or share the result with shareReplay.

resource() and httpResource() in Angular 22

Angular 22 made resource(), rxResource() and httpResource() stable; each API page says "stable since v22.0" (httpResource API). httpResource sends a new request whenever a signal it reads changes, and cancels a request that is still pending before it sends the next one (Angular guide). For reads, that is switchMap with no subscription to manage:

query = input.required<string>();
protected results = httpResource<Item[]>(
  () => `/api/search?q=${encodeURIComponent(this.query())}`,
);

resource() does the same for any async loader: it aborts the pending load when its params change and gives the loader an abortSignal to pass to fetch (resource guide). httpResource has no debounce option, so a signal that changes on every keystroke sends a request on every keystroke. Angular 22 added debounced() for a debounced copy of a signal, but angular.dev marks it experimental (API docs). Angular's guide says to avoid httpResource for mutations such as POST or PUT; use HttpClient with exhaustMap or concatMap for those.

Where GenClass fits

GenClass is an open-source browser library that can report the races you missed while people use the app. In an Angular app it watches the fetch and XMLHttpRequest calls that HttpClient makes, and its model can report the same request sent again without a new intent, such as the second POST of a double click (diagnosis duplicate). It does not discover Angular signals, so a late response about to replace newer data in a signal (diagnosis stale) can be reported only if you register that state with rt.atom or rt.guard (how). It does not catch logic that is always wrong. In observe mode the second POST still reaches your server, so keep the idempotency key.

GenClass's compatibility test ran a small Angular 22 app (SSR, hydration, zoneless) in headless Chromium in October 2026, on a runtime build older than 0.3.0. Observe mode reported its double submit in 10 of 10 seeds on each HttpClient backend, fetch and XHR, and made no false reports in the 120 observe runs where the app was correct (its only reports there were the HTTP 500 and the offline period the test injects on purpose). The stale typeahead went unreported in all 20 of its observe runs, because its results lived in a signal (results). Rates on other apps are on the benchmarks page.

To add it, run npx genclass in the project. It signs you in (a free account is enough), shows the change, then adds GenClass at the top of src/main.ts and turns on visitor analytics (npx genclass setup --no-analytics leaves them off). Or run npm install @genclass/runtime and put the import first yourself. Either way it starts in observe mode, which reports and never holds, delays or changes a request or a response, and during SSR it installs nothing on the server.

// src/main.ts
import "@genclass/runtime/auto"; // first, before Angular
import { bootstrapApplication } from "@angular/platform-browser";
import { App } from "./app/app";
import { appConfig } from "./app/app.config";

bootstrapApplication(App, appConfig).catch((err) =>
  console.error(err),
);

Questions

What is the difference between switchMap, mergeMap, concatMap and exhaustMap?

They differ in what happens when a new value arrives during a request: switchMap cancels the running request, concatMap queues the new one, exhaustMap ignores it, and mergeMap runs both at once.

How do I prevent a double click from sending two requests in Angular?

Send the clicks through a Subject into exhaustMap, which ignores clicks until the request completes, and disable the button while it runs. Keep an idempotency key on the server for retries and second tabs.

Why is my Angular HTTP request sent twice?

Each subscription to an HttpClient observable sends its own request, so two async pipes on one observable, or a subscribe call plus an async pipe, send two. Subscribe once, for example with toSignal, or share the result with shareReplay.

Is debounceTime enough to stop stale search results?

No. It sends fewer requests, but a slow older request can still return after a newer one, so put switchMap after it.

Which operator should an NgRx effect use?

The same rules apply: switchMap for reads where only the latest answer matters, concatMap for writes that must stay in order, exhaustMap to ignore repeats while one runs, and mergeMap for independent work.

Related: race conditions in React, refresh token races when many requests get a 401 and testing races with Playwright.

Talk to sales

Tell us about your team and what you need. A person writes back, usually within a day.