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:
- Only handle
GET. Pass everything else through. After a successful write (POST,PUT,PATCH,DELETE), clear the cache, because the data may have changed. - 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. - Entry:
{ expires: number, response$: Observable<HttpEvent> }. If an entry exists and is fresh, return itsresponse$. Becauseresponse$usesshareReplay(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). - Errors: if the request errors, delete the entry (
catchErrorortap({ error })), so the next call tries again. - Opt out: a custom
HttpContextToken(NO_CACHE) lets a call skip the cache, for example a "refresh" button. - Time to live: short, such as 30 seconds, for data that changes slowly. Use
Date.now()or an injectable clock for tests. HttpClientreturns events: withshareReplay(1)on the interceptor output you replay the last event, which is theHttpResponse(theSentevent is not delivered by default). Usefiltercarefully if you track progress events, and do not cache requests that usereportProgress.
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.
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.