Frontend Patterns

Pattern

Cache Invalidation

Clear or update cached data strategically when underlying information changes.

Cache Invalidation

Problem

Users see stale data after creating, updating, or deleting records. A user adds an item to their cart but the count doesn’t update. They delete a comment but it still appears in the list. The cache provides speed but shows outdated information, creating a confusing and broken experience.

Solution

Invalidate cached entries when mutations complete by tagging cache entries with identifying metadata and clearing or refetching tagged data after updates. This keeps the cache fast while ensuring users always see current information after making changes.

Example

This example shows how to invalidate cached data after performing a mutation to ensure users see fresh data reflecting their changes.

// Perform a mutation and then invalidate affected cache entries
async function deletePost(id) {
  // Execute the delete operation on the server
  await api.delete(`/posts/${id}`);

  // Clear cache entries that would now be stale after this deletion
  // This triggers refetching of posts lists to show updated data
  cache.invalidate(['posts', 'user-posts']);
}

Benefits

  • Ensures users see up-to-date data immediately after mutations.
  • Maintains cache performance benefits while preventing stale data issues.
  • Can selectively invalidate related queries to minimize unnecessary refetching.
  • Provides automatic synchronization between client cache and server state.
  • Reduces bugs caused by displaying outdated information.

Tradeoffs

  • Requires careful design to identify which cache entries relate to each mutation.
  • Overly aggressive invalidation defeats caching benefits by refetching too much.
  • Can cause unnecessary loading states if invalidation triggers are too broad.
  • Complex relationships between data may require intricate invalidation logic.
  • May lead to cascading refetches if not implemented thoughtfully.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.