Angular HTTP Caching
Learn Angular HTTP Caching using HttpClient, RxJS shareReplay, HTTP Interceptors, browser caching, ETag, Cache-Control, service workers, enterprise architecture, best practices, and interview questions.
HTTP Caching is one of the most important optimization techniques for Angular applications.
Instead of calling the backend repeatedly for the same data, Angular applications can reuse previously fetched responses, reducing:
- API Calls
- Server Load
- Network Traffic
- Response Time
- Infrastructure Cost
Caching significantly improves user experience while making enterprise applications more scalable.
HTTP Caching is a frequently asked Angular interview topic.
Table of Contents
- What is HTTP Caching?
- Why Use Caching?
- Types of Caching
- HTTP Caching Architecture
- Browser Caching
- Client-Side Caching
- RxJS shareReplay()
- HTTP Interceptor Caching
- Cache-Control and ETag
- Service Worker Caching
- Enterprise Banking Example
- Performance Best Practices
- Common Mistakes
- Top 10 Interview Questions
- Summary
What is HTTP Caching?
HTTP Caching stores previously retrieved responses so they can be reused without contacting the server again.
Instead of
Angular
↓
REST API
↓
Database
↓
Angular
Every request,
the application can serve data from cache.
HTTP Caching Architecture
flowchart LR
User
User --> Angular
Angular --> Cache
Cache --> CachedData
Cache --> RESTAPI
RESTAPI --> Database
Database --> Response
Response --> Cache
Cache --> User
Why Use HTTP Caching?
Without Caching
- Duplicate API requests
- Slow loading
- Higher server cost
- Increased latency
- Poor user experience
With Caching
- Faster pages
- Reduced bandwidth
- Better scalability
- Lower infrastructure costs
- Better responsiveness
Types of HTTP Caching
| Cache Type | Purpose |
|---|---|
| Browser Cache | Store static assets |
| Client Cache | Store API responses in memory |
| HTTP Interceptor Cache | Centralized response caching |
| Service Worker Cache | Offline support |
| CDN Cache | Cache responses close to users |
| Server Cache | Reduce database access |
Browser Caching
The browser automatically caches static assets such as:
- JavaScript
- CSS
- Images
- Fonts
Example Response Headers
Cache-Control: public, max-age=3600
The browser may reuse the resource for one hour before checking for updates.
Browser Cache Flow
flowchart TD
Browser
Browser --> Cache
Cache --> FileFound
Cache --> Server
Server --> Browser
Client-Side Caching
Angular services can cache frequently used data.
@Injectable({
providedIn: 'root'
})
export class ProductService {
private products?: Product[];
getProducts(): Observable<Product[]> {
if (this.products) {
return of(this.products);
}
return this.http
.get<Product[]>(this.api)
.pipe(
tap(data => {
this.products = data;
})
);
}
}
Benefits
- Fewer API calls
- Faster navigation
- Better performance
Client Cache Architecture
flowchart LR
Component
Component --> Service
Service --> MemoryCache
MemoryCache --> API
API --> MemoryCache
MemoryCache --> Component
Using shareReplay()
One of the most common Angular caching techniques.
products$ = this.http
.get<Product[]>(this.api)
.pipe(
shareReplay(1)
);
shareReplay(1) shares the latest emitted value with future subscribers, helping avoid duplicate HTTP requests while the shared Observable remains active.
Note:
shareReplay()is not a complete cache invalidation strategy. You should decide when cached data should be refreshed or cleared.
shareReplay Architecture
flowchart TD
Request
Request --> HttpClient
HttpClient --> Response
Response --> shareReplay
shareReplay --> Component1
shareReplay --> Component2
shareReplay --> Component3
Cache Invalidation
Cached data should be refreshed when it becomes stale.
Common strategies
- Clear cache after POST, PUT, PATCH, or DELETE
- Time-based expiration (TTL)
- User-initiated refresh
- Version-based invalidation
- ETag validation
Example
refreshProducts(){
this.products = undefined;
return this.getProducts();
}
Cache Invalidation Flow
flowchart LR
Cache
Cache --> DataChanged
DataChanged --> ClearCache
ClearCache --> API
API --> UpdatedCache
HTTP Interceptor Caching
Interceptors can centralize caching for GET requests.
Example
if (
req.method === 'GET'
){
// Return cached response
// or forward request
}
Typical Flow
- Check cache
- Return cached response if available
- Otherwise call the server
- Cache successful responses
Interceptor Architecture
flowchart TD
Component
Component --> HttpClient
HttpClient --> CacheInterceptor
CacheInterceptor --> Cache
Cache --> RESTAPI
RESTAPI --> Cache
Cache --> Component
Cache-Control Header
Servers control caching using HTTP headers.
Example
Cache-Control:
max-age=600
Meaning
Cache the response for 10 minutes.
Other common directives
| Directive | Purpose |
|---|---|
| no-store | Never store the response |
| no-cache | Revalidate before reuse |
| private | Cache only in the user's browser |
| public | Shared caches may store it |
| max-age | Cache lifetime in seconds |
ETag
ETag allows the browser to verify whether cached content has changed.
Request
If-None-Match:
"abc123"
Response
304 Not Modified
If unchanged, the server responds with 304 Not Modified, allowing the browser to reuse the cached resource without downloading it again.
ETag Architecture
flowchart LR
Browser
Browser --> ETag
ETag --> Server
Server --> 304
304 --> BrowserCache
Service Worker Caching
Angular supports offline caching through Angular Service Workers.
Common cached resources
- Images
- CSS
- JavaScript
- API Responses (when configured)
- Offline Pages
Architecture
flowchart TD
Browser
Browser --> ServiceWorker
ServiceWorker --> Cache
Cache --> Network
Network --> API
Benefits
- Offline support
- Faster loading
- Better mobile experience
Enterprise Banking Example
Banking Dashboard
Frequently Cached Data
- Customer Profile
- Branch List
- Currency List
- Product Catalog
- Country Codes
- Interest Rates
- Account Types
Architecture
flowchart TD
AngularUI
AngularUI --> BankingService
BankingService --> Cache
Cache --> HttpClient
HttpClient --> BankingAPI
BankingAPI --> Database
Database --> Cache
Cache --> UI
Benefits
- Faster dashboards
- Lower API traffic
- Better scalability
- Reduced database load
- Improved customer experience
Request Lifecycle
flowchart TD
Request
Request --> Cache
Cache --> Hit
Cache --> Miss
Miss --> API
API --> Cache
Cache --> Response
Performance Best Practices
| Practice | Benefit |
|---|---|
| Cache only reusable GET responses | Reduce duplicate requests |
Use shareReplay() carefully |
Avoid repeated HTTP calls |
| Invalidate stale cache | Prevent outdated data |
| Cache static reference data | Faster navigation |
| Respect Cache-Control headers | Correct HTTP behavior |
| Use ETag when supported | Smaller network usage |
| Monitor cache hit ratio | Measure effectiveness |
Common Mistakes
Caching POST Requests
Avoid caching:
- POST
- PUT
- PATCH
- DELETE
These requests modify data and are generally not cacheable in application logic.
Never Clearing Cache
Old cached data can become stale.
Always define an invalidation strategy.
Caching Sensitive Data
Avoid caching:
- Passwords
- Authentication Tokens
- Banking Transactions
- Personal Health Information
Sensitive information should follow strict security and compliance requirements.
Using Unlimited Cache
Always set:
- Expiration
- Size limits
- Eviction strategy
Ignoring HTTP Headers
Respect server-provided caching directives such as Cache-Control and ETag.
Best Practices
- Cache GET requests only.
- Use
shareReplay()for shared HTTP Observables. - Invalidate cache after data changes.
- Cache reference data aggressively.
- Respect HTTP caching headers.
- Use ETag validation where available.
- Use Service Workers for offline experiences.
- Avoid caching sensitive information.
- Monitor cache effectiveness.
- Test cache invalidation scenarios.
Advantages
| Feature | Benefit |
|---|---|
| Browser Cache | Faster asset loading |
| Memory Cache | Reduced API calls |
| shareReplay() | Shared responses |
| Cache Interceptor | Centralized caching |
| Cache-Control | Standards-based caching |
| ETag | Efficient validation |
| Service Worker | Offline capability |
| Enterprise Ready | High scalability |
Top 10 Angular HTTP Caching Interview Questions
1. What is HTTP Caching?
Answer
HTTP Caching stores previously retrieved resources so they can be reused instead of making repeated requests to the server.
2. Why is caching important?
Answer
Caching improves performance, reduces API calls, lowers server load, decreases bandwidth usage, and enhances user experience.
3. What is shareReplay()?
Answer
shareReplay() is an RxJS operator that shares and replays the latest emitted value to new subscribers, helping avoid duplicate HTTP requests.
4. What is cache invalidation?
Answer
Cache invalidation is the process of removing or refreshing stale cached data after updates or after a defined expiration period.
5. Which HTTP methods should typically be cached?
Answer
GET requests are the primary candidates for caching because they retrieve data without modifying server state.
6. What is Cache-Control?
Answer
Cache-Control is an HTTP response header that tells browsers and intermediaries how long and under what conditions a response may be cached.
7. What is ETag?
Answer
An ETag is a unique identifier for a resource that enables conditional requests. If the resource has not changed, the server can return 304 Not Modified.
8. Why use HTTP Interceptors for caching?
Answer
Interceptors provide a centralized location for implementing reusable caching logic across multiple services.
9. What is Service Worker caching?
Answer
Service Workers cache application resources and, when configured, API responses to improve performance and support offline functionality.
10. What are HTTP Caching best practices?
Answer
- Cache GET requests.
- Use
shareReplay()appropriately. - Define cache invalidation rules.
- Respect
Cache-ControlandETag. - Avoid caching sensitive information.
- Monitor cache performance.
Interview Cheat Sheet
| Topic | Remember |
|---|---|
| Memory Cache | Service variables |
| Shared Requests | shareReplay(1) |
| HTTP Cache | Cache-Control |
| Validation | ETag |
| Offline | Service Worker |
| Centralized Cache | HTTP Interceptor |
| Cache Miss | API Call |
| Cache Hit | Cached Response |
| Invalidation | Refresh stale data |
| Best Practice | Cache GET requests only |
Summary
Angular HTTP Caching is a key optimization technique for improving application performance and scalability. By combining browser caching, in-memory caching, RxJS shareReplay(), HTTP Interceptors, Cache-Control, ETag, and Service Workers, developers can significantly reduce redundant network traffic while delivering faster and more responsive applications. Effective cache invalidation and careful handling of sensitive data are essential for maintaining correctness and security in enterprise systems.
Key Takeaways
- ✔ HTTP Caching reduces unnecessary API requests.
- ✔ Cache GET requests, not data-modifying requests.
- ✔ Use
shareReplay()to share HTTP responses. - ✔ Define a clear cache invalidation strategy.
- ✔ Respect
Cache-ControlandETagheaders. - ✔ Use HTTP Interceptors for centralized caching.
- ✔ Service Workers enable offline caching.
- ✔ Avoid caching sensitive information.
- ✔ Monitor cache effectiveness in production.
- ✔ HTTP Caching is a common Angular enterprise interview topic.
Next Article
➡️ 69-Authentication-and-JWT-QA.md