Caching HTTP data

Intermediate · 9 min

shareReplay for avoiding duplicate requests, and why that's a different, narrower problem than full state-management caching.

Before thisHttpClient fundamentals

Technical Rajni · 9 min

Caching HTTP data

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Technical RajniReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A plain HttpClient observable is cold — each new subscriber triggers its own independent HTTP request, even if two subscribers are asking for the exact same data at nearly the same moment.
  • `shareReplay(1)` turns a cold observable into one that multicasts and replays its last emission — multiple subscribers share one underlying request, and a late subscriber still gets the cached result instead of triggering a new one.
  • `shareReplay` solves "don't send this exact request twice" for one observable's lifetime — it's a narrower problem than full application state management, which also handles invalidation, updates, and sharing data across unrelated parts of the app.

The duplicate-request problem, concretely

getConfig(): Observable<Config> {
  return this.http.get<Config>('/api/config'); // cold — a fresh request per subscription
}

Call getConfig() from two different components that both subscribe around the same time, and — because HttpClient observables are cold, exactly as covered in the HttpClient fundamentals lesson — you get two separate HTTP requests for identical data. Nothing about sharing the same service method protects against this; a cold observable has no memory of having already run, so every new subscription re-triggers the underlying request from scratch.

shareReplay(1): one request, shared and remembered

private config$ = this.http.get<Config>('/api/config').pipe(shareReplay(1));

getConfig(): Observable<Config> {
  return this.config$;
}

The fix is to construct the observable once — stored as a field, not recreated inside the method on every call — and pipe it through shareReplay(1). Two things change: subscribers now share one underlying execution instead of each triggering their own (the “replay” and “share” halves of multicasting, similar in spirit to what a Subject gives you, covered a few lessons back), and the last emission is cached and replayed immediately to any new subscriber, even one that subscribes well after the original request already completed. A third component mounting later gets the cached config instantly, with no second request fired at all.

A real but narrow fix — not a state-management replacement

It’s worth being precise about what problem this actually solves, because it’s easy to reach for shareReplay as if it were a general caching layer and be disappointed. shareReplay(1) solves exactly one thing: don’t re-issue an identical request for data you’re already fetching or have already fetched, within the lifetime of that one cached observable. It does nothing about invalidation — if the underlying data changes on the server, this cached observable has no way of knowing and will keep serving the stale value forever, until the app reloads or you explicitly construct a new cached observable. It does nothing about sharing that data with parts of the app that aren’t going through this specific service method either.

Full application state management — covered in the next section of this roadmap, from a plain service holding signals up through NgRx — is the broader answer to “how does data get shared, updated, and kept consistent across the whole app.” shareReplay is a narrower, genuinely useful tool for its specific job: preventing redundant network requests for data you’re fetching more than once in a short window. Reach for it there; reach for real state management once you need invalidation, updates, or cross-feature sharing that a cached observable alone can’t give you.

A manual escape hatch for invalidation

Since shareReplay(1) has no built-in notion of “this cached value is now stale,” forcing a refresh means giving yourself an explicit way to throw the cached observable away and rebuild it:

private config$?: Observable<Config>;

getConfig(forceRefresh = false): Observable<Config> {
  if (forceRefresh || !this.config$) {
    this.config$ = this.http.get<Config>('/api/config').pipe(shareReplay(1));
  }
  return this.config$;
}

This is a hand-rolled, minimal version of what a real caching layer does properly — the point of showing it isn’t to recommend reimplementing a cache library yourself, but to make the earlier claim concrete: shareReplay(1) genuinely has no opinion about staleness at all, so any invalidation strategy has to be built on top of it deliberately, by you, rather than configured as an option the operator itself exposes.

This lesson’s video covers exactly this shareReplay-for-deduplication pattern directly — a genuinely thin topic in video form across the wider web, so this is presented as the solid single answer rather than one of several options to compare.

Check yourself

  1. 01Two components both call the same service method, `getConfig()`, which returns `this.http.get('/api/config')` with no caching applied. If both components mount around the same time, how many HTTP requests fire?

    Two. A plain HttpClient observable is cold, so each subscription — one from each component — independently triggers its own HTTP request, even though both are asking for identical data at nearly the same moment. Nothing about the shared service method itself prevents the duplication; the observable it returns has no memory of having already been subscribed to.

  2. 02After wrapping that same observable with `.pipe(shareReplay(1))` inside the service (cached once, not recreated per call), what changes for those two components?

    One HTTP request fires, shared by both subscribers — and critically, a *third* component mounting later still gets the already-cached result immediately, without triggering a second request, because `shareReplay(1)` keeps the last emission around to replay to any new subscriber rather than re-running the underlying request.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark