Caching in Node.js
Cache in Node.js with a Map, memoization, Redis or both. Compare node-cache, lru-cache, keyv, cache-manager and lazy-layers-cache, plus Express and NestJS code.
Caching in Node.js means keeping the result of slow work, such as a database query or an API call, where the next request can read it quickly. The copy lives in your process memory, in a shared store such as Redis, or in both. This page covers server-side caching. Browser caches, such as the HTTP cache and the Cache API, are a separate topic.
Level: one to ten · You need: The cache-aside pattern and Redis cache in Node.js
In-memory, Redis, or both?
| In-process memory | Redis | Both (L1 and L2) | |
|---|---|---|---|
| Read cost | Nanoseconds | About 0.5 ms round trip in a datacenter | Nanoseconds on a hit, Redis on a memory miss |
| Shared across processes | No | Yes | Yes |
| Survives a restart | No | If persistence is on | Redis part does |
| Extra server | None | Yes | Yes |
| Fits | One process | Several processes, short staleness is fine | Several processes, hot reads |
One process means one Node.js process. PM2 in cluster mode, Node's cluster module and multiple containers each run several processes, and each has its own memory.
When does each fit?
- One process. A script, a CLI, a small API on one container. A
Maporlru-cacheis faster than anything networked. - Several processes on PM2 or a cluster. Memory is per process, so the same key is cached once per worker, and a delete in one worker does not reach the others. Add Redis, or accept short TTLs.
- Serverless functions. An instance can be created and discarded at any time, so memory is often cold. A shared store matters more. See the serverless setup.
- Cloudflare Workers. Memory lives in an isolate that Cloudflare can start and stop freely, and Redis over TCP is not the usual path. Workers have KV, which is shared but eventually consistent. See Cloudflare KV.
Build a cache in Node.js with a Map
A cache needs a place to store values, an expiry and a way to clear them. A Map plus a timestamp covers the first two:
const store = new Map<string, { value: unknown; expiresAt: number }>()
export function getCached<T>(key: string): T | undefined {
const entry = store.get(key)
if (!entry) return undefined
if (entry.expiresAt <= Date.now()) {
store.delete(key) // expired
return undefined
}
return entry.value as T
}
export function setCached(key: string, value: unknown, ttlMs: number): void {
store.set(key, { value, expiresAt: Date.now() + ttlMs })
}This holds for a small, fixed set of keys. It has no size limit, so a key per user grows until the process runs out of memory. Bounded caches and eviction are the subject of the LRU cache lesson.
Memoize an async function in JavaScript
Memoization caches a function's result by its arguments. For an async function, cache the promise instead of the resolved value. Two callers that arrive before the first request finishes then share one request.
export function memoizeAsync<T>(
fn: (arg: string) => Promise<T>,
ttlMs: number,
): (arg: string) => Promise<T> {
const entries = new Map<string, { promise: Promise<T>; expiresAt: number }>()
return (arg) => {
const hit = entries.get(arg)
if (hit && hit.expiresAt > Date.now()) return hit.promise
const promise = fn(arg)
entries.set(arg, { promise, expiresAt: Date.now() + ttlMs })
promise.catch(() => {
// do not cache a failure
if (entries.get(arg)?.promise === promise) entries.delete(arg)
})
return promise
}
}
const getRepo = memoizeAsync(async (name: string) => {
const res = await fetch(`https://api.github.com/repos/${name}`)
return (await res.json()) as { stargazers_count: number }
}, 60_000)
console.log(await getRepo('nodejs/node'))
console.log(await getRepo('nodejs/node')) // from the cacheWhich npm libraries do people use?
A search for "node cache" or "cache manager" shows these. All of them are real options, and they solve different problems.
| Library | What it is |
|---|---|
| node-cache | A process-local key-value cache with TTLs. Good for a handful of values in one process. |
| lru-cache | A bounded in-memory cache that evicts the least recently used entry when full. Supports TTLs, and its fetch() method shares one load between concurrent callers. |
| keyv | One key-value API over many storage adapters, such as memory, Redis, SQLite or Postgres. You pick where the data lives. |
| cache-manager | A cache API (get, set, wrap) over one or more stores. Version 6 and later is built on Keyv. |
| lazy-layers-cache | A multi-layer cache: memory in front of Redis, getOrSet, and invalidation that reaches every server. |
A rule of thumb: node-cache and lru-cache are single-process tools, keyv and cache-manager let you plug in Redis, and lazy-layers-cache combines a memory layer and Redis with coordination between servers.
For feature-by-feature detail, read the comparison and the features compared table in BENCHMARKS.md. The table is built from each library's own README, so check a library's full documentation before relying on a gap.
How much memory can an in-memory cache use?
Everything in a Map or an in-memory cache counts toward the Node.js heap, and the garbage collector has to scan it. V8's heap has a limit that depends on the machine and that you can change with --max-old-space-size. A cache with no bound on entries will eventually hit that limit and crash the process.
Bound every in-memory cache by entry count, or better by bytes, and keep what you store small. Store the fields a response needs, not the whole database row. lru-cache takes a max option for this, and lazy-layers-cache limits its memory layer by entries and optionally by bytes (the default is 1,000 entries).
What is the best cache for Node.js?
There is no single best cache, only the one that matches your deployment:
- One process, small data: a
Mapwith a TTL, orlru-cachewhen it needs a size limit. - A shared cache with a plain key-value API:
keyvorcache-managerwith a Redis store. - Reads that are hot and many servers: memory in front of Redis, so most reads never leave the process, and deletes that reach every server.
Choose the simplest row that covers your case, and move up when you see a symptom: stale data on another server, a database hit by a stampede, or Redis latency on hot keys.
Where a hand-written cache breaks
Every library above is a better version of the Map, and some problems stay when you use any one of them alone:
- Other processes still hold the old value. A delete in one worker does not reach another's memory.
- Many callers miss together. When a popular key expires, each request loads it. See cache stampede.
- Redis is a hop away. Redis alone costs a round trip on every read, even for a hot key.
- Redis goes down. If every read goes through it, a Redis outage becomes an outage of your app.
The same idea with getOrSet
import { setupCache } from 'lazy-layers-cache'
import type { User } from './db.ts'
export const cache = await setupCache<string, User>({
namespace: 'users-api',
redis: { required: true }, // reads REDIS_URL
ttlMs: 300_000,
})Without Redis, use redis: false to run on memory only.
Express
import express from 'express'
import { cache } from './cache.ts'
import { db } from './db.ts'
const app = express()
app.get('/users/:id', async (req, res) => {
const id = req.params.id
const user = await cache.getOrSet(`user:${id}`, () => db.users.find(id))
if (!user) {
res.status(404).json({ error: 'not found' })
return
}
res.json(user)
})
app.put('/users/:id', express.json(), async (req, res) => {
const id = req.params.id
await db.users.update(id, req.body)
await cache.invalidate(`user:${id}`) // memory on every server and Redis
res.status(204).end()
})
app.listen(3000)NestJS
Nest's own cache module is built on cache-manager. You can also inject a cache like any other dependency. This service creates the cache when the module starts and closes it on shutdown.
import { Injectable, type OnModuleDestroy, type OnModuleInit } from '@nestjs/common'
import { setupCache } from 'lazy-layers-cache'
import { UsersRepository, type User } from './users.repository.ts'
const createUserCache = () =>
setupCache<string, User>({
namespace: 'users-api',
redis: { required: true },
ttlMs: 300_000,
})
@Injectable()
export class UsersService implements OnModuleInit, OnModuleDestroy {
private cache!: Awaited<ReturnType<typeof createUserCache>>
constructor(private readonly users: UsersRepository) {}
async onModuleInit() {
this.cache = await createUserCache()
}
async onModuleDestroy() {
await this.cache.close()
}
findOne(id: string) {
return this.cache.getOrSet(`user:${id}`, () => this.users.find(id))
}
async update(id: string, changes: Partial<User>) {
await this.users.update(id, changes)
await this.cache.invalidate(`user:${id}`)
}
}In both examples the loader only reads data, and a write is followed by invalidate. That keeps the memory layer, Redis and every other server in agreement. For details, see multi-tier caching, single-process setup and the API reference.
Next lesson: database caching with PostgreSQL.
Further reading
- lru-cache for Node.js: its README says at least one of
max,ttlormaxSizeis required to prevent unsafe unbounded storage. - BentoCache: a multi-tier cache for Node.js with an in-memory L1, a distributed L2 and a bus to synchronize instances.
- AWS Builders' Library, Caching challenges and strategies: weighs on-box in-process caches against external caches.
- Redis, client-side caching reference: storing popular replies in application memory, and keeping them correct.
Questions
How do I cache data in Node.js?
Keep a copy of the result where the next request can read it quickly. In one process, a Map with an expiry time is enough. With several processes or servers, store the copy in Redis. On every request, check the cache first, run the slow work only on a miss, and save the result with a TTL.
What is the best cache for Node.js?
It depends on how many processes read the data. For one process, lru-cache or a plain Map is enough. For several processes, use Redis through ioredis, keyv or cache-manager. To keep a memory layer in front of Redis without writing the glue, use a multi-layer library such as lazy-layers-cache.
What is memoization in JavaScript?
Memoization stores a function's result by its arguments, so calling it again with the same arguments returns the saved result. For async functions, store the promise instead of the value. Then two calls made at the same time share one request, instead of both running the slow work.
What is the difference between node-cache and lru-cache?
Both keep data inside one Node.js process. node-cache is a key-value store with per-key TTLs. lru-cache is bounded: it holds a set number of entries and drops the least recently used when full, with optional TTLs and a fetch() method that shares concurrent loads.
Do I need Redis for caching in Node.js?
Not for a single process. A Map or lru-cache is faster than Redis and needs no server. You need a shared store when you run several processes, such as PM2 in cluster mode or many containers, because each process has its own memory and cannot see the others' entries.
How do I add caching to a NestJS app?
NestJS documents a CacheModule and CacheInterceptor in the @nestjs/cache-manager package. You can also inject any cache into a service and call it directly, for example cache.getOrSet(key, loader) inside a method, which keeps the cache logic next to the code that loads the data.
Database caching with PostgreSQL
Database caching for PostgreSQL: what Postgres already caches, why apps still cache query results, and how to do it in Node.js with pg, Prisma and Redis.
Cache stampede and the thundering herd
A cache stampede, or thundering herd, is many requests missing one key at once. See the math and five fixes in TypeScript, from coalescing to TTL jitter.