lru-cache-for-clusters-as-promised

Shared in-memory LRU caches for Node.js cluster workers, with atomic counters, coordinated fetches, and optional worker-local caching.
The primary process holds one cache per namespace. Workers share its entries through an asynchronous API over inter-process communication (IPC), so a value loaded by one worker is available to the others. No separate cache service is required; data stays in memory for the lifetime of the primary.
Quick start · How it works · Examples · Local L1 · API
What you get
| Capability |
How it works |
| Shared cache storage |
One primary-owned cache per namespace, with optional extra copies in worker L1 caches. |
| Shared warm entries |
A value loaded by one worker becomes available to the others. |
| Atomic counters |
incr() and decr() execute in the primary; later increments preserve the original expiration. |
| Coordinated loading |
fetch() and memoize() coordinate concurrent misses for a key through a primary-owned claim. |
| Temporary claims |
setIfAbsent() atomically claims a key while it remains cached. |
| Optional local reads |
L1 can serve repeated reads without IPC, with eventual consistency. |
| Compression and codecs |
wrap() converts values on writes and reads through your encoder and decoder. |
| Metrics and errors |
Namespace statistics, local L1 statistics, and structured IPC errors. |
Install
npm install @0xdoublesharp/lru-cache-clustered lru-cache@^11
For pnpm or Yarn, use pnpm add or yarn add with the same package names. lru-cache is a peer dependency, so your application controls its installed version within the supported range.
Requires Node.js 22 or newer. Includes ESM and CommonJS builds and TypeScript declarations.
This package has moved. New installs should use @0xdoublesharp/lru-cache-clustered.
lru-cache-for-clusters-as-promised is published from the same build as a compatibility alias.
2.1.4 hardens primary cache validation, single-flight fetch coordination, worker listener attachment, and local L1 coherence, backed by TLA+ and Lean 4 formal verification. See the release notes for details.
Quick start
Start a few workers and give their caches the same name. A write from any worker goes into the shared cache in the primary.
Save this as app.mjs and run node app.mjs after installing the packages:
import cluster from 'node:cluster';
import { LRUCacheClustered } from '@0xdoublesharp/lru-cache-clustered';
LRUCacheClustered.bootstrap();
const options = {
namespace: 'greetings',
max: 1000,
ttl: 60_000,
failsafe: 'reject',
};
if (cluster.isPrimary) {
const cache = await LRUCacheClustered.getInstance(options);
await cache.set('hello', 'Hello from the shared cache');
cluster.fork();
cluster.fork();
} else {
const cache = await LRUCacheClustered.getInstance(options);
console.log(`Worker ${cluster.worker.id}: ${await cache.get('hello')}`);
process.disconnect();
}
Both workers read the same entry. getInstance() waits for namespace registration and rejects if initialization fails. Reuse the returned instance in each process, especially with L1 enabled.
Import the package in the primary before cluster.fork(). The import installs the IPC listener; bootstrap() makes that setup explicit. Instances that share a namespace must agree on primary cache options such as max and ttl.
How it works
The primary owns the shared caches. Each namespace identifies one cache, and instances using that namespace must agree on options such as max, ttl, and allowStale. Conflicting options throw during initialization.
- In the primary, operations call the namespace's
LRUCache directly.
- In a worker, operations send typed IPC requests and return promises. With L1 enabled, eligible local hits skip IPC. Writes still reach the primary, which broadcasts invalidations by default.
Initialization. In a worker, new LRUCacheClustered(...) sends an init message immediately. cache.ready waits for ordering but swallows initialization errors. Use await LRUCacheClustered.getInstance(...) or await cache.healthCheck() to fail startup when registration fails.
Use cases
The example guide includes request commands, ports, and environment settings. Run these commands from a checkout with dependencies installed.
| Example |
Pattern |
Run |
| User lookups |
Share database results with memoize() and fetch(). |
pnpm example:users |
| Rate limiting |
Use atomic counters with a fixed TTL window. |
pnpm example:rate-limit |
| Sessions |
Share temporary session reads and writes. |
pnpm example:sessions |
| Job intake |
Suppress duplicate submissions with setIfAbsent(). |
pnpm example:idempotency |
| Compressed documents |
Encode stored values with wrap(). |
pnpm example:documents |
| Local L1 controls |
Try method filters, bypass reads, invalidation, and write-through population. |
pnpm example:l1 |
| Redis layers |
Put shared memory and worker L1 in front of Redis. Requires Redis. |
pnpm example:multilayer |
The basic L1 server also runs with node --import tsx examples/clustered-l1-server.ts.
For example, a report endpoint can use the report parameters as a cache key and fetch() to coordinate generation. Include tenant and authorization context when they affect the result.
The cache belongs to one primary process. Separate clusters, containers, and machines do not share it. Use a remote cache or database when you need that wider scope, durable state, or coordination that must survive eviction and restarts. Shared counters and claims are atomic while their keys remain present; they do not provide durable quotas or exactly-once job processing.
Namespaces separate application data by name. They do not restrict worker access, so all workers must be trusted.
Local L1 mode
Enable localL1 to keep frequently read values inside each worker and avoid repeated IPC reads. The primary owns every write. Invalidation messages tell workers to drop local entries after changes, but delivery is asynchronous.
type Product = { sku: string; name: string };
const products = new LRUCacheClustered<string, Product>({
namespace: 'products',
max: 25_000,
ttl: 60_000,
localL1: { enabled: true, experimental: true, ttl: 2_000 },
});
L1 improves repeated read latency by avoiding IPC, but it can briefly serve stale data. Keep L1 TTL short and bypass L1 for correctness-sensitive reads.
Set experimental: true to opt in. Explicit localL1.ttl values must be positive finite numbers and are honored directly (clamped to the primary TTL with a 1 ms floor). Without an explicit local TTL, the default is 10% of a positive primary TTL, up to 5 seconds, with a 100 ms floor. With no primary expiration, including ttl: 0, it defaults to 5 seconds. Each local entry is also capped at the remaining lifetime reported by the primary.
Reuse one cache instance per namespace in each worker. Each constructor or getInstance() call creates a separate local L1, so recreating the instance per request loses its warm entries.
A cold fetch() claims the key and stores the result in two IPC requests. Followers poll the claim once per cycle without inflating primary miss counts and reuse the leader's result, including oversized values (size > maxEntrySize) that are not admitted into the primary cache.
L1 misses receive values and remaining TTLs in one primary response. A cold mGet() uses one IPC request for the batch, and a fully warm batch uses none. Local hits cannot extend an entry past the primary expiration recorded in that response, even with updateAgeOnGet or allowStale enabled.
Read paths can bypass L1 per call:
await products.get('sku:123', { bypassL1: true });
await products.mGet(['sku:123', 'sku:456'], { bypassL1: true });
await products.fetch('sku:789', loadProduct, { ttl: 60_000, bypassL1: true });
For a reusable fresh-read view, use withoutLocal():
const freshProducts = products.withoutLocal();
await freshProducts.get('sku:123'); // always goes to the primary
Local controls and metrics:
| Method |
Description |
localStats() |
Returns { enabled, hits, misses, sets, invalidations, evictions, staleHits, size, ipcAvoided }. |
clearLocal() |
Flushes this instance's local L1 without touching the primary cache. |
invalidateLocal(key) |
Drops one local L1 key without touching the primary cache. |
withoutLocal() |
Returns a read-through-primary wrapper over the same cache instance. |
on(event, listener) |
Subscribes to L1 events: l1:hit, l1:miss, l1:set, l1:invalidate, l1:evict, and l1:stale-hit. |
off(...) / once(...) |
Standard event listener helpers. |
localL1.methods can restrict which read families use L1:
localL1: {
enabled: true,
experimental: true,
methods: { get: true, has: false, fetch: true },
}
When methods is provided, omitted method keys are disabled. memoize() delegates to fetch(), so its L1 behavior follows the fetch setting.
By default, same-process and cross-worker writes broadcast invalidations so hot local entries are dropped before their TTL expires. If you intentionally want TTL-only consistency, set localL1.invalidation: 'ttl-only'.
See docs/l1.md for the full consistency model, stats, events, method options, and failure modes.
Performance profile
Sharing saves duplicate cache storage, but asking another process for a value takes time. A small local cache can speed up repeated reads, at the cost of extra copies and a brief stale-data window.
| Read path |
Cost and behavior |
| Primary process |
Dispatches to the local lru-cache without IPC. |
| Worker without L1 |
Reads and writes use IPC. A cache hit still crosses processes. |
| Worker with L1 |
Eligible local hits avoid IPC; misses and writes reach the primary. |
| Concurrent cache misses |
One leader runs the fetcher while followers poll for the result, subject to claim expiry and forced refresh. |
Use this package when sharing cached data is worth the IPC cost. Use plain per-process lru-cache when worker independence and the lowest local read latency matter more. Benchmark with your payload sizes, worker count, and read/write mix using pnpm bench.
The benchmark runs real workers with L1 enabled and disabled, checks every returned value, and reports JSON lines with throughput, mean/p95/p99 latency, IPC request counts, local hits, and fetcher calls. It covers hot reads, 95% reads with unrelated writes, batches of ten reads, and concurrent fetch misses. Initialization and warmup are excluded. The default uses two workers and 128-byte and 16-KiB payloads. Fetch cases use at most 50 keys with a simulated 5 ms upstream delay.
BENCH_WORKERS=1,4 BENCH_PAYLOAD_BYTES=128,16384 BENCH_ITERATIONS=2000 pnpm bench
BENCH_SERIALIZATION=advanced pnpm bench
Compare results on the same machine and Node.js version. Latency samples measure the cache operation; aggregate throughput also includes result validation and benchmark messaging.
Options
Choose how much the cache can hold and how long values stay fresh. max limits the number of entries; ttl, or time to live, sets their lifetime in milliseconds.
The serializable subset of lru-cache constructor options passes through (max, maxSize, maxEntrySize, ttl, allowStale, updateAgeOnGet, updateAgeOnHas, noDeleteOnStaleGet, ttlAutopurge). Plus:
| Option |
Type |
Default |
Description |
namespace |
string |
'default' |
Logical name. Instances sharing a namespace share state on the primary. |
timeout |
number |
100 |
Worker IPC timeout in ms. |
failsafe |
'resolve' \| 'reject' |
'resolve' |
On worker IPC timeout: 'resolve' resolves with undefined; 'reject' rejects with Error('IPC timeout'). |
localL1 |
false \| LocalL1Options |
undefined |
Optional local hot-read cache. Pass { enabled: true, experimental: true } to opt in. |
LocalL1Options: