cachefor
v1.2.0
Published
Tiny in-memory cache with human-readable TTLs: cachefor('5m'). LRU max, async getOrSet with in-flight dedup, stale-while-revalidate, memoize, eviction callbacks, no timers. Zero dependencies.
Maintainers
Readme
cachefor
A small in-memory cache where you write the time to live in plain words: cachefor('5m').
cachefor keeps values in memory for a set time, such as 5 minutes, and then forgets them. Use it to cache database calls, API responses or slow functions. The API is small, so you can learn it in a few minutes.
Features
- Readable TTLs (TTL = time to live, how long an entry stays in the cache):
'30s','5m','1h 30m','2 days','forever'or milliseconds. - Typos are TypeScript errors:
'5 minuts'fails at compile time. - Shared loads:
getOrSet()runs the loader once, even when many calls ask for the same missing key at the same time. Failed loads are never cached. - Stale-while-revalidate: return the old value right away and load a new one in the background.
- Size limit and sliding expiration:
maxremoves the least recently used entry;slidingrestarts the TTL on each read. onEvictcallback tells you why each entry left the cache.memoize()caches the results of sync and async functions.- No timers by default, so nothing keeps your process or test runner open.
- Zero dependencies, about 2.5 KB gzipped, ESM and CommonJS, TypeScript types included.
Installation
npm install cacheforpnpm add cachefor
yarn add cachefor
bun add cacheforQuick start
import cachefor, { memoize } from 'cachefor'
// Entries live for 5 minutes. The cache holds at most 1000 entries.
const users = cachefor('5m', { max: 1000 })
users.set('ann', { name: 'Ann' })
users.get('ann') // => { name: 'Ann' }
users.set('bob', { name: 'Bob' }, '30s') // this entry lives 30 seconds only
users.get('nobody') // => undefined
// Load a value when it is missing. Calls at the same time share one load.
const cy = await users.getOrSet('cy', async (id) => ({ name: 'Cy' }))
cy // => { name: 'Cy' }
// Cache the results of a function for 1 hour
const double = memoize((n) => n * 2, '1h')
double(21) // => 42With CommonJS, use const cachefor = require('cachefor') and const { memoize } = require('cachefor').
Table of contents
Usage
Write TTLs in plain words
You can pass a TTL as a number of milliseconds or as a string. This works everywhere a TTL is accepted.
cachefor(5000) // 5 seconds
cachefor('30s')
cachefor('5m') // 5 minutes
cachefor('1h 30m') // also '1h30m', '1 hour, 30 minutes', '1 hour and 30 minutes'
cachefor('1.5h')
cachefor('2 days')
cachefor('1w')
cachefor('forever') // same as Infinity
cachefor(process.env.CACHE_TTL ?? '10m')Units are not case-sensitive:
| Unit | Spellings |
|---|---|
| Milliseconds | ms, msec, msecs, millisecond, milliseconds |
| Seconds | s, sec, secs, second, seconds |
| Minutes | m, min, mins, minute, minutes |
| Hours | h, hr, hrs, hour, hours |
| Days | d, day, days |
| Weeks | w, wk, wks, week, weeks |
A string with only a number, like '1500', means milliseconds. Months and years are not accepted, because their length changes.
An invalid TTL throws a TtlError when you create the cache. So a bad config value fails at startup, not later when the first entry expires.
0 means "do not store". set(key, value, 0) removes any old value and stores nothing. cachefor(0) gives you shared loads with no caching at all.
Load a value when it is missing
getOrSet(key, loader) returns the cached value. If there is none, it calls loader, caches the result and returns it.
const cache = cachefor('10m')
app.get('/users/:id', async (req, res) => {
const user = await cache.getOrSet(req.params.id, (id) => db.users.find(id))
res.json(user)
})- Calls at the same time share one load. If 100 requests ask for the same missing key, the loader runs once. This stops a "cache stampede" (many requests loading the same thing at once).
- Errors are not cached. If the loader throws or rejects, every waiting caller gets the error and nothing is stored. The next call tries again.
getOrSet()always returns a promise. The loader can be sync or async.- If you call
delete(),clear()orset()on the key while a load is running, the result of that load is not cached. Callers still receive it. This makes cache invalidation safe: an older read that finishes late cannot overwrite your change.
For sync work, getOrSetSync(key, loader, ttl?) returns the value directly.
Set the TTL from the loaded value
Pass a TTL as the third argument, or set it inside the loader once you know it:
await cache.getOrSet(key, load, '30s')
await tokens.getOrSet('github', async (key, ctx) => {
const { token, expires_in } = await refreshToken()
ctx.setTtl((expires_in - 60) * 1000) // expire one minute early
return token
})Return old values while a new one loads
Stale-while-revalidate means: when an entry has expired, return the old ("stale") value right away and load a fresh one in the background.
const prices = cachefor('1m', { staleWhileRevalidate: '5m' })
await prices.getOrSet('BTC', fetchPrice)- For up to 5 minutes after an entry expires,
getOrSet(),wrap()andmemoize()return the stale value at once. They refresh it in the background, once. - If the refresh fails, the stale value is still returned and the next call tries again.
- After the 5 minutes, it is a normal miss.
staleWhileRevalidate: truekeeps stale values until they are replaced.get(),has(),peek(),sizeand iteration never return stale values.- The loader can read the old value in
ctx.stale.
Cache the results of a function
memoize() wraps a function and caches its results:
import { memoize } from 'cachefor'
const getUser = memoize(async (id) => db.users.find(id), { ttl: '5m' })
await getUser(1) // runs the query
await getUser(1) // returns the cached result
const slugify = memoize(expensiveSlugify, { max: 10_000 }) // sync functions work too
const getRates = memoize(fetchRates, '1h') // TTL shorthand
getUser.cache.delete(1) // remove one result
getUser.cache.clear() // remove all results- Async functions get the same features as
getOrSet(): shared loads, no caching of errors, and stale-while-revalidate. - Sync functions return values directly. Async functions always return a promise.
- The memoized function keeps
this,nameandlength.
The cache key is the argument itself when the function takes one primitive argument (1 and '1' are different keys). Otherwise it is JSON.stringify(args). Pass key to build it yourself:
const getOrders = memoize(fetchOrders, {
ttl: '1m',
key: (user, opts) => `${user.id}:${opts.status}`,
})To cache a function in a cache you already have, use cache.wrap(fn, { key, ttl }).
Limit the size and restart the TTL on each read
const sessions = cachefor('30m', {
max: 10_000, // above this, remove the least recently used entry
sliding: true, // each get() restarts the 30 minutes
onEvict(session, id, reason) {
if (reason !== 'replaced') log(`session ${id} ended: ${reason}`)
},
})maxturns the cache into an LRU cache (least recently used). When it is full, the entry that was used longest ago is removed.sliding: trueworks like a session timeout. Each read gives the entry its full TTL again.
Know when entries leave the cache
onEvict(value, key, reason) runs after the cache is updated, once for each value that leaves. Use it to close or release values.
| Reason | When |
|---|---|
| 'expired' | The TTL ran out. Reported when the entry is read or pruned, or when an expired entry is deleted, replaced, evicted or cleared. |
| 'evicted' | Removed as least recently used, because of max. |
| 'deleted' | Removed with delete(key). |
| 'replaced' | set() or a reload stored a different value for the key. Not called if the value is the same. |
| 'cleared' | Removed by clear(). |
If onEvict throws, the cache stays correct and the other callbacks in the same batch still run. The first error is then thrown to the caller.
Remove expired entries on a timer
By default there are no timers. An expired entry is never returned. It is removed (and reported to onEvict) when you get() or has() it, or when you call prune(). So there is nothing to close and no open handles in Jest or Vitest.
If you store many keys that are never read again and want the memory back soon, call cache.prune() yourself, or ask for a timer:
const cache = cachefor('5m', { pruneInterval: '1m' })The timer is unref()'d, so it never keeps Node.js running. It stops by itself when the cache is garbage-collected.
Test with a fake clock
Pass your own clock with now:
let now = 0
const cache = cachefor('5m', { now: () => now })
cache.set('a', 1)
now += 5 * 60_000
cache.get('a') // => undefinedThe default clock is Date.now, so fake timers in Vitest or Jest (vi.useFakeTimers(), vi.advanceTimersByTime()) also work.
Use TypeScript types
cachefor<V, K>() sets the value and key types. TTL string literals are checked at compile time:
cachefor('1h 30m') // OK
cachefor('5 minuts') // compile error
cache.set('a', 1, '10 sec') // OK
cache.set('a', 1, '10 sex') // compile errorValues typed as plain string, such as env vars or config, are accepted and checked at runtime. When you pass type arguments, as in cachefor<User>('5m'), TypeScript cannot check that TTL literal. It is checked at runtime only.
import cachefor, { type Cache, type TTL } from 'cachefor'
interface Config { userCacheTtl: TTL } // number | '5m' | ...
const users: Cache<User, number> = cachefor('5m')API
cachefor(ttl, options?)
function cachefor<V = unknown, K = string>(ttl: TTL, options?: CacheOptions<V, K>): Cache<V, K>Creates a cache. ttl is the default time to live for entries. This is also the default export, and is available as cachefor.cachefor. Throws TtlError for an invalid TTL.
| Option | Type | Default | Description |
|---|---|---|---|
| max | number | Infinity | Maximum number of entries. Above it, the least recently used entry is removed. Must be a positive integer or Infinity, otherwise a RangeError is thrown. |
| sliding | boolean | false | Restart an entry's TTL each time get() or a loader hit reads it. |
| staleWhileRevalidate | TTL \| boolean | off | How long after expiry getOrSet(), wrap() and memoize() may return the old value while loading a new one. true means no limit. |
| onEvict | (value, key, reason) => void | none | Called after an entry leaves the cache. See the reasons. |
| now | () => number | Date.now | Clock in milliseconds, for tests. |
| pruneInterval | TTL | off | Remove expired entries on an unref()'d timer, for example '1m'. Must be between 1 ms and about 24.8 days, otherwise a RangeError is thrown. |
Cache methods
| Method | Returns | Description |
|---|---|---|
| get(key) | V \| undefined | The value, if present and not expired. Marks it as recently used and restarts a sliding TTL. |
| set(key, value, ttl?) | this | Stores a value. ttl overrides the default for this entry. 0 means do not store. Chainable. |
| has(key) | boolean | true if a value exists and has not expired. Does not change the LRU order. |
| peek(key) | V \| undefined | Like get(), but with no side effects. |
| delete(key) | boolean | Removes the key. Returns true if it held a value that had not expired. Also stops a running load from being cached. |
| clear() | void | Removes everything, including running loads. |
| ttl(key) | number \| undefined | Milliseconds left. Infinity if it never expires, undefined if missing or expired. Does not change the TTL. |
| size | number | Number of entries that have not expired. A property, not a method. |
| prune() | number | Removes expired entries now. Returns how many were removed. |
| getOrSet(key, loader, ttl?) | Promise<V> | The cached value, or the result of loader(key, ctx), with shared loads. See Load a value when it is missing. |
| getOrSetSync(key, loader, ttl?) | V | Sync version of getOrSet(). |
| wrap(fn, options?) | function | Caches the results of fn in this cache. See cache.wrap. |
| keys(), values(), entries(), [Symbol.iterator] | iterator | Entries that have not expired. new Map(cache) works. |
Iteration order: with max set, least recently used first. Without max, the order in which keys were last set.
The loader gets ctx as its second argument (type LoadContext<V>):
| Property | Type | Description |
|---|---|---|
| ctx.stale | V \| undefined | The expired value being refreshed, if any. |
| ctx.setTtl(ttl) | (ttl: TTL) => void | Sets the TTL for the value being loaded. |
cache.wrap(fn, options?)
cache.wrap(fn: (...args: A) => R, options?: WrapOptions<A, K>): (...args: A) => RReturns a cached version of fn that stores its results in this cache. Async functions get shared loads and stale-while-revalidate, like getOrSet().
| Option | Type | Default | Description |
|---|---|---|---|
| key | (...args) => K | see below | Cache key for a call. Default: the argument itself for one primitive argument, otherwise JSON.stringify(args). |
| ttl | TTL | the cache's TTL | TTL for the results of this function. |
memoize(fn, ttlOrOptions?)
function memoize<F extends (...args: any[]) => any, K = unknown>(
fn: F,
options?: TTL | MemoizeOptions,
): Memoized<F, K> // F plus a `cache` propertyCaches the results of fn in a new cache. The second argument is a TTL, or an object with every cachefor option plus:
| Option | Type | Default | Description |
|---|---|---|---|
| ttl | TTL | Infinity | How long results are cached. |
| key | (...args) => K | see Cache the results of a function | Cache key for a call. |
The returned function has a cache property (a Cache), for example fn.cache.clear().
parseTtl(ttl)
function parseTtl(ttl: TTL): numberThe TTL parser on its own. Returns milliseconds. Throws TtlError for negative numbers, NaN and unknown units.
import { parseTtl } from 'cachefor'
parseTtl('1h 30m') // => 5400000
parseTtl('2 days') // => 172800000
parseTtl(1500) // => 1500
parseTtl('forever') // => InfinityTtlError
class TtlError extends TypeError {
readonly input: unknown
}Thrown for an invalid TTL. The bad value is in error.input.
import { parseTtl, TtlError } from 'cachefor'
try {
parseTtl('5 minuts')
} catch (error) {
error instanceof TtlError // => true
error.input // => '5 minuts'
}Types
All types are exported:
Cache<V, K>, CacheOptions<V, K>, CacheFor, MemoizeOptions, Memoized<F, K>, LoadContext<V>, WrapOptions, EvictReason, TTL, TtlString, TtlUnit, ShortUnit, CheckTtl<T>, IsValidTtl<T>.
Comparison
| | node-cache | lru-cache | memory-cache | p-memoize | memoizee | cachefor |
|---|---|---|---|---|---|---|
| TTL as '5m' / '1h 30m' | No (seconds) | No (ms) | No (ms) | No | No (ms) | Yes |
| Async loader per call (getOrSet) | No | Partial (one fetchMethod per cache) | No | n/a | n/a | Yes |
| Calls at the same time share one load | No | Yes | No | Yes | Yes (promise: true) | Yes |
| Failed loads not cached | n/a | Yes | n/a | Yes | Yes | Yes |
| Stale-while-revalidate | No | Yes | No | No | Partial (preFetch refreshes before expiry) | Yes |
| LRU limit | No (maxKeys throws when full) | Yes | No | Through a custom cache | Yes | Yes |
| Memoize any function | No | Partial (one memoMethod per cache) | No | Async only | Yes | Yes |
| Background timers | Interval by default | unref()'d; per entry with ttlAutopurge | One setTimeout per entry | n/a | Per entry with maxAge | None by default |
| Stores values as they are (no cloning) | No (clones by default) | Yes | Yes | Yes | Yes | Yes |
| Runtime dependencies | 1 | 0 | 0 | 1 | 8 | 0 |
| CommonJS require() | Yes | Yes | Yes | No (ESM only) | Yes | Yes |
| TypeScript types | Yes | Yes | @types/memory-cache | Yes | @types/memoizee | Yes, built in, TTL literals checked |
n/a: the package has no such feature to compare.
lru-cache has many more options (size-based limits, AbortSignals, and more). Use it if you need them. Use cachefor when you want TTL caching with a small API.
Migrating from other packages
From node-cache
Before:
const cache = new NodeCache({ stdTTL: 300 }) // seconds
cache.set(key, value, 60)
cache.get(key)
cache.del(key)
cache.flushAll()After:
const cache = cachefor('5m') // or 300_000 (ms)
cache.set(key, value, '1m')
cache.get(key)
cache.delete(key)
cache.clear()stdTTL: 0(never expire) iscachefor(Infinity).- Values are not cloned. Do not change objects after you cache them, or clone them yourself.
cache.ttl(key)returns the milliseconds left. It does not change the TTL. Useset(key, value, ttl)for that.on('expired')andon('del')becomeonEvict: (value, key, reason) => ....
From lru-cache
Before:
const cache = new LRUCache({ max: 500, ttl: 1000 * 60 * 5, fetchMethod: (key) => load(key) })
await cache.fetch(key)After:
const cache = cachefor('5m', { max: 500 })
await cache.getOrSet(key, load)| lru-cache | cachefor |
|---|---|
| updateAgeOnGet | sliding |
| allowStale + background fetch | staleWhileRevalidate |
| dispose | onEvict |
| reason 'evict' | 'evicted' |
| reason 'set' | 'replaced' |
| reason 'delete' | 'deleted' |
A cache with no expiry is cachefor(Infinity, { max }).
From memory-cache
cache.put(key, value, ms) becomes cache.set(key, value, ms). There is no global shared cache. Create one with cachefor() and export it from a module.
From p-memoize or memoizee
Before:
pMemoize(fn, { cacheKey })
memoize(fn, { maxAge: 60000, promise: true, max: 100 }) // memoizeeAfter:
memoize(fn, { key })
memoize(fn, { ttl: '1m', max: 100 }) // promises are detected automaticallyClear the cache with fn.cache.clear() or fn.cache.delete(key).
Notes and limitations
- Values are not cloned. If you change a cached object, the cached copy changes too.
- Expired entries are removed lazily (only when touched). Use
prune()orpruneIntervalif memory matters. sizeand iteration scan all entries (O(n)) once any entry can expire. Everything else is O(1).- Months and years are not valid TTL units, because their length changes.
- TTL typos are caught at compile time only for literals. With type arguments like
cachefor<User>('5m'), or withstringvalues, the check runs at runtime. - The cache lives in the memory of one process. Each
cachefor()call creates a separate cache.
Requirements
- Node.js 20 or newer. Also works in Bun, Deno and browsers.
- ESM and CommonJS.
- TypeScript types included.
- Zero dependencies.
License
MIT
