BACK
Use casesIn-flight deduplication — one request per key
Use cases · 29

In-flight deduplication — one request per key

Pattern

Two components request the user with id=42 almost simultaneously. The ordinary cache isn't filled yet (the first response hasn't arrived), so the backend gets two identical requests. The fix: cache not the result but the in-flight Observable itself, until it completes.

The problem it solves

This is a race window — the short gap between "request sent" and "response received", when an ordinary response cache is useless. A manual Map<id, Promise> often forgets to delete the key on error/complete, and then a repeat request is blocked forever.

Operators and why they matter

  • defer — the HTTP call starts only on the first subscription. This is lazy creation of the side effect.
  • shareReplay({ bufferSize: 1, refCount: true }) — the second subscriber gets the same request and the same response.
  • finalize — critically important. Removes the key from the in-flight Map after complete/error/unsubscribe. Without it — a key leak.

Gotchas

  • Without finalize, an error leaves a "broken" key in the Map forever. Repeat requests will always return the cached error.
  • refCount: false — the request keeps running even after all subscribers leave. For HTTP that's sometimes fine; for WebSocket it's dangerous.
  • The key must include ALL request parameters (not just the id, but filters, headers too). Otherwise different requests land in the same cache.

What you get

Parallel subscribers share one HTTP request. After it finishes the cache is cleared — the next request goes to the network fresh.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...