@0xdoublesharp/lru-cache-clustered 2.1.1 → 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/CHANGELOG.md +12 -0
- package/README.md +207 -112
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/invalidation.d.ts +6 -0
- package/dist/invalidation.d.ts.map +1 -0
- package/dist/l1.d.ts +9 -3
- package/dist/l1.d.ts.map +1 -1
- package/dist/messages.d.ts +10 -0
- package/dist/messages.d.ts.map +1 -1
- package/dist/primary.d.ts.map +1 -1
- package/dist/worker.d.ts.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
+
# 2.1.2 / 2026-10-15
|
|
2
|
+
|
|
3
|
+
- Handle asynchronous primary response and invalidation send failures when workers disconnect, without retrying mutations.
|
|
4
|
+
- Keep request IDs unique across ESM, CommonJS, and duplicate package copies in the same worker.
|
|
5
|
+
- Deliver worker-originated invalidations to primary-process L1 caches and invalidate applied batch changes even when a later entry fails.
|
|
6
|
+
- Preserve unrelated warm L1 entries during single-key writes and protect outstanding cache fills with temporary per-key fences.
|
|
7
|
+
- Release destroyed namespace version records while retaining monotonic mutation versions.
|
|
8
|
+
- Prevent older fetch claims from overwriting newer explicit mutations. A superseded fetch returns a newer cached value, or rejects if none remains.
|
|
9
|
+
- Benchmark real workers with configurable counts, payload sizes, mixed writes, batches, and coordinated fetches, including exact result checks and IPC counts.
|
|
10
|
+
- Increase the compressed bundle budget from 7 kB to 8 kB to accommodate the correctness fixes and bounded invalidation tracking.
|
|
11
|
+
- Cover all source statements, branches, functions, and lines, and require 100% coverage in the coverage command.
|
|
12
|
+
|
|
1
13
|
# 2.1.1 / 2026-09-11
|
|
2
14
|
|
|
3
15
|
- Override tsup's esbuild dependency to the patched 0.28.2 release, removing the older Windows development-server vulnerability.
|
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="
|
|
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
|
-
|
|
5
|
+
# @0xdoublesharp/lru-cache-clustered
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
[](https://www.npmjs.com/package/@0xdoublesharp/lru-cache-clustered)
|
|
8
|
+
[](https://github.com/doublesharp/lru-cache-clustered/actions/workflows/ci.yml)
|
|
9
|
+
[](https://codecov.io/gh/doublesharp/lru-cache-clustered)
|
|
10
|
+
[](https://www.npmjs.com/package/@0xdoublesharp/lru-cache-clustered)
|
|
8
11
|
|
|
9
|
-
|
|
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
|
-
|
|
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="
|
|
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
|
-
##
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
|
32
|
-
|
|
|
33
|
-
|
|
|
34
|
-
|
|
|
35
|
-
|
|
|
36
|
-
|
|
|
37
|
-
|
|
|
38
|
-
|
|
|
39
|
-
|
|
|
40
|
-
|
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
>
|
|
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
|
-
|
|
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
|
|
66
|
-
namespace: '
|
|
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
|
-
|
|
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
|
-
|
|
75
|
-
console.log(await cache.get('
|
|
76
|
-
|
|
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
|
-
|
|
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.
|
|
81
83
|
|
|
82
|
-
|
|
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.
|
|
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`.
|
|
85
85
|
|
|
86
|
-
##
|
|
86
|
+
## Use cases
|
|
87
87
|
|
|
88
|
-
|
|
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.
|
|
89
89
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
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) |
|
|
95
98
|
|
|
96
|
-
|
|
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.
|
|
97
100
|
|
|
98
|
-
|
|
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.
|
|
99
102
|
|
|
100
|
-
|
|
103
|
+
Namespaces separate application data by name. They do not restrict worker access, so all workers must be trusted.
|
|
101
104
|
|
|
102
|
-
Runnable
|
|
105
|
+
## Runnable examples
|
|
103
106
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
|
107
|
-
|
|
|
108
|
-
|
|
|
109
|
-
|
|
|
110
|
-
|
|
|
111
|
-
|
|
|
112
|
-
|
|
|
113
|
-
|
|
|
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.
|
|
108
|
+
|
|
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
|
-
|
|
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,7 @@ 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
|
-
|
|
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.
|
|
131
141
|
|
|
132
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.
|
|
133
143
|
|
|
@@ -150,7 +160,7 @@ const freshProducts = products.withoutLocal();
|
|
|
150
160
|
await freshProducts.get('sku:123'); // always goes to the primary
|
|
151
161
|
```
|
|
152
162
|
|
|
153
|
-
|
|
163
|
+
Local controls and metrics:
|
|
154
164
|
|
|
155
165
|
| Method | Description |
|
|
156
166
|
| ------------------------ | -------------------------------------------------------------------------------------------------------- |
|
|
@@ -179,9 +189,11 @@ See [`docs/l1.md`](docs/l1.md) for the full consistency model, stats, events, me
|
|
|
179
189
|
|
|
180
190
|
## How it works
|
|
181
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
|
+
|
|
182
194
|
`new LRUCacheClustered(...)` branches at construction:
|
|
183
195
|
|
|
184
|
-
- **In the primary** (`cluster.isPrimary === true`), the instance owns and operates on the in-process `LRUCache` for its namespace directly
|
|
196
|
+
- **In the primary** (`cluster.isPrimary === true`), the instance owns and operates on the in-process `LRUCache` for its namespace directly, without IPC.
|
|
185
197
|
- **In a worker**, every operation becomes a typed IPC request to the primary; the returned Promise resolves with the response.
|
|
186
198
|
|
|
187
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.
|
|
@@ -190,14 +202,30 @@ Instances in different workers that share a `namespace` operate on the same prim
|
|
|
190
202
|
|
|
191
203
|
## Performance profile
|
|
192
204
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
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.
|
|
198
224
|
|
|
199
225
|
## Options
|
|
200
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
|
+
|
|
201
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:
|
|
202
230
|
|
|
203
231
|
| Option | Type | Default | Description |
|
|
@@ -209,41 +237,47 @@ The serializable subset of [`lru-cache`](https://github.com/isaacs/node-lru-cach
|
|
|
209
237
|
|
|
210
238
|
`LocalL1Options`:
|
|
211
239
|
|
|
212
|
-
| Option | Type | Default | Description
|
|
213
|
-
| ---------------- | --------------------------- | ------------- |
|
|
214
|
-
| `enabled` | `boolean` | `true` | Set `false` to disable when an options object is reused.
|
|
215
|
-
| `experimental` | `boolean` | required | Must be `true` in
|
|
216
|
-
| `max` | `number` | `1000` | Maximum local entries per instance.
|
|
217
|
-
| `maxSize` | `number` | `undefined` | Optional local size bound. Uses one size unit per entry.
|
|
218
|
-
| `ttl` | `number` | derived | Local TTL in ms, capped by primary TTL and per-entry remaining TTL.
|
|
219
|
-
| `updateAgeOnGet` | `boolean` | `true` | Passed to the local `lru-cache`.
|
|
220
|
-
| `allowStale` | `boolean` | `false` | Passed to the local `lru-cache`; stale
|
|
221
|
-
| `invalidation` | `'broadcast' \| 'ttl-only'` | `'broadcast'` | Whether this instance subscribes to local/IPC invalidation pushes or relies only on local TTL expiry.
|
|
222
|
-
| `methods` | `{ get?, has?, fetch? }` | all enabled | Restrict which read families use L1. If present, omitted keys are disabled.
|
|
223
|
-
| `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. |
|
|
224
252
|
|
|
225
253
|
Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalculation`, or `fetchMethod` do not cross IPC and are not supported by this wrapper.
|
|
226
254
|
|
|
227
|
-
> **`failsafe: 'resolve'` caveat.**
|
|
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.
|
|
228
256
|
|
|
229
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.
|
|
230
258
|
|
|
231
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.
|
|
232
260
|
|
|
233
|
-
> **Key/value contract.** Like `lru-cache`, keys and values must be non-nullish. Passing `null` or `undefined` rejects
|
|
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.
|
|
234
262
|
|
|
235
263
|
## API
|
|
236
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
|
+
|
|
237
267
|
### Static
|
|
238
268
|
|
|
269
|
+
These helpers set up the shared cache before you start using it.
|
|
270
|
+
|
|
239
271
|
| Method | Description |
|
|
240
272
|
| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
241
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. |
|
|
242
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. |
|
|
243
|
-
| `LRUCacheClustered.getAllCaches()` | Returns the `Map<namespace, LRUCache>` registry.
|
|
275
|
+
| `LRUCacheClustered.getAllCaches()` | Returns the `Map<namespace, LRUCache>` registry. Primary only; throws in workers. |
|
|
244
276
|
|
|
245
277
|
### Core
|
|
246
278
|
|
|
279
|
+
Store a value, read it back, check whether it exists, or remove it.
|
|
280
|
+
|
|
247
281
|
| Method | Returns | Notes |
|
|
248
282
|
| --------------------------------------------- | ------------------------- | -------------------------------------------------------------- |
|
|
249
283
|
| `get(key, { bypassL1? })` | `Promise<V \| undefined>` | |
|
|
@@ -256,6 +290,8 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
256
290
|
|
|
257
291
|
### Multi
|
|
258
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
|
+
|
|
259
295
|
| Method | Returns | Notes |
|
|
260
296
|
| -------------------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
|
261
297
|
| `mGet(keys, { bypassL1? })` | `Promise<Map<K, V \| undefined>>` | Preserves input key order even when L1 partially hits. |
|
|
@@ -264,11 +300,13 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
264
300
|
|
|
265
301
|
### Enumeration
|
|
266
302
|
|
|
303
|
+
Inspect the contents or take a snapshot for later restoration. These methods return whole collections, so large caches create large responses.
|
|
304
|
+
|
|
267
305
|
| Method | Returns | Notes |
|
|
268
306
|
| -------------------------- | ------------------------------- | --------------------------------------------------------------- |
|
|
269
|
-
| `keys()` | `Promise<K[]>` |
|
|
270
|
-
| `values()` | `Promise<V[]>` |
|
|
271
|
-
| `entries()` | `Promise<[K, V][]>` |
|
|
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. |
|
|
272
310
|
| `[Symbol.asyncIterator]()` | `AsyncIterableIterator<[K, V]>` | `for await (const [k, v] of cache)`. Materializes the full set. |
|
|
273
311
|
| `dump()` | `Promise<[K, Entry][]>` | Serializable snapshot. |
|
|
274
312
|
| `load(entries)` | `Promise<void>` | Restores from a `dump()`, preserving per-entry TTL metadata. |
|
|
@@ -276,6 +314,8 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
276
314
|
|
|
277
315
|
### Counters and cache-aside
|
|
278
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
|
+
|
|
279
319
|
| Method | Returns | Notes |
|
|
280
320
|
| ---------------------------------------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
|
281
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). |
|
|
@@ -285,6 +325,8 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
285
325
|
|
|
286
326
|
### Local L1
|
|
287
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
|
+
|
|
288
330
|
| Method / event | Returns / payload | Notes |
|
|
289
331
|
| ------------------------------------------------- | ------------------------- | ---------------------------------------------------------------------------------------- |
|
|
290
332
|
| `localStats()` | `L1Stats \| undefined` | `undefined` when local L1 is disabled. |
|
|
@@ -293,11 +335,13 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
293
335
|
| `withoutLocal()` | `LRUCacheClustered<K, V>` | Bypass view for `get`, `has`, `peek`, `mGet`, and `fetch`; writes pass through normally. |
|
|
294
336
|
| `on('l1:hit' \| 'l1:miss' \| 'l1:set', listener)` | `{ namespace, key }` | Key is the original cache key, not an internal encoded key. |
|
|
295
337
|
| `on('l1:invalidate', listener)` | `{ namespace, key }` | `key` may be `'*'` for namespace-wide invalidation. |
|
|
296
|
-
| `on('l1:evict' \| 'l1:stale-hit', listener)` | `{ namespace, key }` | `stale-hit` fires when
|
|
338
|
+
| `on('l1:evict' \| 'l1:stale-hit', listener)` | `{ namespace, key }` | `stale-hit` also fires when an expired or version-stale local entry is rejected. |
|
|
297
339
|
| `off(event, listener)` / `once(event, listener)` | `this` | Standard event helpers. |
|
|
298
340
|
|
|
299
341
|
### Lifecycle, metrics, tunables
|
|
300
342
|
|
|
343
|
+
Check the cache, inspect its activity, change its limits, or remove its namespace.
|
|
344
|
+
|
|
301
345
|
| Method | Returns | Notes |
|
|
302
346
|
| ---------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
303
347
|
| `getRemainingTTL(key)` | `Promise<number>` | ms until expiry. `Infinity` for keys with no TTL; `0` for missing keys. |
|
|
@@ -306,14 +350,16 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
306
350
|
| `stats()` | `Promise<Stats>` | `{ hits, misses, sets, deletes, evictions, size, namespace }`. |
|
|
307
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. |
|
|
308
352
|
| `getCache()` | `LRUCache \| undefined` | Underlying `lru-cache` for this namespace. **Primary only**. |
|
|
309
|
-
| `ready` | `Promise<void>` |
|
|
353
|
+
| `ready` | `Promise<void>` | Waits for worker initialization but swallows failures. Use `getInstance()` when initialization errors should reject. |
|
|
310
354
|
| `max(value?)` | `Promise<number>` | Getter and setter. Setter preserves primary entries and remaining TTL metadata, then clears this instance's L1. |
|
|
311
355
|
| `ttl(value?)` | `Promise<number>` | Getter and setter. Setter clears this instance's L1. |
|
|
312
356
|
| `allowStale(value?)` | `Promise<boolean>` | Getter and setter. |
|
|
313
357
|
|
|
314
|
-
##
|
|
358
|
+
## Compression and codecs
|
|
359
|
+
|
|
360
|
+
Large documents take less cache space when compressed. A codec converts values before storage and converts them back when you read them.
|
|
315
361
|
|
|
316
|
-
`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.
|
|
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.
|
|
317
363
|
|
|
318
364
|
```ts
|
|
319
365
|
import { gzipSync, gunzipSync } from 'node:zlib';
|
|
@@ -332,20 +378,25 @@ await cache.set('user:42', { id: 42, name: 'ada' });
|
|
|
332
378
|
await cache.get('user:42'); // decoded back to { id: 42, name: 'ada' }
|
|
333
379
|
```
|
|
334
380
|
|
|
335
|
-
`encode` and `decode` may be sync or async. The
|
|
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.
|
|
336
382
|
|
|
337
|
-
`incr`
|
|
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.
|
|
338
384
|
|
|
339
|
-
> **
|
|
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.
|
|
340
386
|
|
|
341
387
|
## `memoize` helper
|
|
342
388
|
|
|
343
|
-
|
|
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.
|
|
344
392
|
|
|
345
393
|
```ts
|
|
346
394
|
import { LRUCacheClustered, memoize } from '@0xdoublesharp/lru-cache-clustered';
|
|
347
395
|
|
|
348
|
-
|
|
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 });
|
|
349
400
|
|
|
350
401
|
const getUser = memoize(
|
|
351
402
|
cache,
|
|
@@ -360,33 +411,77 @@ await getUser('42'); // second call: cached
|
|
|
360
411
|
|
|
361
412
|
### Single-flight semantics
|
|
362
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
|
+
|
|
363
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.
|
|
364
417
|
|
|
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
|
+
|
|
365
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.
|
|
366
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.
|
|
425
|
+
|
|
367
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.
|
|
368
427
|
|
|
369
428
|
## Errors
|
|
370
429
|
|
|
371
|
-
|
|
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`.
|
|
431
|
+
|
|
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.
|
|
372
433
|
|
|
373
|
-
**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))`.
|
|
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.
|
|
374
435
|
|
|
375
436
|
## Debugging
|
|
376
437
|
|
|
438
|
+
Turn on logs to see whether workers are reaching the primary and which requests they send.
|
|
439
|
+
|
|
377
440
|
```sh
|
|
378
441
|
DEBUG=lru-cache-clustered-* node app.js
|
|
379
442
|
```
|
|
380
443
|
|
|
381
444
|
Available namespaces:
|
|
382
445
|
|
|
383
|
-
- `lru-cache-clustered-primary`
|
|
384
|
-
- `lru-cache-clustered-messages`
|
|
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`.
|
|
385
480
|
|
|
386
|
-
|
|
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.
|
|
387
482
|
|
|
388
|
-
|
|
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.
|
|
389
484
|
|
|
390
485
|
## License
|
|
391
486
|
|
|
392
|
-
MIT
|
|
487
|
+
You can use, modify, and distribute this package under the MIT license. See [LICENSE](./LICENSE) for the terms.
|