tricache 0.7.0 → 0.7.1

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.
Files changed (40) hide show
  1. package/README.md +1428 -1428
  2. package/bin/tricache.js +8 -8
  3. package/dist/cache-service-5GATUYAK.js +7 -0
  4. package/dist/{cache-service-BblHuF3i.d.ts → cache-service-D8tIXmzb.d.ts} +23 -1
  5. package/dist/{chunk-3XQUQBOZ.js → chunk-EUGYR7KR.js} +87 -41
  6. package/dist/{chunk-PFB5FMEY.js → chunk-X5AXHPVD.js} +26 -15
  7. package/dist/cli.cjs +113 -56
  8. package/dist/cli.js +3 -3
  9. package/dist/drizzle/index.cjs +114 -57
  10. package/dist/drizzle/index.d.ts +1 -1
  11. package/dist/drizzle/index.js +1 -1
  12. package/dist/http/index.cjs +149 -64
  13. package/dist/http/index.d.ts +1 -1
  14. package/dist/http/index.js +38 -10
  15. package/dist/index.cjs +112 -55
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +2 -2
  18. package/dist/nestjs/index.cjs +112 -55
  19. package/dist/nestjs/index.d.ts +1 -1
  20. package/dist/nestjs/index.js +2 -2
  21. package/dist/next/index.cjs +143 -63
  22. package/dist/next/index.d.ts +10 -6
  23. package/dist/next/index.js +33 -10
  24. package/dist/prisma/index.cjs +2 -1
  25. package/dist/prisma/index.d.ts +1 -1
  26. package/dist/prisma/index.js +2 -1
  27. package/dist/serialize-worker.cjs +26 -15
  28. package/dist/serialize-worker.js +1 -1
  29. package/package.json +4 -2
  30. package/src/cache-service.ts +3294 -3226
  31. package/src/cli.ts +143 -143
  32. package/src/compression.ts +56 -63
  33. package/src/disk-tier.ts +821 -821
  34. package/src/encryption.ts +513 -493
  35. package/src/http/index.ts +265 -223
  36. package/src/next/cache-handler.ts +268 -244
  37. package/src/prisma/index.ts +154 -151
  38. package/src/smart-memory-cache.ts +1026 -1024
  39. package/src/types.ts +911 -902
  40. package/dist/cache-service-AJASH5FX.js +0 -7
package/README.md CHANGED
@@ -1,1428 +1,1428 @@
1
- # TriCache
2
-
3
- [![CI](https://github.com/Kareem411/TriCache/actions/workflows/ci.yml/badge.svg)](https://github.com/Kareem411/TriCache/actions/workflows/ci.yml)
4
- [![npm version](https://img.shields.io/npm/v/tricache.svg)](https://www.npmjs.com/package/tricache)
5
- [![Tests](https://img.shields.io/badge/tests-484%20passing-brightgreen)](tests)
6
- [![Code Quality](https://img.shields.io/badge/oxlint-0%20warnings-brightgreen)](src)
7
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
8
- [![Node.js ≥ 22](https://img.shields.io/badge/node-%3E%3D22-brightgreen)](https://nodejs.org)
9
- [![TypeScript](https://img.shields.io/badge/TypeScript-Strict%20%7C%205.x%20%7C%206.x-blue)](https://www.typescriptlang.org)
10
- [![npm provenance](https://img.shields.io/badge/provenance-verified-brightgreen)](https://www.npmjs.com/package/tricache)
11
-
12
- tricache is a three-tier Node.js cache library — in-memory (L1), local disk spill, and Redis/Valkey (L2). Warm L1 reads run at 2.81 million operations per second on a single thread (356 ns/op) — well below any network round-trip, including a local Redis call. When L1 fills, evicted entries spill to disk instead of being dropped, keeping hit rates high without unbounded RAM growth. Misses that reach L2 are coalesced across concurrent callers, so a spike of simultaneous requests for the same key triggers exactly one fetchFn call, not one per caller. See the performance section for full numbers. Optional configuration adds Stale-While-Revalidate, at-rest encryption (AES-256-GCM by default), pub/sub fleet-wide invalidation, an OOM guard, cold-start snapshots, and Prometheus metrics — none of it required to get started.
13
-
14
- <img src="https://raw.githubusercontent.com/Kareem411/TriCache/master/public/SmartMemoryCache_DiskTier.jpeg" width="600" alt="tricache architecture" />
15
-
16
- ---
17
-
18
- ## 🏆 What Makes TriCache a "No-Brainer"
19
-
20
- | Dimension | Industry Standard (`keyv`, `@neshca/cache-handler`, `cache-manager`) | **TriCache v0.7.0** |
21
- |:---|:---|:---|
22
- | **Storage Hierarchy** | Single-tier (RAM or Redis or Disk) | **Three-Tier (RAM → NVMe Disk → Redis/Valkey)** |
23
- | **Thundering-Herd** | Unhandled / requires external single-flight libraries | **Built-in Inflight Promise Coalescing (10k tested)** |
24
- | **Tag Invalidation** | $O(N)$ bulk key scans or Redis `SMEMBERS` deletions | **$O(1)$ Generational Version Counters (`MULTI/EXEC`)** |
25
- | **Next.js 16 Support** | Basic key-value handlers, broken RSC stream reuse | **Native 5-Method Bridge with stream re-hydration & `cacheLife`** |
26
- | **NestJS Support** | Generic `CacheModule` with missing batch/tag methods | **Dynamic `TriCacheModule` + `@Cacheable` & `@CacheEvict` decorators** |
27
- | **Cluster Invalidation** | At-most-once Pub/Sub (drops messages on network blips) | **Durable Redis Streams (`XADD`/`XREAD`) with reconnect replay** |
28
- | **Memory Hygiene** | Standard JSON stringification, unconstrained RAM | **WASM Bloom filter, Count-Min Sketch, Zero-Copy `transferList` workers** |
29
- | **Failure Tolerance** | Cascading 500s when Redis/Upstream flutters | **Circuit Breaker, `staleIfError` SWR grace, monotonic tag guarantees** |
30
-
31
- ---
32
-
33
- ## ✨ Features
34
-
35
- | Feature | Detail |
36
- |---|---|
37
- | **Next.js 16 & 15 Adapter** | Full `CacheHandler` implementation for Next.js 16 `"use cache"` and legacy ISR; single-use stream re-hydration, dynamic `softTags` checking, and automatic `NEXT_PHASE` build bypass |
38
- | **NestJS Dynamic Module & Store** | Dedicated `TriCacheModule.register()` dynamic module, `TriCacheStore` adapter for `@nestjs/cache-manager`, and declarative `@Cacheable` / `@CacheEvict` method decorators |
39
- | **First-Class Prisma Extension** | `withTriCache(options)` for `$extends` with automatic query key hashing, cache options, and write mutation tag invalidation |
40
- | **First-Class Drizzle Wrapper** | `withCache(query, options)` wrapping Drizzle queries with automatic SQL + params hashing and SWR support |
41
- | **Distributed Mutex Lock** | `cache.lock(key, fn, options)` with Redis `SET NX EX`, atomic Lua token-release, and local promise-chain fallback |
42
- | **Native OpenTelemetry Metrics** | Direct `meter` integration publishing monotonic counters and observable gauges without scrapers |
43
- | **Interactive Developer CLI** | Zero-dependency CLI (`npx tricache inspect`, `ping`, `clear`) with terminal dashboard and latency probes |
44
- | **Universal `cache.wrap()` Primitive** | Options-object wrapper (`{ ttl, swr, tags, dependsOn, priority }`) for ORMs and service layers |
45
- | **Generational Tagging** | $O(1)$ tag invalidations via Redis version counters (`INCR tag_ver:<tag>`); atomic `{d, t, tv}` hash schema, pipelined batch `invalidateTags()`, and time-based self-healing reconciliation |
46
- | **Read Safety (`cloneStrategy`)** | `cloneStrategy: 'structuredClone'` isolates returned objects from caller mutation; sub-microsecond raw reference fallback (`'none'`) |
47
- | **Redis Streams Backplane** | `backplaneMode: 'stream'` replaces at-most-once Pub/Sub with durable `XADD`/`XREAD` append-only log; cluster hash tag slot safety and zero-drop reconnect replay |
48
- | **Atomic Disk Writes** | Atomic staging via unique `.tmp` sibling files with Windows NTFS file-lock micro-retries and background `.tmp` janitor sweep |
49
- | **Adaptive eviction** | LFU × LRU × priority score + Count-Min Sketch cross-eviction frequency; reservoir-sampled O(1) hot path; category limits prevent any prefix monopolising RAM |
50
- | **Count-Min Sketch** | 4 × 512 `Uint16Array` (4 KB) tracks historical access frequency across eviction boundaries — same-priority burst keys cannot displace long-resident entries; **84 % survival rate** in benchmark flood tests |
51
- | **WASM Bloom filter** | 562-byte binary inlined as Base64 — O(k=7) guaranteed-miss detection, no filesystem access, pure-JS fallback |
52
- | **msgpackr serialization** | All entries packed with msgpackr — uniform binary format, no JSON at any payload size |
53
- | **Stale-While-Revalidate** | Serve stale instantly, revalidate in background — zero added latency on cache hit |
54
- | **Stale-if-error** | Extend a stale entry's TTL when SWR revalidation fails — no errors served during upstream outages |
55
- | **Thundering-herd prevention** | Inflight `Promise` registry — only one `fetchFn` call per key regardless of concurrency (10,000 tested) |
56
- | **Pub/sub invalidation backplane** | Redis pub/sub channel propagates deletes across all instances in real time |
57
- | **Tag-based invalidation** | Tag entries on write; `invalidateTag('catalog')` evicts all matching entries from L1, disk, and Redis atomically |
58
- | **Batch read** | `mget()` collects L1 hits, calls `fetchFn` only for misses, preserves ordering |
59
- | **Batch write** | `mset()` / `mdel()` write or delete many keys in a single `Promise.all` call |
60
- | **TTL jitter** | `ttlJitterFactor` spreads expirations across a configurable ± window — prevents thundering-cliff mass-expiry |
61
- | **OpenTelemetry spans** | Structural `ICacheTracer` / `ICacheSpan` interfaces — pass any OTEL-compatible tracer; no peer dep required |
62
- | **L2 circuit breaker** | Suspends Redis after N consecutive failures; auto-probes after cooldown; state visible in `metrics()` |
63
- | **`warmFromL2(pattern)`** | Scan Redis and pre-populate L1 at startup; returns count loaded; no-op when Redis unavailable |
64
- | **OOM guard** | Polls `heapUsed/heapTotal` on a timer; emergency-evicts coldest L1 entries before the process crashes |
65
- | **Cold-start snapshot** | L1 serialised to disk on `SIGTERM`/`SIGINT`, reloaded on next startup — warm cache, cold process |
66
- | **AES-256-GCM encryption** | L2 (Redis) values, disk spill files, and snapshots encrypted at rest; zero-downtime key rotation via `previousEncryptionKey` |
67
- | **Prometheus metrics** | `cache.metrics()` + `CacheService.toPrometheusText()` — drop into any `/metrics` endpoint |
68
- | **Distributed counter** | `cache.increment()` backed by Redis `INCR` for distributed rate limiting; in-process fallback when Redis is disabled |
69
- | **Pluggable logger** | Bring your own `pino`, `winston`, etc. |
70
- | **L2 read-only mode** | `l2WriteMode: 'read-only'` reads from Redis but skips all writes — canary deploys, read replicas |
71
- | **Eviction callback** | `onEviction(key, reason)` fires on every L1 eviction with a typed reason string |
72
- | **Negative caching (`notFoundTtl`)** | Cache `null`/`undefined` fetchFn results for a configurable TTL — prevents hammering upstream on repeated misses |
73
- | **`setIfAbsent()`** | Atomic "set if not cached" — L1 `has()` check → Redis `SET NX EX` → L1 set on success; returns `true` if written, `false` if already present |
74
- | **Refresh-ahead** | Proactively recompute an entry in the background when remaining TTL falls below a configured fraction — zero-latency freshness |
75
- | **XFetch probabilistic early expiry** | Probabilistic background recompute keyed to last fetch duration and `xfetchBeta` — optimal protection against expiry spikes under load |
76
- | **Adaptive TTL** | Tracks per-key fetch latency in a rolling ring buffer; once ≥ 5 samples are collected, automatically sets TTL = `p95LatencyMs × multiplier`. Expensive keys get cached longer; cheap keys stay close to their base TTL — no manual TTL tuning required |
77
- | **`hotKeys(n)`** | Returns top N keys by Count-Min Sketch access frequency with size — no full Map scan |
78
- | **`dependsOn` cascade invalidation** | Tag entries with parent keys; deleting a parent automatically evicts all declared dependents from L1 |
79
- | **`onHit` / `onMiss` callbacks** | Per-operation hit/miss hooks with tier info (`'l1'` \| `'disk'` \| `'l2'`) — no wait for the metrics interval |
80
- | **`frozen` mode** | Dev-time mutation guard — `Object.freeze()` applied recursively to every L1 hit so accidental mutations throw immediately |
81
- | **`tags` in `get()` opts** | Attach tags at read time; when `fetchFn` populates the entry on a miss the tags are registered automatically |
82
-
83
- ---
84
-
85
- ## 📦 Install
86
-
87
- ```bash
88
- npm install tricache
89
- # or
90
- pnpm add tricache
91
- ```
92
-
93
- ---
94
-
95
- ## 🚀 Quick start
96
-
97
- ```typescript
98
- import { CacheService, CachePriority } from 'tricache';
99
-
100
- // Get (or create) the process-level singleton
101
- const cache = CacheService.create({
102
- redisHost: 'my-redis.example.com', // omit or set NODE_ENV!=production to disable L2
103
- });
104
-
105
- // Get-or-fetch with a 5-minute TTL
106
- const user = await cache.get(
107
- `user:${userId}`,
108
- () => db.users.findById(userId),
109
- 300,
110
- );
111
-
112
- // Universal wrap() with options object (alternative to get)
113
- const profile = await cache.wrap(
114
- `user:${userId}:profile`,
115
- () => db.users.findProfile(userId),
116
- { ttl: 300, swr: 60, tags: ['users'] },
117
- );
118
-
119
- // Explicit set
120
- await cache.set(`user:${userId}`, user, 300);
121
-
122
- // Delete one key
123
- await cache.delete(`user:${userId}`);
124
-
125
- // Delete by glob pattern
126
- await cache.delete(`user:${userId}:*`);
127
-
128
- // Stale-While-Revalidate: serve stale for up to 30 s while refreshing in background
129
- const dashboard = await cache.get(
130
- `dashboard:${orgId}`,
131
- () => analytics.buildDashboard(orgId),
132
- 300,
133
- { swr: 30 },
134
- );
135
-
136
- // Distributed rate-limiting counter
137
- const hits = await cache.increment(`ratelimit:${ip}`, 60 /* TTL seconds */);
138
-
139
- // Check if a key is cached (fast, no fetch)
140
- const isCached = cache.has(`user:${userId}`);
141
-
142
- // Batch read
143
- const [userA, userB] = await cache.mget(
144
- [`user:${userIdA}`, `user:${userIdB}`],
145
- (missKeys) => db.users.findByIds(missKeys).then(rowsToMap),
146
- 300,
147
- );
148
-
149
- // Batch write
150
- await cache.mset({
151
- [`user:${userIdA}`]: { value: userA, ttl: 300 },
152
- [`user:${userIdB}`]: { value: userB, ttl: 300 },
153
- });
154
-
155
- // Batch delete
156
- await cache.mdel([`user:${userIdA}`, `user:${userIdB}`]);
157
- ```
158
-
159
- > [!TIP]
160
- > **In-Memory Reference Semantics & Mutation Safety:**
161
- > By default, TriCache returns direct in-memory object references from L1 RAM (`cloneStrategy: 'none'`) to achieve sub-microsecond throughput (**2.81M ops/sec / 356 ns**). If your callers mutate returned objects in-place, enable `cloneStrategy: 'structuredClone'` for deep copy isolation, or enable `frozen: true` in non-production environments to catch mutations at runtime.
162
-
163
- ```typescript
164
- // Warm L1 from Redis at startup
165
- const loaded = await cache.warmFromL2('user:*');
166
- console.log(`Pre-warmed ${loaded} user entries`);
167
-
168
- // Or auto-warm at construction + gate traffic with ready()
169
- const cache2 = CacheService.create({ warmKeys: 'user:*' });
170
- await cache2.ready(); // resolves once warm-up completes — ideal for k8s readiness probes
171
-
172
- // Atomic set-if-absent — returns true if written, false if key already cached
173
- const written = await cache.setIfAbsent(`session:${id}`, sessionData, 3600);
174
-
175
- // Dependency cascade: deleting 'org:42' automatically evicts 'org:42:config'
176
- await cache.set('org:42:config', config, 300, undefined, { dependsOn: ['org:42'] });
177
- await cache.delete('org:42'); // also evicts org:42:config
178
-
179
- // Top 10 hottest keys by Count-Min Sketch frequency
180
- const hot = cache.hotKeys(10);
181
- console.log(hot); // [{ key: 'user:1', hits: 842, sizeBytes: 512 }, ...]
182
-
183
- // Tag entries for group invalidation
184
- await cache.set(`product:${id}`, product, 300, undefined, { tags: ['catalog'] });
185
- await cache.invalidateTag('catalog'); // evict all catalog entries
186
-
187
- // Health check with tier latencies
188
- const { l1, disk, l2 } = await cache.ping();
189
-
190
- // Prometheus metrics
191
- const snap = cache.metrics();
192
- console.log(CacheService.toPrometheusText(snap));
193
- ```
194
-
195
- ---
196
-
197
- ## ⚙️ Configuration
198
-
199
- All options are optional — sensible defaults apply.
200
-
201
- ```typescript
202
- CacheService.create({
203
- // ── Namespace ─────────────────────────────────────────────────────────
204
- // Isolates keys, disk dir, snapshot file, and Redis backplane channel.
205
- // Two instances with different namespaces are fully independent.
206
- namespace: 'my-app',
207
-
208
- // ── Logger ────────────────────────────────────────────────────────────
209
- logger: pinoLogger, // default: console warn/error only
210
-
211
- // ── L1 (in-memory) ───────────────────────────────────────────────────
212
- l1MaxBytes: 200 * 1024 * 1024, // 200 MB total RAM cap (default)
213
- l1MaxEntries: 2_000, // max entries in L1 (default)
214
- l1EvictionWatermark: 0.9, // proactive eviction fires at 90 % of l1MaxEntries / l1MaxBytes (default)
215
- // lower to 0.8 to reduce GC pressure on heap-bound workloads
216
- categoryLimits: {
217
- // per-prefix limits — keys are matched by startsWith()
218
- 'user:': { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 },
219
- 'analytics:': { maxEntries: 100, maxSizeBytes: 20 * 1024 * 1024 },
220
- 'default': { maxEntries: 1000, maxSizeBytes: 100 * 1024 * 1024 },
221
- },
222
-
223
- // ── L1.5 (disk spill) ────────────────────────────────────────────────
224
- diskCacheDir: '/tmp/my-app-cache', // default: os.tmpdir()/tricache-disk
225
- diskMaxBytes: 500 * 1024 * 1024, // 500 MB (default)
226
- diskEntryMaxBytes: 10 * 1024 * 1024, // 10 MB per entry (default)
227
-
228
- // ── L2 (Redis / Valkey) ──────────────────────────────────────────────
229
- redisHost: 'my-redis.example.com', // or REDIS_HOST env var
230
- redisPort: 6379,
231
- redisTls: true, // default: true when NODE_ENV=production
232
- redisProtocol: 3, // default: 3 (RESP3 in ioredis v6+); set to 2 for RESP2 proxies (Twemproxy/Envoy)
233
- disableRedis: false, // default: true when NODE_ENV!=production
234
-
235
- // ── Transparent payload compression ──────────────────────────────────
236
- // 'none' (default) — raw msgpack/JSON representation
237
- // 'brotli' | 'gzip' — compress Redis L2 payloads and disk tier binaries
238
- compression: 'none',
239
- compressionThresholdBytes: 1024, // only compress entries ≥ 1 KB (default)
240
-
241
- // ── Invalidation backplane ───────────────────────────────────────────
242
- invalidationBackplane: true,
243
- // 'pubsub' (default) — Ephemeral Redis Pub/Sub (at-most-once delivery)
244
- // 'stream' — Durable Redis Streams (XADD/XREAD) with replay on reconnect
245
- backplaneMode: 'pubsub',
246
- backplaneStreamMaxLen: 10_000, // max entries retained in invalidation stream
247
- backplaneStreamBlockMs: 2_000, // blocking poll interval for XREAD BLOCK
248
- // backplaneStreamKey: 'tricache:stream:{my-app}', // custom stream key override
249
-
250
- // ── Generational tagging & clone strategy ─────────────────────────────
251
- // 'set' (default) — traditional Redis Set member tracking
252
- // 'generational' — atomic O(1) integer version counters in Redis + memory
253
- tagStrategy: 'set',
254
- tagVersionTtlMs: 5_000, // ms before local generational tag is re-synced from Redis
255
- // 'none' (default) — raw in-memory references (~350 ns performance)
256
- // 'structuredClone' — deep-clones returned values to prevent caller mutation
257
- cloneStrategy: 'none',
258
-
259
- // ── OOM guard ────────────────────────────────────────────────────────
260
- oomProtection: true, // enabled by default
261
- oomHeapThreshold: 0.85, // evict when heapUsed/heapTotal > 85 %
262
- oomCheckIntervalMs: 10_000, // poll every 10 s
263
- oomEvictPercent: 0.20, // evict coldest 20 % of L1 per trigger
264
-
265
- // ── Encryption ───────────────────────────────────────────────────────
266
- // base64-encoded 32-byte key; or set CACHE_ENCRYPTION_KEY env var.
267
- // node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
268
- encryptionKey: process.env.CACHE_ENCRYPTION_KEY,
269
-
270
- // Zero-downtime key rotation — remove after all old entries have expired
271
- previousEncryptionKey: process.env.PREV_ENCRYPTION_KEY,
272
- previousEncryptionMode: 'aes-256-gcm', // defaults to current encryptionMode
273
-
274
- // ── L2 write mode ────────────────────────────────────────────────────
275
- // 'read-write' (default) — reads and writes to Redis
276
- // 'read-only' — reads from Redis, skips all writes (canary / replica)
277
- l2WriteMode: 'read-write',
278
-
279
- // ── Stale-if-error ───────────────────────────────────────────────────
280
- // Extra seconds to extend a stale L1 entry's expiry when a SWR fetchFn fails.
281
- // Prevents serving errors while the upstream is temporarily down.
282
- staleIfError: 300, // keep stale for 5 more minutes on revalidation error
283
-
284
- // ── Eviction callback ────────────────────────────────────────────────
285
- // Called synchronously whenever L1 evicts a key.
286
- // reason: 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual'
287
- onEviction: (key, reason) => metrics.increment(`cache.eviction.${reason}`),
288
-
289
- // ── TTL jitter ────────────────────────────────────────────────────────
290
- // Multiply each TTL by a random factor in [1-j, 1+j] to spread expiry.
291
- // Prevents mass-expiry stampedes ("thundering cliff").
292
- // Range [0, 1]; default 0 (no jitter).
293
- ttlJitterFactor: 0.15, // ± 15 % spread
294
-
295
- // ── Adaptive TTL ──────────────────────────────────────────────────────
296
- // When true, tricache tracks per-key fetch latency in a rolling ring
297
- // buffer and derives an optimal TTL from the p95 fetch duration:
298
- // adaptedTtl = clamp(p95LatencyMs × multiplier, min, max)
299
- // The caller-supplied ttlSeconds is used until ≥ 5 samples are collected,
300
- // then the library takes over TTL management autonomously.
301
- adaptiveTtl: true,
302
- adaptiveTtlMin: 10, // floor: never assign TTL below 10 s (default)
303
- adaptiveTtlMax: 86400, // ceiling: never exceed 24 h (default)
304
- adaptiveTtlMultiplier: 20, // p95Ms × 20 = TTL in seconds (default)
305
-
306
- // ── Singleton + rate-limit safety ──────────────────────────────────────
307
- // strictSingleton: when true, a later create() for an existing namespace
308
- // whose options differ from the first call THROWS instead of silently
309
- // returning the existing instance. Guards against conflicting init points.
310
- strictSingleton: false,
311
- // failClosed: when true, increment() re-throws on a Redis error instead of
312
- // failing open (returning 0). Enforces the rate-limit guard during outages.
313
- failClosed: false,
314
-
315
- // ── OpenTelemetry tracer ──────────────────────────────────────────────
316
- // Pass any @opentelemetry/api-compatible tracer. No peer dependency.
317
- // Spans: 'tricache.get' | 'tricache.set' | 'tricache.delete'
318
- // Attributes: cache.key_prefix, cache.hit ('l1'|'disk'|'l2'|'miss')
319
- tracer: trace.getTracer('my-app'),
320
-
321
- // ── L2 circuit breaker ────────────────────────────────────────────────
322
- // Opens after N consecutive Redis errors; probes after cooldown ms.
323
- // State visible in cache.metrics().l2CircuitBreaker.state
324
- l2CircuitBreakerThreshold: 5, // default
325
- l2CircuitBreakerCooldownMs: 30_000, // default
326
-
327
- // ── Negative caching ──────────────────────────────────────────────────
328
- // Cache null/undefined fetchFn results for this many seconds globally.
329
- // Prevents repeated upstream calls for keys that genuinely don't exist.
330
- // Can be overridden per-call via opts.notFoundTtl in cache.get().
331
- notFoundTtl: 30, // seconds; 0 = disabled (default)
332
-
333
- // ── Startup warm-up ───────────────────────────────────────────────────
334
- // Auto-call warmFromL2(pattern) at construction time.
335
- // cache.ready() resolves once warm-up finishes — use as a k8s readiness gate.
336
- // No-op when Redis is disabled or unreachable.
337
- warmKeys: 'user:*',
338
-
339
- // ── Prometheus instance label ─────────────────────────────────────────
340
- // Adds an `instance` label to every metric in toPrometheusText().
341
- instanceName: 'api-us-east-1',
342
-
343
- // ── Cold-start snapshot ──────────────────────────────────────────────
344
- snapshotPath: '/tmp/my-app-cache-snapshot.msgpack',
345
- snapshotMaxAgeMs: 2 * 60 * 60 * 1000, // 2 hours (default)
346
- forbiddenSnapshotPrefixes: ['auth:', 'session:', 'mfa:', 'rate_limit:'],
347
-
348
- // ── Metrics callback ─────────────────────────────────────────────────
349
- metricsIntervalMs: 60_000, // emit every 60 s (default)
350
- onMetrics: (m) => myMonitoring.record(m), // optional push callback
351
-
352
- // ── Per-operation hooks ───────────────────────────────────────────────
353
- // onHit fires on every L1, disk, or L2 hit with the caller-facing key (no prefix)
354
- // and the tier that served it. Lower latency than waiting for onMetrics.
355
- onHit: (key, tier) => cloudwatch.putMetricData({ key, tier }),
356
-
357
- // onMiss fires when all three tiers are exhausted — before fetchFn is called.
358
- onMiss: (key) => cloudwatch.putMetricData({ key }),
359
-
360
- // ── Development mutation guard ────────────────────────────────────────
361
- // When true, every L1 hit value is deep-frozen before being returned.
362
- // Mutation attempts throw TypeError immediately in development.
363
- // Do NOT enable in production — deep-freezing large objects has measurable overhead.
364
- frozen: process.env.NODE_ENV !== 'production',
365
- });
366
- ```
367
-
368
- ### Environment variables
369
-
370
- | Variable | Purpose |
371
- |---|---|
372
- | `REDIS_HOST` | Redis/Valkey hostname (used when `redisHost` option is not set) |
373
- | `CACHE_ENCRYPTION_KEY` | Base64-encoded 32-byte AES-256-GCM key |
374
- | `NODE_ENV` | When `!== 'production'`, L2 Redis and TLS are disabled by default |
375
-
376
- ---
377
-
378
- ## 📖 API reference
379
-
380
- ### `CacheService.create(options?)` → `CacheService`
381
-
382
- Returns the process-level singleton. Options are only applied on the **first** call per namespace — subsequent calls return the existing instance. When the new options differ from what the existing singleton was built with, this is a **silent no-op by default** (a one-time warning is logged and the `singletonDivergences` metric is incremented). Set `strictSingleton: true` on the first call to instead **throw** on a divergent later call — use this when multiple init points could pass conflicting Redis credentials or TTLs.
383
-
384
- ### `CacheService.createAsync(optionsOrPromise)` → `Promise<CacheService>`
385
-
386
- Async factory that resolves a `Promise<CacheOptions>` before constructing the singleton. Useful when config is fetched from a secret store at startup.
387
-
388
- ```typescript
389
- const cache = await CacheService.createAsync(fetchSecretsFromVault());
390
- ```
391
-
392
- ### `CacheService.reset(options?)` → `CacheService`
393
-
394
- Destroys the existing singleton and creates a fresh one. Useful in tests.
395
-
396
- ### `cache.get<T>(key, fetchFn, ttlSeconds?, opts?)` → `Promise<T>`
397
-
398
- Get from cache or call `fetchFn` on a miss. The inflight map ensures `fetchFn` fires at most once per key regardless of concurrency.
399
-
400
- > **Reference semantics:** on an L1 hit, the returned value is the live JS object stored in the entry — not a deep copy. Mutating it will corrupt the cached entry. Deep-clone at the call site if you need an independent copy.
401
-
402
- | Parameter | Type | Default | Description |
403
- |---|---|---|---|
404
- | `key` | `string` | — | Cache key |
405
- | `fetchFn` | `() => Promise<T>` | — | Called on a miss; result is cached |
406
- | `ttlSeconds` | `number` | `300` | Hard TTL in seconds. **When `adaptiveTtl` is enabled, this is only authoritative until ≥ 5 samples are collected for the key — after that the library derives TTL from the p95 fetch latency** (see Adaptive TTL config). Use `opts` or a separate cache instance if you need a hard floor. |
407
- | `opts.swr` | `number` | `0` | Stale-While-Revalidate grace seconds |
408
- | `opts.priority` | `CachePriority` | auto-inferred | Eviction priority override |
409
- | `opts.refreshAhead` | `number` | — | Fraction `(0, 1]` of TTL — triggers background recompute when `remaining ≤ ttl × (1 - refreshAhead)` |
410
- | `opts.xfetchBeta` | `number` | — | XFetch β ≥ 0 — scales probabilistic early recompute by last fetch duration; higher = recompute earlier |
411
- | `opts.notFoundTtl` | `number` | — | Per-call TTL in seconds for `null`/`undefined` results (overrides global `notFoundTtl`) |
412
- | `opts.tags` | `string[]` | — | Tags to register when `fetchFn` populates the entry on a miss; no-op on L1/L2 hits where tags are already registered |
413
-
414
- ### `cache.set<T>(key, data, ttlSeconds?, priority?, opts?)` → `Promise<void>`
415
-
416
- Writes to L1 and (in production) L2. Publishes an invalidation to the backplane.
417
-
418
- | Parameter | Type | Default | Description |
419
- |---|---|---|---|
420
- | `opts.tags` | `string[]` | `[]` | Associate tags with this entry for group invalidation |
421
- | `opts.dependsOn` | `string[]` | `[]` | Parent keys — when any parent is deleted, this entry is automatically evicted from L1 |
422
-
423
- ```typescript
424
- await cache.set('product:1', data, 60, undefined, { tags: ['catalog', 'featured'] });
425
-
426
- // Cascade invalidation: evicting 'org:42' also evicts 'org:42:members'
427
- await cache.set('org:42:members', members, 300, undefined, { dependsOn: ['org:42'] });
428
- await cache.delete('org:42'); // org:42:members is evicted too
429
- ```
430
-
431
- ### `cache.mget<T>(keys, fetchFn, ttl?, priority?)` → `Promise<(T | undefined)[]>`
432
-
433
- Batch read. Checks **all three tiers** for each key — L1 (RAM), then L2 (Redis, in one pipelined `MGET`), then the L1.5 disk spill — and calls `fetchFn` only for keys that miss every tier. Preserves input ordering and counts exactly one hit per key (no double-counting across tiers).
434
-
435
- `ttl` accepts a **plain number** (uniform TTL) or a **function `(key: string) => number`** (per-key TTL). The function is only called for miss keys — L1 hits are unaffected.
436
-
437
- ```typescript
438
- // Uniform TTL
439
- const [userA, userB] = await cache.mget(
440
- ['user:1', 'user:2'],
441
- (missKeys) => db.users.findByIds(missKeys).then(rowsToMap),
442
- 300,
443
- );
444
-
445
- // Per-key TTL — heterogeneous data in one batch call
446
- const results = await cache.mget(
447
- ['user:1', 'config:global', 'feature:flags'],
448
- fetchFn,
449
- (key) => key.startsWith('config:') ? 3600 : 300,
450
- );
451
- ```
452
-
453
- ### `cache.mset<T>(entries)` → `Promise<void>`
454
-
455
- Write multiple entries in a single call. Each entry accepts `value`, `ttl`, `priority`, and `tags`.
456
-
457
- ```typescript
458
- await cache.mset({
459
- 'user:1': { value: alice, ttl: 300, priority: CachePriority.HIGH, tags: ['users'] },
460
- 'user:2': { value: bob, ttl: 300 },
461
- });
462
- ```
463
-
464
- ### `cache.mdel(keys)` → `Promise<void>`
465
-
466
- Delete multiple keys in a single call. No-op for keys that do not exist.
467
-
468
- ```typescript
469
- await cache.mdel(['user:1', 'user:2', 'user:3']);
470
- ```
471
-
472
- ### `cache.warmFromL2(pattern)` → `Promise<number>`
473
-
474
- Scan Redis for keys matching a glob pattern (e.g. `'user:*'`) and load their values into L1 with a 10-minute TTL. Returns the number of keys loaded. Returns `0` immediately when Redis is disabled or unreachable — safe to call unconditionally at startup.
475
-
476
- ```typescript
477
- // In your application startup
478
- const loaded = await cache.warmFromL2('user:*');
479
- console.log(`Pre-warmed ${loaded} user entries from Redis`);
480
- ```
481
-
482
- ### `cache.ready()` → `Promise<void>`
483
-
484
- Returns a Promise that resolves once the cache is fully initialised. Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once the automatic `warmFromL2` call completes.
485
-
486
- Designed for k8s readiness probes — await before accepting traffic, then never call again:
487
-
488
- ```typescript
489
- const cache = CacheService.create({ warmKeys: 'user:*' });
490
-
491
- // k8s readiness probe endpoint
492
- app.get('/ready', async (_req, res) => {
493
- await cache.ready();
494
- res.sendStatus(200);
495
- });
496
- ```
497
-
498
- ### `cache.has(key)` → `boolean`
499
-
500
- Return `true` if the key exists in L1 and has not expired. Bloom-filter fast-path — no fetch, no disk or Redis round-trip.
501
-
502
- ### `cache.ttl(key)` → `number | null`
503
-
504
- Return the remaining TTL in **seconds** for a key currently held in L1. Returns `null` if the key is absent or expired. Does not fetch or consume the value.
505
-
506
- ```typescript
507
- const remaining = cache.ttl('user:123'); // e.g. 247 (seconds left)
508
- if (remaining !== null && remaining < 30) await cache.touch('user:123', 300);
509
- ```
510
-
511
- ### `cache.touch(key, newTtlSeconds)` → `Promise<boolean>`
512
-
513
- Extend the TTL of a key in L1 (and fire-and-forget `EXPIRE` in Redis) without reading or re-fetching its value. Returns `false` if the key is absent or already expired.
514
-
515
- ### `cache.getIfFresh<T>(key)` → `T | null`
516
-
517
- Return the L1 value only if it is **fresh** (not yet in the SWR grace window). Returns `null` when absent, expired, or stale — without triggering a revalidation.
518
-
519
- ```typescript
520
- const fresh = cache.getIfFresh<User>('user:123');
521
- if (fresh !== null) return fresh; // serve from L1, no network hop
522
- ```
523
-
524
- ### `cache.setIfAbsent<T>(key, value, ttlSeconds?)` → `Promise<boolean>`
525
-
526
- Atomically write `value` only if `key` is not already cached. Checks L1 first, then attempts a Redis `SET NX EX`. Returns `true` if the value was written, `false` if a live entry already existed.
527
-
528
- Useful for distributed lock-style writes, session initialisation, or any pattern where you must not overwrite an already-cached value.
529
-
530
- ```typescript
531
- const written = await cache.setIfAbsent(`session:${id}`, sessionData, 3600);
532
- if (!written) {
533
- // session already exists — do not overwrite
534
- }
535
- ```
536
-
537
- ### `cache.hotKeys(n?)` → `Array<{ key: string; hits: number; sizeBytes: number }>`
538
-
539
- Returns the top `n` live L1 keys ranked by Count-Min Sketch access frequency. Namespace prefix is stripped from each key. Expired entries are excluded. Default `n = 10`.
540
-
541
- ```typescript
542
- const hot = cache.hotKeys(5);
543
- // [
544
- // { key: 'user:1', hits: 1024, sizeBytes: 512 },
545
- // { key: 'product:7', hits: 893, sizeBytes: 256 },
546
- // ...
547
- // ]
548
- ```
549
-
550
- ### `cache.invalidateTag(tag)` / `cache.invalidateTags(tags)` → `Promise<void>`
551
-
552
- Evict all entries associated with one or more tags from L1, disk, and Redis.
553
- When `tagStrategy: 'generational'` is active, `invalidateTags(tags)` pipelines multi-tag increments in a single network round-trip.
554
-
555
- ```typescript
556
- await cache.set('product:1', data, 60, undefined, { tags: ['catalog', 'electronics'] });
557
- await cache.set('product:2', data, 60, undefined, { tags: ['catalog', 'deals'] });
558
-
559
- await cache.invalidateTag('catalog'); // single tag
560
- await cache.invalidateTags(['electronics', 'deals']); // pipelined batch invalidation
561
- ```
562
-
563
- ### `cache.ping()` → `Promise<CachePingResult>`
564
-
565
- Measure L1 / disk / Redis latency in milliseconds. Returns `{ l1, disk, l2 }` — `l2` is `null` when Redis is disabled. Suitable for health-check endpoints.
566
-
567
- ```typescript
568
- app.get('/health', async (_req, res) => {
569
- const { l1, disk, l2 } = await cache.ping();
570
- res.json({ status: 'ok', latencyMs: { l1, disk, l2 } });
571
- });
572
- ```
573
-
574
- ### `cache.drainToL2()` → `Promise<number>`
575
-
576
- Pipeline all live L1 entries to Redis in a single round-trip. Returns the number of keys written. Useful for warming a new Redis node or zero-downtime failover.
577
-
578
- ### `cache.delete(key)` → `Promise<void>`
579
-
580
- Deletes one exact key or a glob pattern (`user:abc:*`). Propagates to disk, Redis, and all backplane peers.
581
-
582
- ### `cache.clear(prefix?)` → `Promise<void>`
583
-
584
- Flush all entries, or only those whose key starts with `prefix`. Propagates to disk and Redis.
585
-
586
- ```typescript
587
- await cache.clear(); // flush everything
588
- await cache.clear('session:'); // flush only session keys
589
- ```
590
-
591
- ### `cache.rebalance()` → `void`
592
-
593
- Evict L1 entries that now violate the current category or global capacity limits. Useful when `categoryLimits` are tightened after startup — normally, existing entries are not re-evaluated until they expire naturally.
594
-
595
- ```typescript
596
- // Tighten analytics limit at runtime, then immediately enforce it
597
- cache.options.categoryLimits['analytics:'].maxEntries = 50;
598
- cache.rebalance();
599
- ```
600
-
601
- ### `cache.increment(key, ttlSeconds?)` → `Promise<number>`
602
-
603
- Distributed counter. With Redis active, atomically increments via `INCR` and returns the fleet-wide value. **By default it fails OPEN on a Redis error** — it returns `0`, so a caller's `if (count > LIMIT) reject()` guard will NOT reject during an outage. Set `failClosed: true` to re-throw the error instead, enforcing the limit even when Redis is unavailable. Track failures via `cache.metrics().counters.errors`.
604
-
605
- When Redis is disabled, it maintains an **in-process** counter with the same TTL semantics so dev/test rate-limiting works — but rate-limiting is then per-instance, **not fleet-wide**. A one-time warning is logged the first time this fallback is used.
606
-
607
- ### `cache.metrics()` → `CacheMetrics`
608
-
609
- Returns a full metrics snapshot including hit rates, bloom filter stats, backplane counters, OOM eviction history, and tier sizes.
610
-
611
- ### `CacheService.toPrometheusText(metrics, prefix?, instanceName?)` → `string`
612
-
613
- Converts a `CacheMetrics` snapshot to Prometheus text exposition format. Pass `instanceName` to add an `instance` label alongside `namespace`.
614
-
615
- ```typescript
616
- app.get('/metrics', (_req, res) => {
617
- res.type('text/plain').send(
618
- CacheService.toPrometheusText(cache.metrics(), 'tricache', 'api-us-east-1'),
619
- );
620
- });
621
- ```
622
-
623
- ### `cache.stats()` → `{ l1, disk }`
624
-
625
- Lightweight L1 and disk stats without the full metrics breakdown.
626
-
627
- ### `cache.writeSnapshot(altPath?)` / `cache.loadSnapshot()`
628
-
629
- Manual snapshot control. Called automatically on `SIGTERM`/`SIGINT` — only needed when you manage shutdown yourself. `writeSnapshot()` accepts an optional path to write to an alternate location without touching the configured default snapshot file.
630
-
631
- ```typescript
632
- // Graceful-shutdown hook — write to a dated backup path
633
- process.on('SIGTERM', async () => {
634
- await cache.writeSnapshot(`/backups/cache-${Date.now()}.snap`);
635
- process.exit(0);
636
- });
637
- ```
638
-
639
- ### `cache.keys()` → `Generator<string>`
640
-
641
- Lazily yields the key for every live (non-expired) L1 entry. Namespace prefix is stripped automatically. Uses a dedicated generator that skips intermediate tuple allocation.
642
-
643
- ```typescript
644
- for (const key of cache.keys()) console.log(key);
645
- ```
646
-
647
- ### `cache.values<T>()` → `Generator<T>`
648
-
649
- Lazily yields the cached value for every live L1 entry. Returns the live deserialized object (same reference semantics as `get()`). Uses `yield*` delegation — no intermediate generator frame.
650
-
651
- ```typescript
652
- for (const session of cache.values<Session>()) evict(session);
653
- ```
654
-
655
- ### `cache.entries<T>()` → `Generator<[string, T]>`
656
-
657
- Lazily yields `[key, value]` pairs for every live L1 entry. Key has namespace prefix stripped.
658
-
659
- ```typescript
660
- for (const [key, user] of cache.entries<User>()) sync(key, user);
661
- ```
662
-
663
- ### `cache.rotateEncryptionKey(newKeyBase64, newMode?)` → `Promise<void>`
664
-
665
- Dynamically rotates the active encryption key at runtime with zero downtime:
666
- - Installs the new key as primary for all subsequent writes.
667
- - Automatically preserves the previous key for seamless fallback decryption of existing cache entries.
668
- - Gracefully drains and re-initializes all worker threads in the crypto pool (`WorkerPool.drainAndReinit()`).
669
-
670
- ```typescript
671
- await cache.rotateEncryptionKey(newKeyBase64, 'aes-256-gcm');
672
- ```
673
-
674
- ### `cache.lock<T>(resourceKey, fn, options?)` → `Promise<T>`
675
-
676
- Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`, execute `fn`, and automatically release the lock on return or throw.
677
- - Prevents concurrent executions of critical tasks across a cluster (e.g. database migrations, nightly syncs, cron jobs).
678
- - Safe token comparison via Redis Lua script prevents deleting a lock acquired by another worker if execution exceeded the lock TTL.
679
- - Automatically falls back to an in-process promise-chain mutex in single-process or dev environments.
680
-
681
- ```typescript
682
- const result = await cache.lock('cron:nightly-sync', async () => {
683
- return await runNightlyDatabaseSync();
684
- }, {
685
- ttl: 60, // Auto-release TTL in seconds (prevents deadlocks on crash)
686
- acquireTimeout: 5000, // Maximum wait time to acquire lock in ms
687
- retryInterval: 100, // Polling retry interval in ms
688
- });
689
- ```
690
-
691
- ### `cache.destroy()` → `Promise<void>`
692
-
693
- Closes the Redis connection, unsubscribes the backplane, and stops all background timers.
694
-
695
- ---
696
-
697
- ## 🗄️ First-Class ORM Extensions (Prisma & Drizzle)
698
-
699
- ### Prisma Client Extension (`tricache/prisma`)
700
-
701
- Add one-line query caching and automatic model tag invalidation to Prisma:
702
-
703
- ```typescript
704
- import { PrismaClient } from '@prisma/client';
705
- import { withTriCache } from 'tricache/prisma';
706
- import { CacheService } from 'tricache';
707
-
708
- const cache = CacheService.create({ redisHost: 'localhost' });
709
-
710
- const prisma = new PrismaClient().$extends(
711
- withTriCache({
712
- cache,
713
- defaultTtl: 300,
714
- autoInvalidate: true, // Automatically invalidates 'user' tag on user.create / update / delete
715
- })
716
- );
717
-
718
- // Automatic caching with explicit options:
719
- const activeUsers = await prisma.user.findMany({
720
- where: { active: true },
721
- cache: { ttl: 60, tags: ['users'], swr: 30 },
722
- });
723
- ```
724
-
725
- ### Drizzle ORM Wrapper (`tricache/drizzle`)
726
-
727
- Wrap any Drizzle query builder with automatic SQL + parameter hashing and caching:
728
-
729
- ```typescript
730
- import { withCache } from 'tricache/drizzle';
731
- import { eq } from 'drizzle-orm';
732
-
733
- const activeUsers = await withCache(
734
- db.select().from(users).where(eq(users.active, true)),
735
- { cache, ttl: 300, tags: ['users'] }
736
- );
737
- ```
738
-
739
- ---
740
-
741
- ## 📊 OpenTelemetry Native Metrics
742
-
743
- TriCache integrates directly with OpenTelemetry `Meter` (`@opentelemetry/api`) to publish monotonic counters and observable gauges without scrapers:
744
-
745
- ```typescript
746
- import { metrics } from '@opentelemetry/api';
747
- import { CacheService } from 'tricache';
748
-
749
- const meter = metrics.getMeter('my-service');
750
-
751
- const cache = CacheService.create({
752
- redisHost: 'localhost',
753
- meter, // Native OpenTelemetry meter integration
754
- });
755
- ```
756
-
757
- ---
758
-
759
- ## 💻 Developer & Troubleshooting CLI (`npx tricache`)
760
-
761
- Inspect running caches, test latency across tiers, or flush namespaces directly from your terminal:
762
-
763
- ```bash
764
- # Display full live dashboard (hit ratios, latencies, Count-Min Sketch hot keys)
765
- npx tricache inspect --redis redis://localhost:6379 --namespace my-app
766
-
767
- # Measure 3-tier response latency
768
- npx tricache ping --redis redis://localhost:6379
769
-
770
- # Flush namespace or prefix
771
- npx tricache clear --redis redis://localhost:6379 --namespace my-app --prefix user:
772
- ```
773
-
774
- ---
775
-
776
- ## 🌐 HTTP Caching & 304 ETag Middleware (`tricache/http`)
777
-
778
- Drop-in HTTP caching with automatic weak ETag generation and RFC-compliant `304 Not Modified` short-circuiting:
779
-
780
- ### Express & Connect
781
- ```typescript
782
- import express from 'express';
783
- import { expressCache } from 'tricache/http';
784
- import { CacheService } from 'tricache';
785
-
786
- const app = express();
787
- const cache = CacheService.create({ redisHost: 'localhost' });
788
-
789
- // Automatically caches GET /api/users, emits ETag, and returns 304 on If-None-Match
790
- app.get('/api/users', expressCache({ cache, ttl: 300, tags: ['users'] }), async (_req, res) => {
791
- const users = await db.user.findMany();
792
- res.json(users);
793
- });
794
- ```
795
-
796
- ### Hono & Web Standards
797
- ```typescript
798
- import { Hono } from 'hono';
799
- import { honoCache } from 'tricache/http';
800
-
801
- const app = new Hono();
802
-
803
- app.get('/api/users', honoCache({ ttl: 300, tags: ['users'] }), async (c) => {
804
- const users = await db.user.findMany();
805
- return c.json(users);
806
- });
807
- ```
808
-
809
- ---
810
-
811
- ## 🎯 Priority levels
812
-
813
- ```typescript
814
- import { CachePriority } from 'tricache';
815
-
816
- CachePriority.LOW // 1 — analytics, reports — evicted first
817
- CachePriority.NORMAL // 2 — general application data (default)
818
- CachePriority.HIGH // 3 — user profiles, config — evicted last
819
- CachePriority.CRITICAL // 4 — never evicted while valid (auth tokens, sessions)
820
- ```
821
-
822
- Priority is **auto-inferred** from the key when not specified:
823
-
824
- | Key contains | Inferred priority |
825
- |---|---|
826
- | `auth:` or `session:` | `CRITICAL` |
827
- | `user:`, `org:`, or `profile:` | `HIGH` |
828
- | `analytics:`, `report:`, or `stats:` | `LOW` |
829
- | anything else | `NORMAL` |
830
-
831
- ---
832
-
833
- ## 🧠 Eviction algorithm
834
-
835
- L1 eviction uses **reservoir sampling** — an O(n) single pass samples 16 candidates, then sorts only those 16 (O(1)). Each candidate is scored:
836
-
837
- ```
838
- score = priority × 1000 + min(hits, 100) × 10 + ttlRemaining/60s − age/60s
839
- ```
840
-
841
- - Higher score = kept longer
842
- - `CRITICAL` entries are excluded from sampling while valid
843
- - When a category limit is breached, entries from that category receive a score penalty
844
-
845
- ---
846
-
847
- ## 🪵 Pluggable logger
848
-
849
- Bring your own structured logger — tricache doesn't care if it's `pino`, `winston`, or `console`.
850
-
851
- ```typescript
852
- import pino from 'pino';
853
- const logger = pino();
854
-
855
- CacheService.create({
856
- logger: {
857
- debug: (msg, meta) => logger.debug(meta ?? {}, msg),
858
- info: (msg, meta) => logger.info(meta ?? {}, msg),
859
- warn: (msg, meta) => logger.warn(meta ?? {}, msg),
860
- error: (msg, meta, err) => logger.error({ ...(meta ?? {}), err }, msg),
861
- },
862
- });
863
- ```
864
-
865
- ---
866
-
867
- ## 🔐 Encryption
868
-
869
- AES-256-GCM for L2 (Redis) values, disk spill files, and cold-start snapshots. Four modes are available via `encryptionMode`:
870
-
871
- | Mode | Key length | Notes |
872
- |---|---|---|
873
- | `aes-256-gcm` | 32 bytes | **Default.** Authenticated encryption (AEAD). |
874
- | `aes-128-gcm` | 16 bytes | ~15% faster than AES-256. Same AEAD guarantees. |
875
- | `aes-128-ctr` | 16 bytes | Fastest cipher mode. AES-NI keystream, no auth tag. Use when integrity is guaranteed elsewhere (TLS, HMAC). |
876
- | `xor` | any (≥ 16 bytes recommended) | **NOT cryptographic.** XOR obfuscation only. Dev/non-sensitive data. |
877
-
878
- **Key generation:**
879
-
880
- ```bash
881
- # AES-256 (32 bytes)
882
- node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
883
-
884
- # AES-128 / AES-128-CTR (16 bytes)
885
- node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
886
-
887
- # XOR — any length, minimum 16 bytes recommended
888
- node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
889
- ```
890
-
891
- ```typescript
892
- // AES-256-GCM (default)
893
- CacheService.create({ encryptionKey: '<base64-32-bytes>' });
894
-
895
- // AES-128-GCM
896
- CacheService.create({ encryptionKey: '<base64-16-bytes>', encryptionMode: 'aes-128-gcm' });
897
-
898
- // AES-128-CTR (fastest cipher, no auth tag)
899
- CacheService.create({ encryptionKey: '<base64-16-bytes>', encryptionMode: 'aes-128-ctr' });
900
-
901
- // XOR obfuscation (NOT cryptographic — dev/non-sensitive only)
902
- CacheService.create({ encryptionKey: '<base64-key>', encryptionMode: 'xor' });
903
-
904
- // or use the env var: CACHE_ENCRYPTION_KEY=<base64-key>
905
- ```
906
-
907
- | Mode | Redis format | Disk / snapshot format |
908
- |---|---|---|
909
- | `aes-256-gcm` | `enc:v1:<base64(IV[12]\|Tag[16]\|CT)>` | `TRIC1ENC\|IV[12]\|Tag[16]\|CT[N]` |
910
- | `aes-128-gcm` | `a128:v1:<base64(IV[12]\|Tag[16]\|CT)>` | `TRIC1128\|IV[12]\|Tag[16]\|CT[N]` |
911
- | `aes-128-ctr` | `ctr:v1:<base64(IV[16]\|CT)>` | `TRIC1CTR\|IV[16]\|CT[N]` |
912
- | `xor` | `xor:v1:<base64(key⊕data)>` | `TRIC1XOR\|key⊕data[N]` |
913
-
914
- Existing plaintext values are read transparently during key rotation.
915
-
916
- ### Zero-downtime key rotation
917
-
918
- Set `previousEncryptionKey` to your old key while rolling out a new one. The cache tries the current key first; if decryption fails it transparently retries with the previous key. Remove `previousEncryptionKey` once all old entries have expired.
919
-
920
- ```typescript
921
- CacheService.create({
922
- encryptionKey: process.env.NEW_ENCRYPTION_KEY, // new AES-256 key
923
- previousEncryptionKey: process.env.OLD_ENCRYPTION_KEY, // fallback for old entries
924
- // previousEncryptionMode defaults to current encryptionMode
925
- });
926
- ```
927
-
928
- ---
929
-
930
- ## 🧵 Worker thread crypto offload
931
-
932
- By default, AES-GCM encryption/decryption runs synchronously on the V8 main thread. For payloads above a configurable size threshold this blocks the event loop for measurable durations. Enable worker thread offload to move encryption off the main thread:
933
-
934
- ```typescript
935
- CacheService.create({
936
- encryptionKey: process.env.CACHE_ENCRYPTION_KEY,
937
- workerThreads: true, // enable off-main-thread crypto
938
- workerThresholdBytes: 131_072, // only offload payloads ≥ 128 KB (default)
939
- workerPoolSize: 4, // threads; 0 = auto (min(4, logical CPUs))
940
- });
941
- ```
942
-
943
- **How it works:**
944
- - A fixed-size pool of Node.js `worker_threads` is created at startup; each worker holds an initialised `CacheEncryption` instance.
945
- - Dispatch is round-robin; inter-thread IPC carries only strings (structured-clone fast path).
946
- - Workers are `unref()`'d — they do not prevent the process from exiting cleanly.
947
- - If worker initialisation fails the pool is silently disabled and synchronous crypto is used as a fallback — zero configuration required in environments where workers are unavailable.
948
-
949
- **When to enable:**
950
- - Payloads routinely exceed a few hundred KB with encryption enabled.
951
- - You observe event-loop lag correlated with L2 read/write operations in APM.
952
- - Rule of thumb: the default 128 KB threshold keeps overhead negligible for typical API response payloads while protecting against multi-MB documents.
953
-
954
- ---
955
-
956
- ## 🗜️ Transparent Payload Compression
957
-
958
- TriCache includes built-in Brotli and Gzip compression for Redis L2 strings and L1.5 disk tier binary payloads, transparently reducing network bandwidth and storage footprints without manual application encoding.
959
-
960
- ```typescript
961
- CacheService.create({
962
- compression: 'brotli', // 'brotli' | 'gzip' | 'none' (default: 'none')
963
- compressionThresholdBytes: 1024, // only compress entries >= 1024 bytes (default)
964
- });
965
- ```
966
-
967
- ### Storage Envelope Matrix
968
-
969
- Entries written to Redis L2 and the disk spill tier use self-describing magic headers, allowing mixed uncompressed, compressed, and encrypted entries to coexist seamlessly during rollout:
970
-
971
- | Envelope Header | State | Description |
972
- |---|---|---|
973
- | `cmp:v1:<data>` | Compressed | Compressed payload (Brotli or Gzip) |
974
- | `ecp:v1:<data>` | Encrypted + Compressed | Payload compressed before encryption |
975
- | `enc:v1:<data>` | Encrypted | AES-256-GCM / AES-128 encrypted without compression |
976
- | `{"d": ...}` / raw | Plaintext | Uncompressed, unencrypted legacy JSON / msgpack |
977
-
978
- ### Worker Thread Offload
979
-
980
- When `workerThreads: true` is enabled, compression and decompression for large payloads above `workerThresholdBytes` are offloaded to background worker threads alongside encryption, keeping the V8 main event loop free for concurrent HTTP requests.
981
-
982
- ---
983
-
984
- ## ⚡ Next.js 16 & 15 Integration (`tricache/next`)
985
-
986
- TriCache provides first-class support for Next.js 16 `"use cache"`, React 19 RSC streaming, and Next.js 15/16 ISR via `tricache/next`.
987
-
988
- ### Setup in `next.config.mjs`
989
-
990
- ```javascript
991
- // next.config.mjs
992
- /** @type {import('next').NextConfig} */
993
- const nextConfig = {
994
- // Point Next.js directly to the default export
995
- cacheHandler: require.resolve('tricache/next'),
996
- cacheMaxMemorySize: 0, // Disable Next.js default in-memory cache to let TriCache manage RAM
997
- };
998
-
999
- export default nextConfig;
1000
- ```
1001
-
1002
- ### Custom Options Factory
1003
-
1004
- To configure TriCache with custom Redis, encryption, or namespace settings:
1005
-
1006
- ```typescript
1007
- // cache-handler.mjs
1008
- import { createNextCacheHandler } from 'tricache/next';
1009
-
1010
- export default createNextCacheHandler({
1011
- namespace: 'my-next-app',
1012
- redisHost: process.env.REDIS_HOST,
1013
- tagStrategy: 'generational',
1014
- backplaneMode: 'stream',
1015
- });
1016
- ```
1017
-
1018
- ```javascript
1019
- // next.config.mjs
1020
- export default {
1021
- cacheHandler: require.resolve('./cache-handler.mjs'),
1022
- };
1023
- ```
1024
-
1025
- ### Key Architectural Highlights
1026
- - **Single-Use Stream Re-hydration:** React 19 RSC streams (`ReadableStream<Uint8Array>`) are drained to contiguous binary buffers on `set()`, and fresh unlocked `ReadableStream` instances are re-hydrated on every `get()` hit.
1027
- - **Dynamic `softTags` Verification:** In Next.js 16 App Router, layout and route boundary invalidations pass `softTags` into `ctx.softTags` at read time. TriCache dynamically validates them against generational tag versions, triggering misses on invalidated boundaries.
1028
- - **Stream Error Boundary:** Mid-flight client disconnects or aborted streams are caught safely without throwing or storing corrupted partial payloads.
1029
- - **Automatic Build Phase Bypass:** Automatically detects `NEXT_PHASE=phase-production-build` during `next build` and runs in-memory without opening Redis network sockets.
1030
-
1031
- ---
1032
-
1033
- ## 🦁 NestJS Integration (`tricache/nestjs`)
1034
-
1035
- TriCache provides an official NestJS dynamic module and `@nestjs/cache-manager` store adapter compatible with `cache-manager` v5/v6:
1036
-
1037
- ### Synchronous Module Registration
1038
-
1039
- ```typescript
1040
- // app.module.ts
1041
- import { Module } from '@nestjs/common';
1042
- import { TriCacheModule } from 'tricache/nestjs';
1043
-
1044
- @Module({
1045
- imports: [
1046
- TriCacheModule.register({
1047
- namespace: 'my-nest-api',
1048
- redisHost: process.env.REDIS_HOST,
1049
- encryptionKey: process.env.CACHE_ENCRYPTION_KEY,
1050
- }),
1051
- ],
1052
- })
1053
- export class AppModule {}
1054
- ```
1055
-
1056
- ### Asynchronous Module Registration (with ConfigService)
1057
-
1058
- ```typescript
1059
- // app.module.ts
1060
- import { Module } from '@nestjs/common';
1061
- import { ConfigModule, ConfigService } from '@nestjs/config';
1062
- import { TriCacheModule } from 'tricache/nestjs';
1063
-
1064
- @Module({
1065
- imports: [
1066
- ConfigModule.forRoot(),
1067
- TriCacheModule.registerAsync({
1068
- imports: [ConfigModule],
1069
- inject: [ConfigService],
1070
- useFactory: (config: ConfigService) => ({
1071
- namespace: config.get<string>('CACHE_NAMESPACE', 'nest-api'),
1072
- redisHost: config.get<string>('REDIS_HOST'),
1073
- redisPort: config.get<number>('REDIS_PORT', 6379),
1074
- tagStrategy: 'generational',
1075
- backplaneMode: 'stream',
1076
- }),
1077
- }),
1078
- ],
1079
- })
1080
- export class AppModule {}
1081
- ```
1082
-
1083
- ### Injecting into Services & Controllers
1084
-
1085
- Use either standard `@Inject(CACHE_MANAGER)` for `@nestjs/cache-manager` compatibility, or `@Inject('TRICACHE_SERVICE')` for direct access to TriCache's three-tier engine:
1086
-
1087
- ```typescript
1088
- import { Injectable, Inject } from '@nestjs/common';
1089
- import { CACHE_MANAGER } from '@nestjs/cache-manager';
1090
- import type { CacheStore } from '@nestjs/cache-manager';
1091
- import type { CacheService } from 'tricache';
1092
-
1093
- @Injectable()
1094
- export class UsersService {
1095
- constructor(
1096
- @Inject(CACHE_MANAGER) private cacheManager: CacheStore,
1097
- @Inject('TRICACHE_SERVICE') private triCache: CacheService,
1098
- ) {}
1099
-
1100
- async getUser(id: string) {
1101
- // Standard NestJS cache-manager API (millisecond TTL)
1102
- const cached = await this.cacheManager.get(`user:${id}`);
1103
- if (cached) return cached;
1104
-
1105
- // Or use TriCache's native SWR & thundering-herd prevention:
1106
- return this.triCache.get(`user:${id}`, () => this.fetchFromDb(id), 300, { swr: 60 });
1107
- }
1108
- }
1109
- ```
1110
-
1111
- ### Declarative Method Decorators (`@Cacheable`, `@CacheEvict`)
1112
-
1113
- Remove cache boilerplate from your NestJS services using declarative method decorators:
1114
-
1115
- ```typescript
1116
- import { Injectable } from '@nestjs/common';
1117
- import { Cacheable, CacheEvict } from 'tricache/nestjs';
1118
-
1119
- @Injectable()
1120
- export class ProductsService {
1121
- // Automatically caches result in TriCache (L1 -> L1.5 -> L2) with stampede coalescing
1122
- @Cacheable({
1123
- key: (id: string) => `product:${id}`,
1124
- ttl: 300,
1125
- swr: 60,
1126
- tags: ['products'],
1127
- })
1128
- async findById(id: string) {
1129
- return this.db.product.findUnique({ where: { id } });
1130
- }
1131
-
1132
- // Automatically invalidates tags or keys after successful method execution
1133
- @CacheEvict({ tags: ['products'] })
1134
- async updateProduct(id: string, dto: UpdateProductDto) {
1135
- return this.db.product.update({ where: { id }, data: dto });
1136
- }
1137
- }
1138
- ```
1139
-
1140
- ---
1141
-
1142
- ## 🏷️ Generational Tag Invalidation (`tagStrategy: 'generational'`)
1143
-
1144
- Traditional tag-based caching stores key sets in Redis and performs $O(N)$ key deletions on `invalidateTag()`. For high-cardinality collections, this triggers blocking Redis spikes and cache stampedes.
1145
-
1146
- With `tagStrategy: 'generational'`:
1147
- - **$O(1)$ Atomic Tag Invalidation:** `cache.invalidateTag('products')` atomically increments an integer version counter in Redis (`INCR tag_ver:products`) and updates local memory.
1148
- - **Atomic Multi-Field Hash Schema:** Entries in Redis are stored as a unified Hash `{ d: envelope, t: timestamp, tv: tagVersionsJson }` with an atomic `MULTI/EXEC` transaction.
1149
- - **Pipelined Batch Invalidation:** `cache.invalidateTags(['t1', 't2'])` pipelines multi-tag version increments in a single network round-trip.
1150
- - **Zero-Tear Compare-and-Delete:** Stale entries are pruned upon access using an atomic Lua script (`deleteIfSetBefore`) on Redis and L1 RAM, eliminating race conditions where concurrent revalidations write newer data.
1151
- - **Self-Healing Reconciliation:** In-memory tag versions are verified against Redis when `Date.now() - lastSyncedAt > tagVersionTtlMs` (default: 5 s), guaranteeing bounded staleness even if a backplane broadcast is dropped during a network partition.
1152
-
1153
- ```typescript
1154
- const cache = CacheService.create({
1155
- tagStrategy: 'generational',
1156
- tagVersionTtlMs: 5_000,
1157
- });
1158
-
1159
- // Cache entry with tags
1160
- await cache.set('item:123', productData, 3600, undefined, { tags: ['catalog', 'electronics'] });
1161
-
1162
- // Invalidate in O(1) time
1163
- await cache.invalidateTag('catalog');
1164
- ```
1165
-
1166
- ---
1167
-
1168
- ## 🌊 Redis Streams Backplane (`backplaneMode: 'stream'`)
1169
-
1170
- Standard Redis Pub/Sub operates on an *at-most-once* delivery model. If an instance experiences a transient network disconnect, container reschedule, or long GC pause, invalidation messages published during the disconnection are lost.
1171
-
1172
- Setting `backplaneMode: 'stream'` switches the backplane to a durable append-only log in Redis using `XADD` and `XREAD`:
1173
-
1174
- ```typescript
1175
- const cache = CacheService.create({
1176
- backplaneMode: 'stream',
1177
- backplaneStreamMaxLen: 10_000, // Approximate MAXLEN trimming
1178
- backplaneStreamBlockMs: 2_000, // XREAD BLOCK timeout
1179
- });
1180
- ```
1181
-
1182
- ### Architecture & Resilience
1183
- - **Cluster Single-Slot Routing:** Stream keys default to `tricache:stream:{<namespace>}`, ensuring multi-node Redis Clusters route all stream operations to a single slot without cross-slot errors.
1184
- - **Dedicated Long-Polling Consumer:** Runs on an isolated Redis client connection (`XREAD BLOCK`) so standard cache `GET`/`SET` pipelines are never blocked.
1185
- - **Zero-Drop Replay on Reconnect:** Tracks `_lastStreamId` to automatically replay all missed invalidations in order after short network drops or GC pauses without flushing L1.
1186
- - **Trim Gap Fallback:** If an instance was disconnected longer than the stream retention window, it detects the gap, increments `metrics().backplane.streamGaps`, safely flushes L1, and resets to `'$'`.
1187
- - **Instant Clean Teardown:** `cache.destroy()` immediately disconnects the dedicated client socket to interrupt blocking long-polls without stalling process shutdown.
1188
-
1189
- ---
1190
-
1191
- ## 🛡️ Read Safety (`cloneStrategy: 'structuredClone'`)
1192
-
1193
- By default (`cloneStrategy: 'none'`), TriCache returns raw in-memory JS references from L1 hits for maximum throughput (~350 ns per hit). If application code mutates the returned object, the cached reference is directly modified.
1194
-
1195
- Setting `cloneStrategy: 'structuredClone'` enables deep clone isolation:
1196
-
1197
- ```typescript
1198
- const cache = CacheService.create({
1199
- cloneStrategy: 'structuredClone',
1200
- });
1201
-
1202
- const user = await cache.get('user:1', () => db.fetchUser(1));
1203
- user.roles.push('admin'); // Mutating caller copy does NOT pollute cached L1 state
1204
- ```
1205
-
1206
- Supported types: plain objects, arrays, Dates, Maps, Sets, and TypedArrays. When `frozen: true` is also enabled, L1 entries remain frozen while callers receive fully mutable clones.
1207
-
1208
- ---
1209
-
1210
- ## ☁️ Serverless / ephemeral disk environments
1211
-
1212
- On Lambda, Cloud Run, Fly.io, Railway, and similar platforms, the filesystem (`os.tmpdir()`) is container-scoped and is wiped on every cold start. Disk spill and cold-start snapshots are therefore useless and waste I/O budget.
1213
-
1214
- TriCache auto-detects serverless runtimes at construction time (zero I/O — environment variable checks only) and automatically disables the disk tier:
1215
-
1216
- | Runtime | Detection env var |
1217
- |---|---|
1218
- | AWS Lambda | `AWS_LAMBDA_FUNCTION_NAME` |
1219
- | Google Cloud Run | `K_SERVICE` |
1220
- | Google Cloud Functions | `FUNCTION_TARGET` |
1221
- | Azure Functions | `WEBSITE_INSTANCE_ID` |
1222
- | Fly.io | `FLY_APP_NAME` |
1223
- | Railway | `RAILWAY_ENVIRONMENT` |
1224
- | Vercel | `VERCEL` |
1225
-
1226
- You can also control disk behaviour explicitly:
1227
-
1228
- ```typescript
1229
- // Force-disable disk tier (e.g., when running inside a Docker container with no writable tmpdir)
1230
- CacheService.create({ disableDisk: true });
1231
-
1232
- // Force-enable disk tier even when a serverless env var is present (advanced override)
1233
- CacheService.create({ disableDisk: false });
1234
- ```
1235
-
1236
- When disk is disabled:
1237
- - The disk spill callback is a no-op.
1238
- - `disk.load()` / `disk.delete()` / `disk.clear()` are never called.
1239
- - `loadSnapshot()` and `writeSnapshot()` are skipped.
1240
- - The background disk janitor timer is not started.
1241
- - `metrics().disk.disabled` is `true`.
1242
-
1243
- ---
1244
-
1245
- ## 🔴 Redis Cluster and Sentinel
1246
-
1247
- TriCache supports Redis Cluster (slot-based sharding) and Redis Sentinel (automatic primary failover) via ioredis built-in support.
1248
-
1249
- ### Redis Cluster
1250
-
1251
- ```typescript
1252
- CacheService.create({
1253
- redisClusterNodes: [
1254
- { host: 'redis-node-1.example.com', port: 6379 },
1255
- { host: 'redis-node-2.example.com', port: 6379 },
1256
- { host: 'redis-node-3.example.com', port: 6379 },
1257
- ],
1258
- redisTls: true,
1259
- useShardedPubSub: true, // Redis 7+ sharded pub/sub (SPUBLISH / SSUBSCRIBE)
1260
- });
1261
- ```
1262
-
1263
- ioredis handles slot routing, moved/ask redirects, and re-queuing commands during slot migrations transparently. You can list any subset of cluster nodes — ioredis discovers the full topology automatically.
1264
-
1265
- #### Sharded Pub/Sub (`useShardedPubSub`)
1266
-
1267
- When `useShardedPubSub: true` is enabled on Redis Cluster (Redis 7+), invalidation messages are published via `SPUBLISH` and subscribed via `SSUBSCRIBE` bound directly to the `{<namespace>}` slot shard. This eliminates cluster-wide broadcast gossip, drastically reducing cluster bus CPU utilization under heavy invalidation load.
1268
-
1269
- ### Redis Sentinel
1270
-
1271
- ```typescript
1272
- CacheService.create({
1273
- redisSentinel: {
1274
- name: 'mymaster',
1275
- sentinels: [
1276
- { host: 'sentinel-1.example.com', port: 26379 },
1277
- { host: 'sentinel-2.example.com', port: 26379 },
1278
- { host: 'sentinel-3.example.com', port: 26379 },
1279
- ],
1280
- },
1281
- redisTls: true,
1282
- });
1283
- ```
1284
-
1285
- ioredis monitors the current master via the Sentinel topology and transparently reconnects to a new primary after failover. The backplane subscriber is also constructed in the appropriate cluster/sentinel mode.
1286
-
1287
- ### Wire Protocol Compatibility (`redisProtocol: 2 | 3`)
1288
-
1289
- TriCache uses `ioredis` v6, which connects using **RESP3** (`redisProtocol: 3`) by default for optimized structured parsing and streaming.
1290
-
1291
- If your infrastructure routes Redis traffic through intermediate proxies that only understand RESP2 (such as **Twemproxy**, **Envoy Redis proxy filter**, or older AWS ElastiCache Serverless proxy configurations that reject the `HELLO 3` handshake), explicitly set `redisProtocol: 2`:
1292
-
1293
- ```typescript
1294
- CacheService.create({
1295
- redisHost: 'envoy-redis-proxy.internal',
1296
- redisProtocol: 2, // force RESP2 wire protocol
1297
- });
1298
- ```
1299
-
1300
- > `redisHost` / `redisPort` are ignored when `redisClusterNodes` or `redisSentinel` is set. All three topology modes support `redisTls` and `redisProtocol` (RESP2/RESP3).
1301
-
1302
- ---
1303
-
1304
- ## ⚡ WASM Bloom filter
1305
-
1306
- A 100,000-bit filter with k=7 hash probes is used when it is large enough for the
1307
- configured `l1MaxEntries`; otherwise a right-sized pure-JS filter is instantiated
1308
- automatically (see `createBloomFilter`). For the default 100K-bit filter:
1309
-
1310
- - At the default `l1MaxEntries: 2,000` — false-positive rate ≈ **0.00007%** (m=100,000, k=7)
1311
- - At its rated capacity (~10,400 entries) — false-positive rate ≈ **1%**
1312
- - When `l1MaxEntries` exceeds the WASM filter's ~10,400-entry capacity, a JS filter sized via the optimal formula (m = ⌈–n·ln p / (ln 2)²⌉, k = round(ln 2 · m / n) clamped to [4, 10]) is used instead — no capacity cliff.
1313
- - The filter rebuilds automatically when stale bits from deleted/expired entries accumulate
1314
-
1315
- Mechanics:
1316
- - `mightContain(key) === false` → **guaranteed miss** — the Map lookup is skipped entirely
1317
- - `mightContain(key) === true` → probable hit — the Map is checked to confirm
1318
-
1319
- The 562-byte WASM binary is inlined as Base64 — zero filesystem access at runtime. Falls back to a pure-JS implementation if `WebAssembly` is unavailable.
1320
-
1321
- ---
1322
-
1323
- ## 🔬 High-Performance Architecture & Memory Hygiene
1324
-
1325
- TriCache is engineered for low-latency, high-throughput environments where garbage collection (GC) pauses and main-thread blocking must be minimized. The codebase employs several advanced V8 and hardware-aware optimizations:
1326
-
1327
- ### ⚡ Performance & Memory Hygiene
1328
- - **Zero-Allocation Hot Paths:** To eliminate object allocation thrashing on hot L1 reads, TriCache reuses a single, pre-allocated static `_hit` object literal in [src/smart-memory-cache.ts](src/smart-memory-cache.ts) to return cache hits synchronously.
1329
- - **Fast-Path Binary Operations (Uint32Array XOR):** The XOR obfuscation engine in [src/encryption.ts](src/encryption.ts) automatically detects if buffers are 4-byte-aligned. If so, it processes the operation using `Uint32Array` views, allowing the V8 JIT compiler to compile the loop into highly-optimized, 32-bit register-level CPU `XOR` instructions instead of a slow byte-by-byte traversal.
1330
- - **Pre-allocated Eviction Pools:** During L1 eviction, candidate selection avoids generating temporary object literals. The system samples candidates into a pre-allocated `_evictPool` array and mutates their fields in-place, eliminating GC pressure when the cache is under heavy write load.
1331
-
1332
- ### 🛡️ Production-First Ergonomics & Resiliency
1333
- - **Next.js HMR Resiliency:** Normal in-memory caches re-instantiate and wipe their state during Next.js Hot Module Replacement (HMR) reloads. TriCache binds its singleton instance to `globalThis` to preserve the L1 cache across hot-reload cycles in server environments.
1334
- - **Graceful Degradation & Fallbacks:**
1335
- - **L2 Circuit Breaker:** Protects your app from cascading failures if Redis gets slow or goes down, automatically failing back to L1/disk and probing Redis health on a cooldown timer.
1336
- - **Dynamic Bloom Filters:** Uses a WebAssembly Bloom filter for fast miss checks, but automatically falls back to a dynamically-sized, memory-optimized pure JS Bloom filter if the cache size exceeds the WebAssembly filter's hardcoded capacity limit.
1337
- - **CPU-Efficient Count-Min Sketch:** Keeps access-frequency history across eviction boundaries in a tight `4 rows × 512 counters` `Uint16Array` (4 KB total). This fits entirely within the CPU's L1d cache, ensuring frequency updates are essentially free.
1338
-
1339
- ---
1340
-
1341
- ## 📊 Performance
1342
-
1343
- Measured on a single Node.js thread (no `await` on synchronous paths):
1344
-
1345
- **L1 SmartMemoryCache**
1346
-
1347
- | Operation | Throughput | Latency | Notes |
1348
- |---|---|---|---|
1349
- | `get` — hot hit (8K entries) | **2.81 M/s** | 356 ns | bloom → Map lookup → return cached value |
1350
- | `get` — cold miss | **7.14 M/s** | 140 ns | bloom gates → early return |
1351
- | `set` — tiny payload | 1.06 M/s | 944 ns | pack() + Map.set + bloom.add |
1352
- | `set` — small payload (< 512 B) | 574.1 K/s | 1.74 µs | pack() same unified path, larger payload |
1353
- | `set` — large payload (≥ 512 B) | 228.6 K/s | 4.37 µs | pack() larger payload |
1354
- | `set` — CRITICAL priority | 843.6 K/s | 1.19 µs | same set path; skipped in eviction sort |
1355
- | `delete` — exact key | **5.36 M/s** | 186 ns | Map.delete |
1356
- | `deletePattern` — glob wildcard | 18.7 K/s | 53.48 µs | O(n) Map scan |
1357
- | Count-Min Sketch estimate | **3.37 M/s** | 297 ns | 4 row lookups — called on every `get()` hit and `set()` |
1358
-
1359
- **Iterator interface (L1 live entries, 500 entries)**
1360
-
1361
- | Method | Throughput | Latency | Notes |
1362
- |---|---|---|---|
1363
- | `cache.keys()` | 26.6 K/s | 37.53 µs | no `[key,entry]` tuple allocation |
1364
- | `cache.values()` | 35.5 K/s | 28.19 µs | `yield*` delegation |
1365
- | `cache.entries()` | 24.0 K/s | 41.73 µs | `[strippedKey, value]` pairs |
1366
- | raw `Map` iteration (baseline) | 277.2 K/s | 3.61 µs | no expiry check, no generator overhead |
1367
-
1368
- **CacheService (end-to-end)**
1369
-
1370
- | Operation | Throughput | Latency | Notes |
1371
- |---|---|---|---|
1372
- | `get` — L1 warm hit | **2.03 M/s** | 491 ns | inflight check → l1.get → return cached value |
1373
- | `get` — SWR stale serve | **1.78 M/s** | 562 ns | serves stale; revalidates async |
1374
- | `get` — miss + fetchFn | 13.7 K/s | 73 µs | Promise microtask + l1.set |
1375
- | `set` | 28.7 K/s | 34.86 µs | l1.set + disk.save (fire-and-forget) |
1376
- | `delete` — exact key | 7.3 K/s | 137.82 µs | l1.delete + disk.delete + backplane |
1377
- | `delete` — glob `*` | 687 K/s | 1.46 µs | l1.deletePattern O(n) + disk glob |
1378
-
1379
- **Encryption** (IV pool, pre-allocated output buffers)
1380
-
1381
- | Mode | Payload | Encrypt | Decrypt |
1382
- |---|---|---|---|
1383
- | AES-256-GCM | 64 B | 140.4 K/s / 7.12 µs | 155.5 K/s / 6.43 µs |
1384
- | AES-256-GCM | 512 B | 103.1 K/s / 9.70 µs | 142.9 K/s / 6.99 µs |
1385
- | AES-256-GCM | 4 KB | 58.4 K/s / 17.12 µs | 48.0 K/s / 20.84 µs |
1386
- | AES-128-GCM | 64 B | 148.8 K/s / 6.72 µs | 173.0 K/s / 5.78 µs |
1387
- | AES-128-GCM | 512 B | 135.7 K/s / 7.37 µs | 158.8 K/s / 6.30 µs |
1388
- | AES-128-GCM | 4 KB | 70.2 K/s / 14.24 µs | 53.2 K/s / 18.79 µs |
1389
- | AES-128-CTR | 64 B | 187.9 K/s / 5.32 µs | 196.9 K/s / 5.08 µs |
1390
- | AES-128-CTR | 512 B | 183.5 K/s / 5.45 µs | 185.6 K/s / 5.39 µs |
1391
- | AES-128-CTR | 4 KB | 78.4 K/s / 12.75 µs | 71.8 K/s / 13.93 µs |
1392
- | XOR _(obfuscation only)_ | 64 B | 2.43 M/s / 412 ns | 2.10 M/s / 476 ns |
1393
- | XOR _(obfuscation only)_ | 512 B | 665.5 K/s / 1.50 µs | 715.3 K/s / 1.40 µs |
1394
- | XOR _(obfuscation only)_ | 4 KB | 114.5 K/s / 8.73 µs | 77.6 K/s / 12.89 µs |
1395
-
1396
- > AES and XOR string-path numbers shown (Redis L2). Buffer path (disk/snapshot) is 5–20% faster — no base64 overhead.
1397
- > AES-128-GCM is 5–50% faster than AES-256-GCM depending on payload (gap widens at mid-range sizes on AES-NI hardware).
1398
- > AES-128-CTR removes the GHASH MAC step: ~50% faster than AES-128-GCM at small payloads; use only when integrity is guaranteed by transport.
1399
- > XOR numbers are for the buffer path (32-bit word-level XOR, 4 bytes/iteration). XOR dominates at small payloads (no cipher setup) and remains ~2× faster than AES at 4 KB.
1400
-
1401
- See [BENCHMARKS.md](BENCHMARKS.md) for the full breakdown: bloom filter cost, serialization by payload size, eviction pressure, concurrency analysis, multi-tenancy isolation, and a realistic 80/15/5 read/miss/write workload.
1402
-
1403
- ---
1404
-
1405
- ## 🤝 Contributing
1406
-
1407
- Bug reports and pull requests are welcome!
1408
-
1409
- 1. Fork the repo and create a feature branch
1410
- 2. Run `pnpm test` — all tests must pass
1411
- 3. Run `pnpm bench` if you touch a hot path and include before/after numbers in your PR
1412
- 4. Open your PR against `master`
1413
-
1414
- > New to the codebase? Start with [src/cache-service.ts](src/cache-service.ts) for the public API and [src/smart-memory-cache.ts](src/smart-memory-cache.ts) for the L1 engine.
1415
-
1416
- ---
1417
-
1418
- ## 🛡️ Security
1419
-
1420
- Found a vulnerability? **Please don't open a public issue.** Report it privately via [GitHub Security Advisories](https://github.com/Kareem411/TriCache/security/advisories/new) so it can be patched before disclosure.
1421
-
1422
- For encryption key generation and rotation best practices, see the [Encryption](#-encryption) section.
1423
-
1424
- ---
1425
-
1426
- ## 📄 License
1427
-
1428
- MIT
1
+ # TriCache
2
+
3
+ [![CI](https://github.com/Kareem411/TriCache/actions/workflows/ci.yml/badge.svg)](https://github.com/Kareem411/TriCache/actions/workflows/ci.yml)
4
+ [![npm version](https://img.shields.io/npm/v/tricache.svg)](https://www.npmjs.com/package/tricache)
5
+ [![Tests](https://img.shields.io/badge/tests-511%20passing-brightgreen)](tests)
6
+ [![Code Quality](https://img.shields.io/badge/oxlint-0%20warnings-brightgreen)](src)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
8
+ [![Node.js ≥ 22](https://img.shields.io/badge/node-%3E%3D22-brightgreen)](https://nodejs.org)
9
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Strict%20%7C%205.x%20%7C%206.x-blue)](https://www.typescriptlang.org)
10
+ [![npm provenance](https://img.shields.io/badge/provenance-verified-brightgreen)](https://www.npmjs.com/package/tricache)
11
+
12
+ tricache is a three-tier Node.js cache library — in-memory (L1), local disk spill, and Redis/Valkey (L2). Warm L1 reads run at 2.81 million operations per second on a single thread (356 ns/op) — well below any network round-trip, including a local Redis call. When L1 fills, evicted entries spill to disk instead of being dropped, keeping hit rates high without unbounded RAM growth. Misses that reach L2 are coalesced across concurrent callers, so a spike of simultaneous requests for the same key triggers exactly one fetchFn call, not one per caller. See the performance section for full numbers. Optional configuration adds Stale-While-Revalidate, at-rest encryption (AES-256-GCM by default), pub/sub fleet-wide invalidation, an OOM guard, cold-start snapshots, and Prometheus metrics — none of it required to get started.
13
+
14
+ <img src="https://raw.githubusercontent.com/Kareem411/TriCache/main/public/SmartMemoryCache_DiskTier.jpeg" width="600" alt="tricache architecture" />
15
+
16
+ ---
17
+
18
+ ## 🏆 What Makes TriCache a "No-Brainer"
19
+
20
+ | Dimension | Industry Standard (`keyv`, `@neshca/cache-handler`, `cache-manager`) | **TriCache v0.7.1** |
21
+ |:---|:---|:---|
22
+ | **Storage Hierarchy** | Single-tier (RAM or Redis or Disk) | **Three-Tier (RAM → NVMe Disk → Redis/Valkey)** |
23
+ | **Thundering-Herd** | Unhandled / requires external single-flight libraries | **Built-in Inflight Promise Coalescing (10k tested)** |
24
+ | **Tag Invalidation** | $O(N)$ bulk key scans or Redis `SMEMBERS` deletions | **$O(1)$ Generational Version Counters (`MULTI/EXEC`)** |
25
+ | **Next.js 16 Support** | Basic key-value handlers, broken RSC stream reuse | **Native 5-Method Bridge with stream re-hydration & `cacheLife`** |
26
+ | **NestJS Support** | Generic `CacheModule` with missing batch/tag methods | **Dynamic `TriCacheModule` + `@Cacheable` & `@CacheEvict` decorators** |
27
+ | **Cluster Invalidation** | At-most-once Pub/Sub (drops messages on network blips) | **Durable Redis Streams (`XADD`/`XREAD`) with reconnect replay** |
28
+ | **Memory Hygiene** | Standard JSON stringification, unconstrained RAM | **WASM Bloom filter, Count-Min Sketch, Zero-Copy `transferList` workers** |
29
+ | **Failure Tolerance** | Cascading 500s when Redis/Upstream flutters | **Circuit Breaker, `staleIfError` SWR grace, monotonic tag guarantees** |
30
+
31
+ ---
32
+
33
+ ## ✨ Features
34
+
35
+ | Feature | Detail |
36
+ |---|---|
37
+ | **Next.js 16 & 15 Adapter** | Full `CacheHandler` implementation for Next.js 16 `"use cache"` and legacy ISR; single-use stream re-hydration, dynamic `softTags` checking, and automatic `NEXT_PHASE` build bypass |
38
+ | **NestJS Dynamic Module & Store** | Dedicated `TriCacheModule.register()` dynamic module, `TriCacheStore` adapter for `@nestjs/cache-manager`, and declarative `@Cacheable` / `@CacheEvict` method decorators |
39
+ | **First-Class Prisma Extension** | `withTriCache(options)` for `$extends` with automatic query key hashing, cache options, and write mutation tag invalidation |
40
+ | **First-Class Drizzle Wrapper** | `withCache(query, options)` wrapping Drizzle queries with automatic SQL + params hashing and SWR support |
41
+ | **Distributed Mutex Lock** | `cache.lock(key, fn, options)` with Redis `SET NX EX`, atomic Lua token-release, and local promise-chain fallback |
42
+ | **Native OpenTelemetry Metrics** | Direct `meter` integration publishing monotonic counters and observable gauges without scrapers |
43
+ | **Interactive Developer CLI** | Zero-dependency CLI (`npx tricache inspect`, `ping`, `clear`) with terminal dashboard and latency probes |
44
+ | **Universal `cache.wrap()` Primitive** | Options-object wrapper (`{ ttl, swr, tags, dependsOn, priority }`) for ORMs and service layers |
45
+ | **Generational Tagging** | $O(1)$ tag invalidations via Redis version counters (`INCR tag_ver:<tag>`); atomic `{d, t, tv}` hash schema, pipelined batch `invalidateTags()`, and time-based self-healing reconciliation |
46
+ | **Read Safety (`cloneStrategy`)** | `cloneStrategy: 'structuredClone'` isolates returned objects from caller mutation; sub-microsecond raw reference fallback (`'none'`) |
47
+ | **Redis Streams Backplane** | `backplaneMode: 'stream'` replaces at-most-once Pub/Sub with durable `XADD`/`XREAD` append-only log; cluster hash tag slot safety and zero-drop reconnect replay |
48
+ | **Atomic Disk Writes** | Atomic staging via unique `.tmp` sibling files with Windows NTFS file-lock micro-retries and background `.tmp` janitor sweep |
49
+ | **Adaptive eviction** | LFU × LRU × priority score + Count-Min Sketch cross-eviction frequency; reservoir-sampled O(1) hot path; category limits prevent any prefix monopolising RAM |
50
+ | **Count-Min Sketch** | 4 × 512 `Uint16Array` (4 KB) tracks historical access frequency across eviction boundaries — same-priority burst keys cannot displace long-resident entries; **84 % survival rate** in benchmark flood tests |
51
+ | **WASM Bloom filter** | 562-byte binary inlined as Base64 — O(k=7) guaranteed-miss detection, no filesystem access, pure-JS fallback |
52
+ | **msgpackr serialization** | L1 and disk-tier entries packed with msgpackr — uniform binary format, no JSON on hot paths; L2 (Redis) string values are JSON-serialised before encryption |
53
+ | **Stale-While-Revalidate** | Serve stale instantly, revalidate in background — zero added latency on cache hit |
54
+ | **Stale-if-error** | Extend a stale entry's TTL when SWR revalidation fails — no errors served during upstream outages |
55
+ | **Thundering-herd prevention** | Inflight `Promise` registry — only one `fetchFn` call per key regardless of concurrency (10,000 tested) |
56
+ | **Pub/sub invalidation backplane** | Redis pub/sub channel propagates deletes across all instances in real time |
57
+ | **Tag-based invalidation** | Tag entries on write; `invalidateTag('catalog')` evicts all matching entries from L1, disk, and Redis atomically |
58
+ | **Batch read** | `mget()` collects L1 hits, calls `fetchFn` only for misses, preserves ordering |
59
+ | **Batch write** | `mset()` / `mdel()` write or delete many keys in a single `Promise.all` call |
60
+ | **TTL jitter** | `ttlJitterFactor` spreads expirations across a configurable ± window — prevents thundering-cliff mass-expiry |
61
+ | **OpenTelemetry spans** | Structural `ICacheTracer` / `ICacheSpan` interfaces — pass any OTEL-compatible tracer; no peer dep required |
62
+ | **L2 circuit breaker** | Suspends Redis after N consecutive failures; auto-probes after cooldown; state visible in `metrics()` |
63
+ | **`warmFromL2(pattern)`** | Scan Redis and pre-populate L1 at startup; returns count loaded; no-op when Redis unavailable |
64
+ | **OOM guard** | Polls `heapUsed/heapTotal` on a timer; emergency-evicts coldest L1 entries before the process crashes |
65
+ | **Cold-start snapshot** | L1 serialised to disk on `SIGTERM`/`SIGINT`, reloaded on next startup — warm cache, cold process |
66
+ | **AES-256-GCM encryption** | L2 (Redis) values, disk spill files, and snapshots encrypted at rest; zero-downtime key rotation via `previousEncryptionKey` |
67
+ | **Prometheus metrics** | `cache.metrics()` + `CacheService.toPrometheusText()` — drop into any `/metrics` endpoint |
68
+ | **Distributed counter** | `cache.increment()` backed by Redis `INCR` for distributed rate limiting; in-process fallback when Redis is disabled |
69
+ | **Pluggable logger** | Bring your own `pino`, `winston`, etc. |
70
+ | **L2 read-only mode** | `l2WriteMode: 'read-only'` reads from Redis but skips all writes — canary deploys, read replicas |
71
+ | **Eviction callback** | `onEviction(key, reason)` fires on every L1 eviction with a typed reason string |
72
+ | **Negative caching (`notFoundTtl`)** | Cache `null`/`undefined` fetchFn results for a configurable TTL — prevents hammering upstream on repeated misses |
73
+ | **`setIfAbsent()`** | Atomic "set if not cached" — L1 `has()` check → Redis `SET NX EX` → L1 set on success; returns `true` if written, `false` if already present |
74
+ | **Refresh-ahead** | Proactively recompute an entry in the background when remaining TTL falls below a configured fraction — zero-latency freshness |
75
+ | **XFetch probabilistic early expiry** | Probabilistic background recompute keyed to last fetch duration and `xfetchBeta` — optimal protection against expiry spikes under load |
76
+ | **Adaptive TTL** | Tracks per-key fetch latency in a rolling ring buffer; once ≥ 5 samples are collected, automatically sets TTL = `p95LatencyMs × multiplier`. Expensive keys get cached longer; cheap keys stay close to their base TTL — no manual TTL tuning required |
77
+ | **`hotKeys(n)`** | Returns top N keys by Count-Min Sketch access frequency with size — no full Map scan |
78
+ | **`dependsOn` cascade invalidation** | Tag entries with parent keys; deleting a parent automatically evicts all declared dependents from L1 |
79
+ | **`onHit` / `onMiss` callbacks** | Per-operation hit/miss hooks with tier info (`'l1'` \| `'disk'` \| `'l2'`) — no wait for the metrics interval |
80
+ | **`frozen` mode** | Dev-time mutation guard — `Object.freeze()` applied recursively to every L1 hit so accidental mutations throw immediately |
81
+ | **`tags` in `get()` opts** | Attach tags at read time; when `fetchFn` populates the entry on a miss the tags are registered automatically |
82
+
83
+ ---
84
+
85
+ ## 📦 Install
86
+
87
+ ```bash
88
+ npm install tricache
89
+ # or
90
+ pnpm add tricache
91
+ ```
92
+
93
+ ---
94
+
95
+ ## 🚀 Quick start
96
+
97
+ ```typescript
98
+ import { CacheService, CachePriority } from 'tricache';
99
+
100
+ // Get (or create) the process-level singleton
101
+ const cache = CacheService.create({
102
+ redisHost: 'my-redis.example.com', // omit or set NODE_ENV!=production to disable L2
103
+ });
104
+
105
+ // Get-or-fetch with a 5-minute TTL
106
+ const user = await cache.get(
107
+ `user:${userId}`,
108
+ () => db.users.findById(userId),
109
+ 300,
110
+ );
111
+
112
+ // Universal wrap() with options object (alternative to get)
113
+ const profile = await cache.wrap(
114
+ `user:${userId}:profile`,
115
+ () => db.users.findProfile(userId),
116
+ { ttl: 300, swr: 60, tags: ['users'] },
117
+ );
118
+
119
+ // Explicit set
120
+ await cache.set(`user:${userId}`, user, 300);
121
+
122
+ // Delete one key
123
+ await cache.delete(`user:${userId}`);
124
+
125
+ // Delete by glob pattern
126
+ await cache.delete(`user:${userId}:*`);
127
+
128
+ // Stale-While-Revalidate: serve stale for up to 30 s while refreshing in background
129
+ const dashboard = await cache.get(
130
+ `dashboard:${orgId}`,
131
+ () => analytics.buildDashboard(orgId),
132
+ 300,
133
+ { swr: 30 },
134
+ );
135
+
136
+ // Distributed rate-limiting counter
137
+ const hits = await cache.increment(`ratelimit:${ip}`, 60 /* TTL seconds */);
138
+
139
+ // Check if a key is cached (fast, no fetch)
140
+ const isCached = cache.has(`user:${userId}`);
141
+
142
+ // Batch read
143
+ const [userA, userB] = await cache.mget(
144
+ [`user:${userIdA}`, `user:${userIdB}`],
145
+ (missKeys) => db.users.findByIds(missKeys).then(rowsToMap),
146
+ 300,
147
+ );
148
+
149
+ // Batch write
150
+ await cache.mset({
151
+ [`user:${userIdA}`]: { value: userA, ttl: 300 },
152
+ [`user:${userIdB}`]: { value: userB, ttl: 300 },
153
+ });
154
+
155
+ // Batch delete
156
+ await cache.mdel([`user:${userIdA}`, `user:${userIdB}`]);
157
+ ```
158
+
159
+ > [!TIP]
160
+ > **In-Memory Reference Semantics & Mutation Safety:**
161
+ > By default, TriCache returns direct in-memory object references from L1 RAM (`cloneStrategy: 'none'`) to achieve sub-microsecond throughput (**2.81M ops/sec / 356 ns**). If your callers mutate returned objects in-place, enable `cloneStrategy: 'structuredClone'` for deep copy isolation, or enable `frozen: true` in non-production environments to catch mutations at runtime.
162
+
163
+ ```typescript
164
+ // Warm L1 from Redis at startup
165
+ const loaded = await cache.warmFromL2('user:*');
166
+ console.log(`Pre-warmed ${loaded} user entries`);
167
+
168
+ // Or auto-warm at construction + gate traffic with ready()
169
+ const cache2 = CacheService.create({ warmKeys: 'user:*' });
170
+ await cache2.ready(); // resolves once warm-up completes — ideal for k8s readiness probes
171
+
172
+ // Atomic set-if-absent — returns true if written, false if key already cached
173
+ const written = await cache.setIfAbsent(`session:${id}`, sessionData, 3600);
174
+
175
+ // Dependency cascade: deleting 'org:42' automatically evicts 'org:42:config'
176
+ await cache.set('org:42:config', config, 300, undefined, { dependsOn: ['org:42'] });
177
+ await cache.delete('org:42'); // also evicts org:42:config
178
+
179
+ // Top 10 hottest keys by Count-Min Sketch frequency
180
+ const hot = cache.hotKeys(10);
181
+ console.log(hot); // [{ key: 'user:1', hits: 842, sizeBytes: 512 }, ...]
182
+
183
+ // Tag entries for group invalidation
184
+ await cache.set(`product:${id}`, product, 300, undefined, { tags: ['catalog'] });
185
+ await cache.invalidateTag('catalog'); // evict all catalog entries
186
+
187
+ // Health check with tier latencies
188
+ const { l1, disk, l2 } = await cache.ping();
189
+
190
+ // Prometheus metrics
191
+ const snap = cache.metrics();
192
+ console.log(CacheService.toPrometheusText(snap));
193
+ ```
194
+
195
+ ---
196
+
197
+ ## ⚙️ Configuration
198
+
199
+ All options are optional — sensible defaults apply.
200
+
201
+ ```typescript
202
+ CacheService.create({
203
+ // ── Namespace ─────────────────────────────────────────────────────────
204
+ // Isolates keys, disk dir, snapshot file, and Redis backplane channel.
205
+ // Two instances with different namespaces are fully independent.
206
+ namespace: 'my-app',
207
+
208
+ // ── Logger ────────────────────────────────────────────────────────────
209
+ logger: pinoLogger, // default: console warn/error only
210
+
211
+ // ── L1 (in-memory) ───────────────────────────────────────────────────
212
+ l1MaxBytes: 200 * 1024 * 1024, // 200 MB total RAM cap (default)
213
+ l1MaxEntries: 2_000, // max entries in L1 (default)
214
+ l1EvictionWatermark: 0.9, // proactive eviction fires at 90 % of l1MaxEntries / l1MaxBytes (default)
215
+ // lower to 0.8 to reduce GC pressure on heap-bound workloads
216
+ categoryLimits: {
217
+ // per-prefix limits — keys are matched by startsWith()
218
+ 'user:': { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 },
219
+ 'analytics:': { maxEntries: 100, maxSizeBytes: 20 * 1024 * 1024 },
220
+ 'default': { maxEntries: 1000, maxSizeBytes: 100 * 1024 * 1024 },
221
+ },
222
+
223
+ // ── L1.5 (disk spill) ────────────────────────────────────────────────
224
+ diskCacheDir: '/tmp/my-app-cache', // default: os.tmpdir()/tricache-disk
225
+ diskMaxBytes: 500 * 1024 * 1024, // 500 MB (default)
226
+ diskEntryMaxBytes: 10 * 1024 * 1024, // 10 MB per entry (default)
227
+
228
+ // ── L2 (Redis / Valkey) ──────────────────────────────────────────────
229
+ redisHost: 'my-redis.example.com', // or REDIS_HOST env var
230
+ redisPort: 6379,
231
+ redisTls: true, // default: true when NODE_ENV=production
232
+ redisProtocol: 3, // default: 3 (RESP3 in ioredis v6+); set to 2 for RESP2 proxies (Twemproxy/Envoy)
233
+ disableRedis: false, // default: true when NODE_ENV!=production
234
+
235
+ // ── Transparent payload compression ──────────────────────────────────
236
+ // 'none' (default) — raw msgpack/JSON representation
237
+ // 'brotli' | 'gzip' — compress Redis L2 payloads and disk tier binaries
238
+ compression: 'none',
239
+ compressionThresholdBytes: 1024, // only compress entries ≥ 1 KB (default)
240
+
241
+ // ── Invalidation backplane ───────────────────────────────────────────
242
+ invalidationBackplane: true,
243
+ // 'pubsub' (default) — Ephemeral Redis Pub/Sub (at-most-once delivery)
244
+ // 'stream' — Durable Redis Streams (XADD/XREAD) with replay on reconnect
245
+ backplaneMode: 'pubsub',
246
+ backplaneStreamMaxLen: 10_000, // max entries retained in invalidation stream
247
+ backplaneStreamBlockMs: 2_000, // blocking poll interval for XREAD BLOCK
248
+ // backplaneStreamKey: 'tricache:stream:{my-app}', // custom stream key override
249
+
250
+ // ── Generational tagging & clone strategy ─────────────────────────────
251
+ // 'set' (default) — traditional Redis Set member tracking
252
+ // 'generational' — atomic O(1) integer version counters in Redis + memory
253
+ tagStrategy: 'set',
254
+ tagVersionTtlMs: 5_000, // ms before local generational tag is re-synced from Redis
255
+ // 'none' (default) — raw in-memory references (~350 ns performance)
256
+ // 'structuredClone' — deep-clones returned values to prevent caller mutation
257
+ cloneStrategy: 'none',
258
+
259
+ // ── OOM guard ────────────────────────────────────────────────────────
260
+ oomProtection: true, // enabled by default
261
+ oomHeapThreshold: 0.85, // evict when heapUsed/heapTotal > 85 %
262
+ oomCheckIntervalMs: 10_000, // poll every 10 s
263
+ oomEvictPercent: 0.20, // evict coldest 20 % of L1 per trigger
264
+
265
+ // ── Encryption ───────────────────────────────────────────────────────
266
+ // base64-encoded 32-byte key; or set CACHE_ENCRYPTION_KEY env var.
267
+ // node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
268
+ encryptionKey: process.env.CACHE_ENCRYPTION_KEY,
269
+
270
+ // Zero-downtime key rotation — remove after all old entries have expired
271
+ previousEncryptionKey: process.env.PREV_ENCRYPTION_KEY,
272
+ previousEncryptionMode: 'aes-256-gcm', // defaults to current encryptionMode
273
+
274
+ // ── L2 write mode ────────────────────────────────────────────────────
275
+ // 'read-write' (default) — reads and writes to Redis
276
+ // 'read-only' — reads from Redis, skips all writes (canary / replica)
277
+ l2WriteMode: 'read-write',
278
+
279
+ // ── Stale-if-error ───────────────────────────────────────────────────
280
+ // Extra seconds to extend a stale L1 entry's expiry when a SWR fetchFn fails.
281
+ // Prevents serving errors while the upstream is temporarily down.
282
+ staleIfError: 300, // keep stale for 5 more minutes on revalidation error
283
+
284
+ // ── Eviction callback ────────────────────────────────────────────────
285
+ // Called synchronously whenever L1 evicts a key.
286
+ // reason: 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual'
287
+ onEviction: (key, reason) => metrics.increment(`cache.eviction.${reason}`),
288
+
289
+ // ── TTL jitter ────────────────────────────────────────────────────────
290
+ // Multiply each TTL by a random factor in [1-j, 1+j] to spread expiry.
291
+ // Prevents mass-expiry stampedes ("thundering cliff").
292
+ // Range [0, 1]; default 0 (no jitter).
293
+ ttlJitterFactor: 0.15, // ± 15 % spread
294
+
295
+ // ── Adaptive TTL ──────────────────────────────────────────────────────
296
+ // When true, tricache tracks per-key fetch latency in a rolling ring
297
+ // buffer and derives an optimal TTL from the p95 fetch duration:
298
+ // adaptedTtl = clamp(p95LatencyMs × multiplier, min, max)
299
+ // The caller-supplied ttlSeconds is used until ≥ 5 samples are collected,
300
+ // then the library takes over TTL management autonomously.
301
+ adaptiveTtl: true,
302
+ adaptiveTtlMin: 10, // floor: never assign TTL below 10 s (default)
303
+ adaptiveTtlMax: 86400, // ceiling: never exceed 24 h (default)
304
+ adaptiveTtlMultiplier: 20, // p95Ms × 20 = TTL in seconds (default)
305
+
306
+ // ── Singleton + rate-limit safety ──────────────────────────────────────
307
+ // strictSingleton: when true, a later create() for an existing namespace
308
+ // whose options differ from the first call THROWS instead of silently
309
+ // returning the existing instance. Guards against conflicting init points.
310
+ strictSingleton: false,
311
+ // failClosed: when true, increment() re-throws on a Redis error instead of
312
+ // failing open (returning 0). Enforces the rate-limit guard during outages.
313
+ failClosed: false,
314
+
315
+ // ── OpenTelemetry tracer ──────────────────────────────────────────────
316
+ // Pass any @opentelemetry/api-compatible tracer. No peer dependency.
317
+ // Spans: 'tricache.get' | 'tricache.set' | 'tricache.delete'
318
+ // Attributes: cache.key_prefix, cache.hit ('l1'|'disk'|'l2'|'miss')
319
+ tracer: trace.getTracer('my-app'),
320
+
321
+ // ── L2 circuit breaker ────────────────────────────────────────────────
322
+ // Opens after N consecutive Redis errors; probes after cooldown ms.
323
+ // State visible in cache.metrics().l2CircuitBreaker.state
324
+ l2CircuitBreakerThreshold: 5, // default
325
+ l2CircuitBreakerCooldownMs: 30_000, // default
326
+
327
+ // ── Negative caching ──────────────────────────────────────────────────
328
+ // Cache null/undefined fetchFn results for this many seconds globally.
329
+ // Prevents repeated upstream calls for keys that genuinely don't exist.
330
+ // Can be overridden per-call via opts.notFoundTtl in cache.get().
331
+ notFoundTtl: 30, // seconds; 0 = disabled (default)
332
+
333
+ // ── Startup warm-up ───────────────────────────────────────────────────
334
+ // Auto-call warmFromL2(pattern) at construction time.
335
+ // cache.ready() resolves once warm-up finishes — use as a k8s readiness gate.
336
+ // No-op when Redis is disabled or unreachable.
337
+ warmKeys: 'user:*',
338
+
339
+ // ── Prometheus instance label ─────────────────────────────────────────
340
+ // Adds an `instance` label to every metric in toPrometheusText().
341
+ instanceName: 'api-us-east-1',
342
+
343
+ // ── Cold-start snapshot ──────────────────────────────────────────────
344
+ snapshotPath: '/tmp/my-app-cache-snapshot.msgpack',
345
+ snapshotMaxAgeMs: 2 * 60 * 60 * 1000, // 2 hours (default)
346
+ forbiddenSnapshotPrefixes: ['auth:', 'session:', 'mfa:', 'rate_limit:'],
347
+
348
+ // ── Metrics callback ─────────────────────────────────────────────────
349
+ metricsIntervalMs: 60_000, // emit every 60 s (default)
350
+ onMetrics: (m) => myMonitoring.record(m), // optional push callback
351
+
352
+ // ── Per-operation hooks ───────────────────────────────────────────────
353
+ // onHit fires on every L1, disk, or L2 hit with the caller-facing key (no prefix)
354
+ // and the tier that served it. Lower latency than waiting for onMetrics.
355
+ onHit: (key, tier) => cloudwatch.putMetricData({ key, tier }),
356
+
357
+ // onMiss fires when all three tiers are exhausted — before fetchFn is called.
358
+ onMiss: (key) => cloudwatch.putMetricData({ key }),
359
+
360
+ // ── Development mutation guard ────────────────────────────────────────
361
+ // When true, every L1 hit value is deep-frozen before being returned.
362
+ // Mutation attempts throw TypeError immediately in development.
363
+ // Do NOT enable in production — deep-freezing large objects has measurable overhead.
364
+ frozen: process.env.NODE_ENV !== 'production',
365
+ });
366
+ ```
367
+
368
+ ### Environment variables
369
+
370
+ | Variable | Purpose |
371
+ |---|---|
372
+ | `REDIS_HOST` | Redis/Valkey hostname (used when `redisHost` option is not set) |
373
+ | `CACHE_ENCRYPTION_KEY` | Base64-encoded 32-byte AES-256-GCM key |
374
+ | `NODE_ENV` | When `!== 'production'`, L2 Redis and TLS are disabled by default |
375
+
376
+ ---
377
+
378
+ ## 📖 API reference
379
+
380
+ ### `CacheService.create(options?)` → `CacheService`
381
+
382
+ Returns the process-level singleton. Options are only applied on the **first** call per namespace — subsequent calls return the existing instance. When the new options differ from what the existing singleton was built with, this is a **silent no-op by default** (a one-time warning is logged and the `singletonDivergences` metric is incremented). Set `strictSingleton: true` on the first call to instead **throw** on a divergent later call — use this when multiple init points could pass conflicting Redis credentials or TTLs.
383
+
384
+ ### `CacheService.createAsync(optionsOrPromise)` → `Promise<CacheService>`
385
+
386
+ Async factory that resolves a `Promise<CacheOptions>` before constructing the singleton. Useful when config is fetched from a secret store at startup.
387
+
388
+ ```typescript
389
+ const cache = await CacheService.createAsync(fetchSecretsFromVault());
390
+ ```
391
+
392
+ ### `CacheService.reset(options?)` → `CacheService`
393
+
394
+ Destroys the existing singleton and creates a fresh one. Useful in tests.
395
+
396
+ ### `cache.get<T>(key, fetchFn, ttlSeconds?, opts?)` → `Promise<T>`
397
+
398
+ Get from cache or call `fetchFn` on a miss. The inflight map ensures `fetchFn` fires at most once per key regardless of concurrency.
399
+
400
+ > **Reference semantics:** on an L1 hit, the returned value is the live JS object stored in the entry — not a deep copy. Mutating it will corrupt the cached entry. Deep-clone at the call site if you need an independent copy.
401
+
402
+ | Parameter | Type | Default | Description |
403
+ |---|---|---|---|
404
+ | `key` | `string` | — | Cache key |
405
+ | `fetchFn` | `() => Promise<T>` | — | Called on a miss; result is cached |
406
+ | `ttlSeconds` | `number` | `300` | Hard TTL in seconds. **When `adaptiveTtl` is enabled, this is only authoritative until ≥ 5 samples are collected for the key — after that the library derives TTL from the p95 fetch latency** (see Adaptive TTL config). Use `opts` or a separate cache instance if you need a hard floor. |
407
+ | `opts.swr` | `number` | `0` | Stale-While-Revalidate grace seconds |
408
+ | `opts.priority` | `CachePriority` | auto-inferred | Eviction priority override |
409
+ | `opts.refreshAhead` | `number` | — | Fraction `(0, 1]` of TTL — triggers background recompute when `remaining ≤ ttl × (1 - refreshAhead)` |
410
+ | `opts.xfetchBeta` | `number` | — | XFetch β ≥ 0 — scales probabilistic early recompute by last fetch duration; higher = recompute earlier |
411
+ | `opts.notFoundTtl` | `number` | — | Per-call TTL in seconds for `null`/`undefined` results (overrides global `notFoundTtl`) |
412
+ | `opts.tags` | `string[]` | — | Tags to register when `fetchFn` populates the entry on a miss; no-op on L1/L2 hits where tags are already registered |
413
+
414
+ ### `cache.set<T>(key, data, ttlSeconds?, priority?, opts?)` → `Promise<void>`
415
+
416
+ Writes to L1 and (in production) L2. Publishes an invalidation to the backplane.
417
+
418
+ | Parameter | Type | Default | Description |
419
+ |---|---|---|---|
420
+ | `opts.tags` | `string[]` | `[]` | Associate tags with this entry for group invalidation |
421
+ | `opts.dependsOn` | `string[]` | `[]` | Parent keys — when any parent is deleted, this entry is automatically evicted from L1 |
422
+
423
+ ```typescript
424
+ await cache.set('product:1', data, 60, undefined, { tags: ['catalog', 'featured'] });
425
+
426
+ // Cascade invalidation: evicting 'org:42' also evicts 'org:42:members'
427
+ await cache.set('org:42:members', members, 300, undefined, { dependsOn: ['org:42'] });
428
+ await cache.delete('org:42'); // org:42:members is evicted too
429
+ ```
430
+
431
+ ### `cache.mget<T>(keys, fetchFn, ttl?, priority?)` → `Promise<(T | undefined)[]>`
432
+
433
+ Batch read. Checks **all three tiers** for each key — L1 (RAM), then L2 (Redis, in one pipelined `MGET`), then the L1.5 disk spill — and calls `fetchFn` only for keys that miss every tier. Preserves input ordering and counts exactly one hit per key (no double-counting across tiers).
434
+
435
+ `ttl` accepts a **plain number** (uniform TTL) or a **function `(key: string) => number`** (per-key TTL). The function is only called for miss keys — L1 hits are unaffected.
436
+
437
+ ```typescript
438
+ // Uniform TTL
439
+ const [userA, userB] = await cache.mget(
440
+ ['user:1', 'user:2'],
441
+ (missKeys) => db.users.findByIds(missKeys).then(rowsToMap),
442
+ 300,
443
+ );
444
+
445
+ // Per-key TTL — heterogeneous data in one batch call
446
+ const results = await cache.mget(
447
+ ['user:1', 'config:global', 'feature:flags'],
448
+ fetchFn,
449
+ (key) => key.startsWith('config:') ? 3600 : 300,
450
+ );
451
+ ```
452
+
453
+ ### `cache.mset<T>(entries)` → `Promise<void>`
454
+
455
+ Write multiple entries in a single call. Each entry accepts `value`, `ttl`, `priority`, and `tags`.
456
+
457
+ ```typescript
458
+ await cache.mset({
459
+ 'user:1': { value: alice, ttl: 300, priority: CachePriority.HIGH, tags: ['users'] },
460
+ 'user:2': { value: bob, ttl: 300 },
461
+ });
462
+ ```
463
+
464
+ ### `cache.mdel(keys)` → `Promise<void>`
465
+
466
+ Delete multiple keys in a single call. No-op for keys that do not exist.
467
+
468
+ ```typescript
469
+ await cache.mdel(['user:1', 'user:2', 'user:3']);
470
+ ```
471
+
472
+ ### `cache.warmFromL2(pattern)` → `Promise<number>`
473
+
474
+ Scan Redis for keys matching a glob pattern (e.g. `'user:*'`) and load their values into L1 with a 10-minute TTL. Returns the number of keys loaded. Returns `0` immediately when Redis is disabled or unreachable — safe to call unconditionally at startup.
475
+
476
+ ```typescript
477
+ // In your application startup
478
+ const loaded = await cache.warmFromL2('user:*');
479
+ console.log(`Pre-warmed ${loaded} user entries from Redis`);
480
+ ```
481
+
482
+ ### `cache.ready()` → `Promise<void>`
483
+
484
+ Returns a Promise that resolves once the cache is fully initialised. Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once the automatic `warmFromL2` call completes.
485
+
486
+ Designed for k8s readiness probes — await before accepting traffic, then never call again:
487
+
488
+ ```typescript
489
+ const cache = CacheService.create({ warmKeys: 'user:*' });
490
+
491
+ // k8s readiness probe endpoint
492
+ app.get('/ready', async (_req, res) => {
493
+ await cache.ready();
494
+ res.sendStatus(200);
495
+ });
496
+ ```
497
+
498
+ ### `cache.has(key)` → `boolean`
499
+
500
+ Return `true` if the key exists in L1 and has not expired. Bloom-filter fast-path — no fetch, no disk or Redis round-trip.
501
+
502
+ ### `cache.ttl(key)` → `number | null`
503
+
504
+ Return the remaining TTL in **seconds** for a key currently held in L1. Returns `null` if the key is absent or expired. Does not fetch or consume the value.
505
+
506
+ ```typescript
507
+ const remaining = cache.ttl('user:123'); // e.g. 247 (seconds left)
508
+ if (remaining !== null && remaining < 30) await cache.touch('user:123', 300);
509
+ ```
510
+
511
+ ### `cache.touch(key, newTtlSeconds)` → `Promise<boolean>`
512
+
513
+ Extend the TTL of a key in L1 (and fire-and-forget `EXPIRE` in Redis) without reading or re-fetching its value. Returns `false` if the key is absent or already expired.
514
+
515
+ ### `cache.getIfFresh<T>(key)` → `T | null`
516
+
517
+ Return the L1 value only if it is **fresh** (not yet in the SWR grace window). Returns `null` when absent, expired, or stale — without triggering a revalidation.
518
+
519
+ ```typescript
520
+ const fresh = cache.getIfFresh<User>('user:123');
521
+ if (fresh !== null) return fresh; // serve from L1, no network hop
522
+ ```
523
+
524
+ ### `cache.setIfAbsent<T>(key, value, ttlSeconds?)` → `Promise<boolean>`
525
+
526
+ Atomically write `value` only if `key` is not already cached. Checks L1 first, then attempts a Redis `SET NX EX`. Returns `true` if the value was written, `false` if a live entry already existed.
527
+
528
+ Useful for distributed lock-style writes, session initialisation, or any pattern where you must not overwrite an already-cached value.
529
+
530
+ ```typescript
531
+ const written = await cache.setIfAbsent(`session:${id}`, sessionData, 3600);
532
+ if (!written) {
533
+ // session already exists — do not overwrite
534
+ }
535
+ ```
536
+
537
+ ### `cache.hotKeys(n?)` → `Array<{ key: string; hits: number; sizeBytes: number }>`
538
+
539
+ Returns the top `n` live L1 keys ranked by Count-Min Sketch access frequency. Namespace prefix is stripped from each key. Expired entries are excluded. Default `n = 10`.
540
+
541
+ ```typescript
542
+ const hot = cache.hotKeys(5);
543
+ // [
544
+ // { key: 'user:1', hits: 1024, sizeBytes: 512 },
545
+ // { key: 'product:7', hits: 893, sizeBytes: 256 },
546
+ // ...
547
+ // ]
548
+ ```
549
+
550
+ ### `cache.invalidateTag(tag)` / `cache.invalidateTags(tags)` → `Promise<void>`
551
+
552
+ Evict all entries associated with one or more tags from L1, disk, and Redis.
553
+ When `tagStrategy: 'generational'` is active, `invalidateTags(tags)` pipelines multi-tag increments in a single network round-trip.
554
+
555
+ ```typescript
556
+ await cache.set('product:1', data, 60, undefined, { tags: ['catalog', 'electronics'] });
557
+ await cache.set('product:2', data, 60, undefined, { tags: ['catalog', 'deals'] });
558
+
559
+ await cache.invalidateTag('catalog'); // single tag
560
+ await cache.invalidateTags(['electronics', 'deals']); // pipelined batch invalidation
561
+ ```
562
+
563
+ ### `cache.ping()` → `Promise<CachePingResult>`
564
+
565
+ Measure L1 / disk / Redis latency in milliseconds. Returns `{ l1, disk, l2 }` — `l2` is `null` when Redis is disabled. Suitable for health-check endpoints.
566
+
567
+ ```typescript
568
+ app.get('/health', async (_req, res) => {
569
+ const { l1, disk, l2 } = await cache.ping();
570
+ res.json({ status: 'ok', latencyMs: { l1, disk, l2 } });
571
+ });
572
+ ```
573
+
574
+ ### `cache.drainToL2()` → `Promise<number>`
575
+
576
+ Pipeline all live L1 entries to Redis in a single round-trip. Returns the number of keys written. Useful for warming a new Redis node or zero-downtime failover.
577
+
578
+ ### `cache.delete(key)` → `Promise<void>`
579
+
580
+ Deletes one exact key or a glob pattern (`user:abc:*`). Propagates to disk, Redis, and all backplane peers.
581
+
582
+ ### `cache.clear(prefix?)` → `Promise<void>`
583
+
584
+ Flush all entries, or only those whose key starts with `prefix`. Propagates to disk and Redis.
585
+
586
+ ```typescript
587
+ await cache.clear(); // flush everything
588
+ await cache.clear('session:'); // flush only session keys
589
+ ```
590
+
591
+ ### `cache.rebalance()` → `void`
592
+
593
+ Evict L1 entries that now violate the current category or global capacity limits. Useful when `categoryLimits` are tightened after startup — normally, existing entries are not re-evaluated until they expire naturally.
594
+
595
+ ```typescript
596
+ // Tighten analytics limit at runtime, then immediately enforce it
597
+ cache.options.categoryLimits['analytics:'].maxEntries = 50;
598
+ cache.rebalance();
599
+ ```
600
+
601
+ ### `cache.increment(key, ttlSeconds?)` → `Promise<number>`
602
+
603
+ Distributed counter. With Redis active, atomically increments via `INCR` and returns the fleet-wide value. **By default it fails OPEN on a Redis error** — it returns `0`, so a caller's `if (count > LIMIT) reject()` guard will NOT reject during an outage. Set `failClosed: true` to re-throw the error instead, enforcing the limit even when Redis is unavailable. Track failures via `cache.metrics().counters.errors`.
604
+
605
+ When Redis is disabled, it maintains an **in-process** counter with the same TTL semantics so dev/test rate-limiting works — but rate-limiting is then per-instance, **not fleet-wide**. A one-time warning is logged the first time this fallback is used.
606
+
607
+ ### `cache.metrics()` → `CacheMetrics`
608
+
609
+ Returns a full metrics snapshot including hit rates, bloom filter stats, backplane counters, OOM eviction history, and tier sizes.
610
+
611
+ ### `CacheService.toPrometheusText(metrics, prefix?, instanceName?)` → `string`
612
+
613
+ Converts a `CacheMetrics` snapshot to Prometheus text exposition format. Pass `instanceName` to add an `instance` label alongside `namespace`.
614
+
615
+ ```typescript
616
+ app.get('/metrics', (_req, res) => {
617
+ res.type('text/plain').send(
618
+ CacheService.toPrometheusText(cache.metrics(), 'tricache', 'api-us-east-1'),
619
+ );
620
+ });
621
+ ```
622
+
623
+ ### `cache.stats()` → `{ l1, disk }`
624
+
625
+ Lightweight L1 and disk stats without the full metrics breakdown.
626
+
627
+ ### `cache.writeSnapshot(altPath?)` / `cache.loadSnapshot()`
628
+
629
+ Manual snapshot control. Called automatically on `SIGTERM`/`SIGINT` — only needed when you manage shutdown yourself. `writeSnapshot()` accepts an optional path to write to an alternate location without touching the configured default snapshot file.
630
+
631
+ ```typescript
632
+ // Graceful-shutdown hook — write to a dated backup path
633
+ process.on('SIGTERM', async () => {
634
+ await cache.writeSnapshot(`/backups/cache-${Date.now()}.snap`);
635
+ process.exit(0);
636
+ });
637
+ ```
638
+
639
+ ### `cache.keys()` → `Generator<string>`
640
+
641
+ Lazily yields the key for every live (non-expired) L1 entry. Namespace prefix is stripped automatically. Uses a dedicated generator that skips intermediate tuple allocation.
642
+
643
+ ```typescript
644
+ for (const key of cache.keys()) console.log(key);
645
+ ```
646
+
647
+ ### `cache.values<T>()` → `Generator<T>`
648
+
649
+ Lazily yields the cached value for every live L1 entry. Returns the live deserialized object (same reference semantics as `get()`). Uses `yield*` delegation — no intermediate generator frame.
650
+
651
+ ```typescript
652
+ for (const session of cache.values<Session>()) evict(session);
653
+ ```
654
+
655
+ ### `cache.entries<T>()` → `Generator<[string, T]>`
656
+
657
+ Lazily yields `[key, value]` pairs for every live L1 entry. Key has namespace prefix stripped.
658
+
659
+ ```typescript
660
+ for (const [key, user] of cache.entries<User>()) sync(key, user);
661
+ ```
662
+
663
+ ### `cache.rotateEncryptionKey(newKeyBase64, newMode?)` → `Promise<void>`
664
+
665
+ Dynamically rotates the active encryption key at runtime with zero downtime:
666
+ - Installs the new key as primary for all subsequent writes.
667
+ - Automatically preserves the previous key for seamless fallback decryption of existing cache entries.
668
+ - Gracefully drains and re-initializes all worker threads in the crypto pool (`WorkerPool.drainAndReinit()`).
669
+
670
+ ```typescript
671
+ await cache.rotateEncryptionKey(newKeyBase64, 'aes-256-gcm');
672
+ ```
673
+
674
+ ### `cache.lock<T>(resourceKey, fn, options?)` → `Promise<T>`
675
+
676
+ Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`, execute `fn`, and automatically release the lock on return or throw.
677
+ - Prevents concurrent executions of critical tasks across a cluster (e.g. database migrations, nightly syncs, cron jobs).
678
+ - Safe token comparison via Redis Lua script prevents deleting a lock acquired by another worker if execution exceeded the lock TTL.
679
+ - Automatically falls back to an in-process promise-chain mutex in single-process or dev environments.
680
+
681
+ ```typescript
682
+ const result = await cache.lock('cron:nightly-sync', async () => {
683
+ return await runNightlyDatabaseSync();
684
+ }, {
685
+ ttl: 60, // Auto-release TTL in seconds (prevents deadlocks on crash)
686
+ acquireTimeout: 5000, // Maximum wait time to acquire lock in ms
687
+ retryInterval: 100, // Polling retry interval in ms
688
+ });
689
+ ```
690
+
691
+ ### `cache.destroy()` → `Promise<void>`
692
+
693
+ Closes the Redis connection, unsubscribes the backplane, and stops all background timers.
694
+
695
+ ---
696
+
697
+ ## 🗄️ First-Class ORM Extensions (Prisma & Drizzle)
698
+
699
+ ### Prisma Client Extension (`tricache/prisma`)
700
+
701
+ Add one-line query caching and automatic model tag invalidation to Prisma:
702
+
703
+ ```typescript
704
+ import { PrismaClient } from '@prisma/client';
705
+ import { withTriCache } from 'tricache/prisma';
706
+ import { CacheService } from 'tricache';
707
+
708
+ const cache = CacheService.create({ redisHost: 'localhost' });
709
+
710
+ const prisma = new PrismaClient().$extends(
711
+ withTriCache({
712
+ cache,
713
+ defaultTtl: 300,
714
+ autoInvalidate: true, // Automatically invalidates 'user' tag on user.create / update / delete
715
+ })
716
+ );
717
+
718
+ // Automatic caching with explicit options:
719
+ const activeUsers = await prisma.user.findMany({
720
+ where: { active: true },
721
+ cache: { ttl: 60, tags: ['users'], swr: 30 },
722
+ });
723
+ ```
724
+
725
+ ### Drizzle ORM Wrapper (`tricache/drizzle`)
726
+
727
+ Wrap any Drizzle query builder with automatic SQL + parameter hashing and caching:
728
+
729
+ ```typescript
730
+ import { withCache } from 'tricache/drizzle';
731
+ import { eq } from 'drizzle-orm';
732
+
733
+ const activeUsers = await withCache(
734
+ db.select().from(users).where(eq(users.active, true)),
735
+ { cache, ttl: 300, tags: ['users'] }
736
+ );
737
+ ```
738
+
739
+ ---
740
+
741
+ ## 📊 OpenTelemetry Native Metrics
742
+
743
+ TriCache integrates directly with OpenTelemetry `Meter` (`@opentelemetry/api`) to publish monotonic counters and observable gauges without scrapers:
744
+
745
+ ```typescript
746
+ import { metrics } from '@opentelemetry/api';
747
+ import { CacheService } from 'tricache';
748
+
749
+ const meter = metrics.getMeter('my-service');
750
+
751
+ const cache = CacheService.create({
752
+ redisHost: 'localhost',
753
+ meter, // Native OpenTelemetry meter integration
754
+ });
755
+ ```
756
+
757
+ ---
758
+
759
+ ## 💻 Developer & Troubleshooting CLI (`npx tricache`)
760
+
761
+ Inspect running caches, test latency across tiers, or flush namespaces directly from your terminal:
762
+
763
+ ```bash
764
+ # Display full live dashboard (hit ratios, latencies, Count-Min Sketch hot keys)
765
+ npx tricache inspect --redis redis://localhost:6379 --namespace my-app
766
+
767
+ # Measure 3-tier response latency
768
+ npx tricache ping --redis redis://localhost:6379
769
+
770
+ # Flush namespace or prefix
771
+ npx tricache clear --redis redis://localhost:6379 --namespace my-app --prefix user:
772
+ ```
773
+
774
+ ---
775
+
776
+ ## 🌐 HTTP Caching & 304 ETag Middleware (`tricache/http`)
777
+
778
+ Drop-in HTTP caching with automatic weak ETag generation and RFC-compliant `304 Not Modified` short-circuiting:
779
+
780
+ ### Express & Connect
781
+ ```typescript
782
+ import express from 'express';
783
+ import { expressCache } from 'tricache/http';
784
+ import { CacheService } from 'tricache';
785
+
786
+ const app = express();
787
+ const cache = CacheService.create({ redisHost: 'localhost' });
788
+
789
+ // Automatically caches GET /api/users, emits ETag, and returns 304 on If-None-Match
790
+ app.get('/api/users', expressCache({ cache, ttl: 300, tags: ['users'] }), async (_req, res) => {
791
+ const users = await db.user.findMany();
792
+ res.json(users);
793
+ });
794
+ ```
795
+
796
+ ### Hono & Web Standards
797
+ ```typescript
798
+ import { Hono } from 'hono';
799
+ import { honoCache } from 'tricache/http';
800
+
801
+ const app = new Hono();
802
+
803
+ app.get('/api/users', honoCache({ ttl: 300, tags: ['users'] }), async (c) => {
804
+ const users = await db.user.findMany();
805
+ return c.json(users);
806
+ });
807
+ ```
808
+
809
+ ---
810
+
811
+ ## 🎯 Priority levels
812
+
813
+ ```typescript
814
+ import { CachePriority } from 'tricache';
815
+
816
+ CachePriority.LOW // 1 — analytics, reports — evicted first
817
+ CachePriority.NORMAL // 2 — general application data (default)
818
+ CachePriority.HIGH // 3 — user profiles, config — evicted last
819
+ CachePriority.CRITICAL // 4 — never evicted while valid (auth tokens, sessions)
820
+ ```
821
+
822
+ Priority is **auto-inferred** from the key when not specified:
823
+
824
+ | Key contains | Inferred priority |
825
+ |---|---|
826
+ | `auth:` or `session:` | `CRITICAL` |
827
+ | `user:`, `org:`, or `profile:` | `HIGH` |
828
+ | `analytics:`, `report:`, or `stats:` | `LOW` |
829
+ | anything else | `NORMAL` |
830
+
831
+ ---
832
+
833
+ ## 🧠 Eviction algorithm
834
+
835
+ L1 eviction uses **reservoir sampling** — an O(n) single pass samples 16 candidates, then sorts only those 16 (O(1)). Each candidate is scored:
836
+
837
+ ```
838
+ score = priority × 1000 + min(hits, 100) × 10 + ttlRemaining/60s − age/60s
839
+ ```
840
+
841
+ - Higher score = kept longer
842
+ - `CRITICAL` entries are excluded from sampling while valid
843
+ - When a category limit is breached, entries from that category receive a score penalty
844
+
845
+ ---
846
+
847
+ ## 🪵 Pluggable logger
848
+
849
+ Bring your own structured logger — tricache doesn't care if it's `pino`, `winston`, or `console`.
850
+
851
+ ```typescript
852
+ import pino from 'pino';
853
+ const logger = pino();
854
+
855
+ CacheService.create({
856
+ logger: {
857
+ debug: (msg, meta) => logger.debug(meta ?? {}, msg),
858
+ info: (msg, meta) => logger.info(meta ?? {}, msg),
859
+ warn: (msg, meta) => logger.warn(meta ?? {}, msg),
860
+ error: (msg, meta, err) => logger.error({ ...(meta ?? {}), err }, msg),
861
+ },
862
+ });
863
+ ```
864
+
865
+ ---
866
+
867
+ ## 🔐 Encryption
868
+
869
+ AES-256-GCM for L2 (Redis) values, disk spill files, and cold-start snapshots. Four modes are available via `encryptionMode`:
870
+
871
+ | Mode | Key length | Notes |
872
+ |---|---|---|
873
+ | `aes-256-gcm` | 32 bytes | **Default.** Authenticated encryption (AEAD). |
874
+ | `aes-128-gcm` | 16 bytes | ~15% faster than AES-256. Same AEAD guarantees. |
875
+ | `aes-128-ctr` | 16 bytes | Fastest cipher mode. AES-NI keystream, no auth tag. Use when integrity is guaranteed elsewhere (TLS, HMAC). |
876
+ | `xor` | any (≥ 16 bytes recommended) | **NOT cryptographic.** XOR obfuscation only. Dev/non-sensitive data. |
877
+
878
+ **Key generation:**
879
+
880
+ ```bash
881
+ # AES-256 (32 bytes)
882
+ node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
883
+
884
+ # AES-128 / AES-128-CTR (16 bytes)
885
+ node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
886
+
887
+ # XOR — any length, minimum 16 bytes recommended
888
+ node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
889
+ ```
890
+
891
+ ```typescript
892
+ // AES-256-GCM (default)
893
+ CacheService.create({ encryptionKey: '<base64-32-bytes>' });
894
+
895
+ // AES-128-GCM
896
+ CacheService.create({ encryptionKey: '<base64-16-bytes>', encryptionMode: 'aes-128-gcm' });
897
+
898
+ // AES-128-CTR (fastest cipher, no auth tag)
899
+ CacheService.create({ encryptionKey: '<base64-16-bytes>', encryptionMode: 'aes-128-ctr' });
900
+
901
+ // XOR obfuscation (NOT cryptographic — dev/non-sensitive only)
902
+ CacheService.create({ encryptionKey: '<base64-key>', encryptionMode: 'xor' });
903
+
904
+ // or use the env var: CACHE_ENCRYPTION_KEY=<base64-key>
905
+ ```
906
+
907
+ | Mode | Redis format | Disk / snapshot format |
908
+ |---|---|---|
909
+ | `aes-256-gcm` | `enc:v1:<base64(IV[12]\|Tag[16]\|CT)>` | `TRIC1ENC\|IV[12]\|Tag[16]\|CT[N]` |
910
+ | `aes-128-gcm` | `a128:v1:<base64(IV[12]\|Tag[16]\|CT)>` | `TRIC1128\|IV[12]\|Tag[16]\|CT[N]` |
911
+ | `aes-128-ctr` | `ctr:v1:<base64(IV[16]\|CT)>` | `TRIC1CTR\|IV[16]\|CT[N]` |
912
+ | `xor` | `xor:v1:<base64(key⊕data)>` | `TRIC1XOR\|key⊕data[N]` |
913
+
914
+ Existing plaintext values are read transparently during key rotation.
915
+
916
+ ### Zero-downtime key rotation
917
+
918
+ Set `previousEncryptionKey` to your old key while rolling out a new one. The cache tries the current key first; if decryption fails it transparently retries with the previous key. Remove `previousEncryptionKey` once all old entries have expired.
919
+
920
+ ```typescript
921
+ CacheService.create({
922
+ encryptionKey: process.env.NEW_ENCRYPTION_KEY, // new AES-256 key
923
+ previousEncryptionKey: process.env.OLD_ENCRYPTION_KEY, // fallback for old entries
924
+ // previousEncryptionMode defaults to current encryptionMode
925
+ });
926
+ ```
927
+
928
+ ---
929
+
930
+ ## 🧵 Worker thread crypto offload
931
+
932
+ By default, AES-GCM encryption/decryption runs synchronously on the V8 main thread. For payloads above a configurable size threshold this blocks the event loop for measurable durations. Enable worker thread offload to move encryption off the main thread:
933
+
934
+ ```typescript
935
+ CacheService.create({
936
+ encryptionKey: process.env.CACHE_ENCRYPTION_KEY,
937
+ workerThreads: true, // enable off-main-thread crypto
938
+ workerThresholdBytes: 131_072, // only offload payloads ≥ 128 KB (default)
939
+ workerPoolSize: 4, // threads; 0 = auto (min(4, logical CPUs))
940
+ });
941
+ ```
942
+
943
+ **How it works:**
944
+ - A fixed-size pool of Node.js `worker_threads` is created at startup; each worker holds an initialised `CacheEncryption` instance.
945
+ - Dispatch is round-robin; inter-thread IPC carries only strings (structured-clone fast path).
946
+ - Workers are `unref()`'d — they do not prevent the process from exiting cleanly.
947
+ - If worker initialisation fails the pool is silently disabled and synchronous crypto is used as a fallback — zero configuration required in environments where workers are unavailable.
948
+
949
+ **When to enable:**
950
+ - Payloads routinely exceed a few hundred KB with encryption enabled.
951
+ - You observe event-loop lag correlated with L2 read/write operations in APM.
952
+ - Rule of thumb: the default 128 KB threshold keeps overhead negligible for typical API response payloads while protecting against multi-MB documents.
953
+
954
+ ---
955
+
956
+ ## 🗜️ Transparent Payload Compression
957
+
958
+ TriCache includes built-in Brotli and Gzip compression for Redis L2 strings and L1.5 disk tier binary payloads, transparently reducing network bandwidth and storage footprints without manual application encoding.
959
+
960
+ ```typescript
961
+ CacheService.create({
962
+ compression: 'brotli', // 'brotli' | 'gzip' | 'none' (default: 'none')
963
+ compressionThresholdBytes: 1024, // only compress entries >= 1024 bytes (default)
964
+ });
965
+ ```
966
+
967
+ ### Storage Envelope Matrix
968
+
969
+ Entries written to Redis L2 and the disk spill tier use self-describing magic headers, allowing mixed uncompressed, compressed, and encrypted entries to coexist seamlessly during rollout:
970
+
971
+ | Envelope Header | State | Description |
972
+ |---|---|---|
973
+ | `cmp:v1:<data>` | Compressed | Compressed payload (Brotli or Gzip) |
974
+ | `ecp:v1:<data>` | Encrypted + Compressed | Payload compressed before encryption |
975
+ | `enc:v1:<data>` | Encrypted | AES-256-GCM / AES-128 encrypted without compression |
976
+ | `{"d": ...}` / raw | Plaintext | Uncompressed, unencrypted legacy JSON / msgpack |
977
+
978
+ ### Worker Thread Offload
979
+
980
+ When `workerThreads: true` is enabled, compression and decompression for large payloads above `workerThresholdBytes` are offloaded to background worker threads alongside encryption, keeping the V8 main event loop free for concurrent HTTP requests.
981
+
982
+ ---
983
+
984
+ ## ⚡ Next.js 16 & 15 Integration (`tricache/next`)
985
+
986
+ TriCache provides first-class support for Next.js 16 `"use cache"`, React 19 RSC streaming, and Next.js 15/16 ISR via `tricache/next`.
987
+
988
+ ### Setup in `next.config.mjs`
989
+
990
+ ```javascript
991
+ // next.config.mjs
992
+ /** @type {import('next').NextConfig} */
993
+ const nextConfig = {
994
+ // Point Next.js directly to the default export
995
+ cacheHandler: require.resolve('tricache/next'),
996
+ cacheMaxMemorySize: 0, // Disable Next.js default in-memory cache to let TriCache manage RAM
997
+ };
998
+
999
+ export default nextConfig;
1000
+ ```
1001
+
1002
+ ### Custom Options Factory
1003
+
1004
+ To configure TriCache with custom Redis, encryption, or namespace settings:
1005
+
1006
+ ```typescript
1007
+ // cache-handler.mjs
1008
+ import { createNextCacheHandler } from 'tricache/next';
1009
+
1010
+ export default createNextCacheHandler({
1011
+ namespace: 'my-next-app',
1012
+ redisHost: process.env.REDIS_HOST,
1013
+ tagStrategy: 'generational',
1014
+ backplaneMode: 'stream',
1015
+ });
1016
+ ```
1017
+
1018
+ ```javascript
1019
+ // next.config.mjs
1020
+ export default {
1021
+ cacheHandler: require.resolve('./cache-handler.mjs'),
1022
+ };
1023
+ ```
1024
+
1025
+ ### Key Architectural Highlights
1026
+ - **Single-Use Stream Re-hydration:** React 19 RSC streams (`ReadableStream<Uint8Array>`) are drained to contiguous binary buffers on `set()`, and fresh unlocked `ReadableStream` instances are re-hydrated on every `get()` hit.
1027
+ - **Dynamic `softTags` Verification:** In Next.js 16 App Router, layout and route boundary invalidations pass `softTags` into `ctx.softTags` at read time. TriCache dynamically validates them against generational tag versions, triggering misses on invalidated boundaries.
1028
+ - **Stream Error Boundary:** Mid-flight client disconnects or aborted streams are caught safely without throwing or storing corrupted partial payloads.
1029
+ - **Automatic Build Phase Bypass:** Automatically detects `NEXT_PHASE=phase-production-build` during `next build` and runs in-memory without opening Redis network sockets.
1030
+
1031
+ ---
1032
+
1033
+ ## 🦁 NestJS Integration (`tricache/nestjs`)
1034
+
1035
+ TriCache provides an official NestJS dynamic module and `@nestjs/cache-manager` store adapter compatible with `cache-manager` v5/v6:
1036
+
1037
+ ### Synchronous Module Registration
1038
+
1039
+ ```typescript
1040
+ // app.module.ts
1041
+ import { Module } from '@nestjs/common';
1042
+ import { TriCacheModule } from 'tricache/nestjs';
1043
+
1044
+ @Module({
1045
+ imports: [
1046
+ TriCacheModule.register({
1047
+ namespace: 'my-nest-api',
1048
+ redisHost: process.env.REDIS_HOST,
1049
+ encryptionKey: process.env.CACHE_ENCRYPTION_KEY,
1050
+ }),
1051
+ ],
1052
+ })
1053
+ export class AppModule {}
1054
+ ```
1055
+
1056
+ ### Asynchronous Module Registration (with ConfigService)
1057
+
1058
+ ```typescript
1059
+ // app.module.ts
1060
+ import { Module } from '@nestjs/common';
1061
+ import { ConfigModule, ConfigService } from '@nestjs/config';
1062
+ import { TriCacheModule } from 'tricache/nestjs';
1063
+
1064
+ @Module({
1065
+ imports: [
1066
+ ConfigModule.forRoot(),
1067
+ TriCacheModule.registerAsync({
1068
+ imports: [ConfigModule],
1069
+ inject: [ConfigService],
1070
+ useFactory: (config: ConfigService) => ({
1071
+ namespace: config.get<string>('CACHE_NAMESPACE', 'nest-api'),
1072
+ redisHost: config.get<string>('REDIS_HOST'),
1073
+ redisPort: config.get<number>('REDIS_PORT', 6379),
1074
+ tagStrategy: 'generational',
1075
+ backplaneMode: 'stream',
1076
+ }),
1077
+ }),
1078
+ ],
1079
+ })
1080
+ export class AppModule {}
1081
+ ```
1082
+
1083
+ ### Injecting into Services & Controllers
1084
+
1085
+ Use either standard `@Inject(CACHE_MANAGER)` for `@nestjs/cache-manager` compatibility, or `@Inject('TRICACHE_SERVICE')` for direct access to TriCache's three-tier engine:
1086
+
1087
+ ```typescript
1088
+ import { Injectable, Inject } from '@nestjs/common';
1089
+ import { CACHE_MANAGER } from '@nestjs/cache-manager';
1090
+ import type { CacheStore } from '@nestjs/cache-manager';
1091
+ import type { CacheService } from 'tricache';
1092
+
1093
+ @Injectable()
1094
+ export class UsersService {
1095
+ constructor(
1096
+ @Inject(CACHE_MANAGER) private cacheManager: CacheStore,
1097
+ @Inject('TRICACHE_SERVICE') private triCache: CacheService,
1098
+ ) {}
1099
+
1100
+ async getUser(id: string) {
1101
+ // Standard NestJS cache-manager API (millisecond TTL)
1102
+ const cached = await this.cacheManager.get(`user:${id}`);
1103
+ if (cached) return cached;
1104
+
1105
+ // Or use TriCache's native SWR & thundering-herd prevention:
1106
+ return this.triCache.get(`user:${id}`, () => this.fetchFromDb(id), 300, { swr: 60 });
1107
+ }
1108
+ }
1109
+ ```
1110
+
1111
+ ### Declarative Method Decorators (`@Cacheable`, `@CacheEvict`)
1112
+
1113
+ Remove cache boilerplate from your NestJS services using declarative method decorators:
1114
+
1115
+ ```typescript
1116
+ import { Injectable } from '@nestjs/common';
1117
+ import { Cacheable, CacheEvict } from 'tricache/nestjs';
1118
+
1119
+ @Injectable()
1120
+ export class ProductsService {
1121
+ // Automatically caches result in TriCache (L1 -> L1.5 -> L2) with stampede coalescing
1122
+ @Cacheable({
1123
+ key: (id: string) => `product:${id}`,
1124
+ ttl: 300,
1125
+ swr: 60,
1126
+ tags: ['products'],
1127
+ })
1128
+ async findById(id: string) {
1129
+ return this.db.product.findUnique({ where: { id } });
1130
+ }
1131
+
1132
+ // Automatically invalidates tags or keys after successful method execution
1133
+ @CacheEvict({ tags: ['products'] })
1134
+ async updateProduct(id: string, dto: UpdateProductDto) {
1135
+ return this.db.product.update({ where: { id }, data: dto });
1136
+ }
1137
+ }
1138
+ ```
1139
+
1140
+ ---
1141
+
1142
+ ## 🏷️ Generational Tag Invalidation (`tagStrategy: 'generational'`)
1143
+
1144
+ Traditional tag-based caching stores key sets in Redis and performs $O(N)$ key deletions on `invalidateTag()`. For high-cardinality collections, this triggers blocking Redis spikes and cache stampedes.
1145
+
1146
+ With `tagStrategy: 'generational'`:
1147
+ - **$O(1)$ Atomic Tag Invalidation:** `cache.invalidateTag('products')` atomically increments an integer version counter in Redis (`INCR tag_ver:products`) and updates local memory.
1148
+ - **Atomic Multi-Field Hash Schema:** Entries in Redis are stored as a unified Hash `{ d: envelope, t: timestamp, tv: tagVersionsJson }` with an atomic `MULTI/EXEC` transaction.
1149
+ - **Pipelined Batch Invalidation:** `cache.invalidateTags(['t1', 't2'])` pipelines multi-tag version increments in a single network round-trip.
1150
+ - **Zero-Tear Compare-and-Delete:** Stale entries are pruned upon access using an atomic Lua script (`deleteIfSetBefore`) on Redis and L1 RAM, eliminating race conditions where concurrent revalidations write newer data.
1151
+ - **Self-Healing Reconciliation:** In-memory tag versions are verified against Redis when `Date.now() - lastSyncedAt > tagVersionTtlMs` (default: 5 s), guaranteeing bounded staleness even if a backplane broadcast is dropped during a network partition.
1152
+
1153
+ ```typescript
1154
+ const cache = CacheService.create({
1155
+ tagStrategy: 'generational',
1156
+ tagVersionTtlMs: 5_000,
1157
+ });
1158
+
1159
+ // Cache entry with tags
1160
+ await cache.set('item:123', productData, 3600, undefined, { tags: ['catalog', 'electronics'] });
1161
+
1162
+ // Invalidate in O(1) time
1163
+ await cache.invalidateTag('catalog');
1164
+ ```
1165
+
1166
+ ---
1167
+
1168
+ ## 🌊 Redis Streams Backplane (`backplaneMode: 'stream'`)
1169
+
1170
+ Standard Redis Pub/Sub operates on an *at-most-once* delivery model. If an instance experiences a transient network disconnect, container reschedule, or long GC pause, invalidation messages published during the disconnection are lost.
1171
+
1172
+ Setting `backplaneMode: 'stream'` switches the backplane to a durable append-only log in Redis using `XADD` and `XREAD`:
1173
+
1174
+ ```typescript
1175
+ const cache = CacheService.create({
1176
+ backplaneMode: 'stream',
1177
+ backplaneStreamMaxLen: 10_000, // Approximate MAXLEN trimming
1178
+ backplaneStreamBlockMs: 2_000, // XREAD BLOCK timeout
1179
+ });
1180
+ ```
1181
+
1182
+ ### Architecture & Resilience
1183
+ - **Cluster Single-Slot Routing:** Stream keys default to `tricache:stream:{<namespace>}`, ensuring multi-node Redis Clusters route all stream operations to a single slot without cross-slot errors.
1184
+ - **Dedicated Long-Polling Consumer:** Runs on an isolated Redis client connection (`XREAD BLOCK`) so standard cache `GET`/`SET` pipelines are never blocked.
1185
+ - **Zero-Drop Replay on Reconnect:** Tracks `_lastStreamId` to automatically replay all missed invalidations in order after short network drops or GC pauses without flushing L1.
1186
+ - **Trim Gap Fallback:** If an instance was disconnected longer than the stream retention window, it detects the gap, increments `metrics().backplane.streamGaps`, safely flushes L1, and resets to `'$'`.
1187
+ - **Instant Clean Teardown:** `cache.destroy()` immediately disconnects the dedicated client socket to interrupt blocking long-polls without stalling process shutdown.
1188
+
1189
+ ---
1190
+
1191
+ ## 🛡️ Read Safety (`cloneStrategy: 'structuredClone'`)
1192
+
1193
+ By default (`cloneStrategy: 'none'`), TriCache returns raw in-memory JS references from L1 hits for maximum throughput (~350 ns per hit). If application code mutates the returned object, the cached reference is directly modified.
1194
+
1195
+ Setting `cloneStrategy: 'structuredClone'` enables deep clone isolation:
1196
+
1197
+ ```typescript
1198
+ const cache = CacheService.create({
1199
+ cloneStrategy: 'structuredClone',
1200
+ });
1201
+
1202
+ const user = await cache.get('user:1', () => db.fetchUser(1));
1203
+ user.roles.push('admin'); // Mutating caller copy does NOT pollute cached L1 state
1204
+ ```
1205
+
1206
+ Supported types: plain objects, arrays, Dates, Maps, Sets, and TypedArrays. When `frozen: true` is also enabled, L1 entries remain frozen while callers receive fully mutable clones.
1207
+
1208
+ ---
1209
+
1210
+ ## ☁️ Serverless / ephemeral disk environments
1211
+
1212
+ On Lambda, Cloud Run, Fly.io, Railway, and similar platforms, the filesystem (`os.tmpdir()`) is container-scoped and is wiped on every cold start. Disk spill and cold-start snapshots are therefore useless and waste I/O budget.
1213
+
1214
+ TriCache auto-detects serverless runtimes at construction time (zero I/O — environment variable checks only) and automatically disables the disk tier:
1215
+
1216
+ | Runtime | Detection env var |
1217
+ |---|---|
1218
+ | AWS Lambda | `AWS_LAMBDA_FUNCTION_NAME` |
1219
+ | Google Cloud Run | `K_SERVICE` |
1220
+ | Google Cloud Functions | `FUNCTION_TARGET` |
1221
+ | Azure Functions | `WEBSITE_INSTANCE_ID` |
1222
+ | Fly.io | `FLY_APP_NAME` |
1223
+ | Railway | `RAILWAY_ENVIRONMENT` |
1224
+ | Vercel | `VERCEL` |
1225
+
1226
+ You can also control disk behaviour explicitly:
1227
+
1228
+ ```typescript
1229
+ // Force-disable disk tier (e.g., when running inside a Docker container with no writable tmpdir)
1230
+ CacheService.create({ disableDisk: true });
1231
+
1232
+ // Force-enable disk tier even when a serverless env var is present (advanced override)
1233
+ CacheService.create({ disableDisk: false });
1234
+ ```
1235
+
1236
+ When disk is disabled:
1237
+ - The disk spill callback is a no-op.
1238
+ - `disk.load()` / `disk.delete()` / `disk.clear()` are never called.
1239
+ - `loadSnapshot()` and `writeSnapshot()` are skipped.
1240
+ - The background disk janitor timer is not started.
1241
+ - `metrics().disk.disabled` is `true`.
1242
+
1243
+ ---
1244
+
1245
+ ## 🔴 Redis Cluster and Sentinel
1246
+
1247
+ TriCache supports Redis Cluster (slot-based sharding) and Redis Sentinel (automatic primary failover) via ioredis built-in support.
1248
+
1249
+ ### Redis Cluster
1250
+
1251
+ ```typescript
1252
+ CacheService.create({
1253
+ redisClusterNodes: [
1254
+ { host: 'redis-node-1.example.com', port: 6379 },
1255
+ { host: 'redis-node-2.example.com', port: 6379 },
1256
+ { host: 'redis-node-3.example.com', port: 6379 },
1257
+ ],
1258
+ redisTls: true,
1259
+ useShardedPubSub: true, // Redis 7+ sharded pub/sub (SPUBLISH / SSUBSCRIBE)
1260
+ });
1261
+ ```
1262
+
1263
+ ioredis handles slot routing, moved/ask redirects, and re-queuing commands during slot migrations transparently. You can list any subset of cluster nodes — ioredis discovers the full topology automatically.
1264
+
1265
+ #### Sharded Pub/Sub (`useShardedPubSub`)
1266
+
1267
+ When `useShardedPubSub: true` is enabled on Redis Cluster (Redis 7+), invalidation messages are published via `SPUBLISH` and subscribed via `SSUBSCRIBE` bound directly to the `{<namespace>}` slot shard. This eliminates cluster-wide broadcast gossip, drastically reducing cluster bus CPU utilization under heavy invalidation load.
1268
+
1269
+ ### Redis Sentinel
1270
+
1271
+ ```typescript
1272
+ CacheService.create({
1273
+ redisSentinel: {
1274
+ name: 'mymaster',
1275
+ sentinels: [
1276
+ { host: 'sentinel-1.example.com', port: 26379 },
1277
+ { host: 'sentinel-2.example.com', port: 26379 },
1278
+ { host: 'sentinel-3.example.com', port: 26379 },
1279
+ ],
1280
+ },
1281
+ redisTls: true,
1282
+ });
1283
+ ```
1284
+
1285
+ ioredis monitors the current master via the Sentinel topology and transparently reconnects to a new primary after failover. The backplane subscriber is also constructed in the appropriate cluster/sentinel mode.
1286
+
1287
+ ### Wire Protocol Compatibility (`redisProtocol: 2 | 3`)
1288
+
1289
+ TriCache uses `ioredis` v6, which connects using **RESP3** (`redisProtocol: 3`) by default for optimized structured parsing and streaming.
1290
+
1291
+ If your infrastructure routes Redis traffic through intermediate proxies that only understand RESP2 (such as **Twemproxy**, **Envoy Redis proxy filter**, or older AWS ElastiCache Serverless proxy configurations that reject the `HELLO 3` handshake), explicitly set `redisProtocol: 2`:
1292
+
1293
+ ```typescript
1294
+ CacheService.create({
1295
+ redisHost: 'envoy-redis-proxy.internal',
1296
+ redisProtocol: 2, // force RESP2 wire protocol
1297
+ });
1298
+ ```
1299
+
1300
+ > `redisHost` / `redisPort` are ignored when `redisClusterNodes` or `redisSentinel` is set. All three topology modes support `redisTls` and `redisProtocol` (RESP2/RESP3).
1301
+
1302
+ ---
1303
+
1304
+ ## ⚡ WASM Bloom filter
1305
+
1306
+ A 100,000-bit filter with k=7 hash probes is used when it is large enough for the
1307
+ configured `l1MaxEntries`; otherwise a right-sized pure-JS filter is instantiated
1308
+ automatically (see `createBloomFilter`). For the default 100K-bit filter:
1309
+
1310
+ - At the default `l1MaxEntries: 2,000` — false-positive rate ≈ **0.00007%** (m=100,000, k=7)
1311
+ - At its rated capacity (~10,400 entries) — false-positive rate ≈ **1%**
1312
+ - When `l1MaxEntries` exceeds the WASM filter's ~10,400-entry capacity, a JS filter sized via the optimal formula (m = ⌈–n·ln p / (ln 2)²⌉, k = round(ln 2 · m / n) clamped to [4, 10]) is used instead — no capacity cliff.
1313
+ - The filter rebuilds automatically when stale bits from deleted/expired entries accumulate
1314
+
1315
+ Mechanics:
1316
+ - `mightContain(key) === false` → **guaranteed miss** — the Map lookup is skipped entirely
1317
+ - `mightContain(key) === true` → probable hit — the Map is checked to confirm
1318
+
1319
+ The 562-byte WASM binary is inlined as Base64 — zero filesystem access at runtime. Falls back to a pure-JS implementation if `WebAssembly` is unavailable.
1320
+
1321
+ ---
1322
+
1323
+ ## 🔬 High-Performance Architecture & Memory Hygiene
1324
+
1325
+ TriCache is engineered for low-latency, high-throughput environments where garbage collection (GC) pauses and main-thread blocking must be minimized. The codebase employs several advanced V8 and hardware-aware optimizations:
1326
+
1327
+ ### ⚡ Performance & Memory Hygiene
1328
+ - **Zero-Allocation Hot Paths:** To eliminate object allocation thrashing on hot L1 reads, TriCache reuses a single, pre-allocated static `_hit` object literal in [src/smart-memory-cache.ts](src/smart-memory-cache.ts) to return cache hits synchronously.
1329
+ - **Fast-Path Binary Operations (Uint32Array XOR):** The XOR obfuscation engine in [src/encryption.ts](src/encryption.ts) automatically detects if buffers are 4-byte-aligned. If so, it processes the operation using `Uint32Array` views, allowing the V8 JIT compiler to compile the loop into highly-optimized, 32-bit register-level CPU `XOR` instructions instead of a slow byte-by-byte traversal.
1330
+ - **Pre-allocated Eviction Pools:** During L1 eviction, candidate selection avoids generating temporary object literals. The system samples candidates into a pre-allocated `_evictPool` array and mutates their fields in-place, eliminating GC pressure when the cache is under heavy write load.
1331
+
1332
+ ### 🛡️ Production-First Ergonomics & Resiliency
1333
+ - **Next.js HMR Resiliency:** Normal in-memory caches re-instantiate and wipe their state during Next.js Hot Module Replacement (HMR) reloads. TriCache binds its singleton instance to `globalThis` to preserve the L1 cache across hot-reload cycles in server environments.
1334
+ - **Graceful Degradation & Fallbacks:**
1335
+ - **L2 Circuit Breaker:** Protects your app from cascading failures if Redis gets slow or goes down, automatically failing back to L1/disk and probing Redis health on a cooldown timer.
1336
+ - **Dynamic Bloom Filters:** Uses a WebAssembly Bloom filter for fast miss checks, but automatically falls back to a dynamically-sized, memory-optimized pure JS Bloom filter if the cache size exceeds the WebAssembly filter's hardcoded capacity limit.
1337
+ - **CPU-Efficient Count-Min Sketch:** Keeps access-frequency history across eviction boundaries in a tight `4 rows × 512 counters` `Uint16Array` (4 KB total). This fits entirely within the CPU's L1d cache, ensuring frequency updates are essentially free.
1338
+
1339
+ ---
1340
+
1341
+ ## 📊 Performance
1342
+
1343
+ Measured on a single Node.js thread (no `await` on synchronous paths):
1344
+
1345
+ **L1 SmartMemoryCache**
1346
+
1347
+ | Operation | Throughput | Latency | Notes |
1348
+ |---|---|---|---|
1349
+ | `get` — hot hit (8K entries) | **2.81 M/s** | 356 ns | bloom → Map lookup → return cached value |
1350
+ | `get` — cold miss | **7.14 M/s** | 140 ns | bloom gates → early return |
1351
+ | `set` — tiny payload | 1.06 M/s | 944 ns | pack() + Map.set + bloom.add |
1352
+ | `set` — small payload (< 512 B) | 574.1 K/s | 1.74 µs | pack() same unified path, larger payload |
1353
+ | `set` — large payload (≥ 512 B) | 228.6 K/s | 4.37 µs | pack() larger payload |
1354
+ | `set` — CRITICAL priority | 843.6 K/s | 1.19 µs | same set path; skipped in eviction sort |
1355
+ | `delete` — exact key | **5.36 M/s** | 186 ns | Map.delete |
1356
+ | `deletePattern` — glob wildcard | 18.7 K/s | 53.48 µs | O(n) Map scan |
1357
+ | Count-Min Sketch estimate | **3.37 M/s** | 297 ns | 4 row lookups — called on every `get()` hit and `set()` |
1358
+
1359
+ **Iterator interface (L1 live entries, 500 entries)**
1360
+
1361
+ | Method | Throughput | Latency | Notes |
1362
+ |---|---|---|---|
1363
+ | `cache.keys()` | 26.6 K/s | 37.53 µs | no `[key,entry]` tuple allocation |
1364
+ | `cache.values()` | 35.5 K/s | 28.19 µs | `yield*` delegation |
1365
+ | `cache.entries()` | 24.0 K/s | 41.73 µs | `[strippedKey, value]` pairs |
1366
+ | raw `Map` iteration (baseline) | 277.2 K/s | 3.61 µs | no expiry check, no generator overhead |
1367
+
1368
+ **CacheService (end-to-end)**
1369
+
1370
+ | Operation | Throughput | Latency | Notes |
1371
+ |---|---|---|---|
1372
+ | `get` — L1 warm hit | **2.03 M/s** | 491 ns | inflight check → l1.get → return cached value |
1373
+ | `get` — SWR stale serve | **1.78 M/s** | 562 ns | serves stale; revalidates async |
1374
+ | `get` — miss + fetchFn | 13.7 K/s | 73 µs | Promise microtask + l1.set |
1375
+ | `set` | 28.7 K/s | 34.86 µs | l1.set + disk.save (fire-and-forget) |
1376
+ | `delete` — exact key | 7.3 K/s | 137.82 µs | l1.delete + disk.delete + backplane |
1377
+ | `delete` — glob `*` | 687 K/s | 1.46 µs | l1.deletePattern O(n) + disk glob |
1378
+
1379
+ **Encryption** (IV pool, pre-allocated output buffers)
1380
+
1381
+ | Mode | Payload | Encrypt | Decrypt |
1382
+ |---|---|---|---|
1383
+ | AES-256-GCM | 64 B | 140.4 K/s / 7.12 µs | 155.5 K/s / 6.43 µs |
1384
+ | AES-256-GCM | 512 B | 103.1 K/s / 9.70 µs | 142.9 K/s / 6.99 µs |
1385
+ | AES-256-GCM | 4 KB | 58.4 K/s / 17.12 µs | 48.0 K/s / 20.84 µs |
1386
+ | AES-128-GCM | 64 B | 148.8 K/s / 6.72 µs | 173.0 K/s / 5.78 µs |
1387
+ | AES-128-GCM | 512 B | 135.7 K/s / 7.37 µs | 158.8 K/s / 6.30 µs |
1388
+ | AES-128-GCM | 4 KB | 70.2 K/s / 14.24 µs | 53.2 K/s / 18.79 µs |
1389
+ | AES-128-CTR | 64 B | 187.9 K/s / 5.32 µs | 196.9 K/s / 5.08 µs |
1390
+ | AES-128-CTR | 512 B | 183.5 K/s / 5.45 µs | 185.6 K/s / 5.39 µs |
1391
+ | AES-128-CTR | 4 KB | 78.4 K/s / 12.75 µs | 71.8 K/s / 13.93 µs |
1392
+ | XOR _(obfuscation only)_ | 64 B | 2.43 M/s / 412 ns | 2.10 M/s / 476 ns |
1393
+ | XOR _(obfuscation only)_ | 512 B | 665.5 K/s / 1.50 µs | 715.3 K/s / 1.40 µs |
1394
+ | XOR _(obfuscation only)_ | 4 KB | 114.5 K/s / 8.73 µs | 77.6 K/s / 12.89 µs |
1395
+
1396
+ > AES and XOR string-path numbers shown (Redis L2). Buffer path (disk/snapshot) is 5–20% faster — no base64 overhead.
1397
+ > AES-128-GCM is 5–50% faster than AES-256-GCM depending on payload (gap widens at mid-range sizes on AES-NI hardware).
1398
+ > AES-128-CTR removes the GHASH MAC step: ~50% faster than AES-128-GCM at small payloads; use only when integrity is guaranteed by transport.
1399
+ > XOR numbers are for the buffer path (32-bit word-level XOR, 4 bytes/iteration). XOR dominates at small payloads (no cipher setup) and remains ~2× faster than AES at 4 KB.
1400
+
1401
+ See [BENCHMARKS.md](BENCHMARKS.md) for the full breakdown: bloom filter cost, serialization by payload size, eviction pressure, concurrency analysis, multi-tenancy isolation, and a realistic 80/15/5 read/miss/write workload.
1402
+
1403
+ ---
1404
+
1405
+ ## 🤝 Contributing
1406
+
1407
+ Contributions of all kinds are welcome! Please check out our [Contributing Guide](CONTRIBUTING.md) and [Code of Conduct](CODE_OF_CONDUCT.md) for detailed instructions on development setup, testing, benchmarking, and PR submission.
1408
+
1409
+ 1. Fork the repo and create a feature branch (`git checkout -b feat/my-feature`)
1410
+ 2. Run `pnpm lint`, `pnpm typecheck:all`, and `pnpm test` — all checks must pass
1411
+ 3. Run `pnpm bench` if you touch a hot path and include before/after numbers in your PR
1412
+ 4. Open your PR against `main`
1413
+
1414
+ > New to the codebase? Start with [src/cache-service.ts](src/cache-service.ts) for the public API and [src/smart-memory-cache.ts](src/smart-memory-cache.ts) for the L1 engine. See [CONTRIBUTING.md](CONTRIBUTING.md#codebase-architecture) for full architecture notes.
1415
+
1416
+ ---
1417
+
1418
+ ## 🛡️ Security
1419
+
1420
+ Found a vulnerability? **Please don't open a public issue.** Report it privately via [GitHub Security Advisories](https://github.com/Kareem411/TriCache/security/advisories/new) so it can be patched before disclosure.
1421
+
1422
+ For encryption key generation and rotation best practices, see the [Encryption](#-encryption) section.
1423
+
1424
+ ---
1425
+
1426
+ ## 📄 License
1427
+
1428
+ MIT