The fastest database query is the one you do not run. Caching means keeping a copy of an answer close at hand, so the next person who asks the same question gets it at once. A product page that 10,000 people view an hour does not need 10,000 database queries, only a few. Caching is also famous for being hard, because a copy can become wrong. This lesson teaches the one pattern that you will use most, and the rules for keeping it honest.
The cache-aside pattern
*Cache-aside* works in three steps. First, look in the cache. If the answer is there, a hit, return it. If not, a miss, load it from the database, store it in the cache with a lifetime, and return it. Your code controls the cache, and the cache never needs to know about the database.
// Cache-aside: look in the cache first; on a miss, load from the slow source and store the answer.
// The cache is behind a tiny interface, so tests use memory and production uses Redis.
export function memoryCache({ now = () => Date.now() } = {}) {
const items = new Map();
return {
async get(key) {
const item = items.get(key);
if (!item) return null;
if (item.expiresAt <= now()) { items.delete(key); return null; }
return item.value;
},
async set(key, value, ttlSeconds) { items.set(key, { value, expiresAt: now() + ttlSeconds * 1000 }); },
async del(key) { items.delete(key); },
};
}
// The same interface on top of Redis. NOT run in this course (it needs a Redis server): npm install ioredis
export function redisCache(redis) {
return {
async get(key) { const text = await redis.get(key); return text ? JSON.parse(text) : null; },
async set(key, value, ttlSeconds) { await redis.set(key, JSON.stringify(value), 'EX', ttlSeconds); },
async del(key) { await redis.del(key); },
};
}
export function cachedProductService({ cache, loadFromDb, ttlSeconds = 60 }) {
const stats = { hits: 0, misses: 0 };
return {
stats,
async get(id) {
const key = `product:${id}`;
const cached = await cache.get(key);
if (cached) { stats.hits += 1; return cached; }
stats.misses += 1;
const product = await loadFromDb(id);
if (product) await cache.set(key, product, ttlSeconds);
return product;
},
// When data changes, remove the old copy. This is the hard part of caching.
async invalidate(id) { await cache.del(`product:${id}`); },
};
}
The file has two caches with the same three methods, get, set and del. memoryCache keeps values in a Map inside your process and can run anywhere. redisCache wraps a Redis client. Because both offer the same methods, cachedProductService works with either, which is dependency injection again. The lifetime, time to live (TTL), is in seconds, and after that the entry is considered expired and the next request refills it. The memory cache takes now as a parameter so that a test can move the clock instead of waiting.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Save the code as
cache.js. The test uses only Node. For the Redis version you also need a Redis server andnpm install redis.
import test from 'node:test';
import assert from 'node:assert/strict';
import { memoryCache, cachedProductService } from './ca35-cache.js';
test('hit, miss, expiry and invalidation', async () => {
let time = 0;
let dbCalls = 0;
const service = cachedProductService({
cache: memoryCache({ now: () => time }),
loadFromDb: async (id) => { dbCalls += 1; return { id, name: 'Lamp' }; },
ttlSeconds: 60,
});
await service.get(1);
await service.get(1);
assert.deepEqual(service.stats, { hits: 1, misses: 1 });
assert.equal(dbCalls, 1);
time = 61_000; // the entry has expired
await service.get(1);
assert.equal(dbCalls, 2);
await service.invalidate(1);
await service.get(1);
assert.equal(dbCalls, 3);
});
ok 1 - hit, miss, expiry and invalidation
The test checks four things: the first read is a miss and goes to the database, the second is a hit and does not, the value expires after the TTL, and after the product is changed, its cache entry is deleted so that the next read loads the new value.
Memory cache or Redis?
A cache inside the process is the fastest and simplest, and it is fine for a single server and for data that can be a little different on each copy. But each copy of a server has its own cache, the cache disappears on restart, and deleting an entry on one copy does not delete it on the others. Redis is a separate, very fast, in-memory data store that all your copies share. It is also used for sessions, rate limiting counters, queues and real-time messaging, so it earns its place in most mid-sized systems.
The hard part: invalidation
- Use short TTLs for data that is allowed to be slightly old, such as a product list. Even 30 seconds removes most of the load.
- Delete on change. When you update or delete a record, delete its cache key at once, as the test does.
- Cache only what is safe to share. Never cache one user's private data under a key that another user could hit.
- Beware of a stampede. When a popular key expires, many requests may miss together and hit the database at the same moment. Short random variation in TTL, or a lock so that only one request refills it, reduces this.
- Measure. Count hits and misses. A cache with a low hit rate is only extra complexity.
Your task
- Add a
stats()function to the memory cache that returns hits and misses. - Cache the result of a list route for 30 seconds, and clear it when a product is added.
- Add a little random jitter to each TTL.
How to check it worked
- The second read does not call the database.
- An update removes the old value from the cache.
- You can explain why two servers cannot share a memory cache.