Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 18

Client-Side Data Fetching Patterns

Recommended resources

Welcome back. In our previous lesson, we established a robust multi-layered caching strategy, using HTTP headers, CDNs, and Service Workers to prevent unnecessary network requests. We saw how the stale-while-revalidate directive can serve stale content from a cache while refreshing it in the background. Now, we'll bring that same powerful pattern, along with others, into the application layer itself.

This lesson dives into the client-side data fetching patterns that define modern, high-performance web applications. Your experience with React Query means you've already put these concepts into practice. Our goal here is to deconstruct them, understand their architectural trade-offs, and learn how to articulate their value in a system design interview. We will architect patterns for stale-while-revalidate, request deduplication, and speculative prefetching—the triad of techniques that make UIs feel instantaneous and resilient.

Stale-While-Revalidate (SWR) at the Application Layer

The stale-while-revalidate pattern is so effective that it exists at nearly every layer of the web stack. While HTTP headers instruct browsers and CDNs, implementing SWR within your client-side application gives you granular control tied to application state and user interactions. The core idea remains the same: balance speed and freshness.

  1. Serve stale data from a cache immediately. The UI renders instantly, providing a snappy user experience.
  2. Send a revalidation request in the background.
  3. Update the cache and UI with fresh data upon response.

This flow ensures users see content right away, eliminating spinners for subsequent views, while still getting up-to-date information.

This flowchart illustrates the SWR logic. Upon receiving a request, the system checks if the data is cached. If not, it fetches from the network. If it is cached, it checks for validity. A valid response is returned. If stale but still within the revalidation window, the stale data is returned immediately while a background fetch is initiated to update the cache for the next request.

To get a deep understanding of the mechanics, let's explore how this pattern is implemented, from the original HTTP header to modern client-side libraries.

Stale-While-Revalidate: The Caching Pattern That Balances Speed and Freshness

This article by Paul Serban provides a fantastic deep dive into the SWR pattern. It connects the original RFC to its modern incarnation in JavaScript libraries, which is exactly the kind of context a senior engineer needs.

Read the introduction and the section on how SWR works. This will solidify the core concepts we've touched on. Pay close attention to the section on client-side implementation. The SWRCache class example is particularly insightful; focus on understanding its logic for separating fresh/stale windows and handling background revalidation. You don't need to memorize the code, but grasp the underlying algorithm.

Libraries like Vercel's SWR and TanStack Query (which you've used) are essentially sophisticated implementations of this SWRCache concept, integrated with framework-specific hooks and features like focus revalidation and network recovery.


Architecting for Consistency: Request Deduplication and Invalidation

In a component-based architecture, it's common for multiple, disparate components on a page to require the same piece of data. A naive implementation would trigger a separate fetch for each component instance, leading to redundant network requests and potential race conditions.

Request Deduplication solves this by ensuring that for a given unique query (e.g., fetching user with ID 123), only one request is in-flight at any time. Any subsequent component that requests the same data before the first request completes will simply subscribe to the result of the pending request.

This is a core feature of libraries like React Query, which uses a queryKey to uniquely identify a request and manage its lifecycle in a central cache.

You Might Not Need TanStack Query - DEV Community

This article offers a great architectural perspective on what problem data-fetching libraries truly solve. It argues that if you have a centralized entity store, you get deduplication "for free." This is a powerful mental model for a system design interview.

Read from the beginning through to the comparison. The key takeaway is understanding that TanStack Query's cache exists to solve the problem of fragmented, component-local server state. This frames deduplication not just as a feature, but as a solution to a specific architectural choice.

Deduplication handles fetching, but the harder problem is invalidation: how do you efficiently update all affected parts of the UI after a data mutation?

Imagine a user adds an item to their cart. This action should likely refetch:

  • The cart contents.
  • The cart icon's item count in the header.
  • The "add to cart" button state on the product page.

A junior approach might involve prop-drilling refetch functions or using a global state manager to broadcast an event. A senior engineer designs a decoupled system.

This is where a strategy like "revalidating live queries" becomes invaluable. Instead of manually tracking which queries to update, you build a system that automatically knows which data is currently being displayed on screen and refetches only that data.

Revalidate Live Queries – No cache management, no manual refetches!

Sam Selikoff provides a masterclass in solving this exact problem. He builds a system to revalidate only "live" queries after a mutation, moving from coupled, brittle solutions to an elegant, decoupled architecture.

Watch the entire video. Follow his thought process: The Problem: A mutation occurs, but parts of the UI show stale data. Initial (Flawed) Solutions: Prop drilling mutate or using global mutate with hardcoded keys, which creates tight coupling. The Senior Solution: Track live queries using SWR middleware and a Set. Putting It Together: Create a function that iterates over the live queries and revalidates them. Encapsulation: Abstract this logic into a reusable useMutation hook. Pay attention to his final point about pragmatism: this approach is often simpler and more robust than complex manual cache manipulation, especially for teams.


Looking Ahead: Speculative Prefetching

SWR and deduplication make an application feel fast on subsequent visits and interactions. Speculative Prefetching aims to make the next navigation feel instantaneous. The strategy is to predict the user's next action and fetch the necessary resources (JS bundles, CSS, and even data) before they even click a link.

Common triggers for prefetching include:

  • On hover: When a user hovers over a link, it's a strong signal they might click it. This is a good balance between proactivity and conserving resources.
  • In viewport: As a link scrolls into the viewport, you can begin prefetching. This is more aggressive but can be effective for critical user journeys.

However, the key to a senior-level approach is not how to prefetch, but when and why. Blindly prefetching every link on a page wastes user bandwidth and increases server load.

How to Improve Website Performance? | Frontend System Design | Prefetching Resources

This video from Devtools Tech moves beyond the "how" of prefetching to the critical "why" and "when." It's a perfect example of thinking like a product-minded senior engineer.

Watch the initial sections to understand the concept of perceived performance and see a demonstration of prefetching in action. The most important part is the discussion on strategy and discovery. Focus on the argument for an analytics-driven approach. You don't guess which links to prefetch; you use data from tools like Amplitude or Google Analytics to identify the most common user paths and optimize those.

This analytics-driven approach is a hallmark of senior-level thinking. It demonstrates that you consider the trade-offs: user bandwidth, client-side computation, and server costs, and make data-informed decisions rather than applying a technical solution for its own sake.


A Quick Note on Request Batching

It's worth briefly distinguishing request deduplication from request batching.

  • Deduplication: Prevents multiple identical requests from being sent.
  • Batching: Combines multiple different requests into a single network call.
This diagram compares individual requests, which require multiple round trips and overhead, with batched requests. Batching accumulates operations and sends them in a single round trip, significantly reducing TCP and authentication overhead.

This pattern is most commonly seen with GraphQL, where libraries like Apollo Client can automatically batch multiple queries that occur in the same tick of the event loop into a single HTTP request. This reduces network overhead but is a distinct optimization from SWR or deduplication.


Senior-Level Insight

A mid-level engineer effectively uses a library like React Query. They know how to call useQuery, useMutation, and how to invalidate queries using keys.

A senior or staff engineer architects the entire data flow. They understand the mechanics of SWR, deduplication, and invalidation so deeply that they can explain the trade-offs of different invalidation strategies (e.g., manual invalidation vs. "revalidate live queries"). When discussing prefetching, they don't just say "we'll prefetch on hover"; they say, "Our analytics show that 70% of users who land on the product listing page navigate to a product detail page within 15 seconds. We'll start by prefetching the data for the top three products in the viewport and run an A/B test to measure the impact on LCP for the subsequent navigation against the increased data cost for the user." They influence API design, perhaps advocating for a BFF that provides a specific, lightweight "prefetch" endpoint for just this purpose.


Conclusion

In this lesson, we deconstructed the core client-side data fetching patterns that power modern frontend applications. You are already familiar with these from using React Query, but now you have the architectural language and deep understanding to justify their use in a system design interview.

Key Takeaways:

  • Stale-While-Revalidate (SWR): The foundation of modern data fetching, providing instant perceived performance by serving cached data while updating it in the background.
  • Request Deduplication: An essential optimization in component-based systems to prevent redundant network calls for the same data, typically solved with a centralized cache.
  • Smart Invalidation: Decoupled invalidation strategies like "revalidate live queries" are more scalable and maintainable than manual, tightly-coupled approaches.
  • Speculative Prefetching: A proactive optimization to make future navigations feel instant, which must be guided by analytics data to be effective and avoid waste.

In our next lesson, we will explore the Backend for Frontend (BFF) pattern. You'll see how creating a dedicated server-side aggregation layer can dramatically simplify the data fetching logic on the client, acting as a perfect partner to the patterns we've discussed today.