Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Fundamentals
  1. 1.Introduction to Frontend System Design
  2. 2.Core Frontend Architecture Concepts
  3. 3.Client-Server Interaction Fundamentals
  4. 4.Basic Performance & Accessibility Considerations
  5. 5.State Management Basics & Data Flow
  6. 6.Advanced State Management & Global Stores
  7. 7.Component Libraries & Design Systems
  8. 8.Frontend Build Tools & Development Workflows
  9. 9.Advanced Performance Optimization Techniques
  10. 10.Data Fetching Strategies & Caching
  11. 11.Frontend Security Essentials
  12. 12.Micro-Frontend Architectures
  13. 13.Real-time Communication & WebSockets
  14. 14.Observability, Monitoring, & Logging
  15. 15.Offline-First & Progressive Web Apps (PWAs)
Frontend System Design Fundamentals
10

Frontend System Design · Lesson 10 of 15 · 6 min

Data Fetching Strategies & Caching

This topic tests if you can design for performance and resilience, not just call an API. Your choices here directly impact user experience and server load.

After this lesson, you'll be able to articulate a data fetching and caching strategy for a frontend system design question, justifying your choices with clear trade-offs.

Choose Your Fetching Model

Your first decision is how the client gets data: by asking for it, or by having the server push it.

The default is request-response. The client sends an HTTP request and gets a response. You have two main API styles here: REST and GraphQL. Use REST for standard resource-based models where clients need whole objects. Use GraphQL when clients need specific, combined, or nested fields from multiple resources, which helps avoid the over-fetching (getting too much data) or under-fetching (making too many requests) common with REST.

In an interview, justify your choice based on the product. For a simple CRUD app, say you'd start with REST for its simplicity. For a complex mobile app where bandwidth is critical and data needs are varied, explain why GraphQL's precision is worth the added server complexity.

For real-time features like chat or live notifications, request-response is not enough. You have a few options, from least to most efficient:

  • Polling: The client asks for updates every N seconds. It's simple to implement but inefficient and creates a lot of useless traffic. Use it only when other options are unavailable or for non-critical, low-frequency updates.
  • Long Polling: The client makes a request, and the server holds it open until there's new data to send. It's more efficient than polling but adds stateful complexity to the backend.
  • Server-Sent Events (SSE): The server pushes data to the client over a standard HTTP connection. It's a one-way street. This is perfect for news feeds, stock tickers, or notification systems where the client is just a listener.
  • WebSockets: A persistent, two-way connection is established between client and server. Both can send data at any time with low latency. This is the best choice for chat, collaborative editing, or multiplayer games, but it's the most complex to scale on the backend because it requires managing stateful connections.

The trap: Merely listing these technologies is not enough. You must compare them. Explain that WebSockets are powerful but stateful, whereas SSE is simpler, stateless, and built on HTTP, making it easier to integrate with existing infrastructure.

Layer Your Caches

Caching is not one thing; it's a series of layers. A smart caching strategy is your most effective tool for creating a fast, responsive UI. Think of these layers as moving from closest to the user outwards.

  1. In-Memory Cache: Data stored in a JavaScript variable, often managed by a library like React Query, SWR, or Apollo Client. It's the fastest cache available, but it's cleared on page refresh. Its purpose is to de-duplicate requests and provide instant data to components within a single session.

  2. Persistent Client Cache: Storage that survives page reloads, using APIs like localStorage or IndexedDB. This is for data you want to keep around, like user settings, a saved shopping cart, or data for offline support.

    The trap: Never store sensitive data like authentication tokens or personal information in localStorage. It's accessible to any script on the page, making it vulnerable to XSS attacks.

  3. Browser HTTP Cache: The browser can store responses for you automatically. This is controlled by HTTP headers sent from the server, like Cache-Control (how long to cache) and ETag (a token to check if the content has changed). This is "free" performance you get by configuring the backend correctly.

  4. Content Delivery Network (CDN): A CDN can cache API responses at edge locations around the world, closer to your users. This dramatically reduces network latency for users far from your origin server.

This flow shows the basic logic for a client-side cache.

Solve the Hardest Problem: Cache Invalidation

"How do you make sure the user doesn't see stale data?" This will be a follow-up question. Having a good answer shows seniority. There are three main strategies.

Time-to-Live (TTL): This is the simplest approach. You cache data for a fixed duration (e.g., 5 minutes). It's easy to implement but guarantees the user might see stale data for up to the TTL. It's best for data that isn't highly sensitive to freshness.

// A simple in-memory cache with a TTL
const cache = new Map<string, { data: any; expires: number }>();

async function fetchWithCache<T>(url: string, ttl_ms: number = 5 * 60 * 1000): Promise<T> {
  const now = Date.now();
  const cachedItem = cache.get(url);

  if (cachedItem && now < cachedItem.expires) {
    return cachedItem.data as T;
  }

  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
  }
  const data: T = await response.json();
  
  cache.set(url, { data, expires: now + ttl_ms });
  return data;
}

Mutation-based Invalidation: When the user performs an action that changes data (a POST, PUT, or DELETE request), you proactively invalidate any cached GET requests that are now out of date. This provides strong consistency and is the default behavior in libraries like React Query.

Stale-While-Revalidate (SWR): This pattern offers the best of both worlds for UI performance.

  1. When data is requested, immediately return the cached (stale) version. The UI can render instantly.
  2. In the background, send a network request to fetch fresh data.
  3. Once the fresh data arrives, update the cache and the UI.

This gives the user an immediate response while ensuring the data is eventually updated. It's an excellent default strategy for non-critical content.

Structure Your Interview Answer

When asked to design a system like a news feed or product page, don't jump to a technology. Start with the requirements and walk the interviewer through your thought process.

"First, I'd clarify the data characteristics. How often does it change? Is real-time a requirement? For a news feed, initial load can be a standard REST request, but for live updates, I'd use Server-Sent Events to push new articles from the server. This is more efficient than polling."

"Next, I'd layer the caching to optimize performance. On the client, I'd use a library that implements a stale-while-revalidate strategy. This makes the feed feel instant on subsequent visits. The API would also set Cache-Control headers, allowing the browser to cache responses. Finally, static assets like images would be served from a CDN."

"For cache invalidation, posting a new comment would trigger a refetch of the comments list for that article, ensuring consistency. For resilience, all network requests would include error handling and a retry mechanism with exponential backoff."

This structured approach demonstrates you can think through a problem from requirements to implementation, considering trade-offs along the way.

Try it

In a new file, write a standalone function that implements a simple stale-while-revalidate pattern. It should take a URL and a callback function. It must immediately call the callback with cached data if it exists, then fetch new data from the URL and call the callback again upon success. Manage the cache in a simple Map object.

Next: Frontend Security Essentials.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Advanced Performance Optimization Techniques

Next

Frontend Security Essentials