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
17

Frontend System Design · Lesson 17 of 86 · 4 min

Cache Invalidation for Frontend Apps

This topic separates candidates who think about data freshness from those who only think about performance. Your answer shows you understand the trade-offs.

Caching is easy. Knowing when to throw that cached data away is hard. Without a clear invalidation strategy, your app will show stale data, leading to user confusion and bugs. In an interview, you need to articulate the different ways to invalidate a cache and choose the right one for a given scenario.

Choose Your Invalidation Strategy

You have three main strategies for deciding when cached data is no longer good. Each has a different trade-off between data freshness, implementation complexity, and performance.

Time-to-Live (TTL): You decide upfront how long data is "fresh." After the timer expires, the data is invalid. This is the simplest strategy. It's great for data that isn't critical or changes infrequently, like a list of blog posts or product categories. The downside is that you might serve stale data if it changes before the TTL expires.

Write-based Invalidation: The cache is invalidated when the data is changed. When a user updates their profile, you immediately invalidate the cached version of that profile. This provides strong consistency. The cost is that your write logic is now coupled with your cache logic.

Event-driven Invalidation: A backend service publishes an event when data changes. Your frontend subscribes to these events (e.g., via WebSockets) and invalidates its cache in response. This is powerful for real-time applications but requires more infrastructure.

A fourth strategy, manual invalidation, is user-initiated. Think "pull-to-refresh." It's a necessary fallback, but it shouldn't be your only strategy.

Implement Time-To-Live (TTL) on the Client

TTL is the most common strategy you'll implement directly on the client. The logic is straightforward: when you cache an item, you store a timestamp alongside it. On the next read, you check if the current time has passed the expiry timestamp.

This flow is a classic interview diagram.

Here is a minimal, framework-agnostic class for a client-side cache that implements this pattern.

type CacheEntry<T> = {
  value: T;
  expiry: number; // Unix timestamp
};

class ClientCache {
  private cache = new Map<string, CacheEntry<any>>();

  set<T>(key: string, value: T, ttlSeconds: number): void {
    const expiry = Date.now() + ttlSeconds * 1000;
    this.cache.set(key, { value, expiry });
  }

  get<T>(key: string): T | null {
    const entry = this.cache.get(key);
    if (!entry) {
      return null;
    }

    // Check if the entry has expired
    if (Date.now() > entry.expiry) {
      this.cache.delete(key);
      return null;
    }

    return entry.value as T;
  }

  invalidate(key: string): void {
    this.cache.delete(key);
  }
}

The trap: Picking the right TTL is a judgment call. Too long, and users see stale data. Too short, and you lose the performance benefit of caching. Your choice should be based on the data's volatility and the business requirements for freshness. For a user's avatar, 24 hours might be fine. For stock prices, it might be 1 second.

Handle Invalidation from the Backend

For data that must be fresh, TTL is not enough. The frontend must react to changes as they happen. This is where write-based and event-driven invalidation come in.

You don't implement these on the client; you respond to them.

After a mutation: When your app sends a POST, PUT, or DELETE request, it should proactively invalidate any related data in the cache. For example, after a user successfully updates their name, you must invalidate the user-profile cache key. Modern data-fetching libraries like TanStack Query or SWR have APIs like invalidateQueries to make this declarative.

Via push events: For real-time updates initiated by other users or the system, the server must push a notification. The client listens for these events over a WebSocket or Server-Sent Events (SSE) connection and calls its invalidation logic.

In an interview, when you design a system with real-time updates (like a chat app, a collaborative editor, or a live dashboard), you must mention a push-based mechanism for invalidation. Simply relying on TTL or user refresh is a red flag. The correct flow is: the backend sends an event, and the client listens and invalidates the specific cache key.

Invalidate a Key, Not the World

A common mistake is to be too aggressive with invalidation. A user updates their name, and you clear the entire application cache. This is lazy, inefficient, and negates much of the benefit of caching.

Your cache invalidation must be granular.

Design your cache keys to be specific. Instead of a single key for all products, use keys that reflect the query, like products?category=shoes&page=1. For entity-specific data, use a normalized key like user:123.

When a mutation occurs, your logic should be smart enough to invalidate only the affected keys. If a user updates their profile, invalidate user:123. If a product's price changes, you might invalidate the specific product key (product:abc) and any list queries that contained it. This requires more thought but results in a much more performant application.

Try it

Modify the ClientCache class to support a "stale-while-revalidate" strategy. When get is called on an expired key, it should return the stale data immediately but also accept a callback function to trigger a background re-fetch of the fresh data. This should take you about 20 minutes.

Next: Learn how these caching patterns fit into the overall architecture in Structuring a Large Single-Page App.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Browser-Level Caching Mechanisms

Next

Structuring a Large Single-Page App