@0xdoublesharp/lru-cache-clustered 2.1.0 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,122 +1,132 @@
1
1
  <p align="center">
2
- <img src="https://raw.githubusercontent.com/doublesharp/lru-cache-clustered/main/assets/LRUCacheClustered.png" alt="LRUCacheClustered" width="180" height="180">
2
+ <img src="https://raw.githubusercontent.com/doublesharp/lru-cache-clustered/main/assets/LRUCacheClustered.png" alt="A pika, the project mascot" width="180" height="180">
3
3
  </p>
4
4
 
5
- <h1 align="center">@0xdoublesharp/lru-cache-clustered</h1>
5
+ # @0xdoublesharp/lru-cache-clustered
6
6
 
7
- <p align="center"><sub>Pikas cache hay for the winter. This package caches everything else.</sub></p>
7
+ [![npm](https://img.shields.io/npm/v/%400xdoublesharp%2Flru-cache-clustered.svg)](https://www.npmjs.com/package/@0xdoublesharp/lru-cache-clustered)
8
+ [![CI](https://github.com/doublesharp/lru-cache-clustered/actions/workflows/ci.yml/badge.svg)](https://github.com/doublesharp/lru-cache-clustered/actions/workflows/ci.yml)
9
+ [![Coverage](https://codecov.io/gh/doublesharp/lru-cache-clustered/branch/main/graph/badge.svg)](https://codecov.io/gh/doublesharp/lru-cache-clustered)
10
+ [![Downloads](https://img.shields.io/npm/dt/%400xdoublesharp%2Flru-cache-clustered.svg)](https://www.npmjs.com/package/@0xdoublesharp/lru-cache-clustered)
8
11
 
9
- <p align="center">
10
- <a href="https://www.npmjs.com/package/@0xdoublesharp/lru-cache-clustered"><img src="https://img.shields.io/npm/v/%400xdoublesharp%2Flru-cache-clustered.svg" alt="npm"></a>
11
- <a href="https://github.com/doublesharp/lru-cache-clustered/actions/workflows/ci.yml"><img src="https://github.com/doublesharp/lru-cache-clustered/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
12
- <a href="https://github.com/doublesharp/lru-cache-clustered/actions/workflows/coverage.yml"><img src="https://github.com/doublesharp/lru-cache-clustered/actions/workflows/coverage.yml/badge.svg" alt="Coverage"></a>
13
- <a href="https://codecov.io/gh/doublesharp/lru-cache-clustered"><img src="https://codecov.io/gh/doublesharp/lru-cache-clustered/branch/main/graph/badge.svg" alt="codecov"></a>
14
- <a href="https://www.npmjs.com/package/@0xdoublesharp/lru-cache-clustered"><img src="https://img.shields.io/npm/dt/%400xdoublesharp%2Flru-cache-clustered.svg" alt="Downloads"></a>
15
- </p>
12
+ Let your Node.js workers share what they have already learned. When one worker caches a database result, the others can reuse it instead of loading and storing their own copies.
16
13
 
17
- ---
14
+ This package keeps namespaced [LRU caches](https://github.com/isaacs/node-lru-cache) in a Node.js cluster's primary process. LRU means least recently used: when the cache fills up, it removes the entries you have used least recently. Workers access the shared cache through an asynchronous API over inter-process communication, or IPC. Atomic counters and fetch coordination also run in the primary.
18
15
 
19
- Node's `cluster` module gives every worker its own heap, so an in-process cache duplicates across workers and every worker cold-starts alone. An 8-worker service with a 200 MB cache pays **1.6 GB to hold the same data eight times**.
20
-
21
- This package keeps a single `lru-cache` in the primary and lets every worker read and write it over `cluster` IPC. One copy of the data, shared warmth across workers, and atomic counters and single-flight fetches that stay correct cluster-wide. No Redis tier, no sidecar.
16
+ No separate cache service is required. The shared data lives in memory for the lifetime of the primary process. Optional local L1 caches keep hot values inside individual workers to avoid repeated IPC reads.
22
17
 
23
18
  <p align="center">
24
- <img src="https://raw.githubusercontent.com/doublesharp/lru-cache-clustered/main/assets/topology.svg" alt="Clustered LRU topology. The primary process owns authoritative namespaced caches and version counters; workers can use typed IPC or optional local L1 caches for hot reads, with writes broadcasting invalidations." width="100%">
19
+ <img src="https://raw.githubusercontent.com/doublesharp/lru-cache-clustered/main/assets/topology.svg" alt="The primary owns shared namespaced caches. Workers read and write through IPC, with optional local caches and invalidation messages." width="100%">
25
20
  </p>
26
21
 
27
- ## Highlights
28
-
29
- | Capability | What it gives you |
30
- | ------------------------------ | ---------------------------------------------------------------------------------------------------------- |
31
- | **One cache, N workers** | The primary owns the data. Memory cost stays flat as you scale workers, instead of multiplying. |
32
- | **No per-worker cold start** | The first worker to load a value warms it for every other worker. |
33
- | **Atomic counters** | `incr` / `decr` execute on the primary, so they stay race-safe under any worker count. |
34
- | **Cluster-wide single-flight** | Concurrent misses for the same key collapse to one fetch via `fetch()` / `memoize()`. |
35
- | **Optional local L1** | Per-worker hot-read cache skips IPC while the primary remains authoritative. |
36
- | **Atomic claims** | `setIfAbsent()` lets exactly one worker win a key &mdash; perfect for idempotent intake or once-only init. |
37
- | **Pluggable codecs** | `wrap()` layers gzip, MessagePack, or any symmetric encoder over a cache without changing call sites. |
38
- | **Per-namespace stats** | Hits, misses, sets, deletes, evictions, size &mdash; ready to scrape, no extra wiring. |
39
- | **Rate-limiter-friendly TTLs** | `incr` keeps the original window ticking instead of resetting it on every bump. |
40
- | **Structured IPC errors** | Worker-side rejections preserve `name`, `code`, `cause`, and `stack` from the primary. |
22
+ ## What you get
23
+
24
+ Each worker can reuse the same cached data, take a turn loading a missing value, and update shared counters without racing another worker.
25
+
26
+ | Capability | How it works |
27
+ | ---------------------- | ------------------------------------------------------------------------------------------------ |
28
+ | Shared cache storage | One primary-owned cache per namespace, with optional extra copies in worker L1 caches. |
29
+ | Shared warm entries | A value loaded by one worker becomes available to the others. |
30
+ | Atomic counters | `incr()` and `decr()` execute in the primary; later increments preserve the original expiration. |
31
+ | Coordinated loading | `fetch()` and `memoize()` coordinate concurrent misses for a key through a primary-owned claim. |
32
+ | Temporary claims | `setIfAbsent()` atomically claims a key while it remains cached. |
33
+ | Optional local reads | L1 can serve repeated reads without IPC, with eventual consistency. |
34
+ | Compression and codecs | `wrap()` converts values on writes and reads through your encoder and decoder. |
35
+ | Metrics and errors | Namespace statistics, local L1 statistics, and structured IPC errors. |
41
36
 
42
37
  ## Install
43
38
 
44
- `lru-cache` is a peer dependency &mdash; install it alongside this package so you control the version.
39
+ Install this package and the cache engine it uses. Both JavaScript and TypeScript applications can use it.
45
40
 
46
41
  ```sh
47
- npm install @0xdoublesharp/lru-cache-clustered lru-cache
48
- pnpm add @0xdoublesharp/lru-cache-clustered lru-cache
49
- yarn add @0xdoublesharp/lru-cache-clustered lru-cache
42
+ npm install @0xdoublesharp/lru-cache-clustered lru-cache@^11
50
43
  ```
51
44
 
52
- TypeScript first. Dual ESM + CJS. Requires Node &ge; 22.
45
+ 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.
46
+
47
+ Requires Node.js 22 or newer. Includes ESM and CommonJS builds and TypeScript declarations.
53
48
 
54
- > The legacy package name `lru-cache-for-clusters-as-promised` is published from the same build at the same version, so existing imports keep working during a phased migration.
49
+ > `@0xdoublesharp/lru-cache-clustered` is the canonical package name. `lru-cache-for-clusters-as-promised` is published from the same build at the same version.
55
50
 
56
51
  ## Quick start
57
52
 
58
- ```ts
53
+ Start a few workers and give their caches the same name. A write from any worker goes into the shared cache in the primary.
54
+
55
+ Save this as `app.mjs` and run `node app.mjs` after installing the packages:
56
+
57
+ ```js
59
58
  import cluster from 'node:cluster';
60
- import { availableParallelism } from 'node:os';
61
59
  import { LRUCacheClustered } from '@0xdoublesharp/lru-cache-clustered';
62
60
 
63
61
  LRUCacheClustered.bootstrap();
64
62
 
65
- const cache = new LRUCacheClustered<string, string>({
66
- namespace: 'sessions',
63
+ const options = {
64
+ namespace: 'greetings',
67
65
  max: 1000,
68
66
  ttl: 60_000,
69
- });
67
+ failsafe: 'reject',
68
+ };
70
69
 
71
70
  if (cluster.isPrimary) {
72
- for (let i = 0; i < availableParallelism(); i++) cluster.fork();
71
+ const cache = await LRUCacheClustered.getInstance(options);
72
+ await cache.set('hello', 'Hello from the shared cache');
73
+ cluster.fork();
74
+ cluster.fork();
73
75
  } else {
74
- await cache.set('user:42', JSON.stringify({ name: 'ada' }));
75
- console.log(await cache.get('user:42'));
76
- // {"name":"ada"} - every worker sees the same value
76
+ const cache = await LRUCacheClustered.getInstance(options);
77
+ console.log(`Worker ${cluster.worker.id}: ${await cache.get('hello')}`);
78
+ process.disconnect();
77
79
  }
78
80
  ```
79
81
 
80
- A few things worth knowing up front:
82
+ 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.
83
+
84
+ 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`.
81
85
 
82
- - **`LRUCacheClustered` is the canonical class.** `LRUCacheForClustersAsPromised` is still exported as a backward-compatible alias.
83
- - **Import in the primary before `cluster.fork()`.** The primary-side IPC listener is installed at module import. Call `LRUCacheClustered.bootstrap()` if you want that setup to be explicit.
84
- - **This is a coordination layer, not a security boundary.** Any code in any worker can use any namespace it knows; do not expose namespaces to untrusted callers.
86
+ ## Use cases
85
87
 
86
- ## When to use it
88
+ Use it when several workers in one Node.js cluster need the same temporary data. The most useful patterns save repeated work or coordinate short-lived state.
87
89
 
88
- Reach for this package when you have a multi-worker Node service and want shared in-process caching without standing up a separate caching tier:
90
+ | Idea | Pattern | Example |
91
+ | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
92
+ | Stop a popular profile from triggering duplicate database queries | `memoize()` or `fetch()` lets workers reuse a cached result and coordinate concurrent misses. | [User lookup server](./examples/clustered-users-server.ts) |
93
+ | Limit API requests across workers | `incr()` updates one shared counter. Its first write starts the TTL window; later increments keep that deadline. | [Rate limiter](./examples/clustered-rate-limit-server.ts) |
94
+ | Share temporary session data | `set()`, `get()`, and `delete()` share entries across workers. Keep durable session state elsewhere. | [Session server](./examples/clustered-session-server.ts) |
95
+ | Suppress repeated job submissions | `setIfAbsent()` lets one worker claim a cached key. Expiration, eviction, or restart can allow another claim. | [Idempotent intake](./examples/clustered-idempotency-server.ts) |
96
+ | Keep large generated documents in less cache space | `wrap()` compresses stored values and decodes them on reads. | [Compressed documents](./examples/clustered-compressed-documents-server.ts) |
97
+ | Reduce repeated Redis reads | Use this shared cache in front of Redis, then add a small worker L1 for hot reads. | [Multilayer cache](./examples/clustered-multilayer-redis-server.ts) |
89
98
 
90
- - Session and profile caches
91
- - Rate limiters and quota counters
92
- - Feature flag snapshots
93
- - Deduplicating expensive API or database calls
94
- - Any cache-aside pattern across workers
99
+ 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.
95
100
 
96
- It is also a strong fit as the **L1 in a multi-layer cache** in front of Redis or Memcached. Hot keys are served in-process, the long tail falls through to the shared remote cache, and the origin only sees true cold misses.
101
+ 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.
97
102
 
98
- Reach for something else when you need sharing across multiple machines (use Redis or Memcached, or layer this in front of one), or when your hottest path cannot tolerate an IPC hop on a miss. See [Performance profile](#performance-profile).
103
+ Namespaces separate application data by name. They do not restrict worker access, so all workers must be trusted.
99
104
 
100
- ## Examples
105
+ ## Runnable examples
101
106
 
102
- Runnable clustered server examples &mdash; see [`examples/README.md`](./examples/README.md) for curl recipes and environment variables.
107
+ Start an example server, send it requests, and watch workers share cached results. The [example guide](./examples/README.md) has curl commands, ports, and environment settings.
103
108
 
104
- | Example | Run | Feature it demonstrates |
105
- | ------------------------------------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------ |
106
- | [`clustered-users-server.ts`](./examples/clustered-users-server.ts) | `pnpm example:users` | Shared read-through user cache via `memoize()` / `fetch()` |
107
- | [`clustered-rate-limit-server.ts`](./examples/clustered-rate-limit-server.ts) | `pnpm example:rate-limit` | Fixed-window rate limiting via atomic `incr()` |
108
- | [`clustered-session-server.ts`](./examples/clustered-session-server.ts) | `pnpm example:sessions` | Shared `set()` / `get()` / `delete()` state across workers |
109
- | [`clustered-idempotency-server.ts`](./examples/clustered-idempotency-server.ts) | `pnpm example:idempotency` | Idempotent job intake via `setIfAbsent()` |
110
- | [`clustered-compressed-documents-server.ts`](./examples/clustered-compressed-documents-server.ts) | `pnpm example:documents` | Compressed document caching via `wrap()` |
111
- | [`clustered-l1-server.ts`](./examples/clustered-l1-server.ts) | `node --import tsx examples/clustered-l1-server.ts` | Local L1 mode with per-worker stats, bypass reads, and invalidation |
112
- | [`clustered-l1-controls-server.ts`](./examples/clustered-l1-controls-server.ts) | `pnpm example:l1` | v2.1 L1 controls: method filtering, `withoutLocal()`, `updateL1`, local invalidation |
113
- | [`clustered-multilayer-redis-server.ts`](./examples/clustered-multilayer-redis-server.ts) | `pnpm example:multilayer` | Clustered LRU as L1 in front of Redis L2 with single-flight cold-miss collapsing |
109
+ | Command | What to explore |
110
+ | -------------------------- | ------------------------------------------------------------------------------------ |
111
+ | `pnpm example:users` | Shared read-through user cache with `memoize()` and `fetch()`. |
112
+ | `pnpm example:rate-limit` | Fixed-window counters across workers. |
113
+ | `pnpm example:sessions` | Shared session reads and writes. |
114
+ | `pnpm example:idempotency` | Temporary job claims with `setIfAbsent()`. |
115
+ | `pnpm example:documents` | Compression with `wrap()`. |
116
+ | `pnpm example:l1` | Method filtering, bypass reads, local invalidation, and write-through L1 population. |
117
+ | `pnpm example:multilayer` | Shared memory caching in front of Redis. Requires Redis. |
118
+
119
+ The [basic L1 server](./examples/clustered-l1-server.ts) can also run with `node --import tsx examples/clustered-l1-server.ts`.
114
120
 
115
121
  ## Local L1 mode
116
122
 
117
- Add a per-worker LRU cache in front of the primary-owned shared cache to skip IPC for hot reads. The primary cache remains the source of truth and still owns every write.
123
+ Keep a small copy of frequently read values inside each worker. Repeated reads can stay in that worker instead of asking the primary again.
124
+
125
+ Enable the optional L1 cache with `localL1`. The primary remains the source of truth and owns every write. Invalidation messages tell workers to drop local entries after changes, but delivery is asynchronous.
118
126
 
119
127
  ```ts
128
+ type Product = { sku: string; name: string };
129
+
120
130
  const products = new LRUCacheClustered<string, Product>({
121
131
  namespace: 'products',
122
132
  max: 25_000,
@@ -127,7 +137,13 @@ const products = new LRUCacheClustered<string, Product>({
127
137
 
128
138
  > 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.
129
139
 
130
- In v2.1, set `experimental: true` to opt in. The L1 TTL is capped at the primary TTL; if omitted, it defaults to `min(primaryTtl * 0.1, 5000)` with a 100 ms floor.
140
+ Set `experimental: true` to opt in. 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.
141
+
142
+ 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.
143
+
144
+ A cold `fetch()` claims the key and stores the result in two IPC requests. Followers poll the claim once per cycle and reuse the leader's result.
145
+
146
+ 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.
131
147
 
132
148
  Read paths can bypass L1 per call:
133
149
 
@@ -144,7 +160,7 @@ const freshProducts = products.withoutLocal();
144
160
  await freshProducts.get('sku:123'); // always goes to the primary
145
161
  ```
146
162
 
147
- The local surface also includes:
163
+ Local controls and metrics:
148
164
 
149
165
  | Method | Description |
150
166
  | ------------------------ | -------------------------------------------------------------------------------------------------------- |
@@ -173,9 +189,11 @@ See [`docs/l1.md`](docs/l1.md) for the full consistency model, stats, events, me
173
189
 
174
190
  ## How it works
175
191
 
192
+ Think of the primary as a shared cupboard and the workers as people borrowing from it. A namespace names one cupboard. Workers with the same namespace share its contents.
193
+
176
194
  `new LRUCacheClustered(...)` branches at construction:
177
195
 
178
- - **In the primary** (`cluster.isPrimary === true`), the instance owns and operates on the in-process `LRUCache` for its namespace directly &mdash; no IPC, no allocation per call.
196
+ - **In the primary** (`cluster.isPrimary === true`), the instance owns and operates on the in-process `LRUCache` for its namespace directly, without IPC.
179
197
  - **In a worker**, every operation becomes a typed IPC request to the primary; the returned Promise resolves with the response.
180
198
 
181
199
  Instances in different workers that share a `namespace` operate on the same primary-side cache. Those instances should agree on cache options (`max`, `ttl`, `allowStale`, ...): reusing a namespace with conflicting options throws rather than silently keeping whichever process initialized it first.
@@ -184,14 +202,30 @@ Instances in different workers that share a `namespace` operate on the same prim
184
202
 
185
203
  ## Performance profile
186
204
 
187
- - **Primary mode** &mdash; operations dispatch directly to the local `lru-cache` instance, bypassing the IPC machinery entirely (no message build, no request-ID allocation, no pending-response bookkeeping).
188
- - **Worker mode** &mdash; every cache operation is an IPC round trip through the primary.
189
- - **Worker mode with local L1** &mdash; hot `get`, `has`, `peek`, `mGet`, and `fetch` reads can be served from process-local memory with no IPC; misses still go to the primary.
190
- - **Hot misses** &mdash; `fetch()` and `memoize()` collapse concurrent misses for the same key across workers, so origin work scales with unique keys, not concurrent callers.
191
- - **Design tradeoff** &mdash; pick this package when cross-worker sharing and single-copy memory matter more than per-call latency; pick plain per-process `lru-cache` when your hottest path cannot afford the IPC hop.
205
+ 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.
206
+
207
+ | Read path | Cost and behavior |
208
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------ |
209
+ | Primary process | Dispatches to the local `lru-cache` without IPC. |
210
+ | Worker without L1 | Reads and writes use IPC. A cache hit still crosses processes. |
211
+ | Worker with L1 | Eligible local hits avoid IPC; misses and writes reach the primary. |
212
+ | Concurrent cache misses | One leader runs the fetcher while followers poll for the result, subject to claim expiry and forced refresh. |
213
+
214
+ 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`.
215
+
216
+ 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.
217
+
218
+ ```sh
219
+ BENCH_WORKERS=1,4 BENCH_PAYLOAD_BYTES=128,16384 BENCH_ITERATIONS=2000 pnpm bench
220
+ BENCH_SERIALIZATION=advanced pnpm bench
221
+ ```
222
+
223
+ 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.
192
224
 
193
225
  ## Options
194
226
 
227
+ 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.
228
+
195
229
  The serializable subset of [`lru-cache`](https://github.com/isaacs/node-lru-cache) constructor options passes through (`max`, `maxSize`, `maxEntrySize`, `ttl`, `allowStale`, `updateAgeOnGet`, `updateAgeOnHas`, `noDeleteOnStaleGet`, `ttlAutopurge`). Plus:
196
230
 
197
231
  | Option | Type | Default | Description |
@@ -203,41 +237,47 @@ The serializable subset of [`lru-cache`](https://github.com/isaacs/node-lru-cach
203
237
 
204
238
  `LocalL1Options`:
205
239
 
206
- | Option | Type | Default | Description |
207
- | ---------------- | --------------------------- | ------------- | ----------------------------------------------------------------------------------------------------- |
208
- | `enabled` | `boolean` | `true` | Set `false` to disable when an options object is reused. |
209
- | `experimental` | `boolean` | required | Must be `true` in v2.1 to acknowledge eventual consistency. |
210
- | `max` | `number` | `1000` | Maximum local entries per instance. |
211
- | `maxSize` | `number` | `undefined` | Optional local size bound. Uses one size unit per entry. |
212
- | `ttl` | `number` | derived | Local TTL in ms, capped by primary TTL and per-entry remaining TTL. |
213
- | `updateAgeOnGet` | `boolean` | `true` | Passed to the local `lru-cache`. |
214
- | `allowStale` | `boolean` | `false` | Passed to the local `lru-cache`; stale reads increment `localStats().staleHits`. |
215
- | `invalidation` | `'broadcast' \| 'ttl-only'` | `'broadcast'` | Whether this instance subscribes to local/IPC invalidation pushes or relies only on local TTL expiry. |
216
- | `methods` | `{ get?, has?, fetch? }` | all enabled | Restrict which read families use L1. If present, omitted keys are disabled. |
217
- | `cacheUndefined` | `boolean` | unsupported | Reserved for future negative-result caching; currently forced off. |
240
+ | Option | Type | Default | Description |
241
+ | ---------------- | --------------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------- |
242
+ | `enabled` | `boolean` | `true` | Set `false` to disable when an options object is reused. |
243
+ | `experimental` | `boolean` | required | Must be `true` to opt in to eventual consistency. |
244
+ | `max` | `number` | `1000` | Maximum local entries per instance. |
245
+ | `maxSize` | `number` | `undefined` | Optional local size bound. Uses one size unit per entry. |
246
+ | `ttl` | `number` | derived | Local TTL in ms, capped by primary TTL and per-entry remaining TTL. |
247
+ | `updateAgeOnGet` | `boolean` | `true` | Passed to the local `lru-cache`. |
248
+ | `allowStale` | `boolean` | `false` | Passed to the local `lru-cache`; Stale returns and rejected expired/version-stale local entries increment `staleHits`. |
249
+ | `invalidation` | `'broadcast' \| 'ttl-only'` | `'broadcast'` | Whether this instance subscribes to local/IPC invalidation pushes or relies only on local TTL expiry. |
250
+ | `methods` | `{ get?, has?, fetch? }` | all enabled | Restrict which read families use L1. If present, omitted keys are disabled. |
251
+ | `cacheUndefined` | `boolean` | unsupported | Reserved for future negative-result caching; currently forced off. |
218
252
 
219
253
  Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalculation`, or `fetchMethod` do not cross IPC and are not supported by this wrapper.
220
254
 
221
- > **`failsafe: 'resolve'` caveat.** On timeout, `'resolve'` returns `undefined` for _every_ op, regardless of declared return type. For `get` / `peek` that is natural; for `has` / `set` / `delete` / `incr` / `decr` / `size` it can surprise callers (`undefined + 1 === NaN`). Use `'reject'` if typed-shape correctness on timeout matters.
255
+ > **`failsafe: 'resolve'` caveat.** Most single-result operations return `undefined` on an IPC timeout with `'resolve'`, even when their declared return type differs. `mGet()` can return an empty or partial map. `fetch()`, `getInstance()`, and `healthCheck()` reject on IPC timeouts. For `get` / `peek` that is natural; for `has` / `set` / `delete` / `incr` / `decr` / `size` it can surprise callers (`undefined + 1 === NaN`). Use `'reject'` if typed-shape correctness on timeout matters.
222
256
 
223
257
  > **Size-bounded caches.** When you use `maxSize` or `maxEntrySize`, provide `size` on every write path (`set`, `setIfAbsent`, `mSet`, `fetch`, `memoize`, and the first `incr` / `decr` for a counter key). `sizeCalculation` does not cross IPC, so the primary cannot infer it for you.
224
258
 
225
259
  > **Fail-fast startup.** `LRUCacheClustered.getInstance()` and `cache.healthCheck()` always reject if the primary cannot answer, regardless of `failsafe`, so you can use them as hard startup checks.
226
260
 
227
- > **Key/value contract.** Like `lru-cache`, keys and values must be non-nullish. Passing `null` or `undefined` rejects instead of relying on ambiguous cache semantics.
261
+ > **Key/value contract.** Like `lru-cache`, keys and values must be non-nullish. Passing `null` or `undefined` rejects. Use string keys across workers: IPC copies object keys, so object identity cannot be shared between processes.
228
262
 
229
263
  ## API
230
264
 
265
+ The same methods work in the primary and in workers. Await shared-cache operations; local-cache controls run immediately in the calling process.
266
+
231
267
  ### Static
232
268
 
269
+ These helpers set up the shared cache before you start using it.
270
+
233
271
  | Method | Description |
234
272
  | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
235
273
  | `LRUCacheClustered.bootstrap()` | Installs the primary-side cluster listener immediately. Useful when you want an explicit bootstrap call instead of relying on module import side effects. |
236
274
  | `LRUCacheClustered.getInstance(options)` | Async factory. In a worker, awaits the init message so the primary has registered the namespace before returning. Preferred when worker startup should fail fast on init errors. |
237
- | `LRUCacheClustered.getAllCaches()` | Returns the `Map<namespace, LRUCache>` registry. **Primary only** &mdash; throws in workers. |
275
+ | `LRUCacheClustered.getAllCaches()` | Returns the `Map<namespace, LRUCache>` registry. Primary only; throws in workers. |
238
276
 
239
277
  ### Core
240
278
 
279
+ Store a value, read it back, check whether it exists, or remove it.
280
+
241
281
  | Method | Returns | Notes |
242
282
  | --------------------------------------------- | ------------------------- | -------------------------------------------------------------- |
243
283
  | `get(key, { bypassL1? })` | `Promise<V \| undefined>` | |
@@ -250,6 +290,8 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
250
290
 
251
291
  ### Multi
252
292
 
293
+ Handle several keys in one call to avoid a separate trip to the primary for every key. Batch writes are not transactions; a later failure can leave earlier writes applied.
294
+
253
295
  | Method | Returns | Notes |
254
296
  | -------------------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
255
297
  | `mGet(keys, { bypassL1? })` | `Promise<Map<K, V \| undefined>>` | Preserves input key order even when L1 partially hits. |
@@ -258,11 +300,13 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
258
300
 
259
301
  ### Enumeration
260
302
 
303
+ Inspect the contents or take a snapshot for later restoration. These methods return whole collections, so large caches create large responses.
304
+
261
305
  | Method | Returns | Notes |
262
306
  | -------------------------- | ------------------------------- | --------------------------------------------------------------- |
263
- | `keys()` | `Promise<K[]>` | MRU first. |
264
- | `values()` | `Promise<V[]>` | MRU first. |
265
- | `entries()` | `Promise<[K, V][]>` | MRU first. |
307
+ | `keys()` | `Promise<K[]>` | Most recently used first. |
308
+ | `values()` | `Promise<V[]>` | Most recently used first. |
309
+ | `entries()` | `Promise<[K, V][]>` | Most recently used first. |
266
310
  | `[Symbol.asyncIterator]()` | `AsyncIterableIterator<[K, V]>` | `for await (const [k, v] of cache)`. Materializes the full set. |
267
311
  | `dump()` | `Promise<[K, Entry][]>` | Serializable snapshot. |
268
312
  | `load(entries)` | `Promise<void>` | Restores from a `dump()`, preserving per-entry TTL metadata. |
@@ -270,6 +314,8 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
270
314
 
271
315
  ### Counters and cache-aside
272
316
 
317
+ Count events without workers overwriting each other, or load a missing value once and share the result. Cache-aside means checking the cache before doing the expensive work.
318
+
273
319
  | Method | Returns | Notes |
274
320
  | ---------------------------------------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------ |
275
321
  | `incr(key, amount?, { ttl?, size? })` | `Promise<number>` | Atomic on the primary. `ttl` is set on the **first** write only; later increments do not reset it (rate limiters). |
@@ -279,6 +325,8 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
279
325
 
280
326
  ### Local L1
281
327
 
328
+ These controls affect the extra cache inside this process. They help you see whether local reads are saving trips to the primary.
329
+
282
330
  | Method / event | Returns / payload | Notes |
283
331
  | ------------------------------------------------- | ------------------------- | ---------------------------------------------------------------------------------------- |
284
332
  | `localStats()` | `L1Stats \| undefined` | `undefined` when local L1 is disabled. |
@@ -287,11 +335,13 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
287
335
  | `withoutLocal()` | `LRUCacheClustered<K, V>` | Bypass view for `get`, `has`, `peek`, `mGet`, and `fetch`; writes pass through normally. |
288
336
  | `on('l1:hit' \| 'l1:miss' \| 'l1:set', listener)` | `{ namespace, key }` | Key is the original cache key, not an internal encoded key. |
289
337
  | `on('l1:invalidate', listener)` | `{ namespace, key }` | `key` may be `'*'` for namespace-wide invalidation. |
290
- | `on('l1:evict' \| 'l1:stale-hit', listener)` | `{ namespace, key }` | `stale-hit` fires when a TTL-stale local value is returned under `allowStale`. |
338
+ | `on('l1:evict' \| 'l1:stale-hit', listener)` | `{ namespace, key }` | `stale-hit` also fires when an expired or version-stale local entry is rejected. |
291
339
  | `off(event, listener)` / `once(event, listener)` | `this` | Standard event helpers. |
292
340
 
293
341
  ### Lifecycle, metrics, tunables
294
342
 
343
+ Check the cache, inspect its activity, change its limits, or remove its namespace.
344
+
295
345
  | Method | Returns | Notes |
296
346
  | ---------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
297
347
  | `getRemainingTTL(key)` | `Promise<number>` | ms until expiry. `Infinity` for keys with no TTL; `0` for missing keys. |
@@ -300,14 +350,16 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
300
350
  | `stats()` | `Promise<Stats>` | `{ hits, misses, sets, deletes, evictions, size, namespace }`. |
301
351
  | `destroy()` | `Promise<boolean>` | Removes the namespace cache, stats, and primary-side coordination state. Later use of the same instance recreates it with the original options. |
302
352
  | `getCache()` | `LRUCache \| undefined` | Underlying `lru-cache` for this namespace. **Primary only**. |
303
- | `ready` | `Promise<void>` | Resolves once worker init has been dispatched. Useful for ordering only; use `getInstance()` if init failures should reject. |
353
+ | `ready` | `Promise<void>` | Waits for worker initialization but swallows failures. Use `getInstance()` when initialization errors should reject. |
304
354
  | `max(value?)` | `Promise<number>` | Getter and setter. Setter preserves primary entries and remaining TTL metadata, then clears this instance's L1. |
305
355
  | `ttl(value?)` | `Promise<number>` | Getter and setter. Setter clears this instance's L1. |
306
356
  | `allowStale(value?)` | `Promise<boolean>` | Getter and setter. |
307
357
 
308
- ## `wrap` &mdash; codec / compression
358
+ ## Compression and codecs
309
359
 
310
- `wrap(cache, codec)` returns a typed view where values pass through an `encode` / `decode` pair on the way in and out. Use it for compression (gzip, brotli), serialization (MessagePack), or any custom symmetric transform. The library stays codec-agnostic &mdash; bring your own.
360
+ Large documents take less cache space when compressed. A codec converts values before storage and converts them back when you read them.
361
+
362
+ `wrap(cache, codec)` returns a typed view where values pass through an `encode` / `decode` pair on the way in and out. Use it for compression (gzip, brotli), serialization (MessagePack), or any custom symmetric transform. Supply the codec that fits your data.
311
363
 
312
364
  ```ts
313
365
  import { gzipSync, gunzipSync } from 'node:zlib';
@@ -326,20 +378,25 @@ await cache.set('user:42', { id: 42, name: 'ada' });
326
378
  await cache.get('user:42'); // decoded back to { id: 42, name: 'ada' }
327
379
  ```
328
380
 
329
- `encode` and `decode` may be sync or async. The wrapped surface covers value-touching ops (`get`, `set`, `setIfAbsent`, `peek`, `mGet`, `mSet`, `values`, `entries`, async iteration, `fetch`) plus the lifecycle and metric pass-throughs (`has`, `delete`, `keys`, `size`, `clear`, `destroy`, `healthCheck`, `purgeStale`, `getRemainingTTL`, `stats`). Wrapped `get`, `has`, `peek`, `mGet`, and `fetch` forward read options such as `{ bypassL1: true }` to the underlying cache.
381
+ `encode` and `decode` may be sync or async. The wrapper encodes or decodes values for (`get`, `set`, `setIfAbsent`, `peek`, `mGet`, `mSet`, `values`, `entries`, async iteration, `fetch`) and forwards lifecycle and metric methods (`has`, `delete`, `keys`, `size`, `clear`, `destroy`, `healthCheck`, `purgeStale`, `getRemainingTTL`, `stats`). Wrapped `get`, `has`, `peek`, `mGet`, and `fetch` forward read options such as `{ bypassL1: true }` to the underlying cache.
330
382
 
331
- `incr` / `decr` and `dump` / `load` are not wrapped &mdash; they speak in numbers or the raw stored form. Reach them via `wrapped.cache` if you need them.
383
+ `incr()` and `decr()` operate on numbers. `dump()` and `load()` operate on raw stored values. The wrapper does not expose those methods. Reach them via `wrapped.cache` if you need them.
332
384
 
333
- > **Buffer-typed values.** Cluster IPC serializes through JSON, which does not preserve `Buffer`. If a codec stores `Buffer` directly, in worker mode the decoded side will receive `{ type: 'Buffer', data: number[] }` and most binary APIs will reject it. Encode to a string (base64, hex) &mdash; or rehydrate inside `decode` &mdash; when the wrapped cache is read from workers. Primary-only use is unaffected.
385
+ > **Binary values.** Default cluster IPC uses JSON serialization and turns a `Buffer` into `{ type: 'Buffer', data: number[] }`. Encode to base64 or rehydrate it in `decode`. If you control cluster setup, `cluster.setupPrimary({ serialization: 'advanced' })` preserves buffers and other supported built-in types. Configure it before forking workers.
334
386
 
335
387
  ## `memoize` helper
336
388
 
337
- Cache-aside in one line. Concurrent calls for the same key coordinate through `cache.fetch()` so only one caller does the underlying work at a time.
389
+ Give a function a memory. Calling it again with the same cache key can reuse the previous result instead of repeating a database query or API request.
390
+
391
+ `memoize(cache, fn, keyFn, opts)` calls `cache.fetch()` under the hood. `keyFn` must include every input that can change the result, including tenant or permission context when relevant.
338
392
 
339
393
  ```ts
340
394
  import { LRUCacheClustered, memoize } from '@0xdoublesharp/lru-cache-clustered';
341
395
 
342
- const cache = new LRUCacheClustered<string, User>({ namespace: 'users', ttl: 60_000 });
396
+ type User = { id: string; name: string };
397
+
398
+ // fetchUserFromDB is your application's database lookup.
399
+ const cache = new LRUCacheClustered<string, User>({ namespace: 'users', max: 1000, ttl: 60_000 });
343
400
 
344
401
  const getUser = memoize(
345
402
  cache,
@@ -354,33 +411,77 @@ await getUser('42'); // second call: cached
354
411
 
355
412
  ### Single-flight semantics
356
413
 
414
+ If several workers ask for the same missing value, one does the work while the others wait. This reduces duplicate requests to your database or upstream API.
415
+
357
416
  Both `memoize()` and `cache.fetch()` coordinate through the primary so concurrent misses for the same key collapse to one in-flight fetch across instances and workers.
358
417
 
359
- Passing `forceRefresh: true` skips both the cache lookup and any in-flight claim and starts a fresh leader fetch. Concurrent callers without `forceRefresh` still wait on whichever fetch is in flight and reuse its result. Passing `bypassL1: true` skips local L1 reads and population for that call while preserving the primary-side single-flight behavior.
418
+ An explicit write supersedes older fetch work for the affected key. This includes `set()`, `delete()`, and batch mutations; `clear()`, `load()`, and `destroy()` supersede claims across the namespace. The fetcher itself keeps running, but its old result cannot overwrite a newer write or restore a removed entry. When it finishes, the fetch returns the newer cached value if one exists, otherwise it rejects with an error indicating that its claim was superseded. A delete cancels a pending claim even when no value has been stored yet. Waiting followers also retain their claim generation, so they cannot take fresh leadership and restore a removed entry after that generation is revoked. Ordinary leader failure or lease expiry still permits takeover.
419
+
420
+ Follower registrations are released when calls settle. Cancellation or an uncertain claim response may require an additional cleanup request. Successful value and store responses clean up directly, so an uncontended cold fetch still uses two requests, and warm L1 hits use none.
421
+
422
+ Passing `forceRefresh: true` skips both the cache lookup and any in-flight claim and starts a fresh leader fetch. On a cache miss, concurrent callers without `forceRefresh` wait on the current fetch and reuse its result. During a forced refresh, other instances can still read an existing cached value until the refresh finishes. Passing `bypassL1: true` skips local L1 reads and population for that call while preserving the primary-side single-flight behavior.
423
+
424
+ A fetch claim has a 30-second lease. A later caller can take over an expired claim, and a worker exit releases its claims. Fetchers must tolerate duplicate execution after a lease expires or a forced refresh replaces a claim.
360
425
 
361
426
  The cache `timeout` option only bounds each worker IPC request. It does not cancel user fetcher work after a worker owns the primary-side single-flight lock, so production fetchers should enforce their own upstream timeout or abort policy.
362
427
 
363
428
  ## Errors
364
429
 
365
- **Worker mode.** When a primary-side handler throws, the worker's promise rejects with a reconstructed `Error` carrying the original `name`, `message`, `code`, `stack`, and `cause` chain. The rejected value is always a plain `Error` (subclass identity is not crossed over IPC), but `.name`, `.code`, and `.cause` are intact, so logging and cause-chain walking work. Errors travel as `{ name, message, code?, stack?, cause? }` on the wire.
430
+ A missing key is normal. A failed operation is different: handle its rejected promise, and choose whether an IPC timeout should reject or return `undefined`.
366
431
 
367
- **Primary mode.** No IPC: a thrown `Error` rejects as-is (subclass identity preserved); a thrown non-`Error` value is wrapped in `new Error(String(value))`. For `Error` throws the two modes are observably equivalent.
432
+ **Worker mode.** When a primary-side handler throws, the worker's promise rejects with a reconstructed `Error` carrying the original `name`, `message`, `code`, `stack`, and `cause` chain. The rejected value is always a plain `Error` (IPC does not preserve subclass identity), but `.name`, `.code`, and `.cause` are intact, so logging and cause-chain walking work. Errors travel as `{ name, message, code?, stack?, cause? }` on the wire.
433
+
434
+ **Primary mode.** No IPC: a thrown `Error` rejects as-is (subclass identity preserved); a thrown non-`Error` value is wrapped in `new Error(String(value))`. Custom error subclasses retain their identity only in primary mode.
368
435
 
369
436
  ## Debugging
370
437
 
438
+ Turn on logs to see whether workers are reaching the primary and which requests they send.
439
+
371
440
  ```sh
372
441
  DEBUG=lru-cache-clustered-* node app.js
373
442
  ```
374
443
 
375
444
  Available namespaces:
376
445
 
377
- - `lru-cache-clustered-primary` &mdash; cache creation, registry events
378
- - `lru-cache-clustered-messages` &mdash; every request/response over IPC
446
+ - `lru-cache-clustered-primary` logs cache creation and registry events.
447
+ - `lru-cache-clustered-messages` logs IPC requests and responses.
448
+ - `lru-cache-clustered-invalidations` logs errors thrown by local invalidation subscribers.
449
+
450
+ ## Migration
451
+
452
+ Existing applications can move to the scoped package name while keeping the compatibility alias during the transition.
453
+
454
+ `LRUCacheClustered` is the canonical class; `LRUCacheForClustersAsPromised` remains an alias. The [migration guide](./docs/migration.md) maps the older methods, options, and package name. The [changelog](./CHANGELOG.md) records release-specific changes.
455
+
456
+ ## Development
457
+
458
+ Clone the project, install its dependencies, and run the checks before changing code. The examples are small servers you can use to explore the behavior yourself.
459
+
460
+ For development, use a current Node.js 22 LTS patch release, at least 22.13, or Node.js 24 LTS. Use the pnpm version recorded in `package.json`; the runtime minimum for applications remains Node.js 22.
461
+
462
+ ```sh
463
+ git clone https://github.com/doublesharp/lru-cache-clustered.git
464
+ cd lru-cache-clustered
465
+ corepack enable
466
+ pnpm install --frozen-lockfile
467
+ pnpm check
468
+ ```
469
+
470
+ | Command | What it does |
471
+ | -------------------- | ------------------------------------------------------------------------------------------------------ |
472
+ | `pnpm check` | Lint, typecheck, tests, unused-code checks, type coverage, build, and bundle-size checks. |
473
+ | `pnpm test` | Unit, fuzz, and real cluster-worker tests. |
474
+ | `pnpm test:coverage` | Text and LCOV reports in `coverage/`; requires 100% source statements, branches, functions, and lines. |
475
+ | `pnpm build` | ESM and CommonJS bundles with TypeScript declarations in `dist/`. |
476
+ | `pnpm bench` | Compare worker reads with and without local L1. |
477
+ | `pnpm example:users` | Start the shared user-cache example. |
478
+
479
+ `src/primary.ts` owns shared state and executes operations. `src/worker.ts` manages IPC requests and responses. `src/index.ts` exposes the public API and connects it to `src/l1.ts`. Codec and memoization helpers live in `src/codec.ts` and `src/memoize.ts`.
379
480
 
380
- ## Upgrading from 1.x
481
+ When changing cache behavior, add a regression test that retains the same cache instances and checks the resulting values. For L1 changes, verify warm hits, invalidation, and expiration. Cluster tests use child processes under both JSON and advanced serialization.
381
482
 
382
- The 2.x line is a TypeScript rewrite on top of `lru-cache@11` with renamed methods and options. See [`docs/migration.md`](./docs/migration.md) for the full method, option, and package mapping, and [`CHANGELOG.md`](./CHANGELOG.md) for the complete 2.0 release notes.
483
+ Dependency resolution waits seven days after publication through `minimumReleaseAge` in `pnpm-workspace.yaml`. Use frozen lockfile installs for reproducible checks. Release preparation with `pnpm prepare:publish` creates scoped and legacy package directories under `dist-publish/`; the [publishing workflow](./.github/workflows/npm-publish.yml) handles publication.
383
484
 
384
485
  ## License
385
486
 
386
- MIT &mdash; see [LICENSE](./LICENSE).
487
+ You can use, modify, and distribute this package under the MIT license. See [LICENSE](./LICENSE) for the terms.