Client Cache vs CDN vs Redis¶
1. Decision¶
Implement a multi-tier caching strategy using Client/Browser Caching for static assets local to the user, Content Delivery Networks (CDN) for geographically distributed static and dynamic media content, and Redis for server-side in-memory application state and database query caching.
2. 30-Second Answer¶
Modern high-scale architectures layer caching at three distinct network boundaries. Client Cache (Browser / HTTP headers) stores static assets (JS, CSS, images) directly on the user's device, eliminating network requests entirely (\(0\text{ms}\) latency). CDN (e.g., CloudFront, Cloudflare) caches static files and dynamic edge responses at geographically distributed Points of Presence (PoPs) close to users, cutting round-trip time (RTT) latency (\(10-30\text{ms}\)). Redis operates on the application server side as a centralized in-memory datastore, caching database query results, user sessions, and shared microservice state (\(<1\text{ms}\)). Selecting where to cache depends on content privacy, update frequency, geographic distribution, and cache invalidation control.
3. Decision Matrix¶
| Option | Best For | Avoid When | Latency | Scalability | Consistency | Operational Complexity |
|---|---|---|---|---|---|---|
| Client / Browser Cache | Static UI assets (JS, CSS, logos), immutable user preferences | Sensitive private data, rapidly changing real-time backend state | Zero (0ms - local disk/RAM) | Infinite (Offloaded to client device) | Weakest (Hard to invalidate without cache-busting URLs) | Low (HTTP Headers Cache-Control) |
| CDN (Edge Caching) | Static images, videos, HLS streams, global public API responses | Private personalized user data, real-time transactional writes | Very Low (10-30ms RTT at Edge PoP) | Global Linear Scale (Terabytes/sec edge bandwidth) | Medium (Purge API / Tag invalidation latency) | Low to Medium |
| Redis (Server Side) | Database query results, user session tokens, rate limit counters, microservice state | Multi-gigabyte static media binary files | Sub-millisecond (<1ms in-datacenter) | Scale-up RAM; Redis Cluster (16384 Hash Slots) | Strong Control (Instant application-driven invalidation) | Medium |
4. Selection Rules¶
| Requirement | Best Choice | Rationale / Example |
|---|---|---|
| Static Web App Bundles (JS/CSS) | Client Cache + CDN | Immutable asset hashing (app.a8f9.js) cached forever on browser & CDN |
| Global Video / Image Streaming | CDN | Edge PoPs stream video segments directly, bypassing origin servers |
| Dynamic Shared User Session State | Redis | Microservices require instant, synchronized read/write access to sessions |
| Zero-Network-Latency Repeat Requests | Client Cache | HTTP Cache-Control: max-age=31536000, immutable serves from browser memory |
| Database Query Offloading | Redis | Caches pre-computed SQL join queries or aggregations near DB tier |
| Edge Compute & Security Rate Limiting | CDN (Cloudflare Workers) | Filter DDoS attacks and inspect JWT tokens before traffic reaches origin |
5. Tradeoffs¶
- Local Latency Elimination vs Invalidation Control
- Gain (Client): \(0\text{ms}\) latency; zero server network bandwidth consumed.
- Lose (Client): Impossible to forcibly invalidate once cached on browser unless cache-busting URLs are used.
- Global Geographic Proximity vs Cache Cold-Start Origin Shielding
- Gain (CDN): Users fetch content from edge PoP 10ms away instead of 200ms cross-ocean RTT.
- Lose (CDN): Cold cache misses at hundreds of global PoPs cause traffic spikes on origin server without Origin Shielding.
- Application Control vs Infrastructure Offloading
- Gain (Redis): Instant programmatic cache deletion and fine-grained data structure access.
- Lose (Redis): Consumes expensive server RAM; does not reduce network RTT between client and backend.
- Public Static Content vs Private Personalized Content
- Gain (CDN): Caches identical assets once for millions of global users.
- Lose (CDN): High risk of leaking private user data if HTTP headers (
Cache-Control: private) are misconfigured. - Cost Structure Economics
- Gain (Client/CDN): Bandwidth served at CDN edge is significantly cheaper than origin server egress bandwidth.
- Lose (CDN): Frequent global CDN cache purges or API calls incur vendor API costs.
6. Interview Counter Questions¶
- How do
Cache-Controlheaders (no-cache,no-store,private,public,must-revalidate,immutable) work? - How does Cache-Busting (fingerprinting/hashing) solve the browser cache invalidation problem?
- What is an Origin Shield in a CDN architecture and why is it necessary?
- How do ETags and
If-None-MatchHTTP headers execute conditional validation requests? - What is the security risk of caching personalized API responses on a CDN?
- How does Edge Compute (Cloudflare Workers / AWS Lambda@Edge) alter traditional CDN caching?
- What happens when a user updates their profile picture across Client Cache, CDN, and Redis?
- How does SWR (Stale-While-Revalidate) HTTP header directive optimize user experience?
- When would you use Redis for dynamic API caching instead of CDN Edge Caching?
- How do you prevent CDN Cache Poisoning attacks?
7. Gold Standard Answers¶
no-storeforbids any caching.no-cacheforces browser to revalidate with origin before serving cached copy.privaterestricts caching to end-user browser only.publicallows shared CDN caching.immutabletells browser content will never change.- Build tools append a content hash to filenames (e.g.,
main.d41d8cd9.js). HTML references the new filename; when content updates, the URL changes, forcing browsers to fetch the new file while older files stay cached permanently. - Origin Shield is a centralized intermediate caching tier between global edge PoPs and the origin server. It consolidates cache misses from 100+ global PoPs into a single fetch, protecting the backend database from traffic thundering herds.
- Origin sends
ETag: "hash123". On subsequent request, browser sendsIf-None-Match: "hash123". If unchanged, origin returnsHTTP 304 Not Modifiedwith zero body payload, saving bandwidth. - Misconfiguring
Cache-Control: publicon user-specific endpoints (/api/me) allows CDNs to cache User A's private profile and serve it to User B. Always setCache-Control: private, no-storefor authenticated routes. - Edge compute executes serverless code at CDN PoPs, allowing dynamic JWT verification, request routing, and personalized HTML rendering directly at the edge without hitting the origin datacenter.
- Profile update invalidation: (1) Invalidate Redis key, (2) Purge CDN cache key via API or use versioned image URL (
avatar.jpg?v=2), (3) Client cache revalidates viaETagor new query parameter. stale-while-revalidate=60instructs the browser/CDN to immediately return a stale cached asset while asynchronously fetching the updated asset in the background for future requests.- Use Redis when API responses are personalized per authenticated session, require complex database joins, or require instant programmatic invalidation across microservices.
- CDN Cache Poisoning occurs when an attacker crafts malicious HTTP headers (e.g.,
X-Forwarded-Host) that the origin reflects into responses cached by the CDN. Mitigate by un-keying unvalidated headers or stripping them at the CDN layer.
8. Common Mistakes¶
- Setting
Cache-Control: publicon authenticated private API routes, leaking user data through CDN caches. - Forgetting Cache-Busting hashes on static JS/CSS assets, leaving users stuck with broken legacy code on browser caches.
- Deploying a CDN without an Origin Shield, leading to origin backend crashes during global cache invalidations.
- Confusing
no-cache(revalidate before use) withno-store(do not cache anywhere). - Using Redis to cache multi-megabyte static media files instead of offloading them to S3 and CDN.
9. Keywords¶
Client Cache, CDN, Redis, Cache-Control, ETag, Cache-Busting, Origin Shield, Stale-While-Revalidate, PoP, Edge Compute, Lambda@Edge, Cloudflare Workers, Cache Poisoning, HTTP 304.
10. Cheat Sheet¶
- Multi-Tier Boundary: Browser (0ms, local) \(\rightarrow\) CDN Edge (10-30ms, global static/media) \(\rightarrow\) Redis (1ms, server DB query/session).
- HTTP Headers:
- Static Immutable Assets:
Cache-Control: public, max-age=31536000, immutable+ asset hashing. - Private User APIs:
Cache-Control: private, no-store. - Revalidate Always:
Cache-Control: no-cache. - CDN Origin Shield: Always place an Origin Shield in front of backend servers to collapse global edge misses.
- Cache-Busting: Append content hashes (
app.v2.js) to break browser cache instantly upon deployment. - Validation: Use
ETagandIf-None-Matchto return304 Not Modifiedand save network bandwidth.