Community JavaScript Snippet

Memoize With TTL and Bounded Cache Size

The official memoize is unbounded and has no TTL, which works in tests and leaks memory in production. This is the version I ship: bounded LRU + per-entry expiry, in 40 lines.

Memoize With TTL and Bounded Cache Size

The official memoize is unbounded and has no TTL, which works in tests and leaks memory in production. This is the version I ship: bounded LRU + per-entry expiry, in 40 lines.

JavaScript
Frontend
3 snippets
memoization
lru-cache
ttl
jordandubois

By @jordandubois

November 27, 2025

·

Updated May 20, 2026

1,094 views

11

4.6 (10)

Two guards do the heavy lifting. The TTL field on each entry handles staleness without a sweep timer, because expiry is checked lazily on read; the entry sits dead until something tries to use it or the LRU evicts it. The LRU bound exploits a trick of Map: iteration order is insertion order, so deleting and re-inserting on a hit moves the entry to the back, making the first key in cache.keys() always the least-recently-used. Real production caches I have shipped use TTL=60s and maxSize=10k as defaults; tune the size to match your service's working set. The default keyOf = JSON.stringify is fine for primitive args; pass a custom keyOf for objects with cycles or non-stable key order.