← Back to Angular, page 7

angular-0127 · Medium mid

What causes memory leaks with RxJS in Angular apps, and how does shareReplay without refCount leak?

A leak happens when a long-lived source keeps a subscription that holds a destroyed component. shareReplay without refCount keeps its source subscribed forever after the first subscriber, so an infinite source (interval, WebSocket) never stops. Use shareReplay with refCount true, takeUntilDestroyed, async pipe and toSignal.

Full answer

RxJS leaks follow one rule: a source holds a reference to every subscriber's callback. If the source lives longer than the subscriber and never completes, the callback (and the component it references) stays alive.

Common causes:

  1. Subscribing to a root service Subject, interval, fromEvent(window), or store stream in a component and not unsubscribing.
  2. Forgetting to unsubscribe in nested subscriptions, so inner subscriptions pile up (use flattening operators).
  3. shareReplay without refCount. shareReplay(1) means refCount: false, and it still does in RxJS 7.8 for backward compatibility: once started, it never unsubscribes from its source. So with a source like interval(1000) or a WebSocket, the source keeps running after the last subscriber leaves. Even if the first subscriber was a component that is now destroyed, the timer continues forever.
  4. Event listeners added with addEventListener and not removed.
  5. Keeping large values in ReplaySubject with a large bufferSize or no time window.

Fixes:

  • shareReplay({ bufferSize: 1, refCount: true }): when the subscriber count drops to zero, the source is unsubscribed, and a later subscriber restarts it. This is usually what you want for page-level data. For app-level caches that should live for the whole session (user profile), refCount: false is deliberate, so document it.
  • takeUntilDestroyed() last in the pipe, async pipe, toSignal.
  • take(1), first() or takeUntil(stop$) for finite use.
  • A Subscription container and unsubscribe() for old code.

Finding leaks: use the browser Memory tab, take heap snapshots before and after navigating away and back, and look for detached DOM nodes and component instances that are still reachable. A simple check: add a teardown log inside a custom Observable and watch whether it runs when the component closes.

typescript
import { Observable, shareReplay } from 'rxjs';

function makeSource(name: string): Observable<number> {
  return new Observable<number>((subscriber) => {
    const id = setInterval(() => subscriber.next(1), 5);
    console.log(name, 'source started');
    return () => {
      clearInterval(id);
      console.log(name, 'source torn down');
    };
  });
}

const leaky$ = makeSource('shareReplay(1)').pipe(shareReplay(1));
const safe$ = makeSource('refCount true').pipe(shareReplay({ bufferSize: 1, refCount: true }));

const a = leaky$.subscribe();
const b = safe$.subscribe();

setTimeout(() => {
  a.unsubscribe();
  b.unsubscribe();
  setTimeout(() => {
    console.log('after the last unsubscribe, only the refCount source is torn down');
    process.exit(0);
  }, 20);
}, 20);

RxJS 7.8. The script was run in Node 24 twice with identical output. It counts source teardowns with and without refCount.

Key points

  • Leaks come from long-lived sources keeping subscriber callbacks alive.
  • `shareReplay(1)` does not unsubscribe from the source. Use `{ bufferSize: 1, refCount: true }`.
  • Prefer `async`, `toSignal`, `takeUntilDestroyed`.
  • Find leaks with heap snapshots and teardown logs.

Common mistakes

  • Using `shareReplay(1)` on an infinite source in a component-level stream.
  • Using `refCount: true` for a cache that must survive route changes, losing the data.
  • Nested subscribes that never clean up.

Follow-ups

  • When is `refCount: false` the right choice?
  • How would you write a test that proves the source was unsubscribed?
  • What is the difference between `share` and `shareReplay`?

Tips

  • Show the `shareReplay` teardown demo. It proves the point.
  • Mention that `refCount: false` can be deliberate.
  • Describe how you find leaks with the profiler.

Evaluation rubric

  • Explains the root cause of RxJS leaks.
  • Identifies the shareReplay refCount issue.
  • Gives fixes and a way to detect leaks.