tricache 1.0.1 → 2.0.0

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 (127) hide show
  1. package/README.md +89 -93
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/cache-service-BV5T8-20.d.cts +1064 -0
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  10. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  11. package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
  12. package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
  13. package/dist/chunk-RBJRTGFK.js +94 -0
  14. package/dist/chunk-S5N65I45.js +17 -0
  15. package/dist/cli.cjs +3694 -1070
  16. package/dist/cli.d.cts +12 -0
  17. package/dist/cli.js +210 -14
  18. package/dist/dashboard/index.cjs +111 -29
  19. package/dist/dashboard/index.d.cts +185 -0
  20. package/dist/dashboard/index.d.ts +5 -3
  21. package/dist/dashboard/index.js +1 -1
  22. package/dist/drizzle/index.cjs +3578 -1068
  23. package/dist/drizzle/index.d.cts +46 -0
  24. package/dist/drizzle/index.d.ts +2 -2
  25. package/dist/drizzle/index.js +6 -2
  26. package/dist/edge/index.cjs +368 -162
  27. package/dist/edge/index.d.cts +134 -0
  28. package/dist/edge/index.d.ts +11 -4
  29. package/dist/edge/index.js +314 -155
  30. package/dist/hono/index.cjs +3614 -1087
  31. package/dist/hono/index.d.cts +93 -0
  32. package/dist/hono/index.d.ts +7 -5
  33. package/dist/hono/index.js +16 -9
  34. package/dist/hono-CMv2VdQ6.d.cts +404 -0
  35. package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
  36. package/dist/http/index.cjs +3712 -1124
  37. package/dist/http/index.d.cts +103 -0
  38. package/dist/http/index.d.ts +13 -5
  39. package/dist/http/index.js +92 -43
  40. package/dist/index.cjs +4067 -1252
  41. package/dist/index.d.cts +1071 -0
  42. package/dist/index.d.ts +123 -27
  43. package/dist/index.js +878 -21
  44. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
  45. package/dist/murmur3-DF8BFRnu.d.ts +99 -0
  46. package/dist/nestjs/index.cjs +3635 -1112
  47. package/dist/nestjs/index.d.cts +299 -0
  48. package/dist/nestjs/index.d.ts +120 -33
  49. package/dist/nestjs/index.js +132 -43
  50. package/dist/next/index.cjs +3704 -1175
  51. package/dist/next/index.d.cts +238 -0
  52. package/dist/next/index.d.ts +39 -11
  53. package/dist/next/index.js +202 -102
  54. package/dist/prisma/index.cjs +29 -18
  55. package/dist/prisma/index.d.cts +62 -0
  56. package/dist/prisma/index.d.ts +2 -2
  57. package/dist/prisma/index.js +17 -18
  58. package/dist/serialize-worker.cjs +162 -39
  59. package/dist/serialize-worker.d.cts +2 -0
  60. package/dist/serialize-worker.js +9 -7
  61. package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
  62. package/dist/types-F8vRWMrE.d.ts +1636 -0
  63. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  64. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  65. package/package.json +116 -37
  66. package/src/adapters/auto-pipeliner.ts +150 -26
  67. package/src/adapters/node-redis.ts +106 -27
  68. package/src/cache-service.ts +2215 -793
  69. package/src/cli.ts +25 -14
  70. package/src/codec.ts +3 -3
  71. package/src/compression.ts +39 -16
  72. package/src/cross-region.ts +22 -4
  73. package/src/dashboard/handler.ts +26 -6
  74. package/src/dashboard/html.ts +35 -10
  75. package/src/dashboard/index.ts +35 -13
  76. package/src/dashboard/types.ts +3 -1
  77. package/src/disk-tier.ts +448 -102
  78. package/src/drizzle/index.ts +2 -1
  79. package/src/edge/adapters/cloudflare-do.ts +25 -10
  80. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  81. package/src/edge/adapters/upstash.ts +27 -11
  82. package/src/edge/cache.ts +200 -110
  83. package/src/edge/hono.ts +23 -6
  84. package/src/edge/types.ts +17 -5
  85. package/src/encryption.ts +50 -18
  86. package/src/env.d.ts +1 -1
  87. package/src/errors.ts +12 -0
  88. package/src/hono/index.ts +19 -9
  89. package/src/http/express.ts +62 -17
  90. package/src/http/fastify.ts +35 -21
  91. package/src/http/utils.ts +60 -20
  92. package/src/index.ts +6 -0
  93. package/src/ipc-telemetry.ts +35 -9
  94. package/src/latency-watchdog.ts +5 -1
  95. package/src/nestjs/decorators.ts +11 -6
  96. package/src/nestjs/index.ts +2 -0
  97. package/src/nestjs/keyv-adapter.ts +68 -0
  98. package/src/nestjs/tricache.module.ts +15 -12
  99. package/src/nestjs/tricache.store.ts +69 -26
  100. package/src/nestjs/types.ts +30 -16
  101. package/src/next/cache-handler.ts +151 -53
  102. package/src/next/index.ts +1 -0
  103. package/src/next/types.ts +25 -0
  104. package/src/origin-capacity.ts +134 -0
  105. package/src/prisma/index.ts +17 -24
  106. package/src/remote-snapshot.ts +37 -27
  107. package/src/serialize-worker.ts +8 -5
  108. package/src/sigv4-snapshot-adapter.ts +37 -27
  109. package/src/smart-memory-cache.ts +121 -44
  110. package/src/types.ts +117 -37
  111. package/src/utils/cgroup.ts +12 -0
  112. package/src/utils/config-comparison.ts +29 -0
  113. package/src/utils/deadline.ts +14 -0
  114. package/src/utils/diagnostics.ts +27 -0
  115. package/src/utils/lz4-size.ts +74 -0
  116. package/src/utils/namespace-key.ts +48 -0
  117. package/src/utils/query-key.ts +13 -0
  118. package/src/utils/redis-slot.ts +13 -0
  119. package/src/utils/snapshot-transfer.ts +83 -0
  120. package/src/utils/work-limits.ts +73 -0
  121. package/src/utils/write-revision.ts +4 -0
  122. package/src/wasm/bloom-filter-wasm.ts +25 -5
  123. package/src/worker-pool.ts +44 -15
  124. package/src/wtiny-lfu.ts +82 -20
  125. package/dist/cache-service-MG7PN6MX.js +0 -12
  126. package/dist/chunk-3I5L7K6I.js +0 -704
  127. package/dist/chunk-BQRURGGD.js +0 -60
package/README.md CHANGED
@@ -4,144 +4,140 @@
4
4
  [![Docs](https://img.shields.io/badge/docs-VitePress-blue.svg)](https://kareem411.github.io/TriCache/)
5
5
  [![npm version](https://img.shields.io/npm/v/tricache.svg)](https://www.npmjs.com/package/tricache)
6
6
  [![npm downloads](https://img.shields.io/npm/dm/tricache.svg)](https://www.npmjs.com/package/tricache)
7
- [![Tests](https://img.shields.io/badge/tests-926%20passing-brightgreen)](tests)
8
- [![Code Quality](https://img.shields.io/badge/oxlint-0%20warnings-brightgreen)](src)
7
+ [![Tests](https://img.shields.io/badge/tests-1524%20passing-brightgreen)](https://github.com/Kareem411/TriCache/tree/main/tests)
8
+ [![Code Quality](https://img.shields.io/badge/oxlint-0%20warnings-brightgreen)](https://github.com/Kareem411/TriCache/tree/main/src)
9
9
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
10
10
  [![Node.js ≥ 20](https://img.shields.io/badge/node-%3E%3D20-brightgreen)](https://nodejs.org)
11
11
 
12
- > 🌐 **Documentation Site**: **[https://kareem411.github.io/TriCache/](https://kareem411.github.io/TriCache/)**
13
- > 📦 **npm Package**: **[`npm install tricache`](https://www.npmjs.com/package/tricache)**
12
+ **Node.js caching with bounded local memory and Redis/Valkey sharing.** TriCache adds tags, stale-while-revalidate, per-process request coalescing, observability, and framework adapters. Local disk spill is optional—start with RAM + Redis and measure before adding another tier.
14
13
 
15
- **TriCache** is an enterprise three-tier caching engine for Node.js: **L1 RAM** $\rightarrow$ **L1.5 Off-Heap `/dev/shm`** $\rightarrow$ **L2 Redis/Valkey**. Warm in-memory reads run at **2.81 million ops/sec (356 ns/op)**. By absorbing 95%+ of queries locally in zero-GC POSIX shared memory with Singleflight stampede coalescing, TriCache slashes cloud Redis bills and latency without risking stale data.
14
+ **Quick links:** [Docs](https://kareem411.github.io/TriCache/) · [API reference](https://kareem411.github.io/TriCache/api-reference) · [When to choose](https://kareem411.github.io/TriCache/when-to-choose) · [Benchmarks](https://kareem411.github.io/TriCache/benchmarks)
16
15
 
17
16
  ---
18
17
 
19
- ## ⚡ 30-Second Quickstart
18
+ ## Quick start
20
19
 
21
20
  ```bash
22
- npm install tricache # or pnpm add tricache
21
+ npm install tricache
23
22
  ```
24
23
 
24
+ This example uses Redis and explicitly disables disk spill. Set `REDIS_HOST` to your Redis/Valkey endpoint before running it.
25
+
25
26
  ```typescript
26
27
  import { CacheService } from 'tricache';
27
28
 
28
- // 1. One-line preset: W-TinyLFU, Redis Streams, /dev/shm off-heap spill, & SWR
29
- const cache = CacheService.preset('nextjs', { redisHost: process.env.REDIS_HOST });
29
+ const cache = CacheService.create({
30
+ namespace: 'catalog',
31
+ redisHost: process.env.REDIS_HOST ?? '127.0.0.1',
32
+ disableDisk: true,
33
+ });
34
+ await cache.ready();
30
35
 
31
- // 2. Get-or-fetch with thundering-herd coalescing & 60s background SWR
32
- const user = await cache.get(
33
- `user:${userId}`,
34
- () => db.users.findById(userId),
35
- 300, // 5-minute TTL
36
- { swr: 60 } // Serve stale for 60s while refreshing in the background
37
- );
36
+ // TTLs are seconds. Same-key concurrent misses coalesce within this process.
37
+ const product = await cache.get('product:42', () => loadProduct(42), 300, {
38
+ swr: 30,
39
+ tags: ['catalog'],
40
+ });
38
41
 
39
- // 3. Invalidate group entries in O(1) time across your entire cluster
40
- await cache.invalidateTag('users');
42
+ await cache.invalidateTag('catalog');
41
43
  ```
42
44
 
45
+ **2.0.0 is an unpublished breaking-change candidate.** It uses a versioned, typed keyspace; earlier entries, snapshots, and counters are not read or migrated. Coordinate all writers during migration or isolate the new deployment, and use separate namespaces for Node and Edge. See the [upgrade guide](docs/upgrade-to-2.0.0.md).
46
+
43
47
  ---
44
48
 
45
- ## 🔬 Under the Hood (Architectural Core)
49
+ ## What you get
46
50
 
47
- ```
48
- [Incoming Read Request]
49
- │
50
- ▼
51
- ┌──────────────────────────────────────────────────┐
52
- │ L1: Smart Memory (W-TinyLFU + CMS) │ ~350 ns (2.81M ops/s)
53
- │ Window LRU (1%) + Segmented Main SLRU (99%) │ Zero V8 allocation
54
- └────────────────────────┬─────────────────────────┘
55
- │ Miss / Eviction Spill
56
- ▼
57
- ┌──────────────────────────────────────────────────┐
58
- │ L1.5: Off-Heap /dev/shm & NVMe Spill Tier │ ~20 µs (RAM speed)
59
- │ POSIX tmpfs bypasses V8 GC & cloud EBS IOPS │ readOnlyRootFilesystem
60
- └────────────────────────┬─────────────────────────┘
61
- │ Miss
62
- ▼
63
- ┌──────────────────────────────────────────────────┐
64
- │ L2: Redis / Valkey Distributed Tier │ ~1.2 ms (Network)
65
- │ AES-256-GCM AEAD at-rest + msgpackr records │ Pipelined MGET/MSET
66
- └────────────────────────┬─────────────────────────┘
67
- │ Complete Cache Miss
68
- ▼
69
- ┌──────────────────────────────────────────────────┐
70
- │ Upstream Database / API (Singleflight Lock) │ Exactly 1 execution
71
- │ Inflight Promise Map coalesces 10,000 callers │ Zero stampedes
72
- └──────────────────────────────────────────────────┘
73
- ```
51
+ | Capability | Summary |
52
+ | --- | --- |
53
+ | **Bounded L1 cache** | Process-local memory with adaptive or W-TinyLFU admission and configurable limits. |
54
+ | **Redis / Valkey L2** | Shared values, remaining-TTL promotion where supported, and Pub/Sub or Redis Streams invalidation. |
55
+ | **Freshness & invalidation** | TTL, stale-while-revalidate, tags, dependency invalidation, and mutation fences. |
56
+ | **Origin protection** | Per-process same-key singleflight and configurable work limits. This is not fleet-wide coalescing. |
57
+ | **Optional local spill** | Disk/tmpfs tier for workloads that benefit from it; ephemeral cache only, not durable storage. |
58
+ | **Integrations** | Next.js, NestJS, Prisma, Drizzle, Express, Fastify, Hono, and a separate Edge package entry. |
74
59
 
75
- * **Window TinyLFU (W-TinyLFU)**: ~1% Window LRU absorbs recency bursts; 4-row Count-Min Sketch rejects table scans. [[Internals $\rightarrow$](https://kareem411.github.io/TriCache/architecture-internals)]
76
- * **WebAssembly Zstandard Compression**: Out-of-the-box `zstd` WASM engine compresses payloads $>1$ KB by ~95% with automatic Brotli fallback and optional LZ4.
77
- * **Off-Heap `/dev/shm` RAM Spill**: Targets Linux POSIX shared memory tmpfs ($\ge 256\text{MB}$ total, $\ge 128\text{MB}$ free), burning 0 cloud IOPS. [[SRE Guide $\rightarrow$](https://kareem411.github.io/TriCache/kubernetes-production-guide)]
78
- * **Dynamic Latency Watchdog**: Graduated shedding (0% $\rightarrow$ 25% $\rightarrow$ 75% $\rightarrow$ 100%) with asymmetric Redis hysteresis (15ms cutoff, 10ms recovery floor).
79
- * **Ephemeral Quotas & K8s Eviction Defense**: Chunked watermark pruning (80% $\rightarrow$ 60% in 500-entry batches) and proactive $<10\%$ space spill pauses.
80
- * **Wildcard & Hierarchical Tag Invalidation**: Glob matching (`user:*`) and parent-child tree cascading (`{ cascade: true }`) over $O(1)$ generational version counters.
81
- * **Differential Multi-Tier Waterfall Batching**: Cascading `cache.mget` resolves L1 $\rightarrow$ L2 $\rightarrow$ Disk $\rightarrow$ DB miss fetch with zero $N+1$ queries.
82
- * **Zero-Dependency Cloud Hydration (SigV4)**: Hydrates cold pods from S3/R2 in milliseconds via native Web Crypto. [[Cloud Guide $\rightarrow$](https://kareem411.github.io/TriCache/cold-start-cloud-hydration)]
60
+ For a local-only cache, set both `disableRedis: true` and `disableDisk: true`. To evaluate spill, set `disableDisk: false`, select a writable `diskCacheDir`, and set a suitable `diskMaxBytes` budget.
83
61
 
84
62
  ---
85
63
 
86
- ## 🏆 Feature Comparison
64
+ ## How it works
87
65
 
88
- | Dimension | `lru-cache` | `keyv` / `cache-manager` | `@neshca/cache-handler` | **TriCache** |
89
- |:---|:---|:---|:---|:---|
90
- | **Storage Hierarchy** | In-Memory only | Single Remote (Redis) | Memory + Redis | **Three-Tier (RAM $\rightarrow$ `/dev/shm` $\rightarrow$ Redis)** |
91
- | **Warm Hit Latency** | ~300 ns | 1,200,000 ns (1.2 ms) | ~400 ns | **356 ns (2.81M ops/sec)** |
92
- | **Thundering-Herd Defense**| ❌ No | ❌ External plugin | ❌ No | **✅ Native Singleflight Coalescing** |
93
- | **Tag Invalidation** | ❌ None | $O(N)$ blocking scan | $O(N)$ Redis Set | **✅ $O(1)$ Generational + Wildcards & Cascades** |
94
- | **Cluster Sync Backplane**| ❌ None | At-most-once Pub/Sub | Pub/Sub | **✅ Durable Redis Streams (`XADD`/`XREAD`)** |
95
- | **Compression** | ❌ None | ❌ Manual | ❌ None | **✅ WebAssembly Zstandard (Default) & LZ4** |
96
- | **Waterfall Batching (`mget`)**| ❌ None | ❌ Manual loops | ❌ None | **✅ Multi-Tier Cascading ($0$ $N+1$ Queries)** |
97
- | **Container Memory Safety**| Unbounded GC | N/A (Remote only) | Heap-bound | **✅ Off-heap tmpfs + 80% OOM Guard** |
98
- | **Encryption at Rest** | ❌ None | ❌ None | ❌ None | **✅ AES-256-GCM / Web Crypto AEAD** |
66
+ `Request → bounded L1 RAM → [optional local spill] → Redis/Valkey → origin callback`
99
67
 
100
- ---
68
+ Raw `CacheService.create()` uses the adaptive admission policy; built-in presets select W-TinyLFU. Single-key and batch reads have different tier orders, documented in the [API guide](https://kareem411.github.io/TriCache/api-reference). Compression is configurable, and payload-dependent CPU/size tradeoffs should be measured.
101
69
 
102
- ## 🎯 Production Presets (`CacheService.preset`)
70
+ ### Operational limits
103
71
 
104
- ```typescript
105
- // 1. Next.js 16 / 15 App Router (Optimized for React 19 RSC streams & generational tags)
106
- const cache = CacheService.preset('nextjs', { redisHost: 'redis.internal' });
72
+ For on-call setup, the [Redis incident runbook](docs/observability.md#prometheus-alert-rules-dashboards-tricache-alerts-yaml) explains the per-instance breaker panel, alert timing, and how to verify a shared read after recovery.
107
73
 
108
- // 2. High-Throughput Microservice (Streams backplane, TTL jitter, circuit breakers)
109
- const cache = CacheService.preset('microservice', { redisHost: 'redis.internal' });
74
+ The [cold rollback rehearsal](docs/cloud-degradation-contract.md#two-process-cold-rollback-rehearsal) reproduced a stale peer read during Redis loss with Streams enabled. For freshness-critical reads, budget origin capacity for a bypass or define when the application must reject the read.
110
75
 
111
- // 3. Serverless (AWS Lambda / Cloud Run: memory-only, fast 1s timeouts, pubsub)
112
- const cache = CacheService.preset('serverless', { redisHost: 'redis.internal' });
76
+ Opt in with `rejectCachedReadsOnInvalidationLoss: true` to reject reads with `CacheInvalidationUnavailableError` while the invalidation consumer is unavailable or misses its `backplaneMaxStalenessMs` challenge deadline. The shared gate covers every cache tier, batch reads, SWR, and racing fills. Strict startup begins cold and skips snapshot hydration. See the [behavior table and recovery contract](docs/invalidation-read-protection.md); compatibility behavior remains the default.
113
77
 
114
- // 4. Enterprise Hardened (Generational tags, strict singletons, fail-closed rate limits, 80% OOM guard)
115
- const cache = CacheService.preset('enterprise-hardened', { redisHost: 'redis.internal' });
116
- ```
78
+ - **Spill is not durable storage.** It may be unavailable or shed under filesystem, quota, process, or container failure. `/dev/shm` consumes container memory. A Redis outage after a cache miss can still invoke the origin.
79
+ - **Singleflight is process-local**, not a fleet-wide origin lock. Redis Streams replay is bounded by retention; awaiting publication is not peer acknowledgment.
80
+ - **Encryption migration is explicit.** CacheService rejects malformed supplied keys by default and, when AES-GCM is enabled, rejects plaintext/legacy context-free reads unless `allowLegacyPlaintextRead` is opted into for migration.
81
+ - **Spill is not a default performance recommendation.** The historical multi-replica screen found expanded RAM matched or beat spill's outage-origin peaks with lower healthy-period CPU in the tested workloads. [Read the report](https://github.com/Kareem411/TriCache/blob/main/bench/results-examples/2026-11-18-multi-replica-outage.md).
82
+
83
+ ### Should we use it in production?
84
+
85
+ **7/10 for a Node.js service that needs bounded RAM + Redis, tag invalidation, and framework integration.** The December 5 frozen `2.0.0` candidate passed complete Windows, isolated Linux and container validation, including 1,517 unit tests and 82 required live Redis tests on each platform, package/worker consumers, recovery and rollout checks. These results belong to the [recorded frozen source fingerprint](docs/candidate-validation.md#200-complete-frozen-validation-—-december-5-2026); subsequent reporting edits are outside it. Hosted CI on the final revision and service-specific staging/rollback remain release and rollout checks. The comparison found a simpler LRU + Redis composition competitive; independent production pilots are still pending. See the [scorecard](docs/when-to-choose.md) and [comparison results](docs/m5-validation.md).
86
+
87
+ Start with the [two-tier production configuration](docs/production-start.md). Before rollout, compare it with your current cache under peak traffic and through a Redis restart. Check what users see (p99 latency and freshness) **and** what the origin absorbs when the cache is cold. The [production priorities](docs/improvement-roadmap.md#production-priorities) give concrete rollout and rollback criteria.
117
88
 
118
89
  ---
119
90
 
120
- ## 🗄️ Turnkey Ecosystem Integrations
91
+ ## Presets
92
+
93
+ | Preset | Starting point |
94
+ | --- | --- |
95
+ | `nextjs` | Next.js Cache Components, generational tags, and framework-specific defaults. |
96
+ | `microservice` | Redis Streams, TTL jitter, and circuit-breaker settings. |
97
+ | `serverless` | Disk disabled and short Redis command timeouts. |
98
+ | `enterprise-hardened` | Strict singleton and fail-closed lock settings. Not a compliance certification. |
99
+
100
+ Presets are configuration starting points; review their behavior and override options for your deployment.
101
+
102
+ ---
103
+
104
+ ## Integrations
121
105
 
122
106
  | Integration | Import Path | Description |
123
107
  |:---|:---|:---|
124
- | **Next.js 16 & 15** | `tricache/next` | Drop-in `cacheHandler` with RSC stream re-hydration and dynamic `softTags`. |
125
- | **NestJS Module** | `tricache/nestjs` | Official `TriCacheModule.register()`, `@nestjs/cache-manager` store adapter, and `@Cacheable`. |
108
+ | **Next.js 16** | `tricache/next` | Native Cache Components `cacheHandlers` with bounded RSC streams, timing preservation, and soft-tag expiry. |
109
+ | **NestJS 10–12** | `tricache/nestjs` | `TriCacheModule`, millisecond TTL facade, Keyv 5/cache-manager 7 adapter, and `@Cacheable`. |
126
110
  | **Prisma ORM** | `tricache/prisma` | `$extends` client extension with query hashing and auto-mutation tag eviction. |
127
111
  | **Drizzle ORM** | `tricache/drizzle` | `withCache(query, opts)` query wrapper with SQL+parameters hashing and background SWR. |
128
112
  | **Express & Fastify** | `tricache/http` | Route caching middleware with deterministic query sorting, weak ETag, and `304 Not Modified`. |
129
- | **Node Hono** | `tricache/hono` | First-class `cacheMiddleware` on `CacheService` with ttl/tags/SWR and `304 Not Modified`. |
130
- | **Edge Isolates & Hono** | `tricache/edge` | Zero-Node-dependency implementation for Cloudflare Workers, Fastly Compute, Hono, and Vercel Edge. |
131
- | **SSE Dashboard** | `tricache/dashboard` | Zero-dependency Server-Sent Events real-time admin dashboard. |
113
+ | **Node Hono** | `tricache/hono` | Response caching with TTL/tags, privacy guards, and `304 Not Modified`. |
114
+ | **Edge Isolates & Hono** | `tricache/edge` | Web Standards implementation without Node built-in dependencies for Cloudflare Workers, Fastly Compute, Hono, and Vercel Edge. |
115
+ | **SSE Dashboard** | `tricache/dashboard` | Self-contained Server-Sent Events admin dashboard. |
132
116
  | **Live CLI Top** | `npx tricache top` | Real-time terminal ASCII monitor over Unix sockets and Windows named pipes. |
133
117
 
134
- ---
118
+ ### Safety and consistency
135
119
 
136
- ## 📚 Documentation & Deep Dives
120
+ - HTTP middleware bypasses credentialed requests by default and excludes private, cookie-setting, partial, and unkeyed `Vary` responses. Response refreshes run on live requests; use `cache.get()`/`wrap()` for data-level SWR.
121
+ - Default HTTP response keys include validated `Host`/`:authority`; forwarded host headers are not trusted implicitly. Add tenant, locale, and other representation-changing inputs to your key policy.
122
+ - Dashboard access should be authenticated and private. It defaults to `readOnly: true`; administrative writes require explicit opt-in.
123
+ - Redis Streams provide replay only while events are retained. A detected gap flushes local state. `awaitInvalidationBackplane: true` confirms publication, not peer acknowledgments or exactly-once delivery.
124
+ - Redis timed reads pair the value/hash and PTTL atomically when scripts or transactions are supported. Custom drivers without either capability use a reduced fallback; edge legacy JSON without expiry metadata is read without local promotion.
125
+ - `/dev/shm` reduces disk I/O but still consumes container memory. Encryption and cache configuration do not by themselves establish regulatory compliance.
126
+
127
+ ---
137
128
 
138
- * 📖 **[Documentation Portal](https://kareem411.github.io/TriCache/)** — Official VitePress guides, architecture, and API reference
139
- * 🔬 **[Architecture & Mathematical Internals](docs/architecture-internals.md)** — W-TinyLFU, CMS, Bloom filters, SigV4 signer
140
- * ☸️ **[Kubernetes SRE & Production Guide](docs/kubernetes-production-guide.md)** — `/dev/shm`, cgroups, eviction defense, readiness probes
141
- * ☁️ **[Cold-Start Cloud Snapshot Hydration](docs/cold-start-cloud-hydration.md)** — S3, Cloudflare R2, readiness gates
142
- * 📈 **[Prometheus /metrics Scraping Recipe](docs/metrics-recipe.md)** — Express / Fastify / Next.js endpoints, scrape config, and one-command local Grafana stack
143
- * 💰 **[Cloud ROI Financial Simulation](bench/cloud-roi-simulation.ts)** — Deterministic Mulberry32 Zipfian benchmark (`pnpm bench:roi`)
144
- * 📊 **[Full Benchmark Suite](BENCHMARKS.md)** — Throughput, serialization, concurrency analysis
129
+ ## Documentation and benchmarks
130
+
131
+ - [Documentation portal](https://kareem411.github.io/TriCache/)
132
+ - [When to choose TriCache](https://kareem411.github.io/TriCache/when-to-choose) — fit, competitor assessment, and tradeoffs
133
+ - [API reference](https://kareem411.github.io/TriCache/api-reference) · [Security](https://kareem411.github.io/TriCache/security) · [Kubernetes guide](https://kareem411.github.io/TriCache/kubernetes-production-guide)
134
+ - [Production starting point](https://kareem411.github.io/TriCache/production-start) · [Provider conformance](https://kareem411.github.io/TriCache/provider-conformance) · [Independent pilot runbook](https://kareem411.github.io/TriCache/pilot-runbook)
135
+ - [Three-container HTTP service reference](examples/production-service/README.md) — shared origin capacity, strict invalidation reads, separate credentials, telemetry and local Redis-loss checks
136
+ - [Benchmark methodology](https://kareem411.github.io/TriCache/benchmarks) · [Linux comparison harness](https://github.com/Kareem411/TriCache/tree/main/bench/compare)
137
+ - [Current candidate validation](docs/candidate-validation.md#200-complete-frozen-validation-—-december-5-2026) — complete frozen `2.0.0` checks, exact provenance and retained failures
138
+ - [Historical candidate measurements](https://github.com/Kareem411/TriCache/blob/main/bench/results-examples/2026-11-29-candidate-improvements.md) — separate fingerprints and no superiority claim
139
+ - [Historical multi-replica outage results](https://github.com/Kareem411/TriCache/blob/main/bench/results-examples/2026-11-18-multi-replica-outage.md) — scoped findings, not current performance guarantees
140
+ - [Changelog](https://github.com/Kareem411/TriCache/blob/main/CHANGELOG.md)
145
141
 
146
142
  ---
147
143
 
@@ -18,15 +18,23 @@ spec:
18
18
  summary: "TriCache emergency OOM evictions detected on instance {{ $labels.instance }}"
19
19
  description: "Node.js heap memory has breached the safe watermark, triggering emergency L1 cache evictions. Consider increasing container memory or lowering l1MaxBytes."
20
20
 
21
- # Alert 2: L2 Redis Circuit Breaker Tripped / Invalidation Errors
21
+ # Include half-open probes so a failed probe does not reset the pending timer.
22
22
  - alert: TriCacheCircuitBreakerOpen
23
- expr: rate(tricache_cross_region_errors_total[2m]) > 5 or rate(tricache_backplane_sent_total[1m]) == 0 and rate(tricache_sets_total[1m]) > 10
23
+ expr: tricache_l2_circuit_state > 0
24
24
  for: 2m
25
25
  labels:
26
26
  severity: critical
27
27
  annotations:
28
- summary: "TriCache L2/Backplane degradation or circuit breaker open on {{ $labels.instance }}"
29
- description: "Cache operations are falling back to L1/disk due to persistent L2 network errors or cross-region relay failures."
28
+ summary: "Redis circuit has not closed on {{ $labels.instance }}"
29
+ description: "The local breaker has stayed open or half-open for two minutes. Check request p99, origin load and Redis connectivity before shifting traffic."
30
+
31
+ - alert: TriCacheCrossRegionRelayErrors
32
+ expr: rate(tricache_cross_region_errors_total[2m]) > 5
33
+ for: 2m
34
+ labels:
35
+ severity: warning
36
+ annotations:
37
+ summary: "Elevated cross-region relay errors on {{ $labels.instance }}"
30
38
 
31
39
  # Alert 3: Cache Hit Ratio Degraded
32
40
  - alert: TriCacheHitRatioDegraded
@@ -52,3 +60,71 @@ spec:
52
60
  annotations:
53
61
  summary: "High volume of coalesced cache stampedes on {{ $labels.instance }}"
54
62
  description: "Singleflight guard is coalescing over 100 in-flight requests/second. Indicates a thundering herd on popular expiring keys."
63
+
64
+ # Inventory must be produced independently of the monitored applications.
65
+ # `up == 0` alone cannot detect a target removed from service discovery.
66
+ - alert: TriCacheMonitoringInventoryMissing
67
+ expr: absent(tricache_target_expected{job="tricache"})
68
+ for: 1m
69
+ labels:
70
+ severity: critical
71
+ annotations:
72
+ summary: "TriCache deployment monitoring inventory is absent"
73
+ description: "Expected-target inventory is missing. Restore the independent deployment inventory before relying on missing-target or missing-series alerts."
74
+
75
+ - alert: TriCacheScrapeUnavailable
76
+ expr: (tricache_target_expected == 1) unless on (job, instance) (up == 1)
77
+ for: 1m
78
+ labels:
79
+ severity: critical
80
+ annotations:
81
+ summary: "Expected TriCache scrape unavailable on {{ $labels.instance }}"
82
+ description: "The deployment inventory expects this target, but no successful scrape exists. Check discovery, process health, authentication and network access before interpreting cache panels."
83
+
84
+ - alert: TriCacheServiceTelemetryMissing
85
+ expr: |
86
+ ((tricache_target_expected == 1) and on (job, instance) (up == 1))
87
+ unless on (job, instance)
88
+ (tricache_app_container_memory_bytes
89
+ and on (job, instance) tricache_origin_active
90
+ and on (job, instance) tricache_origin_capacity
91
+ and on (job, instance) tricache_origin_rejections_total)
92
+ for: 1m
93
+ labels:
94
+ severity: warning
95
+ annotations:
96
+ summary: "Required service telemetry missing on {{ $labels.instance }}"
97
+ description: "Scraping works, but total container memory or shared physical origin-budget series are absent. Missing data is not healthy zero; verify the service exporter and container instrumentation."
98
+
99
+ - alert: TriCacheNamespaceTelemetryMissing
100
+ expr: |
101
+ ((tricache_cache_expected == 1) and on (job, instance) (up == 1))
102
+ unless on (job, instance, namespace)
103
+ (tricache_gets_total
104
+ and on (job, instance, namespace) tricache_backplane_read_protection_active
105
+ and on (job, instance, namespace) tricache_app_request_duration_seconds_count
106
+ and on (job, instance, namespace) tricache_app_origin_calls_total)
107
+ for: 1m
108
+ labels:
109
+ severity: warning
110
+ annotations:
111
+ summary: "Required namespace telemetry missing on {{ $labels.instance }} ({{ $labels.namespace }})"
112
+ description: "The deployment inventory expects this cache namespace, but cache, invalidation, request-duration or physical origin-attempt series are absent. Check exporter wiring and namespace labels."
113
+
114
+ - alert: TriCacheInvalidationReadProtectionActive
115
+ expr: tricache_backplane_read_protection_active > 0
116
+ for: 30s
117
+ labels:
118
+ severity: warning
119
+ annotations:
120
+ summary: "Cached reads blocked on {{ $labels.instance }} ({{ $labels.namespace }})"
121
+ description: "The invalidation consumer has not proved healthy progress. Verify bounded authoritative fallback, origin headroom and consumer recovery before restoring the cache route."
122
+
123
+ - alert: TriCacheOriginCapacityRejected
124
+ expr: rate(tricache_origin_rejections_total[1m]) > 0
125
+ for: 30s
126
+ labels:
127
+ severity: warning
128
+ annotations:
129
+ summary: "Physical origin capacity exhausted on {{ $labels.instance }}"
130
+ description: "The shared fill/bypass budget is rejecting work. Reduce offered load and inspect origin latency; bypassing the cache cannot increase this physical budget."
@@ -481,6 +481,59 @@
481
481
  ],
482
482
  "title": "Invalidation Backplane & Cross-Region Mesh",
483
483
  "type": "timeseries"
484
+ },
485
+ {
486
+ "id": 12,
487
+ "type": "timeseries",
488
+ "title": "Redis circuit and invalidation read protection by instance",
489
+ "description": "0: closed, 1: half-open probe, 2: open. A closed circuit alone does not prove connectivity.",
490
+ "gridPos": { "h": 6, "w": 24, "x": 0, "y": 21 },
491
+ "datasource": "${datasource}",
492
+ "fieldConfig": { "defaults": { "min": 0, "max": 2, "custom": { "lineInterpolation": "stepAfter" } }, "overrides": [] },
493
+ "targets": [
494
+ { "refId": "A", "expr": "tricache_l2_circuit_state{namespace=~\"$namespace\", instance=~\"$pod\"}", "legendFormat": "circuit {{namespace}} {{instance}}" },
495
+ { "refId": "B", "expr": "tricache_backplane_read_protection_active{namespace=~\"$namespace\", instance=~\"$pod\"}", "legendFormat": "reads blocked {{namespace}} {{instance}}" }
496
+ ]
497
+ },
498
+ {
499
+ "id": 13, "type": "timeseries", "title": "Application request p99 (seconds)",
500
+ "description": "Application-supplied request histogram. No data until the integration records it; include errors and cold reads.",
501
+ "gridPos": { "h": 7, "w": 8, "x": 0, "y": 27 }, "datasource": "${datasource}",
502
+ "fieldConfig": { "defaults": { "unit": "s" }, "overrides": [] },
503
+ "targets": [{ "refId": "A", "expr": "histogram_quantile(0.99, sum by (le, namespace, instance) (rate(tricache_app_request_duration_seconds_bucket{namespace=~\"$namespace\", instance=~\"$pod\"}[$__rate_interval])))", "legendFormat": "{{namespace}} {{instance}}" }]
504
+ },
505
+ {
506
+ "id": 14, "type": "timeseries", "title": "Origin calls per second",
507
+ "description": "Application-supplied counter of calls reaching the origin, including retries, refreshes, and bypass traffic.",
508
+ "gridPos": { "h": 7, "w": 8, "x": 8, "y": 27 }, "datasource": "${datasource}",
509
+ "targets": [{ "refId": "A", "expr": "sum by (namespace, instance) (rate(tricache_app_origin_calls_total{namespace=~\"$namespace\", instance=~\"$pod\"}[$__rate_interval]))", "legendFormat": "{{namespace}} {{instance}}" }]
510
+ },
511
+ {
512
+ "id": 15, "type": "timeseries", "title": "Container memory usage (bytes)",
513
+ "description": "One total cgroup sample per application container, including tmpfs. Shared across cache namespaces; never sum namespace copies. Missing instrumentation remains no data.",
514
+ "gridPos": { "h": 7, "w": 8, "x": 16, "y": 27 }, "datasource": "${datasource}",
515
+ "fieldConfig": { "defaults": { "unit": "bytes" }, "overrides": [] },
516
+ "targets": [{ "refId": "A", "expr": "max by (instance) (tricache_app_container_memory_bytes{instance=~\"$pod\"})", "legendFormat": "{{instance}}" }]
517
+ },
518
+ {
519
+ "id": 16, "type": "timeseries", "title": "Shared physical origin slots",
520
+ "description": "Process-wide fill and bypass reservations. Ignored cancellation holds a slot until physical work settles.",
521
+ "gridPos": { "h": 7, "w": 8, "x": 0, "y": 34 }, "datasource": "${datasource}",
522
+ "targets": [
523
+ { "refId": "A", "expr": "tricache_origin_active{instance=~\"$pod\"}", "legendFormat": "active {{instance}}" },
524
+ { "refId": "B", "expr": "tricache_origin_capacity{instance=~\"$pod\"}", "legendFormat": "capacity {{instance}}" }
525
+ ]
526
+ },
527
+ {
528
+ "id": 17, "type": "timeseries", "title": "Origin capacity rejections per second",
529
+ "gridPos": { "h": 7, "w": 8, "x": 8, "y": 34 }, "datasource": "${datasource}",
530
+ "targets": [{ "refId": "A", "expr": "rate(tricache_origin_rejections_total{instance=~\"$pod\"}[$__rate_interval])", "legendFormat": "{{instance}}" }]
531
+ },
532
+ {
533
+ "id": 18, "type": "timeseries", "title": "Expected targets without a successful scrape",
534
+ "description": "Independent deployment inventory detects failed scrapes and targets removed from discovery. Requires tricache_target_expected; absent inventory is unqualified monitoring.",
535
+ "gridPos": { "h": 7, "w": 8, "x": 16, "y": 34 }, "datasource": "${datasource}",
536
+ "targets": [{ "refId": "A", "expr": "tricache_target_expected{instance=~\"$pod\"} unless on (job, instance) (up == 1)", "legendFormat": "missing {{instance}}" }]
484
537
  }
485
538
  ],
486
539
  "refresh": "5s",
@@ -544,5 +597,5 @@
544
597
  "timezone": "browser",
545
598
  "title": "TriCache Observability & Performance Dashboard",
546
599
  "uid": "tricache-overview",
547
- "version": 1
600
+ "version": 3
548
601
  }
@@ -0,0 +1,21 @@
1
+ # Example only: render this inventory from the deployment's desired replicas and
2
+ # namespaces. It is evaluated by Prometheus, independently of app availability.
3
+ # Keep job/instance identical to the labels after scrape relabeling.
4
+ groups:
5
+ - name: tricache.deployment-inventory
6
+ rules:
7
+ - record: tricache_target_expected
8
+ expr: vector(1)
9
+ labels: { job: tricache, instance: 'app-1:3000' }
10
+ - record: tricache_target_expected
11
+ expr: vector(1)
12
+ labels: { job: tricache, instance: 'app-2:3000' }
13
+ - record: tricache_target_expected
14
+ expr: vector(1)
15
+ labels: { job: tricache, instance: 'app-3:3000' }
16
+ - record: tricache_cache_expected
17
+ expr: tricache_target_expected
18
+ labels: { namespace: service }
19
+ - record: tricache_cache_expected
20
+ expr: tricache_target_expected
21
+ labels: { namespace: 'service:a' }