Caching is one of those things where a small amount of code buys a lot of relief: you stop hammering an API, you stop recomputing the same thing, and you keep the latency down. The catch is that a cache without an expiry turns into a memory leak with extra steps.
Here is a small cache with a time to live (TTL) in plain JavaScript, no dependencies, plus a test you can run yourself.
What we want
-
set(key, value)andget(key) - entries that disappear on their own after a TTL
- an optional per-key TTL for the one value that should live longer
- a way to keep the store from growing forever
- a clock we can control in tests
That last point matters. If the code calls Date.now() directly, every test has to wait in real time or stub globals. Passing a now function in makes the tests instant and deterministic.
The implementation
export function createTtlCache({ ttlMs, now = () => Date.now(), maxEntries = Infinity } = {}) { if (typeof ttlMs !== 'number' || ttlMs <= 0) { throw new TypeError('ttlMs must be a positive number'); } const store = new Map(); // key -> { value, expiresAt } const isExpired = (entry) => entry.expiresAt <= now(); return { set(key, value, customTtlMs = ttlMs) { store.delete(key); // re-insert so insertion order stays honest store.set(key, { value, expiresAt: now() + customTtlMs }); if (store.size > maxEntries) { const oldest = store.keys().next(); if (!oldest.done) store.delete(oldest.value); } return this; }, get(key) { const entry = store.get(key); if (!entry) return undefined; if (isExpired(entry)) { store.delete(key); return undefined; } return entry.value; }, has(key) { return this.get(key) !== undefined; }, delete(key) { return store.delete(key); }, prune() { for (const [key, entry] of store) { if (isExpired(entry)) store.delete(key); } return store.size; }, get size() { this.prune(); return store.size; }, }; } A few decisions worth spelling out:
Expiry is lazy. get checks the timestamp and deletes the entry it just found expired. Nothing runs on a timer, so an idle cache costs nothing. The downside is that expired keys you never read again stay in memory until something prunes them, which is why prune() and maxEntries exist.
The boundary is inclusive. expiresAt <= now() means a value with a 1000 ms TTL is gone at exactly 1000 ms, not at 1001. Pick one and be consistent, because tests will pin it.
maxEntries is a guard rail, not an eviction policy. It drops the oldest inserted key when the map grows past the limit. That is fine for a small process-level cache and wrong for anything where some keys matter more than others. If you need real LRU behaviour, you need a different data structure (a Map plus a doubly linked list, or a library).
store.delete(key) before set keeps insertion order meaningful: re-setting a key moves it to the end, so the "oldest" eviction does not throw away something you just wrote.
The test
import assert from 'node:assert/strict'; import { createTtlCache } from './ttl-cache.mjs'; let clock = 0; const now = () => clock; const cache = createTtlCache({ ttlMs: 1000, now }); // basic set/get cache.set('a', 1); assert.equal(cache.get('a'), 1); // still alive one millisecond before expiry clock = 999; assert.equal(cache.get('a'), 1); // expires exactly at ttl (boundary is inclusive) clock = 1000; assert.equal(cache.get('a'), undefined); assert.equal(cache.has('a'), false); // per-key ttl overrides the default cache.set('b', 2, 5000); clock = 2000; assert.equal(cache.get('b'), 2); // delete removes immediately cache.delete('b'); assert.equal(cache.get('b'), undefined); // prune drops expired entries and leaves live ones clock = 0; cache.set('c', 3, 10); cache.set('d', 4, 1000); clock = 20; assert.equal(cache.size, 1); // maxEntries evicts the oldest inserted key const small = createTtlCache({ ttlMs: 10000, now, maxEntries: 2 }); small.set('x', 1); small.set('y', 2); small.set('z', 3); assert.equal(small.get('x'), undefined); assert.equal(small.get('y'), 2); assert.equal(small.get('z'), 3); // re-setting an existing key refreshes its expiry clock = 0; cache.set('e', 5, 100); clock = 60; cache.set('e', 6, 100); clock = 120; assert.equal(cache.get('e'), 6); clock = 170; assert.equal(cache.get('e'), undefined); console.log('all assertions passed'); Save the first block as ttl-cache.mjs and the second as ttl-cache.test.mjs, then run node ttl-cache.test.mjs. It prints all assertions passed in a few milliseconds, because the clock is a number we move by hand.
Where this is useful
- A short-lived cache in front of an HTTP call, so two components asking for the same thing in the same second produce one request.
- Memoising an expensive pure function whose inputs change slowly.
- Session or token lookups where you already know how long the thing is valid.
Where it is not enough
- Multiple processes. Each copy of the cache has its own view. For anything shared, you want Redis or similar.
- Big values. Everything lives in the heap. A cache of 200 MB of JSON is a way to find out what your memory limit is at the worst possible moment.
- Correctness-critical data. A cache that can serve a stale value is a decision about what happens when it does. For prices, balances, permissions, and anything a user acts on, either keep the TTL very short or skip the cache.
The whole thing is about thirty lines. The useful part is not the code, it is deciding what a stale value would cost you if it showed up.