tricache 0.6.6 → 0.6.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -2
- package/dist/index.cjs +9 -1
- package/dist/index.js +9 -1
- package/package.json +12 -11
- package/src/cache-service.ts +19 -3
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
[](BENCHMARKS.md)
|
|
10
10
|
[](BENCHMARKS.md)
|
|
11
11
|
|
|
12
|
-
tricache is
|
|
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
13
|
|
|
14
14
|
<img src="https://raw.githubusercontent.com/Kareem411/TriCache/master/public/SmartMemoryCache_DiskTier.jpeg" width="600" alt="tricache architecture" />
|
|
15
15
|
|
|
@@ -663,7 +663,7 @@ CacheService.create({
|
|
|
663
663
|
|
|
664
664
|
## 🔐 Encryption
|
|
665
665
|
|
|
666
|
-
AES-256-GCM for L2 (Redis) values, disk spill files, and cold-start snapshots.
|
|
666
|
+
AES-256-GCM for L2 (Redis) values, disk spill files, and cold-start snapshots. Four modes are available via `encryptionMode`:
|
|
667
667
|
|
|
668
668
|
| Mode | Key length | Notes |
|
|
669
669
|
|---|---|---|
|
|
@@ -862,6 +862,24 @@ The 562-byte WASM binary is inlined as Base64 — zero filesystem access at runt
|
|
|
862
862
|
|
|
863
863
|
---
|
|
864
864
|
|
|
865
|
+
## 🔬 High-Performance Architecture & Memory Hygiene
|
|
866
|
+
|
|
867
|
+
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:
|
|
868
|
+
|
|
869
|
+
### ⚡ Performance & Memory Hygiene
|
|
870
|
+
- **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.
|
|
871
|
+
- **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.
|
|
872
|
+
- **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.
|
|
873
|
+
|
|
874
|
+
### 🛡️ Production-First Ergonomics & Resiliency
|
|
875
|
+
- **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.
|
|
876
|
+
- **Graceful Degradation & Fallbacks:**
|
|
877
|
+
- **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.
|
|
878
|
+
- **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.
|
|
879
|
+
- **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.
|
|
880
|
+
|
|
881
|
+
---
|
|
882
|
+
|
|
865
883
|
## 📊 Performance
|
|
866
884
|
|
|
867
885
|
Measured on a single Node.js thread (no `await` on synchronous paths):
|
package/dist/index.cjs
CHANGED
|
@@ -2656,7 +2656,8 @@ var CacheService = class _CacheService {
|
|
|
2656
2656
|
_jitterTtl(ttlMs) {
|
|
2657
2657
|
const j = this.opts.ttlJitterFactor;
|
|
2658
2658
|
if (j === 0) return ttlMs;
|
|
2659
|
-
|
|
2659
|
+
const rand = import_crypto3.default.randomInt(0, 1e5) / 5e4 - 1;
|
|
2660
|
+
return Math.round(ttlMs * (1 + rand * j));
|
|
2660
2661
|
}
|
|
2661
2662
|
/** Shared no-op span for the common case where no tracer is configured.
|
|
2662
2663
|
* Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
|
|
@@ -2747,6 +2748,12 @@ var CacheService = class _CacheService {
|
|
|
2747
2748
|
_handleBackplaneMessage(message) {
|
|
2748
2749
|
try {
|
|
2749
2750
|
const msg = JSON.parse(message);
|
|
2751
|
+
if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob") {
|
|
2752
|
+
this.logger.warn("Backplane: rejected invalid pubsub message format", {
|
|
2753
|
+
raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
|
|
2754
|
+
});
|
|
2755
|
+
return;
|
|
2756
|
+
}
|
|
2750
2757
|
if (msg.src === this.instanceId) {
|
|
2751
2758
|
this.counters.invSkipped++;
|
|
2752
2759
|
return;
|
|
@@ -2766,6 +2773,7 @@ var CacheService = class _CacheService {
|
|
|
2766
2773
|
key: msg.key.slice(0, 60)
|
|
2767
2774
|
});
|
|
2768
2775
|
} catch {
|
|
2776
|
+
this.logger.warn("Backplane: malformed message JSON parse failed");
|
|
2769
2777
|
}
|
|
2770
2778
|
}
|
|
2771
2779
|
async publishInvalidation(op, key) {
|
package/dist/index.js
CHANGED
|
@@ -2274,7 +2274,8 @@ var CacheService = class _CacheService {
|
|
|
2274
2274
|
_jitterTtl(ttlMs) {
|
|
2275
2275
|
const j = this.opts.ttlJitterFactor;
|
|
2276
2276
|
if (j === 0) return ttlMs;
|
|
2277
|
-
|
|
2277
|
+
const rand = crypto2.randomInt(0, 1e5) / 5e4 - 1;
|
|
2278
|
+
return Math.round(ttlMs * (1 + rand * j));
|
|
2278
2279
|
}
|
|
2279
2280
|
/** Shared no-op span for the common case where no tracer is configured.
|
|
2280
2281
|
* Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
|
|
@@ -2365,6 +2366,12 @@ var CacheService = class _CacheService {
|
|
|
2365
2366
|
_handleBackplaneMessage(message) {
|
|
2366
2367
|
try {
|
|
2367
2368
|
const msg = JSON.parse(message);
|
|
2369
|
+
if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob") {
|
|
2370
|
+
this.logger.warn("Backplane: rejected invalid pubsub message format", {
|
|
2371
|
+
raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
|
|
2372
|
+
});
|
|
2373
|
+
return;
|
|
2374
|
+
}
|
|
2368
2375
|
if (msg.src === this.instanceId) {
|
|
2369
2376
|
this.counters.invSkipped++;
|
|
2370
2377
|
return;
|
|
@@ -2384,6 +2391,7 @@ var CacheService = class _CacheService {
|
|
|
2384
2391
|
key: msg.key.slice(0, 60)
|
|
2385
2392
|
});
|
|
2386
2393
|
} catch {
|
|
2394
|
+
this.logger.warn("Backplane: malformed message JSON parse failed");
|
|
2387
2395
|
}
|
|
2388
2396
|
}
|
|
2389
2397
|
async publishInvalidation(op, key) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tricache",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.7",
|
|
4
4
|
"description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cache",
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
"nodejs"
|
|
19
19
|
],
|
|
20
20
|
"license": "MIT",
|
|
21
|
+
"packageManager": "pnpm@11.3.0",
|
|
21
22
|
"type": "module",
|
|
22
23
|
"main": "./dist/index.js",
|
|
23
24
|
"module": "./dist/index.js",
|
|
@@ -35,6 +36,15 @@
|
|
|
35
36
|
"README.md",
|
|
36
37
|
"LICENSE"
|
|
37
38
|
],
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --clean",
|
|
41
|
+
"postbuild": "node --input-type=module -e \"import{rmSync}from'fs';['dist/index.d.cts','dist/serialize-worker.d.cts'].forEach(f=>rmSync(f,{force:true}));\"",
|
|
42
|
+
"dev": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --watch",
|
|
43
|
+
"typecheck": "tsc --noEmit",
|
|
44
|
+
"test": "vitest run",
|
|
45
|
+
"test:watch": "vitest",
|
|
46
|
+
"bench": "node --expose-gc --import tsx/esm bench/benchmark.ts"
|
|
47
|
+
},
|
|
38
48
|
"dependencies": {
|
|
39
49
|
"ioredis": "5.11.1",
|
|
40
50
|
"msgpackr": "2.0.4"
|
|
@@ -53,14 +63,5 @@
|
|
|
53
63
|
"repository": {
|
|
54
64
|
"type": "git",
|
|
55
65
|
"url": "git+https://github.com/Kareem411/TriCache.git"
|
|
56
|
-
},
|
|
57
|
-
"scripts": {
|
|
58
|
-
"build": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --clean",
|
|
59
|
-
"postbuild": "node --input-type=module -e \"import{rmSync}from'fs';['dist/index.d.cts','dist/serialize-worker.d.cts'].forEach(f=>rmSync(f,{force:true}));\"",
|
|
60
|
-
"dev": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --watch",
|
|
61
|
-
"typecheck": "tsc --noEmit",
|
|
62
|
-
"test": "vitest run",
|
|
63
|
-
"test:watch": "vitest",
|
|
64
|
-
"bench": "node --expose-gc --import tsx/esm bench/benchmark.ts"
|
|
65
66
|
}
|
|
66
|
-
}
|
|
67
|
+
}
|
package/src/cache-service.ts
CHANGED
|
@@ -775,7 +775,8 @@ export class CacheService {
|
|
|
775
775
|
private _jitterTtl(ttlMs: number): number {
|
|
776
776
|
const j = this.opts.ttlJitterFactor;
|
|
777
777
|
if (j === 0) return ttlMs;
|
|
778
|
-
|
|
778
|
+
const rand = (crypto.randomInt(0, 100_000) / 50_000) - 1; // uniform [-1.0, +1.0)
|
|
779
|
+
return Math.round(ttlMs * (1 + rand * j));
|
|
779
780
|
}
|
|
780
781
|
|
|
781
782
|
/** Shared no-op span for the common case where no tracer is configured.
|
|
@@ -877,7 +878,20 @@ export class CacheService {
|
|
|
877
878
|
/** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
|
|
878
879
|
_handleBackplaneMessage(message: string): void {
|
|
879
880
|
try {
|
|
880
|
-
const msg = JSON.parse(message)
|
|
881
|
+
const msg = JSON.parse(message);
|
|
882
|
+
if (
|
|
883
|
+
!msg ||
|
|
884
|
+
typeof msg !== 'object' ||
|
|
885
|
+
Array.isArray(msg) ||
|
|
886
|
+
typeof msg.src !== 'string' ||
|
|
887
|
+
typeof msg.key !== 'string' ||
|
|
888
|
+
(msg.op !== 'del' && msg.op !== 'del-glob')
|
|
889
|
+
) {
|
|
890
|
+
this.logger.warn('Backplane: rejected invalid pubsub message format', {
|
|
891
|
+
raw: typeof message === 'string' ? message.slice(0, 100).replace(/[\r\n\t]/g, ' ') : String(message),
|
|
892
|
+
});
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
881
895
|
if (msg.src === this.instanceId) {
|
|
882
896
|
this.counters.invSkipped++;
|
|
883
897
|
return; // own message — our L1 is already current
|
|
@@ -902,7 +916,9 @@ export class CacheService {
|
|
|
902
916
|
this.logger.debug('Backplane: peer invalidation applied', {
|
|
903
917
|
op: msg.op, key: msg.key.slice(0, 60),
|
|
904
918
|
});
|
|
905
|
-
} catch {
|
|
919
|
+
} catch {
|
|
920
|
+
this.logger.warn('Backplane: malformed message JSON parse failed');
|
|
921
|
+
}
|
|
906
922
|
}
|
|
907
923
|
|
|
908
924
|
private async publishInvalidation(op: 'del' | 'del-glob', key: string): Promise<void> {
|