# What is caching? (https://layerscache.com/docs/learn/what-is-caching)

> What is caching? A cache keeps a copy of data in faster storage so repeat requests skip the slow fetch. Learn cache hits, misses, TTL and hit ratio.



**Caching** is keeping a copy of data in storage that is faster to reach than the original, so the next request can use the copy instead of fetching or computing the data again. A **cache** is that faster storage: a CPU cache in front of RAM, a browser cache in front of the network, or an in-memory cache and Redis in front of a database.

Caching works because most systems read the same data again and again. If 1,000 requests ask for the same product in a minute, a cache lets one of them query the database and the other 999 read memory.

**Level:** zero to one · &#x2A;*You need:** basic JavaScript or TypeScript, nothing else

```mermaid
flowchart LR
  A["Request for product:42"] --> B{"Copy in the cache?"}
  B -->|"Hit"| C["Return the copy"]
  B -->|"Miss"| D["Load from the database"]
  D --> E["Store a copy with a TTL"]
  E --> C
```

## What does cache mean? [#what-does-cache-mean]

The word comes from the French *cacher*, "to hide", and is pronounced like "cash". In computing, a cache is a small, fast store of data that sits in front of a bigger, slower one. The data inside it is **cached data**: a copy, never the original. The original, called the **source of truth**, stays in the database or on the other server.

## How does caching work? [#how-does-caching-work]

Every cache read ends in one of two ways.

* A **cache hit**: the cache has a usable copy and returns it.
* A **cache miss**: the cache has no copy, or its copy has expired. The application loads the data from the source of truth, stores it in the cache, and returns it.

```ts title="cache-basics.ts"
const cache = new Map<string, { value: string; expiresAt: number }>()

async function getProductName(id: string): Promise<string> {
  const key = `product:${id}`
  const entry = cache.get(key)
  if (entry && entry.expiresAt > Date.now()) return entry.value // cache hit

  const value = await loadFromDatabase(id) // cache miss
  cache.set(key, { value, expiresAt: Date.now() + 60_000 }) // keep it for 60 s
  return value
}

async function loadFromDatabase(id: string): Promise<string> {
  await new Promise((resolve) => setTimeout(resolve, 50)) // a slow query
  return `Product ${id}`
}
```

Those dozen lines hold the four ideas every cache has: a **key** (`product:42`), a **value**, a **time to live**, and a **loader** that fetches the value on a miss. This pattern is called [cache-aside](/docs/learn/cache-aside-pattern), and most applications use it.

## What is TTL (time to live)? [#what-is-ttl-time-to-live]

**TTL**, short for **time to live**, is how long a cached copy may be used before it expires. In the code above it is 60 seconds. After that, the next read is a miss, so the application loads a fresh copy.

A TTL is the simplest way to limit stale data, because even if you forget to remove a copy, it disappears on its own. Short TTLs keep data fresher but cause more misses. Long TTLs give more hits but risk older data. [Cache invalidation](/docs/learn/cache-invalidation) covers the other way to remove a copy: delete it when the original changes.

## What is a cache hit ratio? [#what-is-a-cache-hit-ratio]

The **cache hit ratio** is hits divided by all lookups. 900 hits in 1,000 reads is a 90% hit ratio. Read-heavy web caches commonly aim for 80% or more. A low ratio usually means the TTL is too short, the keys are too specific, or the cache is too small to hold the data people ask for.

## Cache terms you will see everywhere [#cache-terms-you-will-see-everywhere]

| Term               | Meaning                                                                                      |
| ------------------ | -------------------------------------------------------------------------------------------- |
| Cache hit          | The cache answered from its copy                                                             |
| Cache miss         | The cache had no usable copy, so the source was read                                         |
| Hit ratio          | Hits divided by all lookups                                                                  |
| TTL (time to live) | How long a copy may be used before it expires                                                |
| Eviction           | Removing entries when the cache is full. [LRU](/docs/learn/lru-cache) is the best-known rule |
| Invalidation       | Removing or replacing a copy because the original changed                                    |
| Stale data         | A copy that no longer matches the source                                                     |
| Cache key          | The name a value is stored under, such as `user:42`                                          |
| Working set        | The data a system reads often enough that caching it pays                                    |

## Why is a cache faster? [#why-is-a-cache-faster]

A cache is faster because it is closer to whoever reads it and built from faster hardware. The same rule repeats at every level of a computer and a network. These are the approximate figures from the widely cited "Latency numbers every programmer should know":

| Operation                                       | Approximate time      |
| ----------------------------------------------- | --------------------- |
| Level 1 CPU cache reference                     | 0.5 ns                |
| Main memory (RAM) reference                     | 100 ns                |
| Round trip inside one datacenter (a Redis call) | 500,000 ns (0.5 ms)   |
| Disk seek                                       | 10,000,000 ns (10 ms) |

### Why is a CPU cache faster than RAM? [#why-is-a-cpu-cache-faster-than-ram]

The two use different memory cells, and that is the whole difference in SRAM vs DRAM.

|          | SRAM (CPU cache)                 | DRAM (RAM)                                  |
| -------- | -------------------------------- | ------------------------------------------- |
| Cell     | A latch of about six transistors | One transistor and one capacitor            |
| Refresh  | None while powered               | The capacitor leaks and must be refreshed   |
| Location | On the processor die             | Separate modules on a memory bus            |
| Speed    | A few clock cycles               | Open a row, sense the charge, cross the bus |
| Size     | Megabytes                        | Gigabytes                                   |

SRAM takes far more chip area per bit, which is why caches are small and RAM is large.

### Why is an application cache faster than a database? [#why-is-an-application-cache-faster-than-a-database]

An in-memory cache inside your Node.js process answers from the same process: no network, no query planner, no disk. A lazy-layers-cache hit in reference mode measured 180 ns on an Apple M5. Redis is a separate server, so a read costs a network round trip, usually under a millisecond, but every server can share it. A database query can take milliseconds to seconds and uses a connection from a limited pool.

## Where do caches live in a web application? [#where-do-caches-live-in-a-web-application]

```mermaid
flowchart LR
  U["User"] --> B["Browser cache"]
  B --> C["CDN"]
  C --> M["App memory"]
  M --> R["Redis"]
  R --> D[("Database")]
```

A request travels right until some layer has a copy. Each layer you pass makes the answer slower, so you want most requests to stop early.

| Layer              | Example                                         | What it caches                                                                       |
| ------------------ | ----------------------------------------------- | ------------------------------------------------------------------------------------ |
| Browser            | HTTP cache, `Cache-Control` headers             | Pages, scripts, images, API responses                                                |
| CDN or edge        | Cloudflare, CloudFront                          | Static files and cacheable responses near the user                                   |
| Application memory | A `Map`, lru-cache, the L1 of lazy-layers-cache | Hot objects inside one process                                                       |
| Cache server       | Redis, Memcached, Cloudflare KV                 | Values shared by every app server                                                    |
| Database           | PostgreSQL shared buffers                       | Table and index pages. See [database caching](/docs/learn/database-caching-postgres) |

A **cache server** is a separate process, such as Redis or Memcached, that does nothing but hold cached values in memory for many application servers to share. A **caching layer** is any one of the rows above, seen from the application: memory first, then Redis, then the database. Stacking two of them is a [multi-level cache](/docs/learn/distributed-cache-system-design#multi-level-caching-l1-and-l2).

## When not to cache [#when-not-to-cache]

Caching trades freshness and simplicity for speed. Skip it, or keep TTLs very short, when:

* the data changes on almost every read, so the hit ratio would be low;
* a stale value is dangerous, such as permissions after a user is removed;
* the source is already fast enough and is not under load.

## The same idea in one call [#the-same-idea-in-one-call]

The hand-written cache above has three problems you will meet in production. Two requests that miss at the same moment both query the database ([cache stampede](/docs/learn/cache-stampede)). The `Map` grows until the process runs out of memory ([eviction](/docs/learn/lru-cache)). Each server keeps its own copy that nobody invalidates ([distributed caching](/docs/learn/distributed-cache-system-design)). lazy-layers-cache handles all three inside one call:

```ts title="product.ts"
import { setupCache } from 'lazy-layers-cache'
import { loadFromDatabase } from './db.ts'

const cache = await setupCache<string, string>({ redis: false, ttlMs: 60_000 })

export function getProductName(id: string): Promise<string | undefined> {
  return cache.getOrSet(`product:${id}`, () => loadFromDatabase(id))
}
```

For how those layers fit together in the library, read [layers](/docs/concepts/layers).

Next lesson: [caching strategies](/docs/learn/caching-strategies).

## Further reading [#further-reading]

* [Jeff Dean, LADIS 2009 keynote](https://www.cs.cornell.edu/projects/ladis2009/talks/dean-keynote-ladis2009.pdf): its storage hierarchy slides list DRAM at 100 ns and disk at 10 ms.
* [Latency Numbers Every Programmer Should Know](https://gist.github.com/jboner/2841832): the table behind the numbers in this lesson, from L1 cache 0.5 ns, main memory 100 ns, a datacenter round trip 500 us, a disk seek 10 ms.
* [Hello Interview, Caching for System Design Interviews](https://www.hellointerview.com/learn/system-design/core-concepts/caching): how caching comes up in interviews, with its example of a 50 ms database read against a 1 ms Redis read.


## Questions

### What is caching in simple words?

Caching is keeping a copy of something you will need again in a place that is faster to reach than where it came from. A web app keeps a database row in memory so the next request reads the copy in microseconds instead of querying the database again.

### What is cached data?

Cached data is a stored copy of data whose original lives somewhere else, such as a database row, an API response or a rendered page. The copy can go stale, so caches give it a time to live (TTL) or delete it when the original changes.

### What is a cache hit and a cache miss?

A cache hit is a request the cache answers from its copy. A cache miss is a request the cache cannot answer, so the application loads the data from the original source, usually stores it in the cache, and returns it.

### What is TTL in a cache?

TTL (time to live) is how long a cached copy may be used before it expires. After the TTL, the next read is a miss and loads a fresh copy. Short TTLs keep data fresher; long TTLs give more hits.

### Why is a CPU cache faster than RAM?

A CPU cache is built from SRAM on the processor chip, a few cycles from the execution units. RAM is DRAM on separate modules: each bit is a capacitor that must be refreshed and read through more circuitry, and the data travels further. A level 1 cache reference takes about 0.5 ns; a main memory reference takes about 100 ns.

### What is a good cache hit ratio?

It depends on the workload, but read-heavy web caches commonly aim for 80% or more. The hit ratio is hits divided by all lookups. A low ratio usually means TTLs are too short, keys are too specific, or the cache is too small for the working set.