Caching invalidation patterns

From farming-labs/fm-skills · View interactive version

Caching invalidation patterns is an AI agent skill from the GitHub repository farming-labs/fm-skills. Explains cache invalidation strategies in web applications including cache keys, freshness windows, mutation-driven invalidation, revalidation, and eviction tradeoffs. Use when designing server-state caching, deciding when data is stale, or fixing bugs caused by stale or inconsistent cached data.

How to use this skill

Skill file

Caching Invalidation Patterns

Overview

Caching makes applications fast by reusing previously fetched or computed data.

The problem is not storing data in a cache. The hard part is knowing:

This is why cache invalidation is a core application design problem, not just a performance trick.

What Invalidation Means

Invalidation means telling the system that cached data should no longer be treated as authoritative.

That can lead to one of several outcomes:

Different systems use different APIs, but the underlying choices are the same.

Core Questions

Before choosing an invalidation strategy, answer these:

  1. What data is cached?
  2. Who owns the source of truth?
  3. How quickly can that data change?
  4. What mutations can make it stale?
  5. Is stale data acceptable for seconds, minutes, or not at all?

If those answers are unclear, invalidation bugs are usually inevitable.

Cache Types

| Cache Type | Example | Common Invalidation Trigger |

|------------|---------|-----------------------------|

| In-memory client cache | Query library cache, store | Mutation, window focus, timer |

| Browser HTTP cache | Cache-Control, ETag | TTL expiry, revalidation |

| CDN / edge cache | HTML, JSON, images | Purge, tag revalidation, TTL |

| Server application cache | Redis, memory cache | Write-through, pub/sub, TTL |

| Build-time cache | Static generation output | Rebuild, webhook, revalidate |

Most real apps use several of these at once, so invalidation often has to happen at multiple layers.

Freshness vs Correctness

Caching always trades freshness for speed.

| Strategy | Speed | Freshness | Use Case |

|----------|-------|-----------|----------|

| Long TTL, no eager revalidation | Highest | Lowest | Rarely changing public content |

| Short TTL | Good | Better | Frequently viewed but non-critical data |

| Mutation-triggered invalidation | Good | High | User-owned records, dashboards |

| Immediate replace with canonical response | Good | Highest | Mutations returning updated record |

| No cache | Lowest | Highest | High-risk data where staleness is unacceptable |

Not all stale data is a bug. The right question is whether the staleness is acceptable for that feature.

Cache Keys

Good invalidation starts with good cache keys.

Characteristics of Good Keys

['products']
['products', { page: 2, sort: 'price' }]
['product', productId]
['user', userId, 'orders']

Bad Keys Cause Bad Invalidation

Common failures:

If the key design is sloppy, invalidation becomes broad, expensive, or incorrect.

Common Invalidation Strategies

1. Time-Based Invalidation

Cached data expires after a freshness window.

cache.set(key, data, { ttl: 60000 });

Best for:

Pros:

Cons:

2. Mutation-Driven Invalidation

When a write succeeds, invalidate affected reads.

await api.updateProduct(productId, input);
cache.invalidate(['product', productId]);
cache.invalidate(['products']);

Best for:

Pros:

Cons:

3. Revalidation on Access

Serve cached data first, then verify it in the background.

Read cache -> show cached value -> revalidate -> update if changed

Best for:

This is the basic stale-while-revalidate model.

4. Event-Driven Invalidation

A cache is invalidated in response to external events.

Examples:

Best for:

5. Tag or Group Invalidation

Invalidate all entries associated with a shared tag or group.

Examples:

Best for:

List and Detail Invalidation

A very common bug: a mutation updates the detail view but leaves lists stale.

Example:

When a record changes, consider all derived reads:

If invalidating all related data is too expensive, prefer replacing known entries directly and invalidating the rest lazily.

Replace vs Invalidate

After a mutation, you often have two choices.

Replace Cached Data Directly

Use when the mutation response contains canonical updated data.

const updated = await api.updateTodo(id, input);
cache.set(['todo', id], updated);

Good for:

Invalidate and Refetch

Use when the mutation affects more data than you can patch safely.

await api.updateTodo(id, input);
cache.invalidate(['todos']);

Good for:

Hybrid Approach

Often best:

Broad vs Narrow Invalidation

| Approach | Example | Tradeoff |

|----------|---------|----------|

| Narrow | Invalidate ['product', 123] only | Efficient, but easy to miss related views |

| Medium | Invalidate detail + product lists | Balanced default for CRUD apps |

| Broad | Invalidate all product-related queries | Safe, but more network churn |

Start as narrow as correctness allows, but not narrower.

If you routinely ship stale data bugs, your invalidation is probably too narrow.

Optimistic Updates and Invalidation

Optimistic UI does not remove the need for invalidation.

After an optimistic mutation:

  1. Apply the optimistic patch
  2. Send the mutation
  3. Reconcile with server response
  4. Invalidate or refresh dependent queries

Without step 4, adjacent views often remain stale even when the edited component looks correct.

Pagination, Filters, and Search

Invalidation becomes harder once data appears in many shapes.

Examples:

When a product changes, you may not know every cached list that contains it.

Common approaches:

HTTP and CDN Caching

Not all invalidation happens in JavaScript state libraries.

HTTP Freshness Controls

Common tools:

These are useful when the browser or CDN should participate in caching decisions.

CDN / Edge Revalidation

Useful for:

Common invalidation mechanisms:

Common Bugs

| Bug | Cause |

|-----|-------|

| Updated detail view, stale list | Related list query not invalidated |

| User sees old data after mutation | Background refetch won the race |

| Refetch storm | Invalidation is too broad or too frequent |

| Wrong tenant/user data | Cache key missing auth or tenant scope |

| Stale search results | Search and filtered variants not included in strategy |

| Flickering UI | Cache replaced repeatedly with partial or out-of-order data |

Practical Patterns

Mutation with Targeted Invalidation

const updated = await api.updatePost(postId, input);

cache.set(['post', postId], updated);
cache.invalidate(['posts']);
cache.invalidate(['dashboard']);

TTL Plus Mutation Invalidation

Use both when reads happen often but writes still need fast correctness.

useQuery({
  key: ['notifications'],
  ttl: 30000,
});

await api.markAllRead();
cache.invalidate(['notifications']);

Webhook-Based Static Revalidation

CMS publish -> webhook -> purge or regenerate affected pages -> next request gets fresh HTML

Choosing a Strategy

Use this decision guide:

Rules of Thumb

Related Skills

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.