User Agents

Web browsers and everyday web tech, explained

Cache API Fragment Collisions: Giving Each Chunk Its Own Key

· 6 min read · Cookies and Cache

In this article
  1. Background: How the Cache API Works
  2. Why Fragment Collisions Happen
  3. How to Give Each Chunk Its Own Key
  4. Choosing a Key Strategy
  5. Common Problems and Misconceptions
  6. Comparing Cache API to Other Storage
  7. Costs and Performance Considerations
  8. Frequently Asked Questions

Cache API fragment collisions happen when different pieces of content (chunks) end up stored under the same cache key, causing one to overwrite the other. The fix is to make each chunk's key unique by incorporating a stable identifier—like a chunk name, version, or content hash—into the key string. This article explains why collisions occur and gives you concrete patterns to prevent them.

Background: How the Cache API Works

The Cache API is a browser storage mechanism that lets web apps store HTTP responses (or any Request/Response pairs) for offline use or performance. It's part of the Service Worker specification and is also available in some other contexts. You interact with it through a caches.open('my-cache') call, which returns a Cache object. To store something, you use cache.put(request, response), and to retrieve it, cache.match(request).

The key for a cached item is a Request object (or a URL string that gets converted to a Request). The browser matches requests by URL, and optionally by method and Vary headers. This is where collisions can creep in: if two different chunks share the same URL (or a URL that matches after ignoring some query parameters), they'll overwrite each other.

Why Fragment Collisions Happen

Fragment collisions are common when you're caching partial content—like HTML fragments, API responses for pagination, or component data. The typical causes:

  • Same URL, different content: The URL is identical, but the content varies by user, session, or time. For example, /api/user/profile returns different data for different users.
  • Query parameters ignored: The Cache API's default matching ignores query strings unless you set ignoreSearch: false in the match options. So /api/items?page=1 and /api/items?page=2 are considered the same key.
  • Path normalization: Trailing slashes or case differences can cause the same resource to map to the same key.
  • Hash collisions: If you use a short hash (like 4 characters) to differentiate chunks, you might get accidental collisions.

When a collision happens, the most recent put() overwrites the old response. If you're caching fragments for offline use, you might serve the wrong fragment to the wrong page, or lose data entirely.

How to Give Each Chunk Its Own Key

The core principle is to make the key (the Request URL) unique for each distinct chunk. Here are the most reliable patterns:

  1. Append a query parameter with a unique ID. For example, /api/items?page=1&chunk=abc123. This is simple and works with the default matching (since query strings are ignored, you need to set ignoreSearch: false when matching).
  2. Use a path-based key. Instead of /api/items, use /api/items/chunk-abc123. This avoids the query-parameter pitfall entirely.
  3. Include the content hash in the URL. If you have a hash of the content (e.g., from a build tool), append it: /static/js/main.8f3d9c.js. This is a common pattern for cache-busting.
  4. Use a custom key with cache.put(). You can create a Request with a synthetic URL like /my-cache/chunk-abc123 and store your response there. This gives you full control.

When you retrieve, you must use the same key. If you used query parameters, pass { ignoreSearch: false } to match().

Choosing a Key Strategy

Which strategy you pick depends on your use case:

  • For API data that varies by user: Include the user ID or session ID in the key, but be careful about storing sensitive data in the URL (it's visible in browser history).
  • For paginated content: Use the page number and maybe a sort parameter: /api/items?page=2&sort=date.
  • For static assets: Use the content hash from your build process. This is the most robust because it automatically invalidates when the content changes.
  • For fragments that are part of a larger page: Use a combination of the page route and a fragment identifier: /page/about/header.

Remember: the key should be deterministic—given the same chunk, you should always generate the same key. If you use a random ID, you'll never be able to retrieve it later.

Common Problems and Misconceptions

One common mistake is assuming that the Cache API automatically handles query strings. It doesn't by default. If you store /api/items?page=1 and then try to match /api/items?page=2, you'll get the first response unless you set ignoreSearch: false.

Another misconception is that you can't store custom data in the Cache API. You can—the response can be any Response object, including one with a custom body (like JSON) and headers. So you can store metadata along with the fragment.

Also, be aware that the Cache API is not designed for extremely large amounts of data. It's best for resources, not for a database. If you have thousands of fragments, consider IndexedDB instead.

Comparing Cache API to Other Storage

Here's how the Cache API stacks up against other browser storage options:

  • LocalStorage: Synchronous, limited to about 5MB, only strings. Not suitable for responses or large data.
  • IndexedDB: Asynchronous, can store large amounts of structured data, supports indexes. Better for complex data, but more verbose.
  • Cache API: Designed for HTTP responses, works well with Service Workers, has built-in request matching. Perfect for caching fragments that are fetched from a server.

For fragment caching, the Cache API is often the right choice because it's built for exactly this—storing responses to requests.

Costs and Performance Considerations

Giving each chunk its own key has a storage cost: more entries in the cache, which can increase memory and disk usage. But the Cache API is efficient; it stores the response body once per unique URL. If you have many chunks, you might want to set a limit on the number of entries or use a cleanup strategy (e.g., delete old entries based on a timestamp).

There's also a performance cost when generating keys—hashing content on the fly can be expensive. If you're hashing, do it once at build time or cache the hash.

Finally, be mindful of the URL length. Browsers have limits on URL length (typically around 2MB in Chrome, but much smaller in some contexts). If your key includes a long hash or many parameters, you might hit that limit. Keep keys reasonably short.

Frequently Asked Questions

Why does my cache return the wrong fragment?

This is almost always because two different chunks are being stored under the same key. Check if you're using query parameters and whether you're matching with ignoreSearch: false. Also, ensure that your key generation is deterministic—if you use a random value, you'll get a miss on retrieval.

Can I use the Cache API to store data that isn't a fetch response?

Yes. You can create a Response object with any body (e.g., JSON) and store it. For example, cache.put('/my-data', new Response(JSON.stringify(data))). This is useful for caching structured data.

How do I delete a specific chunk from the cache?

Use cache.delete(request) with the exact key you used to store it. If you used query parameters, pass the full URL. If you used a custom key, pass that Request.

What's the difference between cache.match() and cache.matchAll()?

match() returns the first response that matches the request (or undefined). matchAll() returns an array of all responses that match. This is useful if you have multiple entries with the same key (which you should avoid, but it can happen).

Is it safe to use the URL as the key?

Yes, as long as the URL is unique and doesn't contain sensitive information. If you're caching user-specific data, avoid putting the user ID in the URL if it's sensitive; instead, use a hash or store it in IndexedDB.

What happens if I run out of storage space?

The browser will evict data from caches, starting with the least recently used. You can check the storage estimate with navigator.storage.estimate() and handle the 'persistent' storage permission if you need to avoid eviction.