← Back to Angular, page 8

angular-0150 · Hard senior

Write an HTTP interceptor that caches GET responses for a short time and shares one request among simultaneous callers.

Keep a Map from URL to a shared observable and an expiry time. For a GET without a no-cache flag, return the stored observable if it is fresh, otherwise forward the request with shareReplay(1) and store it. Remove failed requests so errors are not cached, and clear the cache when a write request succeeds.

Full answer

Many components ask for the same data (the course list in the header and on the page). Without care, each asks the server. An interceptor can fix this once.

Design:

  1. Only handle GET. Pass everything else through. After a successful write (POST, PUT, PATCH, DELETE), clear the cache, because the data may have changed.
  2. Key: req.urlWithParams. Add the headers that change the response (language, authorization) to the key if they matter, or the cache would leak data between users. Clear the cache on logout.
  3. Entry: { expires: number, response$: Observable<HttpEvent> }. If an entry exists and is fresh, return its response$. Because response$ uses shareReplay(1), callers that arrive while the request is still running share it (deduplication), and later callers within the time to live get the replayed response (caching).
  4. Errors: if the request errors, delete the entry (catchError or tap({ error })), so the next call tries again.
  5. Opt out: a custom HttpContextToken (NO_CACHE) lets a call skip the cache, for example a "refresh" button.
  6. Time to live: short, such as 30 seconds, for data that changes slowly. Use Date.now() or an injectable clock for tests.
  7. HttpClient returns events: with shareReplay(1) on the interceptor output you replay the last event, which is the HttpResponse (the Sent event is not delivered by default). Use filter carefully if you track progress events, and do not cache requests that use reportProgress.

Memory: limit entry count or remove expired entries when you read or write.

Alternatives: httpResource and TanStack Query handle caching at the data layer, and the browser HTTP cache handles it with headers (Cache-Control). Use an interceptor when the server cannot send good cache headers, or when you also need deduplication.

Testing: use HttpTestingController. Two calls to the same URL should produce one request, the second after the TTL should produce another, and an error should not be cached.

typescript
import { HttpContextToken, HttpEvent, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
import { Observable, shareReplay, tap } from 'rxjs';

export const NO_CACHE = new HttpContextToken<boolean>(() => false);

interface Entry {
  expires: number;
  response$: Observable<HttpEvent<unknown>>;
}

const TTL_MS = 30_000;
const cache = new Map<string, Entry>();

export function clearHttpCache(): void {
  cache.clear();
}

export const cacheInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next) => {
  if (req.method !== 'GET') {
    return next(req).pipe(tap({ next: (e) => e.type !== 0 && cache.clear() }));
  }
  if (req.context.get(NO_CACHE)) {
    return next(req);
  }

  const key = req.urlWithParams;
  const hit = cache.get(key);
  if (hit && hit.expires > Date.now()) {
    return hit.response$;
  }

  const response$ = next(req).pipe(
    tap({ error: () => cache.delete(key) }),
    shareReplay(1),
  );
  cache.set(key, { expires: Date.now() + TTL_MS, response$ });
  return response$;
};

Angular 20.3. A Karma test with `HttpTestingController` checks that two simultaneous GETs make one request, and that a failed request is retried on the next call.

Key points

  • Cache only GET. Key by URL with params. Clear the cache after writes and on logout.
  • Store a `shareReplay(1)` observable per key with an expiry. It deduplicates and caches.
  • Delete entries on error. Offer a `NO_CACHE` context token.
  • Keep a short time to live and limit the size.

Common mistakes

  • Caching error responses.
  • Sharing cached data between different users.
  • Never clearing the cache after a write.

Follow-ups

  • How would you add stale-while-revalidate?
  • How does this differ from `httpResource`?
  • How would you bound the cache size?

Tips

  • Mention both deduplication and caching.
  • Say you clear on write and logout.
  • Point out the user data leak risk.

Evaluation rubric

  • Implements dedup and TTL cache correctly.
  • Handles errors, writes and opt-out.
  • Considers security and memory.