LazyLayersv9.1.0
Learn caching

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 · You need: basic JavaScript or TypeScript, nothing else

Rendering diagram...

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?

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.
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, and most applications use it.

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 covers the other way to remove a copy: delete it when the original changes.

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

TermMeaning
Cache hitThe cache answered from its copy
Cache missThe cache had no usable copy, so the source was read
Hit ratioHits divided by all lookups
TTL (time to live)How long a copy may be used before it expires
EvictionRemoving entries when the cache is full. LRU is the best-known rule
InvalidationRemoving or replacing a copy because the original changed
Stale dataA copy that no longer matches the source
Cache keyThe name a value is stored under, such as user:42
Working setThe data a system reads often enough that caching it pays

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":

OperationApproximate time
Level 1 CPU cache reference0.5 ns
Main memory (RAM) reference100 ns
Round trip inside one datacenter (a Redis call)500,000 ns (0.5 ms)
Disk seek10,000,000 ns (10 ms)

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)
CellA latch of about six transistorsOne transistor and one capacitor
RefreshNone while poweredThe capacitor leaks and must be refreshed
LocationOn the processor dieSeparate modules on a memory bus
SpeedA few clock cyclesOpen a row, sense the charge, cross the bus
SizeMegabytesGigabytes

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?

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?

Rendering diagram...

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.

LayerExampleWhat it caches
BrowserHTTP cache, Cache-Control headersPages, scripts, images, API responses
CDN or edgeCloudflare, CloudFrontStatic files and cacheable responses near the user
Application memoryA Map, lru-cache, the L1 of lazy-layers-cacheHot objects inside one process
Cache serverRedis, Memcached, Cloudflare KVValues shared by every app server
DatabasePostgreSQL shared buffersTable and index pages. See database caching

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.

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 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). The Map grows until the process runs out of memory (eviction). Each server keeps its own copy that nobody invalidates (distributed caching). lazy-layers-cache handles all three inside one call:

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.

Next lesson: caching strategies.

Further reading

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.

On this page