Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
15

Frontend System Design · Lesson 15 of 86 · 5 min

HTTP Caching: Cache-Control, ETag, Last-Modified

This is how you explain reducing latency and server load by avoiding unnecessary network requests.

In an interview, you need to show you understand two fundamental caching concepts: freshness and validation. Freshness means the browser can use a cached resource without asking the server. Validation means the browser has to ask the server if its cached copy is still good. Get this right, and you demonstrate a core competency in web performance.

Control freshness with Cache-Control

The Cache-Control response header is the main directive. It tells the browser and any intermediate caches (like a CDN) how to handle a resource.

The most important directive is max-age=<seconds>. This tells the browser how long, in seconds, a resource is "fresh." While it's fresh, the browser will not make a network request for it. It will serve it directly from the disk or memory cache.

Cache-Control: public, max-age=31536000, immutable

For versioned static assets like main.a4b2c1.js, use a long max-age (e.g., one year) and add immutable. The immutable directive tells the browser the file will never change, preventing revalidation requests even after a user hard-refreshes the page. This is the ideal strategy for cache-busted assets.

Other key Cache-Control directives:

  • private: The response is for a single user and can be stored by their browser, but not by a shared cache like a CDN. Use this for user-specific API responses.
  • public: The response can be stored by any cache. This is the default for most assets.

The trap: Candidates constantly mix up no-cache and no-store.

  • no-cache does not mean "don't cache." It means the browser must revalidate with the server every single time before using the cached version. It's useful for resources like an application's main index.html file, where you want the user to always check for a new version but can still benefit from a 304 Not Modified response if nothing has changed.
  • no-store is the one that means "do not cache this at all." The browser is forbidden from storing the file. Use this for responses containing highly sensitive data.

Validate stale caches with ETag and Last-Modified

When a resource's max-age expires, it becomes "stale." The browser won't use it without first checking if it's still valid. This check is called a conditional request.

The browser sends the server a fingerprint of the version it has, and the server replies with either the new version or a confirmation that the old one is still good.

ETag (Entity Tag) is the preferred mechanism. The server provides an ETag header, which is a unique identifier for the resource's content (often a hash).

ETag: "a4b2c1d3e5f6"

When the browser revalidates, it sends this value back in an If-None-Match request header. If the server's current ETag for the file matches, it sends back a 304 Not Modified status with an empty body. This saves downloading the entire resource again.

Last-Modified is the fallback. The server sends the date the file was last changed. The browser sends this back in an If-Modified-Since header. It's less reliable than ETag because timestamps aren't always granular enough and don't change if a file is regenerated with the same content. If both ETag and Last-Modified are present, ETag takes precedence.

In an interview, explaining the 304 Not Modified flow is crucial. It shows you understand that even a "stale" cache can save significant bandwidth. The cost is a small HTTP request for validation, but you avoid re-downloading a potentially large payload.

The complete caching and validation flow

This is the decision process a browser goes through for every subresource on a page.

How to answer "Design a caching strategy"

Structure your answer by resource type. This shows you understand there's no one-size-fits-all solution.

  • Versioned Static Assets (JS/CSS bundles, fonts): "For assets with a fingerprint in the filename, like app.1a2b3c.js, I'd use an aggressive caching strategy: Cache-Control: public, max-age=31536000, immutable. The long max-age and immutable tell the browser to never request it again. Cache invalidation is handled by changing the filename during the build process, which forces a download."

  • Unversioned Static Assets (e.g., logo.png): "For a static asset that doesn't have a versioned filename, I'd use a shorter max-age, maybe a few hours: Cache-Control: public, max-age=7200. I would also ensure the server sends an ETag header. This allows the browser to efficiently revalidate after the cache expires."

  • Main HTML Document (index.html): "For the main entry point of a single-page app, I'd use Cache-Control: no-cache. This forces the browser to always revalidate with the server, ensuring the user gets the latest HTML which might reference new JS/CSS bundles. If the HTML hasn't changed, the server can just return a 304."

  • Dynamic API Responses (e.g., /api/user/profile): "For authenticated API calls that return user-specific data, I'd use Cache-Control: private, no-cache. private prevents CDNs from caching it, and no-cache ensures the data is revalidated on every request, providing freshness while still allowing 304 Not Modified responses for data that hasn't changed."

Code: A server that handles validation

This Node.js/Express example shows a server implementing ETag and Last-Modified for a resource that can be updated. It correctly handles conditional requests and returns 304 Not Modified when appropriate.

import express from 'express';
import crypto from 'crypto';

const app = express();
const PORT = 3001;

let resourceContent = 'Initial content of my resource.';
let lastModifiedTime = new Date();

function generateETag(content: string): string {
  const hash = crypto.createHash('md5').update(content).digest('hex');
  return `"${hash}"`; // ETags are typically quoted strings
}

app.get('/my-resource', (req, res) => {
  const currentETag = generateETag(resourceContent);
  const currentLastModified = lastModifiedTime.toUTCString();

  // ETag takes precedence
  if (req.headers['if-none-match'] === currentETag) {
    return res.status(304).send();
  }

  // Fallback to Last-Modified
  const ifModifiedSince = req.headers['if-modified-since'];
  if (ifModifiedSince && new Date(ifModifiedSince) >= lastModifiedTime) {
    return res.status(304).send();
  }

  res.setHeader('Cache-Control', 'public, max-age=60');
  res.setHeader('ETag', currentETag);
  res.setHeader('Last-Modified', currentLastModified);
  res.status(200).send(resourceContent);
});

// Endpoint to simulate updating the resource
app.post('/update-resource', (req, res) => {
  resourceContent = `Updated content at ${new Date().toISOString()}`;
  lastModifiedTime = new Date();
  res.status(200).send('Resource updated successfully.');
});

app.listen(PORT, () => {
  console.log(`Server at http://localhost:${PORT}`);
  console.log(`1. Access http://localhost:${PORT}/my-resource`);
  console.log(`2. Refresh to see a 304 response.`);
  console.log(`3. To update: curl -X POST http://localhost:${PORT}/update-resource`);
});

Try it

Open your browser's DevTools to the Network tab. Visit a content-heavy site like a news outlet. Find a request for a static image. Inspect its response headers for Cache-Control, ETag, and Last-Modified. Refresh the page and find the same request; observe if the status is 304 or 200 (from disk cache).

Next: Browser-Level Caching Mechanisms

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Choosing the Right Client-Side Storage

Next

Browser-Level Caching Mechanisms