Caching
suggest changeA cache keeps the result of slow work (a database query, an HTTP call, a big computation, reading a file) so the next request for the same thing can be answered from memory.
Node.js programs cache at several levels:
| Where | Typical tool | Shared between processes | Survives restart |
|---|---|---|---|
| a single function | memoization with a Map |
no | no |
| in-process cache | Map, WeakMap, the lru-cache package |
no | no |
| external cache | Redis or Valkey via the redis package |
yes | yes (depending on config) |
| HTTP | Cache-Control and ETag headers, read by browsers and CDNs |
n/a | n/a |
Every cache has to answer the same questions: what is the key, when does an entry become invalid, and how much memory is it allowed to use. An in-memory cache that never removes anything is a memory leak.
The examples were run with Node.js 24, lru-cache 11.5, redis 6.3 and express 5.3, in a project whose package.json has "type": "module".
Memoizing a function
The simplest cache wraps a function and remembers its results by argument:
function memoize(fn) {
const cache = new Map();
return function (arg) {
if (cache.has(arg)) return cache.get(arg);
const result = fn(arg);
cache.set(arg, result);
return result;
};
}
function slowSquare(n) {
const end = Date.now() + 200; // pretend this is expensive
while (Date.now() < end) {}
return n * n;
}
const fastSquare = memoize(slowSquare);
for (const n of [4, 4, 5, 4]) {
const start = performance.now();
const value = fastSquare(n);
console.log(`square(${n}) = ${value} in ${(performance.now() - start).toFixed(0)} ms`);
}
square(4) = 16 in 200 ms
square(4) = 16 in 0 ms
square(5) = 25 in 200 ms
square(4) = 16 in 0 ms
cache.has() followed by cache.get() is used instead of just checking cache.get(arg) !== undefined, so a function that legitimately returns undefined is cached too.
Memoization also turns some exponential algorithms into linear ones. The naive recursive Fibonacci makes over a billion calls for fib(45); with a cache, each value is computed once:
const cache = new Map();
let calls = 0;
function fib(n) {
calls++;
if (n < 2) return n;
if (cache.has(n)) return cache.get(n);
const result = fib(n - 1) + fib(n - 2);
cache.set(n, result);
return result;
}
console.log(fib(70), 'calls:', calls);
calls = 0;
console.log(fib(71), 'calls:', calls);
190392490709135 calls: 139
308061521170129 calls: 3
Only memoize pure functions: ones whose result depends only on their arguments and that have no side effects. Memoizing something like getCurrentUser() or Math.random() gives wrong answers.
Cache keys for multiple arguments
A Map compares keys with === (strictly, SameValueZero). That works for strings and numbers, but objects are compared by identity: two objects with the same content are different keys. For several arguments, or for plain-object arguments, build a string key:
function memoize(fn, keyFn = (...args) => JSON.stringify(args)) {
const cache = new Map();
return (...args) => {
const key = keyFn(...args);
if (cache.has(key)) return cache.get(key);
const result = fn(...args);
cache.set(key, result);
return result;
};
}
let computed = 0;
const distance = memoize((x1, y1, x2, y2) => {
computed++;
return Math.hypot(x2 - x1, y2 - y1);
});
console.log(distance(0, 0, 3, 4));
console.log(distance(0, 0, 3, 4));
console.log(distance(1, 1, 4, 5));
console.log('computed', computed, 'times');
// objects as Map keys are compared by identity, not by content
const m = new Map();
m.set({ id: 1 }, 'a');
console.log(m.get({ id: 1 }));
5
5
5
computed 2 times
undefined
JSON.stringify is convenient but has traps: {a: 1, b: 2} and {b: 2, a: 1} produce different keys, and undefined, functions, Map and Set don't serialize the way you might expect. When you know the arguments, a hand-written keyFn such as (user, page) => ${user.id}:${page}`` is faster and more precise.
The memoize functions above never forget anything. That's fine when the set of possible arguments is small, but with arbitrary input (user IDs, URLs, search queries) the Map grows without limit. The sections below add expiration and size limits.
Caching promises
For async functions, cache the promise rather than the resolved value. If you only store the value after await, ten requests arriving at the same moment all miss the cache and all start the slow operation. Storing the promise immediately makes them share one call:
let requests = 0;
async function fetchUser(id) {
requests++;
await new Promise((r) => setTimeout(r, 100)); // simulated network call
if (id < 0) throw new Error(`no user ${id}`);
return { id, name: `user${id}` };
}
const userCache = new Map();
function getUser(id) {
let promise = userCache.get(id);
if (!promise) {
promise = fetchUser(id);
userCache.set(id, promise);
// don't keep failures: the next call should try again
promise.catch(() => userCache.delete(id));
}
return promise;
}
// 3 concurrent calls for the same user share one request
const users = await Promise.all([getUser(1), getUser(1), getUser(1)]);
console.log(users.map((u) => u.name), 'requests:', requests);
await getUser(1);
console.log('after another call, requests:', requests);
for (let i = 0; i < 2; i++) {
try {
await getUser(-1);
} catch (err) {
console.log(err.message, '| cached:', userCache.has(-1), '| requests:', requests);
}
}
[ 'user1', 'user1', 'user1' ] requests: 1
after another call, requests: 1
no user -1 | cached: false | requests: 2
no user -1 | cached: false | requests: 3
Two details matter:
- A rejected promise must be removed, otherwise one network glitch is cached forever. The
.catch()handler does that; it also marks the rejection as handled for that branch, while the caller still gets the error from the original promise. getUseris notasync. Anasyncfunction would wrap the result in a new promise on every call, which is harmless here but unnecessary.
Deduplicating concurrent requests like this also protects against a cache stampede: when a popular entry expires, hundreds of requests would otherwise hit the database at once to rebuild it.
Expiring entries (TTL)
Most cached data goes stale: exchange rates change, users edit their profiles. A time-to-live (TTL) says how long an entry may be used. The simplest correct implementation stores an expiry time and checks it on read, plus an occasional sweep that removes entries nobody reads again:
import { setTimeout as sleep } from 'node:timers/promises';
class TTLCache {
#entries = new Map();
#ttl;
constructor({ ttl, sweepInterval = 60_000 }) {
this.#ttl = ttl;
// remove expired entries that nobody asks for again;
// unref() so the timer doesn't keep the process alive
setInterval(() => this.prune(), sweepInterval).unref();
}
get(key) {
const entry = this.#entries.get(key);
if (!entry) return undefined;
if (entry.expires <= Date.now()) {
this.#entries.delete(key);
return undefined;
}
return entry.value;
}
set(key, value, ttl = this.#ttl) {
this.#entries.set(key, { value, expires: Date.now() + ttl });
}
delete(key) {
return this.#entries.delete(key);
}
prune() {
const now = Date.now();
for (const [key, entry] of this.#entries) {
if (entry.expires <= now) this.#entries.delete(key);
}
}
get size() {
return this.#entries.size;
}
}
const cache = new TTLCache({ ttl: 100 });
cache.set('rate:EUR', 1.08);
cache.set('rate:GBP', 1.27, 300); // custom TTL for one entry
console.log(cache.get('rate:EUR'), cache.get('rate:GBP'));
await sleep(150);
console.log(cache.get('rate:EUR'), cache.get('rate:GBP'), 'size:', cache.size);
await sleep(200);
cache.prune();
console.log(cache.get('rate:GBP'), 'size:', cache.size);
1.08 1.27
undefined 1.27 size: 1
undefined size: 0
Avoid the tempting alternative of calling setTimeout(() => map.delete(key), ttl) for every entry. It creates one timer per entry, and when a key is overwritten the old timer still fires and deletes the new value.
Limiting size: LRU eviction
A TTL bounds how old data is, not how much memory the cache uses. The usual policy for a size limit is LRU (least recently used): when the cache is full, drop the entry that was used longest ago.
A JavaScript Map iterates keys in insertion order, which makes a basic LRU cache short. On every access, delete the key and insert it again so it moves to the end; the first key is then always the least recently used:
class LRUCache {
#map = new Map();
#max;
constructor(max) {
this.#max = max;
}
get(key) {
if (!this.#map.has(key)) return undefined;
const value = this.#map.get(key);
// move to the end: Map iterates in insertion order
this.#map.delete(key);
this.#map.set(key, value);
return value;
}
set(key, value) {
this.#map.delete(key);
this.#map.set(key, value);
if (this.#map.size > this.#max) {
// the first key is the least recently used one
const oldest = this.#map.keys().next().value;
this.#map.delete(oldest);
}
}
keys() {
return [...this.#map.keys()];
}
}
const lru = new LRUCache(3);
lru.set('a', 1);
lru.set('b', 2);
lru.set('c', 3);
console.log(lru.keys());
lru.get('a'); // 'a' is now the most recently used
lru.set('d', 4); // evicts 'b'
console.log(lru.keys());
console.log(lru.get('b'));
[ 'a', 'b', 'c' ]
[ 'c', 'a', 'd' ]
undefined
The lru-cache package
For production code, use lru-cache, which is what npm itself and many popular packages use. It combines LRU eviction, TTLs, size accounting and promise deduplication, and it's carefully optimized.
npm install lru-cache
import { LRUCache } from 'lru-cache';
import { setTimeout as sleep } from 'node:timers/promises';
const cache = new LRUCache({
max: 500, // at most 500 entries
ttl: 1000 * 60 * 5, // each entry lives 5 minutes
dispose: (value, key, reason) => console.log(`dropped ${key} (${reason})`),
});
cache.set('a', { n: 1 });
cache.set('b', { n: 2 });
console.log(cache.get('a'), cache.has('b'), cache.size);
cache.set('a', { n: 10 }); // replacing an entry
cache.delete('b');
// a per-entry TTL, and how long an entry has left
cache.set('short', 'x', { ttl: 50 });
console.log('remaining ms:', Math.round(cache.getRemainingTTL('short')));
await sleep(80);
console.log(cache.get('short'));
{ n: 1 } true 2
dropped a (set)
dropped b (delete)
remaining ms: 63
dropped short (expire)
undefined
You must give at least one of max, maxSize or ttl, so the cache can't grow forever by accident. dispose is called whenever an entry leaves the cache, with the reason (evict, set, delete, expire, fetch); use it to close file handles or connections stored as values.
Expired entries are not removed by a timer; like the TTLCache above, they are dropped when you read them or when they are evicted. Add ttlAutopurge: true if you need them actively removed.
Limiting by bytes
When values vary a lot in size (file contents, rendered pages), limit total size instead of entry count. sizeCalculation returns the size of each value, in whatever unit you like:
import { LRUCache } from 'lru-cache';
// cache file contents, limited by total bytes instead of entry count
const files = new LRUCache({
maxSize: 1_000_000, // about 1 MB in total
maxEntrySize: 250_000, // never cache a single item above 250 KB
sizeCalculation: (buf) => buf.length,
});
files.set('a.txt', Buffer.alloc(100_000));
files.set('b.txt', Buffer.alloc(200_000));
console.log(files.size, 'entries,', files.calculatedSize, 'bytes');
files.set('big.bin', Buffer.alloc(300_000)); // too big, silently not stored
console.log('big.bin cached:', files.has('big.bin'));
for (const name of ['c.txt', 'd.txt', 'e.txt', 'f.txt']) {
files.set(name, Buffer.alloc(200_000));
}
// 1.1 MB would not fit, so the least recently used a.txt was evicted
console.log([...files.keys()], files.calculatedSize, 'bytes');
2 entries, 300000 bytes
big.bin cached: false
[ 'f.txt', 'e.txt', 'd.txt', 'c.txt', 'b.txt' ] 1000000 bytes
Note that keys() lists entries from most to least recently used.
fetch(): loading on a miss
fetchMethod turns the cache into a loader: cache.fetch(key) returns the cached value, or calls fetchMethod on a miss and stores the result. Concurrent fetches for the same key share one call, exactly like the promise cache above. With allowStale: true, an expired entry is returned immediately while a fresh value loads in the background (stale-while-revalidate), so callers never wait for a refresh:
import { LRUCache } from 'lru-cache';
import { setTimeout as sleep } from 'node:timers/promises';
let version = 0;
async function loadPrice(symbol) {
await sleep(100); // pretend this is a slow API
version++;
console.log(` loaded ${symbol} v${version}`);
return { symbol, price: 100 + version };
}
const prices = new LRUCache({
max: 1000,
ttl: 200,
allowStale: true, // return the old value while a new one loads
fetchMethod: async (symbol, staleValue, { signal }) => loadPrice(symbol),
});
// concurrent fetches for one key make a single call
const [a, b] = await Promise.all([prices.fetch('ACME'), prices.fetch('ACME')]);
console.log(a, a === b);
console.log(await prices.fetch('ACME')); // fresh: from cache
await sleep(250); // now the entry is stale
console.log(await prices.fetch('ACME')); // stale value, refresh started
await sleep(150);
console.log(await prices.fetch('ACME')); // refreshed value
loaded ACME v1
{ symbol: 'ACME', price: 101 } true
{ symbol: 'ACME', price: 101 }
{ symbol: 'ACME', price: 101 }
loaded ACME v2
{ symbol: 'ACME', price: 102 }
signal is an AbortSignal that fires if the entry is deleted or replaced while loading; pass it to fetch() or your database driver to cancel work whose result would be thrown away. If fetchMethod throws, the error propagates to the caller and nothing is cached.
WeakMap: caching data about objects
Sometimes the key is an object and the cached value is derived from it. A WeakMap holds its keys weakly: when nothing else references the key object, both the key and its cached value can be garbage collected. You get a cache with no eviction logic and no leaks:
const statsCache = new WeakMap();
function getStats(order) {
let stats = statsCache.get(order);
if (!stats) {
console.log(' computing stats for order', order.id);
const total = order.items.reduce((sum, it) => sum + it.price * it.qty, 0);
const count = order.items.reduce((sum, it) => sum + it.qty, 0);
stats = { total, count };
statsCache.set(order, stats);
}
return stats;
}
let order = {
id: 42,
items: [
{ price: 5, qty: 2 },
{ price: 20, qty: 1 },
],
};
console.log(getStats(order));
console.log(getStats(order));
order = null; // the order and its cached stats can now be garbage collected
computing stats for order 42
{ total: 30, count: 3 }
{ total: 30, count: 3 }
WeakMap keys must be objects (or non-registered symbols), and a WeakMap can't be iterated or sized. It also doesn't notice if the object is mutated: if order.items changes, the cached stats are wrong. Use it for objects that are treated as immutable, such as parsed configuration, request objects or AST nodes. See V8 memory and garbage collection for how the garbage collector decides what is unreachable.
Shared cache with Redis
An in-process cache has limits: each process in a cluster or each container has its own copy, the copies can disagree, and everything is lost on restart. An external cache server such as Redis (or its open source fork Valkey) is shared by all processes.
The common pattern is cache-aside: read from the cache, on a miss load from the database and store the result with an expiration. On writes, delete the cached key so the next read reloads it:
import { createClient } from 'redis';
import { setTimeout as sleep } from 'node:timers/promises';
const redis = await createClient({ url: process.env.REDIS_URL }).connect();
let dbQueries = 0;
async function queryProduct(id) {
dbQueries++;
await sleep(50); // pretend this is a slow database query
return { id, name: `Product ${id}`, price: 9.99 };
}
async function getProduct(id) {
const key = `product:${id}`;
const cached = await redis.get(key);
if (cached !== null) return JSON.parse(cached);
const product = await queryProduct(id);
// store as JSON, expire after 60 seconds
await redis.set(key, JSON.stringify(product), { expiration: { type: 'EX', value: 60 } });
return product;
}
async function updateProductPrice(id, price) {
// ... UPDATE products SET price = ... in the database ...
await redis.del(`product:${id}`); // invalidate, next read reloads it
}
console.log(await getProduct(7));
console.log(await getProduct(7));
console.log('db queries:', dbQueries, '| ttl:', await redis.ttl('product:7'));
await updateProductPrice(7, 12.5);
await getProduct(7);
console.log('db queries after update:', dbQueries);
await redis.close();
{ id: 7, name: 'Product 7', price: 9.99 }
{ id: 7, name: 'Product 7', price: 9.99 }
db queries: 1 | ttl: 60
db queries after update: 2
Run it with REDIS_URL=redis://localhost:6379 node redis-cache.js. Redis stores strings, so values go through JSON.stringify/JSON.parse; note that Date objects come back as strings. Deleting on write (rather than updating the cached value) avoids races where two writers update the database and the cache in different orders. The TTL is a safety net: even if an invalidation is missed, stale data disappears within a minute.
Older code uses redis.set(key, value, { EX: 60 }) or redis.setEx(key, 60, value), which also still work. For connecting and other commands see NodeJS with Redis.
A request to Redis takes a network round trip (typically 0.1 to 1 ms), so for very hot keys it's common to put a small, short-lived lru-cache in front of Redis.
HTTP caching
The fastest request is one the server never sees. HTTP caching lets browsers, proxies and CDNs reuse responses, controlled by headers:
| Header | Meaning |
|---|---|
Cache-Control: max-age=60 |
the response may be reused for 60 seconds without asking the server |
Cache-Control: s-maxage=300 |
like max-age, but only for shared caches (CDNs, proxies) |
Cache-Control: public / private |
may be stored by shared caches / only by the user's browser |
Cache-Control: no-cache |
may be stored, but must be revalidated before every use |
Cache-Control: no-store |
must not be stored at all |
Cache-Control: immutable |
the content will never change; don't revalidate even on reload |
ETag: "abc" |
a version identifier for the response |
If-None-Match: "abc" |
sent by the client: "I have version abc"; the server answers 304 Not Modified with no body if it's still current |
Here is revalidation with ETags in a plain node:http server. The ETag is a hash of the body; when the client sends it back and nothing has changed, the server responds with an empty 304:
import { createServer } from 'node:http';
import { createHash } from 'node:crypto';
const body = JSON.stringify({ products: ['apple', 'pear', 'plum'] });
const etag = `"${createHash('sha1').update(body).digest('base64url')}"`;
const server = createServer((req, res) => {
res.setHeader('Cache-Control', 'public, max-age=60');
res.setHeader('ETag', etag);
if (req.headers['if-none-match'] === etag) {
res.statusCode = 304; // Not Modified: no body
res.end();
return;
}
res.setHeader('Content-Type', 'application/json');
res.end(body);
});
server.listen(0, async () => {
const url = `http://localhost:${server.address().port}/products`;
const first = await fetch(url);
console.log(first.status, first.headers.get('etag'), first.headers.get('cache-control'));
console.log(await first.text());
// a client that kept the ETag asks "has it changed?"
const second = await fetch(url, { headers: { 'If-None-Match': first.headers.get('etag') } });
console.log(second.status, JSON.stringify(await second.text()));
server.close();
});
200 "WExHFndRpjq7NBJTAKpRXz1oHUM" public, max-age=60
{"products":["apple","pear","plum"]}
304 ""
A real implementation should also handle a list of ETags in If-None-Match and the * value; Express does this for you.
Caching in Express
Express generates a weak ETag for every res.send()/res.json() response and answers 304 automatically. express.static sets ETag and Last-Modified and accepts a maxAge. You only need to choose Cache-Control per route:
import express from 'express';
import { get } from 'node:http';
const app = express();
// fingerprinted file names never change content: cache them for a year
app.use('/static', express.static('public', { maxAge: '1y', immutable: true }));
app.get('/api/news', (req, res) => {
// shared caches (CDN) may keep it 5 minutes, browsers must revalidate
res.set('Cache-Control', 'public, max-age=0, s-maxage=300');
res.json({ headline: 'Node.js 24 released' });
});
app.get('/api/me', (req, res) => {
res.set('Cache-Control', 'private, no-store'); // never cache personal data
res.json({ user: 'alice' });
});
// fetch() adds "Cache-Control: no-cache" to conditional requests, which makes
// Express (correctly) skip the 304, so revalidate with http.get() like a browser
function statusOf(url, headers) {
return new Promise((resolve, reject) => {
get(url, { headers }, (res) => {
res.resume();
resolve(res.statusCode);
}).on('error', reject);
});
}
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const css = await fetch(`${base}/static/app.3f9a2c.css`);
console.log('css: ', css.status, css.headers.get('cache-control'));
const news = await fetch(`${base}/api/news`);
const etag = news.headers.get('etag');
console.log('news:', news.status, news.headers.get('cache-control'), etag);
console.log('news:', await statusOf(`${base}/api/news`, { 'If-None-Match': etag }));
const me = await fetch(`${base}/api/me`);
console.log('me: ', me.status, me.headers.get('cache-control'));
server.close();
server.closeAllConnections();
});
css: 200 public, max-age=31536000, immutable
news: 200 public, max-age=0, s-maxage=300 W/"22-dJNj/LrUKFGN7BiymhVezd3CO0g"
news: 304
me: 200 private, no-store
The gotcha in the comment is real: Node's built-in fetch() follows the Fetch standard and adds Cache-Control: no-cache and Pragma: no-cache when you set If-None-Match yourself, and Express treats no-cache as "send the full response". Keep that in mind when testing caching with fetch().
Even when the server builds the full response before sending a 304, revalidation saves bandwidth. To also save the work, cache the response data on the server with one of the in-memory caches above. Fingerprinted file names (app.3f9a2c.css, produced by bundlers) are what make immutable safe: a new version gets a new URL.
Choosing what and how to cache
- Measure first. Cache operations that are slow and frequent; caching a 1 ms lookup adds complexity for nothing. See Profiling.
- Always bound the cache:
max,maxSizeor a TTL. Watch for unboundedMaps used as caches; they're one of the most common causes of memory leaks in Node.js services. - Include everything that affects the result in the key: user ID, language, query parameters, API version. A key that's too broad shows one user's data to another.
- Prefer deleting cached entries on writes over updating them, and keep a TTL as a safety net.
- Deduplicate concurrent loads (promise cache or
lru-cache'sfetch()) to avoid stampedes when a hot entry expires. - Add a little randomness to TTLs (for example
ttl: 60_000 + Math.random() * 10_000) when many entries are created at once, so they don't all expire in the same second. - Don't hand out cached objects that callers might mutate; one caller's change would leak into everyone's results. Return copies (
structuredClone(value)) or freeze them (Object.freeze). - In-process caches are per process. With several processes or servers, use a shared cache like Redis, or accept that processes may briefly see different data.