A high-performance, lightweight LRU (Least Recently Used) cache for JavaScript with O(1) operations and optional TTL support.
What is an LRU Cache?
Think of an LRU cache like a limited-size bookshelf. When you add a new book and the shelf is full, you remove the least recently used book to make room. Every time you read a book, it moves to the front. This pattern is perfect for caching where you want to keep the most frequently accessed items.
The tiny-lru library provides:
O(1) operations for get, set, delete, and has
Optional TTL (Time-To-Live) support for automatic expiration
Zero dependencies - pure JavaScript
100% test coverage - fully tested and reliable
TypeScript support - full type definitions included
~1.6 KB minified and gzipped (compared to ~5.8 KB for lru-cache)
Installation
npm install tiny-lru
Requires Node.js ≥14 or modern browsers with ES Module support.
Quick Start
import { lru } from "tiny-lru";// Create a cache that holds up to 100 itemsconst cache = lru(100);// Store and retrieve datacache.set("user:42", { name: "Alice", score: 1500 });const user = cache.get("user:42"); // { name: "Alice", score: 1500 }// Chain operationscache.set("a", 1).set("b", 2).set("c", 3);// Check what's in the cachecache.has("a"); // truecache.size; // 3cache.keys(); // ['a', 'b', 'c'] (LRU order)
TypeScript
import { LRU } from "tiny-lru";interface User { id: number; name: string;}const cache = new LRU<User>(100);cache.set("user:1", { id: 1, name: "Alice" });const user: User | undefined = cache.get("user:1");
With TTL (Time-to-Live)
Items can automatically expire after a set time:
// Cache that expires after 5 secondsconst sessionCache = lru(100, 5000);sessionCache.set("session:id", { userId: 123 });// After 5 seconds, this returns undefinedsessionCache.get("session:id");
Want TTL to reset when you update an item? Enable resetTtl:
const cache = lru(100, 60000, true); // 1 minute TTL, resets on updatecache.set("key", "value");cache.set("key", "new value"); // TTL resets
When to Use Tiny LRU
Great for:
API response caching
Function memoization
Session storage with expiration
Rate limiting
LLM response caching
Database query result caching
Any scenario where you want to limit memory usage
Not ideal for:
Non-string keys (keys are coerced to strings, so objects and other non-primitives can collide)
Very large caches (consider a database)
API Reference
Factory Function: lru(max?, ttl?, resetTtl?)
Creates a new LRU cache instance with parameter validation.
import { lru } from "tiny-lru";const cache1 = lru(); // 1000 items, no TTLconst cache2 = lru(500); // 500 items, no TTLconst cache3 = lru(100, 30000); // 100 items, 30s TTLconst cache4 = lru(100, 60000, true); // with resetTtl enabled
Parameters:
Name
Type
Default
Description
max
number
1000
Maximum items. 0 = unlimited. Must be >= 0.
ttl
number
0
Time-to-live in milliseconds. 0 = no expiration. Must be >= 0.
resetTTL
boolean
false
Reset TTL when updating existing items via set()
Returns:LRU - New cache instance
Throws:TypeError if parameters are invalid
Class: new LRU(max?, ttl?, resetTtl?)
Creates an LRU cache instance with parameter validation.
import { LRU } from "tiny-lru";const cache = new LRU(100, 5000);
Parameters:
Name
Type
Default
Description
max
number
0
Maximum items. 0 = unlimited.
ttl
number
0
Time-to-live in milliseconds. 0 = no expiration.
resetTTL
boolean
false
Reset TTL when updating via set()
Properties
Property
Type
Description
first
object | null
Least recently used item (node with key, value, prev, next, expiry)
items
object
Internal hash map of key → item nodes
last
object | null
Most recently used item (node with key, value, prev, next, expiry)
max
number
Maximum items allowed
resetTTL
boolean
Whether TTL resets on set() updates
size
number
Current number of items
ttl
number
Time-to-live in milliseconds
Methods
Method
Description
cleanup(fireOnEvict?)
Remove expired items without LRU update. Returns count of removed items. Pass true to fire onEvict for each removed item.
clear()
Remove all items. Returns this for chaining.
delete(key)
Remove an item by key. Returns this for chaining.
entries(keys?)
Get [key, value] pairs. Without keys: LRU order. With keys: input array order.
evict()
Remove the least recently used item. Returns this for chaining.
expiresAt(key)
Get expiration timestamp for a key. Returns `number
forEach(callback, thisArg?)
Iterate over items in LRU order. Returns this for chaining.
get(key)
Retrieve a value. Moves item to most recent. Returns value or undefined.
getMany(keys)
Batch retrieve multiple items. Returns object mapping keys to values (undefined for missing/expired keys).
has(key)
Check if key exists and is not expired. Returns boolean.
hasAll(keys)
Check if ALL keys exist. Returns boolean.
hasAny(keys)
Check if ANY key exists. Returns boolean.
keys()
Get all keys in LRU order (oldest first). Returns any[].
keysByTTL()
Get keys by TTL status. Returns {valid, expired, noTTL}.
onEvict(callback)
Register eviction callback (triggers on evict() or when set() evicts). Returns this for chaining.
peek(key)
Retrieve a value without LRU update or TTL check. Returns value or undefined.
set(key, value)
Store a value. Returns this for chaining.
setWithEvicted(key, value)
Store value, return evicted item if full. Returns `{key, value, expiry}
sizeByTTL()
Get counts by TTL status. Returns {valid, expired, noTTL}.
stats()
Get cache statistics. Returns {hits, misses, sets, deletes, evictions}.
toJSON()
Serialize cache to JSON format. Returns array of items.
values(keys?)
Get all values, or values for specific keys. Returns array of values.
valuesByTTL()
Get values by TTL status. Returns {valid, expired, noTTL}.
Common Patterns
Memoization
function memoize(fn, maxSize = 100) { const cache = lru(maxSize); return function (...args) { const key = JSON.stringify(args); if (cache.has(key)) { return cache.get(key); } const result = fn(...args); cache.set(key, result); return result; };}// Cache expensive computationsconst fib = memoize((n) => (n <= 1 ? n : fib(n - 1) + fib(n - 2)), 50);fib(100); // fast - cachedfib(100); // even faster - from cache
Cache-Aside Pattern
// Cache instance shared across calls (outside the function)const cache = lru(1000, 60000); // 1 minute cacheasync function getUser(userId) { // Check cache first const cached = cache.get(`user:${userId}`); if (cached) { return cached; } // Fetch from database const user = await db.users.findById(userId); // Store in cache cache.set(`user:${userId}`, user); return user;}
npm install # Install dependenciesnpm test # Run lint and testsnpm run lint # Lint and check formattingnpm run fix # Fix lint and formatting issuesnpm run build # Build distribution filesnpm run coverage # Generate test coverage report
Build Output
Build produces multiple module formats. When you install from npm, you'll get:
dist/tiny-lru.js - ES Modules
dist/tiny-lru.cjs - CommonJS
types/lru.d.ts - TypeScript definitions
The minified version (dist/tiny-lru.min.js) is available in the repository for local testing but is not shipped via npm.
Tests
Metric
Count
Tests
169
Suites
27
Test Coverage
Metric
Coverage
Lines
100%
Branches
99.39%
Functions
100%
Contributing
Fork the repository
Create a feature branch (git checkout -b feature/amazing-feature)
Run npm test to ensure all tests pass
Commit your changes (git commit -m 'Add amazing feature')
Push to the branch (git push origin feature/amazing-feature)
Open a Pull Request
Security
tiny-lru is a pure in-memory cache with no network or I/O surface. For guidance on key naming conventions that prevent cross-domain data leakage when using the cache, see the Technical Documentation.