Imagine you're building an e-commerce application. The navigation bar needs the current user's profile. The account menu needs the same information. The checkout component also needs the user's details.
Each component independently calls the same endpoint.
// Navigation
const user = await fetchUser(123);
// Account menu
const user = await fetchUser(123);
// Checkout
const user = await fetchUser(123);
Three different components. Three identical API requests. Three responses containing essentially the same information.
Now imagine this happening throughout a larger application, with multiple components requesting product information, user permissions, application settings and notification counts. Your backend might be performing considerably more work than necessary.
The obvious solution is caching. But there's an interesting problem with the way many developers implement a JavaScript cache: caching the response doesn't necessarily prevent duplicate requests.
To understand why, let's build a simple caching mechanism from scratch and gradually improve it. We'll start with an ordinary JavaScript Map, without Redis, external dependencies or a complicated caching framework.
1. The problem with a traditional JavaScript cache
Let's start with a basic function that retrieves user information.
async function fetchUser(id) {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
Every time we call this function, it attempts another fetch. Unless something else in the HTTP caching or network layer handles these requests, we're unnecessarily fetching the same information three times.
We can improve this using a Map.
const userCache = new Map();
async function fetchUser(id) {
if (userCache.has(id)) {
return userCache.get(id);
}
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const user = await response.json();
userCache.set(id, user);
return user;
}
The first call retrieves information from the API. Subsequent calls retrieve it directly from memory.
await fetchUser(123); // API request
await fetchUser(123); // Cache hit
await fetchUser(123); // Cache hit
For sequential requests, it works well. But what happens when all three calls occur at approximately the same time?
const users = await Promise.all([
fetchUser(123),
fetchUser(123),
fetchUser(123)
]);
All three executions check the cache before the first API response arrives. All three discover that the cache is empty. And all three initiate a fetch.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 310" width="760" height="310" role="img" aria-label="Traditional cache: concurrent cache misses">
<rect x="0" y="0" width="760" height="310" rx="6" fill="#f6f4ee" stroke="none"/>
<text x="24" y="33" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start">Traditional cache: concurrent cache misses</text>
<rect x="24" y="58" width="150" height="42" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="99.0" y="84.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Component 1</text>
<line x1="174" y1="79" x2="254" y2="79" stroke="#6d7268" stroke-width="1.5"/>
<rect x="254" y="58" width="140" height="42" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="324.0" y="84.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Cache miss</text>
<line x1="394" y1="79" x2="566" y2="79" stroke="#6d7268" stroke-width="1.5"/>
<rect x="24" y="120" width="150" height="42" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="99.0" y="146.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Component 2</text>
<line x1="174" y1="141" x2="254" y2="141" stroke="#6d7268" stroke-width="1.5"/>
<rect x="254" y="120" width="140" height="42" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="324.0" y="146.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Cache miss</text>
<line x1="394" y1="141" x2="566" y2="141" stroke="#6d7268" stroke-width="1.5"/>
<rect x="24" y="182" width="150" height="42" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="99.0" y="208.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Component 3</text>
<line x1="174" y1="203" x2="254" y2="203" stroke="#6d7268" stroke-width="1.5"/>
<rect x="254" y="182" width="140" height="42" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="324.0" y="208.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Cache miss</text>
<line x1="394" y1="203" x2="566" y2="203" stroke="#6d7268" stroke-width="1.5"/>
<rect x="566" y="58" width="170" height="166" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="651.0" y="146.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">API: 3 requests</text>
<text x="380" y="280" font-family="Arial, sans-serif" font-size="14" fill="#6d7268" text-anchor="middle">The cache remains empty until the first response arrives.</text>
</svg>Three concurrent callers encounter an empty cache and independently initiate the same request.
Our cache works, but it hasn't solved the duplicate request problem.
2. What if we cached the promise instead of the response?
Rather than waiting for the API request to complete before updating the cache, we could store the promise representing that request immediately.
const userCache = new Map();
function fetchUser(id) {
if (userCache.has(id)) {
return userCache.get(id);
}
const promise = fetch(`/api/users/${id}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
});
userCache.set(id, promise);
return promise;
}
Notice that we're no longer storing the user object in the cache. We're storing the promise.
The first caller initiates the request and immediately stores its promise in the Map. Any subsequent caller requesting the same user receives that existing promise.
const request1 = fetchUser(123);
const request2 = fetchUser(123);
const request3 = fetchUser(123);
console.log(request1 === request2); // true
console.log(request2 === request3); // true
const users = await Promise.all([
request1, request2, request3
]);
Only one fetch operation is initiated. When the promise resolves, all three callers receive its result.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 310" width="760" height="310" role="img" aria-label="Promise cache: shared operation">
<rect x="0" y="0" width="760" height="310" rx="6" fill="#f6f4ee" stroke="none"/>
<text x="24" y="33" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start">Promise cache: shared operation</text>
<rect x="24" y="58" width="150" height="42" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="99.0" y="84.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Component 1</text>
<line x1="174" y1="79" x2="264" y2="141" stroke="#6d7268" stroke-width="1.5"/>
<rect x="24" y="120" width="150" height="42" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="99.0" y="146.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Component 2</text>
<line x1="174" y1="141" x2="264" y2="141" stroke="#6d7268" stroke-width="1.5"/>
<rect x="24" y="182" width="150" height="42" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="99.0" y="208.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Component 3</text>
<line x1="174" y1="203" x2="264" y2="141" stroke="#6d7268" stroke-width="1.5"/>
<rect x="264" y="99" width="210" height="84" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="369.0" y="146.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Cached promise</text>
<line x1="474" y1="141" x2="556" y2="141" stroke="#242b25" stroke-width="1.5"/>
<rect x="556" y="99" width="180" height="84" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="646.0" y="146.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">API: 1 request</text>
<text x="380" y="280" font-family="Arial, sans-serif" font-size="14" fill="#6d7268" text-anchor="middle">All callers share one operation.</text>
</svg>Storing the promise immediately allows concurrent callers to share an existing request.
This technique is commonly referred to as request deduplication, request coalescing or in-flight promise caching. JavaScript promises can have multiple consumers. Attaching another handler to an existing promise does not restart the underlying operation.
We've solved the duplicate request problem without introducing another dependency. However, our implementation now has a different problem.
3. Don't accidentally cache your failures
Our promise-based cache works nicely when the API responds successfully. But what happens when the server returns an error?
try {
await fetchUser(123);
} catch (error) {
console.error("Failed to retrieve user");
}
Perhaps the server was temporarily unavailable. A few seconds later, we try again.
await fetchUser(123);
Surprisingly, the request fails immediately again. Even if the server has fully recovered, our application doesn't initiate another request. Why? Because the cache contains a rejected promise.
Once a promise has settled, its state doesn't change. A rejected promise remains rejected, regardless of how many times we await it.
We've accidentally turned a temporary API failure into a persistent application failure. Fortunately, the solution is straightforward: remove failed promises from the cache.
const userCache = new Map();
function fetchUser(id) {
if (userCache.has(id)) {
return userCache.get(id);
}
const promise = fetch(`/api/users/${id}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
})
.catch(error => {
// Only remove the entry if it still belongs
// to this request.
if (userCache.get(id) === promise) {
userCache.delete(id);
}
throw error;
});
userCache.set(id, promise);
return promise;
}
Now, when an API request fails, its promise is removed from the cache. Every caller waiting for that promise receives the error, but a subsequent call can initiate a fresh request.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 290" width="760" height="290" role="img" aria-label="Handling rejected promises">
<rect x="0" y="0" width="760" height="290" rx="6" fill="#f6f4ee" stroke="none"/>
<text x="24" y="33" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start">Handling rejected promises</text>
<text x="24" y="67" font-family="Arial, sans-serif" font-size="14" fill="#ab4932" text-anchor="start">Without failure eviction</text>
<rect x="24" y="82" width="220" height="53" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="134.0" y="113.5" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">API fails</text>
<line x1="244" y1="108" x2="270" y2="108" stroke="#6d7268" stroke-width="1.5"/>
<rect x="270" y="82" width="220" height="53" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="380.0" y="113.5" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Rejected promise cached</text>
<line x1="490" y1="108" x2="516" y2="108" stroke="#6d7268" stroke-width="1.5"/>
<rect x="516" y="82" width="220" height="53" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="626.0" y="113.5" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Future calls fail</text>
<text x="24" y="184" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="start">With failure eviction</text>
<rect x="24" y="199" width="220" height="53" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="134.0" y="230.5" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">API fails</text>
<line x1="244" y1="225" x2="270" y2="225" stroke="#6d7268" stroke-width="1.5"/>
<rect x="270" y="199" width="220" height="53" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="380.0" y="230.5" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Remove cached promise</text>
<line x1="490" y1="225" x2="516" y2="225" stroke="#6d7268" stroke-width="1.5"/>
<rect x="516" y="199" width="220" height="53" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="626.0" y="230.5" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Next call can retry</text>
</svg>Removing rejected promises allows future requests to recover from temporary API failures.
Notice the additional identity check before deleting the cached entry. This prevents an older failed request from accidentally deleting a newer cached request if the original entry was invalidated or replaced while it was running.
There are situations where temporarily caching failures makes sense, such as preventing repeated requests for a resource known not to exist. But that should be an intentional policy, rather than an accidental consequence of storing promises.
4. Cached data shouldn't live forever
Our cache now prevents duplicate concurrent requests and handles temporary failures. However, once we successfully retrieve a user's profile, we keep returning the same information indefinitely.
What happens when the user updates their email address or changes their display name? Our application could continue displaying outdated information.
We need a way to determine when cached data is no longer fresh. This is where Time to Live (TTL) comes in.
const userCache = new Map();
const TTL = 60_000; // 60 seconds
function fetchUser(id) {
const cached = userCache.get(id);
if (cached && Date.now() < cached.expiresAt) {
return cached.promise;
}
const entry = {
promise: null,
expiresAt: Infinity // Share while pending.
};
entry.promise = fetch(`/api/users/${id}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
})
.then(user => {
entry.expiresAt = Date.now() + TTL;
return user;
})
.catch(error => {
if (userCache.get(id) === entry) {
userCache.delete(id);
}
throw error;
});
userCache.set(id, entry);
return entry.promise;
}
One important decision here is when we start the expiration timer. Suppose our TTL is ten seconds, but the API takes eight seconds to respond. If we start the TTL when the request begins, the successful response will remain fresh for only two more seconds.
Worse, if the request takes longer than the TTL, another caller might initiate a duplicate request while the original one is still running.
By starting the TTL after successful completion, we separate the lifetime of an in-flight request from the freshness of its result.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 240" width="760" height="240" role="img" aria-label="The lifecycle of a cached request">
<rect x="0" y="0" width="760" height="240" rx="6" fill="#f6f4ee" stroke="none"/>
<text x="24" y="33" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start">The lifecycle of a cached request</text>
<rect x="40" y="98" width="90" height="44" rx="6" fill="#6d7268" stroke="none"/>
<rect x="130" y="98" width="540" height="44" rx="6" fill="#e6eadd" stroke="none"/>
<rect x="670" y="98" width="45" height="44" rx="6" fill="#ab4932" stroke="none"/>
<text x="85" y="124" font-family="Arial, sans-serif" font-size="12" fill="#fffef9" text-anchor="middle">Pending</text>
<text x="400" y="125" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle">Fresh response — 60 seconds</text>
<line x1="40" y1="88" x2="40" y2="156" stroke="#6d7268" stroke-width="1.5"/>
<text x="40" y="176" font-family="Arial, sans-serif" font-size="12" fill="#242b25" text-anchor="middle">0s</text>
<text x="40" y="199" font-family="Arial, sans-serif" font-size="11" fill="#6d7268" text-anchor="start">Request starts</text>
<line x1="130" y1="88" x2="130" y2="156" stroke="#6d7268" stroke-width="1.5"/>
<text x="130" y="176" font-family="Arial, sans-serif" font-size="12" fill="#242b25" text-anchor="middle">10s</text>
<text x="130" y="199" font-family="Arial, sans-serif" font-size="11" fill="#6d7268" text-anchor="start">TTL starts</text>
<line x1="670" y1="88" x2="670" y2="156" stroke="#6d7268" stroke-width="1.5"/>
<text x="670" y="176" font-family="Arial, sans-serif" font-size="12" fill="#242b25" text-anchor="middle">70s</text>
<text x="670" y="199" font-family="Arial, sans-serif" font-size="11" fill="#ab4932" text-anchor="middle">Expired</text>
</svg>The freshness timer begins after the request succeeds, not when it starts.
| Data | Illustrative TTL |
|---|---|
| Application configuration | 5–30 minutes |
| Product categories | 5–15 minutes |
| User profile | 30–60 seconds |
| Product inventory | 5–30 seconds |
| Notification count | 5–15 seconds |
| Live market prices | Near real-time updates |
These are example settings, not recommended defaults for every application. The appropriate duration depends on how quickly the data changes and what happens when users receive outdated information.
For some financial, security or inventory operations, cached information should never be treated as the authoritative source when performing a critical action. A cache is useful only when the application can tolerate the freshness guarantees it provides.
5. Sometimes, we can't wait for the cache to expire
A TTL helps keep cached data reasonably fresh, but there are situations where we know the data has changed. Imagine a user updates their profile. The update succeeds, but the navigation bar still displays the user's previous name.
We could reduce the TTL to five seconds, but that doesn't really solve the problem. It simply reduces the amount of time for which the problem exists.
A better solution is to invalidate the cached entry after a successful update.
function invalidateUser(id) {
userCache.delete(id);
}
async function updateUser(id, changes) {
const response = await fetch(`/api/users/${id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(changes)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
invalidateUser(id);
return response.json();
}
The next call to fetchUser(id) initiates a new request.
What if the API already returns the updated data?
If the update endpoint returns a complete, authoritative user profile, we might not need another request at all. We can update the cache directly.
function setCachedUser(id, user) {
userCache.set(id, {
promise: Promise.resolve(user),
expiresAt: Date.now() + TTL
});
}
// After successfully updating the user:
const updatedUser = await response.json();
setCachedUser(id, updatedUser);
| Approach | Behaviour |
|---|---|
| Cache invalidation | Remove the entry and fetch fresh data when needed |
| Cache replacement | Replace the entry with an authoritative updated value |
Cache invalidation is generally simpler when an operation affects several related resources. Cache replacement can avoid unnecessary requests when the updated resource is already available.
There is one subtle complication: invalidating a cache entry doesn't cancel an outstanding request or prevent its existing consumers from receiving an older result. Applications that display the results of overlapping reads and writes may still need version checks or cancellation.
Also, updating the cache doesn't automatically update every React component that previously consumed its data. That requires a subscription or state-management mechanism.
6. An expired cache entry still occupies memory
Every time we retrieve a different user, we create another entry in the Map. The expiration timestamp tells us when an entry should no longer be reused. But it doesn't automatically remove the entry from memory.
Unless the same key is accessed again, explicitly deleted, or the entire cache becomes unreachable, the expired entry remains in the Map.
For a small frontend application, this might not be noticeable. For a long-running Node.js backend, it could become a significant memory-management problem.
Expiration: When cached data should no longer be considered fresh.
Eviction: When cached data should actually be removed from memory.
One straightforward solution is to periodically remove expired entries.
function removeExpiredEntries() {
const now = Date.now();
for (const [key, entry] of userCache) {
if (entry.expiresAt <= now) {
userCache.delete(key);
}
}
}
Another option is to limit how many entries the cache can contain.
Using a simple LRU strategy
JavaScript's Map preserves insertion order. We can use that behaviour to implement a basic Least Recently Used (LRU) cache.
Whenever an entry is accessed, we move it to the end of the Map.
function markAsRecentlyUsed(key, entry) {
userCache.delete(key);
userCache.set(key, entry);
}
When we need to free some space, the first key represents the least recently accessed entry, assuming we've consistently maintained this ordering.
const oldestKey = userCache.keys().next().value;
userCache.delete(oldestKey);
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 275" width="760" height="275" role="img" aria-label="Least Recently Used cache">
<rect x="0" y="0" width="760" height="275" rx="6" fill="#f6f4ee" stroke="none"/>
<text x="24" y="33" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start">Least Recently Used cache</text>
<text x="24" y="63" font-family="Arial, sans-serif" font-size="13" fill="#6d7268" text-anchor="start">Before accessing B</text>
<rect x="24" y="78" width="120" height="46" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="84.0" y="106.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">A</text>
<rect x="172" y="78" width="120" height="46" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="232.0" y="106.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">B</text>
<rect x="320" y="78" width="120" height="46" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="380.0" y="106.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">C</text>
<rect x="468" y="78" width="120" height="46" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="528.0" y="106.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">D</text>
<rect x="616" y="78" width="120" height="46" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="676.0" y="106.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">E</text>
<text x="24" y="143" font-family="Arial, sans-serif" font-size="11" fill="#ab4932" text-anchor="start">Least recently used</text>
<text x="736" y="143" font-family="Arial, sans-serif" font-size="11" fill="#6d7268" text-anchor="end">Most recently used</text>
<text x="24" y="175" font-family="Arial, sans-serif" font-size="13" fill="#6d7268" text-anchor="start">After accessing B</text>
<rect x="24" y="190" width="120" height="46" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="84.0" y="218.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">A</text>
<rect x="172" y="190" width="120" height="46" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="232.0" y="218.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">C</text>
<rect x="320" y="190" width="120" height="46" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="380.0" y="218.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">D</text>
<rect x="468" y="190" width="120" height="46" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="528.0" y="218.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">E</text>
<rect x="616" y="190" width="120" height="46" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="676.0" y="218.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">B</text>
<text x="24" y="255" font-family="Arial, sans-serif" font-size="11" fill="#ab4932" text-anchor="start">Least recently used</text>
<text x="736" y="255" font-family="Arial, sans-serif" font-size="11" fill="#6d7268" text-anchor="end">Most recently used</text>
</svg>Accessing an entry moves it to the end of the cache, leaving less recently used entries available for eviction.
However, if we evict a pending promise, another caller requesting the same resource might initiate a duplicate request while the first one is still running.
A useful solution is to maintain separate collections for pending requests and completed responses. That separation also makes the implementation easier to reason about.
7. Building a reusable JavaScript cache
Rather than writing a separate caching mechanism for every API endpoint, let's combine everything we've learned into a reusable utility.
pending— stores asynchronous operations that are currently running.cache— stores successfully retrieved data, together with its expiration time.
The pending collection prevents duplicate requests. The completed cache prevents unnecessary future requests.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 400" width="760" height="400" role="img" aria-label="Request deduplication and response caching">
<rect x="0" y="0" width="760" height="400" rx="6" fill="#f6f4ee" stroke="none"/>
<text x="24" y="33" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start">Request deduplication and response caching</text>
<rect x="260" y="54" width="240" height="40" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="380.0" y="79.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Request a resource</text>
<line x1="380" y1="94" x2="380" y2="119" stroke="#6d7268" stroke-width="1.5"/>
<rect x="260" y="119" width="240" height="44" rx="6" fill="#fffef9" stroke="#242b25"/>
<text x="380.0" y="146.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Fresh cached response?</text>
<line x1="500" y1="141" x2="548" y2="141" stroke="#6d7268" stroke-width="1.5"/>
<text x="524" y="132" font-family="Arial, sans-serif" font-size="11" fill="#242b25" text-anchor="middle">Yes</text>
<rect x="548" y="119" width="188" height="44" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="642.0" y="146.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Return cached data</text>
<text x="391" y="179" font-family="Arial, sans-serif" font-size="11" fill="#6d7268" text-anchor="start">No</text>
<line x1="380" y1="169" x2="380" y2="194" stroke="#6d7268" stroke-width="1.5"/>
<rect x="260" y="194" width="240" height="44" rx="6" fill="#fffef9" stroke="#242b25"/>
<text x="380.0" y="221.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Request already pending?</text>
<line x1="500" y1="216" x2="548" y2="216" stroke="#6d7268" stroke-width="1.5"/>
<text x="524" y="207" font-family="Arial, sans-serif" font-size="11" fill="#242b25" text-anchor="middle">Yes</text>
<rect x="548" y="194" width="188" height="44" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="642.0" y="221.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Share existing promise</text>
<text x="391" y="254" font-family="Arial, sans-serif" font-size="11" fill="#6d7268" text-anchor="start">No</text>
<line x1="380" y1="238" x2="380" y2="269" stroke="#6d7268" stroke-width="1.5"/>
<rect x="260" y="269" width="240" height="44" rx="6" fill="#fffef9" stroke="#242b25"/>
<text x="380.0" y="296.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Start a new request</text>
<line x1="380" y1="313" x2="380" y2="329" stroke="#6d7268" stroke-width="1.5"/>
<line x1="192" y1="329" x2="568" y2="329" stroke="#6d7268" stroke-width="1.5"/>
<line x1="192" y1="329" x2="192" y2="345" stroke="#6d7268" stroke-width="1.5"/>
<line x1="568" y1="329" x2="568" y2="345" stroke="#6d7268" stroke-width="1.5"/>
<rect x="24" y="345" width="336" height="38" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="192.0" y="369.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Success: cache result, remove pending</text>
<rect x="400" y="345" width="336" height="38" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="568.0" y="369.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Failure: remove pending, propagate error</text>
</svg>Separating pending requests from completed responses makes deduplication, expiration and eviction easier to manage.
Step 1: Create the cache utility
// request-cache.js
export function createRequestCache({
ttl = 60_000,
maxEntries = 100
} = {}) {
if (!Number.isFinite(ttl) || ttl < 0) {
throw new RangeError("Invalid TTL");
}
if (!Number.isInteger(maxEntries) || maxEntries < 1) {
throw new RangeError("Invalid cache size");
}
const cache = new Map();
const pending = new Map();
function get(key, loader) {
const cached = cache.get(key);
// 1. Return a fresh cached response.
if (cached) {
if (Date.now() < cached.expiresAt) {
cache.delete(key);
cache.set(key, cached);
return Promise.resolve(cached.data);
}
cache.delete(key);
}
// 2. Share an existing asynchronous operation.
if (pending.has(key)) {
return pending.get(key);
}
// 3. Start a new operation.
const promise = Promise.resolve()
.then(loader)
.then(data => {
// Don't restore an invalidated request.
if (pending.get(key) === promise && ttl > 0) {
cache.set(key, {
data,
expiresAt: Date.now() + ttl
});
// Remove least recently used entries.
while (cache.size > maxEntries) {
const oldestKey = cache.keys().next().value;
cache.delete(oldestKey);
}
}
return data;
})
.finally(() => {
// Remove only this particular request.
if (pending.get(key) === promise) {
pending.delete(key);
}
});
pending.set(key, promise);
return promise;
}
function invalidate(key) {
cache.delete(key);
pending.delete(key);
}
function clear() {
cache.clear();
pending.clear();
}
function prune() {
const now = Date.now();
for (const [key, entry] of cache) {
if (entry.expiresAt <= now) {
cache.delete(key);
}
}
}
function stats() {
return {
cached: cache.size,
pending: pending.size
};
}
return { get, invalidate, clear, prune, stats };
}
There are several interesting decisions in this implementation.
First, Promise.resolve().then(loader) schedules the loader to run after the pending promise has been registered. It also turns synchronous exceptions thrown by the loader into promise rejections.
Second, we check the identity of the pending promise before storing its result. Imagine a request is running when we invalidate its cache key. A second request then starts. If the original request completes later, we don't want it to overwrite the newer cached information. The identity check prevents that.
Finally, our maximum cache size applies to completed responses rather than pending operations. This prevents normal LRU eviction from accidentally removing an outstanding request and defeating deduplication. However, it doesn't limit the number of simultaneous requests for different keys. If that's a concern, introduce a separate concurrency limiter.
Step 2: Create a reusable API client
// api.js
import { createRequestCache } from "./request-cache.js";
const requestCache = createRequestCache({
ttl: 60_000,
maxEntries: 500
});
export function getJSON(url) {
return requestCache.get(url, async () => {
const response = await fetch(url, {
signal: AbortSignal.timeout(10_000)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
});
}
export function invalidate(url) {
requestCache.invalidate(url);
}
export function clearCache() {
requestCache.clear();
}
The request timeout prevents an unresponsive API from leaving a pending fetch waiting indefinitely under normal runtime conditions. The example assumes a modern JavaScript runtime supporting AbortSignal.timeout().
Step 3: Use it throughout the application
import { getJSON, invalidate } from "./api.js";
const [user1, user2, user3] = await Promise.all([
getJSON("/api/users/123"),
getJSON("/api/users/123"),
getJSON("/api/users/123")
]);
// Cache hit within the TTL:
const user = await getJSON("/api/users/123");
// After updating the user:
invalidate("/api/users/123");
All three calls share one outstanding fetch operation. Subsequent calls within the 60-second TTL reuse the completed response. After invalidation, the next request retrieves fresh information.
8. Let's prove that request deduplication actually works
Rather than relying on an external API, we can test the utility using a simulated asynchronous operation.
import { createRequestCache } from "./request-cache.js";
const cache = createRequestCache({
ttl: 1000,
maxEntries: 100
});
let requestCount = 0;
async function fetchProduct() {
requestCount++;
console.log(`API call #${requestCount}`);
await new Promise(resolve => setTimeout(resolve, 100));
return {
id: 123,
name: "Mechanical Keyboard",
price: 89
};
}
const results = await Promise.all(
Array.from({ length: 100 }, () =>
cache.get("product:123", fetchProduct)
)
);
console.log("Callers:", results.length);
console.log("API calls:", requestCount);
console.log("Cache:", cache.stats());
Expected output:
API call #1
Callers: 100
API calls: 1
Cache: { cached: 1, pending: 0 }
One hundred callers, but only one invocation of the simulated API. That's a 99% reduction in loader invocations for this particular scenario.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 210" width="760" height="210" role="img" aria-label="100 concurrent callers requesting the same resource">
<rect x="0" y="0" width="760" height="210" rx="6" fill="#f6f4ee" stroke="none"/>
<text x="24" y="33" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start">100 concurrent callers requesting the same resource</text>
<text x="24" y="66" font-family="Arial, sans-serif" font-size="13" fill="#242b25" text-anchor="start">Without request deduplication</text>
<rect x="24" y="79" width="650" height="34" rx="6" fill="#ab4932" stroke="none"/>
<text x="690" y="101" font-family="Arial, sans-serif" font-size="14" fill="#ab4932" text-anchor="start">100</text>
<text x="24" y="143" font-family="Arial, sans-serif" font-size="13" fill="#242b25" text-anchor="start">With request deduplication</text>
<rect x="24" y="155" width="650" height="34" rx="6" fill="#e6eadd" stroke="none"/>
<rect x="24" y="155" width="6.5" height="34" rx="6" fill="#242b25" stroke="none"/>
<text x="42" y="177" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="start">1 API call</text>
</svg>Illustrative request counts for 100 concurrent callers using an identical cache key. This is not a production performance benchmark.
The actual benefit in a real application depends on how frequently identical requests occur, how long data remains cached and whether requests are already being deduplicated elsewhere.
Testing cache expiration
await cache.get("product:123", fetchProduct);
console.log(requestCount); // Expected: 1
await new Promise(resolve => setTimeout(resolve, 1100));
await cache.get("product:123", fetchProduct);
console.log(requestCount); // Expected: 2
The first call reuses the cached data. The second initiates a new operation because the TTL has expired.
Testing failure recovery
const testCache = createRequestCache();
let attempts = 0;
async function unreliableAPI() {
attempts++;
if (attempts === 1) {
throw new Error("Service unavailable");
}
return { success: true };
}
try {
await testCache.get("status", unreliableAPI);
} catch (error) {
console.log(error.message);
}
const result = await testCache.get("status", unreliableAPI);
console.log(result);
console.log(attempts);
Expected output:
Service unavailable
{ success: true }
2
The failed request hasn't poisoned the cache. The next caller is free to try again. These three scenarios cover the fundamental behaviours we want: deduplication, expiration and recovery.
9. Your cache key is more important than you think
So far, we've used the request URL as the cache key. For a simple application running within a single authenticated browser session, this can be sufficient. But consider these two requests:
fetch("/api/products", {
headers: { "Accept-Language": "en" }
});
fetch("/api/products", {
headers: { "Accept-Language": "ja" }
});
Both requests use the same URL, but they could return different information. The same problem occurs with currency preferences, user permissions, tenant identifiers, API versions and authentication contexts.
Consider two users accessing GET /api/account. If a shared backend cache uses only the URL as its key, one user could potentially receive another user's account information.
That's no longer just a caching bug. It's a security vulnerability.
function createCacheKey({
url, userId, tenantId, language, currency
}) {
return JSON.stringify([
url, userId, tenantId, language, currency
]);
}
const key = createCacheKey({
url: "/api/products",
userId: "user-123",
tenantId: "company-456",
language: "en",
currency: "SGD"
});
const products = await requestCache.get(key, fetchProducts);
This is a simplified example. The actual key should include every relevant dimension affecting the returned data. Authentication and authorization must still be enforced independently of caching. A user ID in a cache key isn't a substitute for access control.
Avoid including raw access tokens, passwords or other secrets in cache keys, especially when those keys might appear in application logs.
If we're maintaining a browser-side cache, we should also clear it when a user logs out or switches accounts.
async function logout() {
clearCache();
await revokeSession();
}
The same principle appears in TanStack Query's query key documentation.
Two requests should only share a cache entry if their results are genuinely interchangeable.
10. Be careful when cancelling a shared request
Suppose three React components are waiting for the same API response. One component unmounts. Should we cancel the request?
Normally, cancelling an unnecessary network request is a good idea. But in this case, the other two components still need the result. If we abort the shared request, all three callers receive a rejection.
| Action | Effect |
|---|---|
| Cancel an individual consumer | One caller stops waiting for the result |
| Cancel the shared request | Every caller loses the underlying operation |
| Invalidate the cache | Future callers no longer reuse the entry |
One possible approach is to track how many consumers are waiting for a shared operation and only cancel the underlying fetch when no consumers remain.
Another approach is to allow each component to ignore the result after it unmounts, while the shared request continues for the remaining consumers.
import { useEffect, useState } from "react";
import { getJSON } from "./api.js";
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
let active = true;
setUser(null);
setError(null);
getJSON(`/api/users/${userId}`)
.then(data => {
if (active) setUser(data);
})
.catch(error => {
if (active) setError(error);
});
return () => {
active = false;
};
}, [userId]);
if (error) return <p>Unable to load profile.</p>;
if (!user) return <p>Loading...</p>;
return <h2>{user.name}</h2>;
}
When the component unmounts, it stops applying the result to its state. The shared request continues running and can still provide information to other components.
This is consumer-level cleanup rather than network-level cancellation. For a larger application, maintaining consumer counts, cancellation policies and subscriptions can become complicated. Established data-fetching libraries are often worth considering at that point.
11. A shared response can introduce another unexpected bug
Consider what happens when two components retrieve the same cached object.
const user1 = await getJSON("/api/users/123");
const user2 = await getJSON("/api/users/123");
console.log(user1 === user2); // true, within the TTL
user1.name = "Updated Name";
console.log(user2.name); // "Updated Name"
We've unintentionally modified the cached information. Another component may now display data that was never saved to the server. This is particularly problematic when using cached information to populate editable forms.
A better approach is to treat cached responses as read-only. When creating an editable draft, make an independent copy.
const user = await getJSON("/api/users/123");
const editableUser = structuredClone(user);
editableUser.name = "Updated Name";
The original cached response remains unchanged. TypeScript developers can also use readonly types to discourage accidental mutations at compile time.
type User = Readonly<{
id: number;
name: string;
email: string;
}>;
Remember that Readonly<T> is shallow and doesn't enforce immutability at runtime. We could return a deep copy on every cache access, but that introduces additional memory and processing overhead. Treating cached data as immutable is a more practical starting point.
12. Do we really need Redis for this?
Whenever caching comes up in backend discussions, Redis is often one of the first technologies mentioned. Redis is an excellent choice for many caching requirements, but it solves a different set of problems from the small JavaScript cache we've built.
Consider a Node.js application running in a single process. An in-memory Map can be sufficient for sharing data between different parts of that process.
However, suppose the application runs across three Docker containers. Each container has its own JavaScript runtime. Each runtime has its own Map. A request reaching Container A cannot access a promise stored in Container B.
SVG source
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 300" width="760" height="300" role="img" aria-label="Local cache vs. shared cache">
<rect x="0" y="0" width="760" height="300" rx="6" fill="#f6f4ee" stroke="none"/>
<text x="24" y="33" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start">Local cache vs. shared cache</text>
<text x="24" y="61" font-family="Arial, sans-serif" font-size="13" fill="#6d7268" text-anchor="start">Process-local JavaScript caches</text>
<text x="24" y="180" font-family="Arial, sans-serif" font-size="13" fill="#6d7268" text-anchor="start">Shared response cache</text>
<line x1="24" y1="157" x2="736" y2="157" stroke="#d9ddd2" stroke-width="1.5"/>
<rect x="24" y="76" width="220" height="65" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="134.0" y="113.5" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Container 1: local Map</text>
<rect x="24" y="191" width="220" height="34" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="134.0" y="213.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Container 1</text>
<line x1="134" y1="225" x2="134" y2="236" stroke="#6d7268" stroke-width="1.5"/>
<line x1="134" y1="236" x2="380" y2="236" stroke="#6d7268" stroke-width="1.5"/>
<rect x="270" y="76" width="220" height="65" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="380.0" y="113.5" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Container 2: local Map</text>
<rect x="270" y="191" width="220" height="34" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="380.0" y="213.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Container 2</text>
<line x1="380" y1="225" x2="380" y2="236" stroke="#6d7268" stroke-width="1.5"/>
<line x1="380" y1="236" x2="380" y2="236" stroke="#6d7268" stroke-width="1.5"/>
<rect x="516" y="76" width="220" height="65" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="626.0" y="113.5" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Container 3: local Map</text>
<rect x="516" y="191" width="220" height="34" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="626.0" y="213.0" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Container 3</text>
<line x1="626" y1="225" x2="626" y2="236" stroke="#6d7268" stroke-width="1.5"/>
<line x1="626" y1="236" x2="380" y2="236" stroke="#6d7268" stroke-width="1.5"/>
<line x1="380" y1="236" x2="380" y2="247" stroke="#6d7268" stroke-width="1.5"/>
<rect x="270" y="247" width="220" height="39" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="380.0" y="271.5" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Shared Redis cache</text>
</svg>An in-memory cache is local to each process, whereas Redis can provide shared cached data across application instances.
Redis allows multiple application instances to retrieve and update shared cached information. However, we cannot simply store an active JavaScript promise in Redis and expect another process to await it.
Even with Redis, multiple processes can simultaneously encounter a cache miss and initiate the same expensive operation. Preventing that requires additional coordination, such as distributed request coalescing or carefully implemented distributed locking.
| Feature | JavaScript Map | Redis |
|---|---|---|
| External service required | No | Yes |
| Shared across processes | No | Yes |
| Store live JavaScript promises | Yes | No |
| Built-in expiration | No | Yes |
| Built-in eviction policies | No | Yes |
| Network overhead | None | Yes |
| Cross-process request deduplication | No | Requires coordination |
In practice, the two approaches can complement each other. A backend service might use a local promise cache to deduplicate concurrent operations within each process, Redis to share completed responses across application instances, and the database or external API as the authoritative source.
But if we're simply preventing duplicate API calls from several components in a single browser application, introducing Redis would usually be unnecessary. Start with the smallest solution that addresses the actual problem.
13. How does this differ from the browser's HTTP cache?
An application-level JavaScript cache is not the same as the browser's built-in HTTP cache. The HTTP cache operates according to request properties, response headers and HTTP caching rules.
For example, an API could return:
Cache-Control: max-age=60
ETag: "product-123-v2"
The browser may reuse a fresh cached HTTP response or revalidate it when appropriate. Our JavaScript cache operates at a different level. It can share an outstanding promise, reuse already parsed data and manage application-specific invalidation.
| Capability | HTTP cache | Application cache |
|---|---|---|
| Reuse HTTP responses | Yes | Not its primary purpose |
| HTTP conditional revalidation | Yes | Must be implemented separately |
| Share an active JavaScript promise | No direct application-level API | Yes |
| Reuse parsed application objects | No | Yes |
| Custom resource invalidation | Limited application control | Yes |
| Honour HTTP caching headers automatically | Yes, according to HTTP rules | No |
The final row is important. Our custom implementation doesn't automatically interpret Cache-Control, Vary, ETag or other HTTP response headers.
If an endpoint returns sensitive information with a restrictive caching policy, we shouldn't blindly retain it in application memory. HTTP caching rules are defined by RFC 9111, including directives such as private and no-store.
For production applications, define which endpoints may be cached and what freshness and confidentiality guarantees they require. Our JavaScript cache should complement those policies, not silently bypass them.
14. When should you use an existing caching library instead?
Building our own cache has been a useful exercise. We've learned how request deduplication works, why failed promises need to be removed, how expiration differs from eviction, and why cache keys matter.
But maintaining a complete data-fetching solution involves considerably more than what we've implemented: automatically refreshing stale data, synchronising components, managing loading and error states, optimistic updates, retries, pagination, server-side rendering and hydration.
If you're building a React application, libraries such as TanStack Query and SWR already address many of these requirements.
Using TanStack Query
npm install @tanstack/react-query
Assuming we've configured a QueryClientProvider at the application level, we can create a reusable hook.
import { useQuery } from "@tanstack/react-query";
export function useUser(id) {
return useQuery({
queryKey: ["user", id],
queryFn: async ({ signal }) => {
const response = await fetch(`/api/users/${id}`, { signal });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
},
staleTime: 60_000,
gcTime: 300_000
});
}
Any component can now use this hook.
function Navigation({ userId }) {
const { data: user } = useUser(userId);
return <span>{user?.name}</span>;
}
function AccountMenu({ userId }) {
const { data: user } = useUser(userId);
return <span>{user?.email}</span>;
}
Within the same query client, both components can share the cached query and its outstanding fetch.
staleTime determines how long the data is considered fresh. gcTime determines how long an inactive query remains in memory before being garbage collected. These are essentially the expiration and eviction concepts we discussed earlier, although TanStack Query's behaviour is more sophisticated than our simple implementation. Stale data can remain available while a background refresh takes place.
SWR also provides built-in caching and request deduplication, allowing components using the same resource key to avoid unnecessary network requests.
Which approach should you choose?
| Requirement | Suggested solution |
|---|---|
| Prevent duplicate calls in a small JavaScript utility | Promise cache |
| Cache results within a Node.js process | Map with TTL and eviction |
| Manage API data in React | TanStack Query or SWR |
| Share cached results across backend containers | Redis |
| Cache public HTTP responses | HTTP caching or CDN |
| Prevent cross-process duplicate operations | Distributed coordination |
| Persist data across browser sessions | IndexedDB or an appropriate persistence layer |
You don't necessarily need to introduce a library to solve a small problem. But you also don't need to reinvent an entire data-fetching framework when an established solution already meets your requirements.
Understanding how the underlying mechanism works helps you make that decision.
Final thoughts
When developers talk about improving API performance, the conversation often revolves around database indexes, faster servers, response compression, connection pooling and infrastructure upgrades. All of those can be useful.
But sometimes, there's a much simpler question worth asking.
Why are we making the same request multiple times in the first place?
A traditional cache helps us avoid retrieving information we've already received. A promise cache goes one step further: it helps us avoid retrieving information we're already retrieving.
That distinction is easy to overlook, yet it can make a meaningful difference in applications where multiple components or services depend on the same information.
The implementation doesn't necessarily require Redis, a new npm package or a complicated architectural change. Sometimes, all it takes is a JavaScript Map and an understanding of how promises work.
The fastest API request is often the one you don't have to make.
THE CONVERSATION
Comments
Questions, useful examples and different approaches are welcome. Keep the discussion thoughtful and on topic.
Loading comments…