Cache
Example
const cache = new Map();
async function getUser(id) {
if (!cache.has(id)) cache.set(id, await fetchUser(id));
return cache.get(id);
}const cache = new Map();
const TTL = 60_000;
async function getUser(id) {
const hit = cache.get(id);
if (hit && Date.now() - hit.time < TTL) return hit.value;
const value = await fetchUser(id);
cache.set(id, { value, time: Date.now() });
return value;
}Entries now expire after a minute, so changed user data is fetched again instead of being served stale forever.
Common mistakes
- Users see stale data because the cache is never invalidated.
- One user sees another user's data because the cache key ignored who asked.
Key points
- Every cache entry has an expiry or a clear invalidation rule.
- Cache keys include every input that changes the result, such as user ID or locale.
- Private or per-user data is never stored in a shared cache.
- In-memory caches have a size limit so they cannot grow forever.
Interview questions
What is cache invalidation?
Removing or updating cached data when the source changes, so readers do not get outdated results.
What is a cache hit and a cache miss?
A hit means the data was found in the cache. A miss means it was not, so it must be fetched from the slower source.