# Cache

> The Cache is a small, fast memory storage that temporarily holds frequently accessed data to speed up future access.

## What is a cache and how does caching work?

The high-speed storage area used to store frequently accessed data for quick retrieval. It improves performance by reducing the time to fetch data from slower storage.

- Topic: Basics
- Type: concept

## Example

Wrong:

```js
const cache = new Map();
async function getUser(id) {
  if (!cache.has(id)) cache.set(id, await fetchUser(id));
  return cache.get(id);
}
```

Right:

```js
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.

## Related cards

- [CDN](https://wonderium.dev/web/cdn.md)
- [HTTP Header](https://wonderium.dev/web/http-header.md)
- [Memory](https://wonderium.dev/engineering/memory.md)
- [Prompt Caching](https://wonderium.dev/ai/prompt-caching.md)
- [Hash Table](https://wonderium.dev/algorithms/hash-table.md)

---

- Level: [Engineering](https://wonderium.dev/engineering.md)
- HTML version: https://wonderium.dev/engineering/cache
- Last updated: 2026-11-25
