@0xdoublesharp/lru-cache-clustered 2.1.1 → 2.1.3
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 +24 -0
- package/README.md +183 -121
- 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 +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,27 @@
|
|
|
1
|
+
# 2.1.3 / 2026-11-08
|
|
2
|
+
|
|
3
|
+
- Simplify the README, consolidate runnable examples, and redraw the cache topology with larger labels and a high-resolution PNG embed linked to the SVG.
|
|
4
|
+
- Update README links and npm repository metadata to the canonical `0xdoublesharp/lru-cache-clustered` repository.
|
|
5
|
+
- Update seven development dependencies within their existing major versions while preserving the seven-day release waiting policy.
|
|
6
|
+
- Resolve Zod 4.6.7 and override affected glob and minimatch versions with 14.0.3 and 11.0.3 to address development-tool resource-exhaustion and cancellation advisories.
|
|
7
|
+
- Backport the import plugin's minimatch 11 compatibility fix while its upstream release completes the waiting period.
|
|
8
|
+
- Add a deterministic regression test proving that an asynchronous IPC response failure does not resend the response or apply a counter mutation twice.
|
|
9
|
+
- Authenticate Codecov uploads with GitHub OIDC and scope coverage and Pages permissions to their respective jobs.
|
|
10
|
+
|
|
11
|
+
The runtime API, runtime dependencies, and Node.js 22 minimum are unchanged.
|
|
12
|
+
|
|
13
|
+
# 2.1.2 / 2026-10-15
|
|
14
|
+
|
|
15
|
+
- Handle asynchronous primary response and invalidation send failures when workers disconnect, without retrying mutations.
|
|
16
|
+
- Keep request IDs unique across ESM, CommonJS, and duplicate package copies in the same worker.
|
|
17
|
+
- Deliver worker-originated invalidations to primary-process L1 caches and invalidate applied batch changes even when a later entry fails.
|
|
18
|
+
- Preserve unrelated warm L1 entries during single-key writes and protect outstanding cache fills with temporary per-key fences.
|
|
19
|
+
- Release destroyed namespace version records while retaining monotonic mutation versions.
|
|
20
|
+
- Prevent older fetch claims from overwriting newer explicit mutations. A superseded fetch returns a newer cached value, or rejects if none remains.
|
|
21
|
+
- Benchmark real workers with configurable counts, payload sizes, mixed writes, batches, and coordinated fetches, including exact result checks and IPC counts.
|
|
22
|
+
- Increase the compressed bundle budget from 7 kB to 8 kB to accommodate the correctness fixes and bounded invalidation tracking.
|
|
23
|
+
- Cover all source statements, branches, functions, and lines, and require 100% coverage in the coverage command.
|
|
24
|
+
|
|
1
25
|
# 2.1.1 / 2026-09-11
|
|
2
26
|
|
|
3
27
|
- 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,126 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img src="https://raw.githubusercontent.com/
|
|
2
|
+
<img src="https://raw.githubusercontent.com/0xdoublesharp/lru-cache-clustered/main/assets/LRUCacheClustered.png" alt="A pika, the project mascot" width="128" height="128">
|
|
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/0xdoublesharp/lru-cache-clustered/actions/workflows/ci.yml)
|
|
9
|
+
[](https://codecov.io/gh/0xdoublesharp/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>
|
|
16
|
-
|
|
17
|
-
---
|
|
12
|
+
Shared in-memory [LRU caches](https://github.com/isaacs/node-lru-cache) for Node.js cluster workers, with atomic counters, coordinated fetches, and optional worker-local caching.
|
|
18
13
|
|
|
19
|
-
|
|
14
|
+
The primary process holds one cache per namespace. Workers share its entries through an asynchronous API over inter-process communication (IPC), so a value loaded by one worker is available to the others. No separate cache service is required; data stays in memory for the lifetime of the primary.
|
|
20
15
|
|
|
21
|
-
|
|
16
|
+
[Quick start](#quick-start) · [How it works](#how-it-works) · [Examples](#use-cases) · [Local L1](#local-l1-mode) · [API](#api)
|
|
22
17
|
|
|
23
|
-
|
|
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%">
|
|
25
|
-
</p>
|
|
18
|
+
## What you get
|
|
26
19
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
|
30
|
-
|
|
|
31
|
-
|
|
|
32
|
-
|
|
|
33
|
-
|
|
|
34
|
-
|
|
|
35
|
-
|
|
|
36
|
-
|
|
|
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 — 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. |
|
|
20
|
+
| Capability | How it works |
|
|
21
|
+
| ---------------------- | ------------------------------------------------------------------------------------------------ |
|
|
22
|
+
| Shared cache storage | One primary-owned cache per namespace, with optional extra copies in worker L1 caches. |
|
|
23
|
+
| Shared warm entries | A value loaded by one worker becomes available to the others. |
|
|
24
|
+
| Atomic counters | `incr()` and `decr()` execute in the primary; later increments preserve the original expiration. |
|
|
25
|
+
| Coordinated loading | `fetch()` and `memoize()` coordinate concurrent misses for a key through a primary-owned claim. |
|
|
26
|
+
| Temporary claims | `setIfAbsent()` atomically claims a key while it remains cached. |
|
|
27
|
+
| Optional local reads | L1 can serve repeated reads without IPC, with eventual consistency. |
|
|
28
|
+
| Compression and codecs | `wrap()` converts values on writes and reads through your encoder and decoder. |
|
|
29
|
+
| Metrics and errors | Namespace statistics, local L1 statistics, and structured IPC errors. |
|
|
41
30
|
|
|
42
31
|
## Install
|
|
43
32
|
|
|
44
|
-
`lru-cache` is a peer dependency — install it alongside this package so you control the version.
|
|
45
|
-
|
|
46
33
|
```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
|
|
34
|
+
npm install @0xdoublesharp/lru-cache-clustered lru-cache@^11
|
|
50
35
|
```
|
|
51
36
|
|
|
52
|
-
|
|
37
|
+
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.
|
|
53
38
|
|
|
54
|
-
|
|
39
|
+
Requires **Node.js 22 or newer**. Includes ESM and CommonJS builds and TypeScript declarations.
|
|
40
|
+
|
|
41
|
+
> `@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.
|
|
42
|
+
|
|
43
|
+
**2.1.3** is a maintenance release with clearer documentation and security updates to development tooling. See the [release notes](./CHANGELOG.md#213--2026-11-08) for details.
|
|
55
44
|
|
|
56
45
|
## Quick start
|
|
57
46
|
|
|
58
|
-
|
|
47
|
+
Start a few workers and give their caches the same name. A write from any worker goes into the shared cache in the primary.
|
|
48
|
+
|
|
49
|
+
Save this as `app.mjs` and run `node app.mjs` after installing the packages:
|
|
50
|
+
|
|
51
|
+
```js
|
|
59
52
|
import cluster from 'node:cluster';
|
|
60
|
-
import { availableParallelism } from 'node:os';
|
|
61
53
|
import { LRUCacheClustered } from '@0xdoublesharp/lru-cache-clustered';
|
|
62
54
|
|
|
63
55
|
LRUCacheClustered.bootstrap();
|
|
64
56
|
|
|
65
|
-
const
|
|
66
|
-
namespace: '
|
|
57
|
+
const options = {
|
|
58
|
+
namespace: 'greetings',
|
|
67
59
|
max: 1000,
|
|
68
60
|
ttl: 60_000,
|
|
69
|
-
|
|
61
|
+
failsafe: 'reject',
|
|
62
|
+
};
|
|
70
63
|
|
|
71
64
|
if (cluster.isPrimary) {
|
|
72
|
-
|
|
65
|
+
const cache = await LRUCacheClustered.getInstance(options);
|
|
66
|
+
await cache.set('hello', 'Hello from the shared cache');
|
|
67
|
+
cluster.fork();
|
|
68
|
+
cluster.fork();
|
|
73
69
|
} else {
|
|
74
|
-
|
|
75
|
-
console.log(await cache.get('
|
|
76
|
-
|
|
70
|
+
const cache = await LRUCacheClustered.getInstance(options);
|
|
71
|
+
console.log(`Worker ${cluster.worker.id}: ${await cache.get('hello')}`);
|
|
72
|
+
process.disconnect();
|
|
77
73
|
}
|
|
78
74
|
```
|
|
79
75
|
|
|
80
|
-
|
|
76
|
+
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
77
|
|
|
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.
|
|
78
|
+
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
79
|
|
|
86
|
-
##
|
|
80
|
+
## How it works
|
|
81
|
+
|
|
82
|
+
The primary owns the shared caches. Each namespace identifies one cache, and instances using that namespace must agree on options such as `max`, `ttl`, and `allowStale`. Conflicting options throw during initialization.
|
|
83
|
+
|
|
84
|
+
<p align="center">
|
|
85
|
+
<a href="https://raw.githubusercontent.com/0xdoublesharp/lru-cache-clustered/main/assets/topology.svg">
|
|
86
|
+
<img src="https://raw.githubusercontent.com/0xdoublesharp/lru-cache-clustered/main/assets/topology.png" alt="One primary process holds shared namespaced caches. Workers send IPC requests and receive responses. Each worker can optionally keep an L1 cache for local hits; writes reach the primary and trigger asynchronous invalidation." width="800">
|
|
87
|
+
</a>
|
|
88
|
+
</p>
|
|
89
|
+
|
|
90
|
+
- **In the primary**, operations call the namespace's `LRUCache` directly.
|
|
91
|
+
- **In a worker**, operations send typed IPC requests and return promises. With L1 enabled, eligible local hits skip IPC. Writes still reach the primary, which broadcasts invalidations by default.
|
|
87
92
|
|
|
88
|
-
|
|
93
|
+
> **Initialization.** In a worker, `new LRUCacheClustered(...)` sends an `init` message immediately. `cache.ready` waits for ordering but swallows initialization errors. Use `await LRUCacheClustered.getInstance(...)` or `await cache.healthCheck()` to fail startup when registration fails.
|
|
89
94
|
|
|
90
|
-
|
|
91
|
-
- Rate limiters and quota counters
|
|
92
|
-
- Feature flag snapshots
|
|
93
|
-
- Deduplicating expensive API or database calls
|
|
94
|
-
- Any cache-aside pattern across workers
|
|
95
|
+
## Use cases
|
|
95
96
|
|
|
96
|
-
|
|
97
|
+
The [example guide](./examples/README.md) includes request commands, ports, and environment settings. Run these commands from a checkout with dependencies installed.
|
|
97
98
|
|
|
98
|
-
|
|
99
|
+
| Example | Pattern | Run |
|
|
100
|
+
| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | -------------------------- |
|
|
101
|
+
| [User lookups](./examples/clustered-users-server.ts) | Share database results with `memoize()` and `fetch()`. | `pnpm example:users` |
|
|
102
|
+
| [Rate limiting](./examples/clustered-rate-limit-server.ts) | Use atomic counters with a fixed TTL window. | `pnpm example:rate-limit` |
|
|
103
|
+
| [Sessions](./examples/clustered-session-server.ts) | Share temporary session reads and writes. | `pnpm example:sessions` |
|
|
104
|
+
| [Job intake](./examples/clustered-idempotency-server.ts) | Suppress duplicate submissions with `setIfAbsent()`. | `pnpm example:idempotency` |
|
|
105
|
+
| [Compressed documents](./examples/clustered-compressed-documents-server.ts) | Encode stored values with `wrap()`. | `pnpm example:documents` |
|
|
106
|
+
| [Local L1 controls](./examples/clustered-l1-controls-server.ts) | Try method filters, bypass reads, invalidation, and write-through population. | `pnpm example:l1` |
|
|
107
|
+
| [Redis layers](./examples/clustered-multilayer-redis-server.ts) | Put shared memory and worker L1 in front of Redis. Requires Redis. | `pnpm example:multilayer` |
|
|
99
108
|
|
|
100
|
-
|
|
109
|
+
The [basic L1 server](./examples/clustered-l1-server.ts) also runs with `node --import tsx examples/clustered-l1-server.ts`.
|
|
101
110
|
|
|
102
|
-
|
|
111
|
+
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.
|
|
103
112
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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 |
|
|
113
|
+
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.
|
|
114
|
+
|
|
115
|
+
Namespaces separate application data by name. They do not restrict worker access, so all workers must be trusted.
|
|
114
116
|
|
|
115
117
|
## Local L1 mode
|
|
116
118
|
|
|
117
|
-
|
|
119
|
+
Enable `localL1` to keep frequently read values inside each worker and avoid repeated IPC reads. The primary owns every write. Invalidation messages tell workers to drop local entries after changes, but delivery is asynchronous.
|
|
118
120
|
|
|
119
121
|
```ts
|
|
122
|
+
type Product = { sku: string; name: string };
|
|
123
|
+
|
|
120
124
|
const products = new LRUCacheClustered<string, Product>({
|
|
121
125
|
namespace: 'products',
|
|
122
126
|
max: 25_000,
|
|
@@ -127,7 +131,7 @@ const products = new LRUCacheClustered<string, Product>({
|
|
|
127
131
|
|
|
128
132
|
> 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
133
|
|
|
130
|
-
|
|
134
|
+
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
135
|
|
|
132
136
|
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
137
|
|
|
@@ -150,7 +154,7 @@ const freshProducts = products.withoutLocal();
|
|
|
150
154
|
await freshProducts.get('sku:123'); // always goes to the primary
|
|
151
155
|
```
|
|
152
156
|
|
|
153
|
-
|
|
157
|
+
Local controls and metrics:
|
|
154
158
|
|
|
155
159
|
| Method | Description |
|
|
156
160
|
| ------------------------ | -------------------------------------------------------------------------------------------------------- |
|
|
@@ -177,27 +181,32 @@ By default, same-process and cross-worker writes broadcast invalidations so hot
|
|
|
177
181
|
|
|
178
182
|
See [`docs/l1.md`](docs/l1.md) for the full consistency model, stats, events, method options, and failure modes.
|
|
179
183
|
|
|
180
|
-
##
|
|
184
|
+
## Performance profile
|
|
181
185
|
|
|
182
|
-
|
|
186
|
+
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.
|
|
183
187
|
|
|
184
|
-
|
|
185
|
-
|
|
188
|
+
| Read path | Cost and behavior |
|
|
189
|
+
| ----------------------- | ------------------------------------------------------------------------------------------------------------ |
|
|
190
|
+
| Primary process | Dispatches to the local `lru-cache` without IPC. |
|
|
191
|
+
| Worker without L1 | Reads and writes use IPC. A cache hit still crosses processes. |
|
|
192
|
+
| Worker with L1 | Eligible local hits avoid IPC; misses and writes reach the primary. |
|
|
193
|
+
| Concurrent cache misses | One leader runs the fetcher while followers poll for the result, subject to claim expiry and forced refresh. |
|
|
186
194
|
|
|
187
|
-
|
|
195
|
+
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`.
|
|
188
196
|
|
|
189
|
-
|
|
197
|
+
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.
|
|
190
198
|
|
|
191
|
-
|
|
199
|
+
```sh
|
|
200
|
+
BENCH_WORKERS=1,4 BENCH_PAYLOAD_BYTES=128,16384 BENCH_ITERATIONS=2000 pnpm bench
|
|
201
|
+
BENCH_SERIALIZATION=advanced pnpm bench
|
|
202
|
+
```
|
|
192
203
|
|
|
193
|
-
|
|
194
|
-
- **Worker mode** — every cache operation is an IPC round trip through the primary.
|
|
195
|
-
- **Worker mode with local L1** — hot `get`, `has`, `peek`, `mGet`, and `fetch` reads can be served from process-local memory with no IPC; misses still go to the primary.
|
|
196
|
-
- **Hot misses** — `fetch()` and `memoize()` collapse concurrent misses for the same key across workers, so origin work scales with unique keys, not concurrent callers.
|
|
197
|
-
- **Design tradeoff** — 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.
|
|
204
|
+
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
205
|
|
|
199
206
|
## Options
|
|
200
207
|
|
|
208
|
+
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.
|
|
209
|
+
|
|
201
210
|
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
211
|
|
|
203
212
|
| Option | Type | Default | Description |
|
|
@@ -209,38 +218,40 @@ The serializable subset of [`lru-cache`](https://github.com/isaacs/node-lru-cach
|
|
|
209
218
|
|
|
210
219
|
`LocalL1Options`:
|
|
211
220
|
|
|
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.
|
|
221
|
+
| Option | Type | Default | Description |
|
|
222
|
+
| ---------------- | --------------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------- |
|
|
223
|
+
| `enabled` | `boolean` | `true` | Set `false` to disable when an options object is reused. |
|
|
224
|
+
| `experimental` | `boolean` | required | Must be `true` to opt in to eventual consistency. |
|
|
225
|
+
| `max` | `number` | `1000` | Maximum local entries per instance. |
|
|
226
|
+
| `maxSize` | `number` | `undefined` | Optional local size bound. Uses one size unit per entry. |
|
|
227
|
+
| `ttl` | `number` | derived | Local TTL in ms, capped by primary TTL and per-entry remaining TTL. |
|
|
228
|
+
| `updateAgeOnGet` | `boolean` | `true` | Passed to the local `lru-cache`. |
|
|
229
|
+
| `allowStale` | `boolean` | `false` | Passed to the local `lru-cache`; Stale returns and rejected expired/version-stale local entries increment `staleHits`. |
|
|
230
|
+
| `invalidation` | `'broadcast' \| 'ttl-only'` | `'broadcast'` | Whether this instance subscribes to local/IPC invalidation pushes or relies only on local TTL expiry. |
|
|
231
|
+
| `methods` | `{ get?, has?, fetch? }` | all enabled | Restrict which read families use L1. If present, omitted keys are disabled. |
|
|
232
|
+
| `cacheUndefined` | `boolean` | unsupported | Reserved for future negative-result caching; currently forced off. |
|
|
224
233
|
|
|
225
234
|
Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalculation`, or `fetchMethod` do not cross IPC and are not supported by this wrapper.
|
|
226
235
|
|
|
227
|
-
> **`failsafe: 'resolve'` caveat.**
|
|
236
|
+
> **`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
237
|
|
|
229
238
|
> **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
239
|
|
|
231
240
|
> **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
241
|
|
|
233
|
-
> **Key/value contract.** Like `lru-cache`, keys and values must be non-nullish. Passing `null` or `undefined` rejects
|
|
242
|
+
> **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
243
|
|
|
235
244
|
## API
|
|
236
245
|
|
|
246
|
+
The same methods work in the primary and in workers. Await shared-cache operations; local-cache controls run immediately in the calling process.
|
|
247
|
+
|
|
237
248
|
### Static
|
|
238
249
|
|
|
239
250
|
| Method | Description |
|
|
240
251
|
| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
241
252
|
| `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
253
|
| `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.
|
|
254
|
+
| `LRUCacheClustered.getAllCaches()` | Returns the `Map<namespace, LRUCache>` registry. Primary only; throws in workers. |
|
|
244
255
|
|
|
245
256
|
### Core
|
|
246
257
|
|
|
@@ -256,6 +267,8 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
256
267
|
|
|
257
268
|
### Multi
|
|
258
269
|
|
|
270
|
+
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.
|
|
271
|
+
|
|
259
272
|
| Method | Returns | Notes |
|
|
260
273
|
| -------------------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
|
261
274
|
| `mGet(keys, { bypassL1? })` | `Promise<Map<K, V \| undefined>>` | Preserves input key order even when L1 partially hits. |
|
|
@@ -264,11 +277,13 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
264
277
|
|
|
265
278
|
### Enumeration
|
|
266
279
|
|
|
280
|
+
Inspect the contents or take a snapshot for later restoration. These methods return whole collections, so large caches create large responses.
|
|
281
|
+
|
|
267
282
|
| Method | Returns | Notes |
|
|
268
283
|
| -------------------------- | ------------------------------- | --------------------------------------------------------------- |
|
|
269
|
-
| `keys()` | `Promise<K[]>` |
|
|
270
|
-
| `values()` | `Promise<V[]>` |
|
|
271
|
-
| `entries()` | `Promise<[K, V][]>` |
|
|
284
|
+
| `keys()` | `Promise<K[]>` | Most recently used first. |
|
|
285
|
+
| `values()` | `Promise<V[]>` | Most recently used first. |
|
|
286
|
+
| `entries()` | `Promise<[K, V][]>` | Most recently used first. |
|
|
272
287
|
| `[Symbol.asyncIterator]()` | `AsyncIterableIterator<[K, V]>` | `for await (const [k, v] of cache)`. Materializes the full set. |
|
|
273
288
|
| `dump()` | `Promise<[K, Entry][]>` | Serializable snapshot. |
|
|
274
289
|
| `load(entries)` | `Promise<void>` | Restores from a `dump()`, preserving per-entry TTL metadata. |
|
|
@@ -276,6 +291,8 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
276
291
|
|
|
277
292
|
### Counters and cache-aside
|
|
278
293
|
|
|
294
|
+
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.
|
|
295
|
+
|
|
279
296
|
| Method | Returns | Notes |
|
|
280
297
|
| ---------------------------------------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
|
281
298
|
| `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). |
|
|
@@ -293,7 +310,7 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
293
310
|
| `withoutLocal()` | `LRUCacheClustered<K, V>` | Bypass view for `get`, `has`, `peek`, `mGet`, and `fetch`; writes pass through normally. |
|
|
294
311
|
| `on('l1:hit' \| 'l1:miss' \| 'l1:set', listener)` | `{ namespace, key }` | Key is the original cache key, not an internal encoded key. |
|
|
295
312
|
| `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
|
|
313
|
+
| `on('l1:evict' \| 'l1:stale-hit', listener)` | `{ namespace, key }` | `stale-hit` also fires when an expired or version-stale local entry is rejected. |
|
|
297
314
|
| `off(event, listener)` / `once(event, listener)` | `this` | Standard event helpers. |
|
|
298
315
|
|
|
299
316
|
### Lifecycle, metrics, tunables
|
|
@@ -306,14 +323,16 @@ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalc
|
|
|
306
323
|
| `stats()` | `Promise<Stats>` | `{ hits, misses, sets, deletes, evictions, size, namespace }`. |
|
|
307
324
|
| `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
325
|
| `getCache()` | `LRUCache \| undefined` | Underlying `lru-cache` for this namespace. **Primary only**. |
|
|
309
|
-
| `ready` | `Promise<void>` |
|
|
326
|
+
| `ready` | `Promise<void>` | Waits for worker initialization but swallows failures. Use `getInstance()` when initialization errors should reject. |
|
|
310
327
|
| `max(value?)` | `Promise<number>` | Getter and setter. Setter preserves primary entries and remaining TTL metadata, then clears this instance's L1. |
|
|
311
328
|
| `ttl(value?)` | `Promise<number>` | Getter and setter. Setter clears this instance's L1. |
|
|
312
329
|
| `allowStale(value?)` | `Promise<boolean>` | Getter and setter. |
|
|
313
330
|
|
|
314
|
-
##
|
|
331
|
+
## Compression and codecs
|
|
315
332
|
|
|
316
|
-
|
|
333
|
+
Large documents take less cache space when compressed. A codec converts values before storage and converts them back when you read them.
|
|
334
|
+
|
|
335
|
+
`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
336
|
|
|
318
337
|
```ts
|
|
319
338
|
import { gzipSync, gunzipSync } from 'node:zlib';
|
|
@@ -332,20 +351,23 @@ await cache.set('user:42', { id: 42, name: 'ada' });
|
|
|
332
351
|
await cache.get('user:42'); // decoded back to { id: 42, name: 'ada' }
|
|
333
352
|
```
|
|
334
353
|
|
|
335
|
-
`encode` and `decode` may be sync or async. The
|
|
354
|
+
`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
355
|
|
|
337
|
-
`incr`
|
|
356
|
+
`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
357
|
|
|
339
|
-
> **
|
|
358
|
+
> **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
359
|
|
|
341
360
|
## `memoize` helper
|
|
342
361
|
|
|
343
|
-
|
|
362
|
+
`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
363
|
|
|
345
364
|
```ts
|
|
346
365
|
import { LRUCacheClustered, memoize } from '@0xdoublesharp/lru-cache-clustered';
|
|
347
366
|
|
|
348
|
-
|
|
367
|
+
type User = { id: string; name: string };
|
|
368
|
+
|
|
369
|
+
// fetchUserFromDB is your application's database lookup.
|
|
370
|
+
const cache = new LRUCacheClustered<string, User>({ namespace: 'users', max: 1000, ttl: 60_000 });
|
|
349
371
|
|
|
350
372
|
const getUser = memoize(
|
|
351
373
|
cache,
|
|
@@ -360,17 +382,27 @@ await getUser('42'); // second call: cached
|
|
|
360
382
|
|
|
361
383
|
### Single-flight semantics
|
|
362
384
|
|
|
385
|
+
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.
|
|
386
|
+
|
|
363
387
|
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
388
|
|
|
389
|
+
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.
|
|
390
|
+
|
|
391
|
+
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.
|
|
392
|
+
|
|
365
393
|
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
394
|
|
|
395
|
+
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.
|
|
396
|
+
|
|
367
397
|
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
398
|
|
|
369
399
|
## Errors
|
|
370
400
|
|
|
371
|
-
|
|
401
|
+
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`.
|
|
372
402
|
|
|
373
|
-
**
|
|
403
|
+
**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.
|
|
404
|
+
|
|
405
|
+
**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
406
|
|
|
375
407
|
## Debugging
|
|
376
408
|
|
|
@@ -380,13 +412,43 @@ DEBUG=lru-cache-clustered-* node app.js
|
|
|
380
412
|
|
|
381
413
|
Available namespaces:
|
|
382
414
|
|
|
383
|
-
- `lru-cache-clustered-primary`
|
|
384
|
-
- `lru-cache-clustered-messages`
|
|
415
|
+
- `lru-cache-clustered-primary` logs cache creation and registry events.
|
|
416
|
+
- `lru-cache-clustered-messages` logs IPC requests and responses.
|
|
417
|
+
- `lru-cache-clustered-invalidations` logs errors thrown by local invalidation subscribers.
|
|
418
|
+
|
|
419
|
+
## Migration
|
|
420
|
+
|
|
421
|
+
`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.
|
|
422
|
+
|
|
423
|
+
## Development
|
|
424
|
+
|
|
425
|
+
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.
|
|
426
|
+
|
|
427
|
+
```sh
|
|
428
|
+
git clone https://github.com/0xdoublesharp/lru-cache-clustered.git
|
|
429
|
+
cd lru-cache-clustered
|
|
430
|
+
corepack enable
|
|
431
|
+
pnpm install --frozen-lockfile
|
|
432
|
+
pnpm check
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
| Command | What it does |
|
|
436
|
+
| -------------------- | ------------------------------------------------------------------------------------------------------ |
|
|
437
|
+
| `pnpm check` | Lint, typecheck, tests, unused-code checks, type coverage, build, and bundle-size checks. |
|
|
438
|
+
| `pnpm test` | Unit, fuzz, and real cluster-worker tests. |
|
|
439
|
+
| `pnpm test:coverage` | Text and LCOV reports in `coverage/`; requires 100% source statements, branches, functions, and lines. |
|
|
440
|
+
| `pnpm build` | ESM and CommonJS bundles with TypeScript declarations in `dist/`. |
|
|
441
|
+
| `pnpm bench` | Compare worker reads with and without local L1. |
|
|
442
|
+
| `pnpm example:users` | Start the shared user-cache example. |
|
|
443
|
+
|
|
444
|
+
`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`.
|
|
445
|
+
|
|
446
|
+
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.
|
|
385
447
|
|
|
386
|
-
|
|
448
|
+
Dependency resolution waits seven days after publication through `minimumReleaseAge` in `pnpm-workspace.yaml`. Use frozen lockfile installs for reproducible checks. The [dependency update notes](./docs/dependency-updates.md) describe security overrides and the import-plugin compatibility patch.
|
|
387
449
|
|
|
388
|
-
|
|
450
|
+
Release preparation with `pnpm prepare:publish` creates scoped and legacy package directories under `dist-publish/`. Pushing a `vX.Y.Z` tag matching the version in `package.json` triggers the [publishing workflow](./.github/workflows/npm-publish.yml), which runs the package checks and publishes both names to npm with provenance through GitHub OIDC.
|
|
389
451
|
|
|
390
452
|
## License
|
|
391
453
|
|
|
392
|
-
MIT
|
|
454
|
+
[MIT](./LICENSE).
|