tricache 1.0.2 → 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 (101) hide show
  1. package/README.md +78 -90
  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-CWI4jkS7.d.cts → cache-service-BV5T8-20.d.cts} +122 -21
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-B108FzER.d.ts → cache-service-tpyrXvlH.d.ts} +122 -21
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-H4GFLQ26.js → chunk-KV7KISK2.js} +47 -1
  10. package/dist/{chunk-WYF7NOAT.js → chunk-MB3DMVWN.js} +2111 -543
  11. package/dist/{chunk-OYDU3SMI.js → chunk-RBJRTGFK.js} +5 -0
  12. package/dist/chunk-S5N65I45.js +17 -0
  13. package/dist/cli.cjs +2454 -572
  14. package/dist/cli.js +186 -11
  15. package/dist/dashboard/index.d.cts +2 -2
  16. package/dist/dashboard/index.d.ts +2 -2
  17. package/dist/drizzle/index.cjs +2335 -571
  18. package/dist/drizzle/index.d.cts +2 -2
  19. package/dist/drizzle/index.d.ts +2 -2
  20. package/dist/drizzle/index.js +6 -2
  21. package/dist/edge/index.cjs +145 -43
  22. package/dist/edge/index.d.cts +11 -4
  23. package/dist/edge/index.d.ts +11 -4
  24. package/dist/edge/index.js +118 -43
  25. package/dist/hono/index.cjs +2322 -569
  26. package/dist/hono/index.d.cts +2 -2
  27. package/dist/hono/index.d.ts +2 -2
  28. package/dist/hono/index.js +2 -2
  29. package/dist/{hono-C886ok3X.d.cts → hono-CMv2VdQ6.d.cts} +18 -5
  30. package/dist/{hono-3rDMYVtY.d.ts → hono-Dvq04kX9.d.ts} +18 -5
  31. package/dist/http/index.cjs +2323 -570
  32. package/dist/http/index.d.cts +3 -3
  33. package/dist/http/index.d.ts +3 -3
  34. package/dist/http/index.js +4 -4
  35. package/dist/index.cjs +2554 -620
  36. package/dist/index.d.cts +88 -23
  37. package/dist/index.d.ts +88 -23
  38. package/dist/index.js +873 -16
  39. package/dist/{murmur3-CMGw9PbV.d.cts → murmur3-DF8BFRnu.d.cts} +1 -0
  40. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.ts} +1 -0
  41. package/dist/nestjs/index.cjs +2292 -574
  42. package/dist/nestjs/index.d.cts +19 -5
  43. package/dist/nestjs/index.d.ts +19 -5
  44. package/dist/nestjs/index.js +25 -19
  45. package/dist/next/index.cjs +2306 -571
  46. package/dist/next/index.d.cts +8 -2
  47. package/dist/next/index.d.ts +8 -2
  48. package/dist/next/index.js +36 -9
  49. package/dist/prisma/index.cjs +26 -25
  50. package/dist/prisma/index.d.cts +2 -2
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +14 -25
  53. package/dist/serialize-worker.cjs +162 -39
  54. package/dist/serialize-worker.js +9 -7
  55. package/dist/{types-BA4pz1A0.d.cts → types-F8vRWMrE.d.cts} +162 -45
  56. package/dist/{types-BA4pz1A0.d.ts → types-F8vRWMrE.d.ts} +162 -45
  57. package/package.json +21 -2
  58. package/src/adapters/auto-pipeliner.ts +52 -11
  59. package/src/cache-service.ts +1537 -415
  60. package/src/cli.ts +2 -9
  61. package/src/codec.ts +3 -3
  62. package/src/compression.ts +39 -16
  63. package/src/cross-region.ts +1 -1
  64. package/src/disk-tier.ts +283 -43
  65. package/src/drizzle/index.ts +2 -1
  66. package/src/edge/adapters/cloudflare-do.ts +25 -10
  67. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  68. package/src/edge/adapters/upstash.ts +27 -11
  69. package/src/edge/cache.ts +59 -17
  70. package/src/edge/types.ts +15 -5
  71. package/src/encryption.ts +50 -18
  72. package/src/env.d.ts +1 -1
  73. package/src/errors.ts +12 -0
  74. package/src/http/utils.ts +6 -0
  75. package/src/index.ts +6 -0
  76. package/src/latency-watchdog.ts +5 -1
  77. package/src/nestjs/decorators.ts +11 -6
  78. package/src/nestjs/tricache.module.ts +2 -1
  79. package/src/nestjs/tricache.store.ts +21 -9
  80. package/src/nestjs/types.ts +1 -1
  81. package/src/next/cache-handler.ts +24 -4
  82. package/src/next/types.ts +4 -0
  83. package/src/origin-capacity.ts +134 -0
  84. package/src/prisma/index.ts +14 -32
  85. package/src/remote-snapshot.ts +37 -27
  86. package/src/serialize-worker.ts +8 -5
  87. package/src/sigv4-snapshot-adapter.ts +37 -27
  88. package/src/smart-memory-cache.ts +62 -22
  89. package/src/types.ts +92 -35
  90. package/src/utils/config-comparison.ts +29 -0
  91. package/src/utils/lz4-size.ts +74 -0
  92. package/src/utils/namespace-key.ts +48 -0
  93. package/src/utils/query-key.ts +13 -0
  94. package/src/utils/snapshot-transfer.ts +83 -0
  95. package/src/utils/work-limits.ts +73 -0
  96. package/src/utils/write-revision.ts +4 -0
  97. package/src/wasm/bloom-filter-wasm.ts +16 -1
  98. package/src/worker-pool.ts +28 -8
  99. package/src/wtiny-lfu.ts +62 -14
  100. package/dist/cache-service-GYPZFB7O.js +0 -12
  101. package/dist/chunk-VNRDL5RA.js +0 -666
package/README.md CHANGED
@@ -4,120 +4,104 @@
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-980%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 a three-tier caching engine for Node.js: **L1 RAM** $\rightarrow$ **L1.5 disk or `/dev/shm` spill** $\rightarrow$ **L2 Redis/Valkey**. It combines bounded local storage, per-process singleflight, configurable stale-while-revalidate, and distributed invalidation. Performance and savings depend on your workload; [benchmark your deployment](BENCHMARKS.md).
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
+ });
30
34
  await cache.ready();
31
35
 
32
- // 2. Get-or-fetch with thundering-herd coalescing & 60s background SWR
33
- const user = await cache.get(
34
- `user:${userId}`,
35
- () => db.users.findById(userId),
36
- 300, // 5-minute TTL
37
- { swr: 60, tags: ['users'] } // Serve stale for 60s while refreshing in the background
38
- );
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
+ });
39
41
 
40
- // 3. Bump a concrete tag generation and publish invalidation to peers
41
- await cache.invalidateTag('users');
42
+ await cache.invalidateTag('catalog');
42
43
  ```
43
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
+
44
47
  ---
45
48
 
46
- ## 🔬 Under the Hood (Architectural Core)
49
+ ## What you get
47
50
 
48
- ```
49
- [Incoming Read Request]
50
- │
51
- ▼
52
- ┌──────────────────────────────────────────────────┐
53
- │ L1: Smart Memory (W-TinyLFU + CMS) │ Bounded RAM
54
- │ Window LRU (1%) + Segmented Main SLRU (99%) │ Packed values
55
- └────────────────────────┬─────────────────────────┘
56
- │ Miss / Eviction Spill
57
- ▼
58
- ┌──────────────────────────────────────────────────┐
59
- │ L1.5: Off-Heap /dev/shm & NVMe Spill Tier │ Bounded I/O
60
- │ tmpfs counts toward container memory usage │ Writable mount needed
61
- └────────────────────────┬─────────────────────────┘
62
- │ Miss
63
- ▼
64
- ┌──────────────────────────────────────────────────┐
65
- │ L2: Redis / Valkey Distributed Tier │ ~1.2 ms (Network)
66
- │ Optional AES-GCM + expiry/tag metadata │ Pipelined commands
67
- └────────────────────────┬─────────────────────────┘
68
- │ Complete Cache Miss
69
- ▼
70
- ┌──────────────────────────────────────────────────┐
71
- │ Upstream Database / API (Singleflight) │ Per process/key
72
- │ Inflight Promise Map coalesces concurrent work│ Not a fleet-wide lock
73
- └──────────────────────────────────────────────────┘
74
- ```
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. |
75
59
 
76
- * **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)]
77
- * **WebAssembly Zstandard Compression**: Out-of-the-box `zstd` WASM engine compresses payloads $>1$ KB by ~95% with automatic Brotli fallback and optional LZ4.
78
- * **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)]
79
- * **Dynamic Latency Watchdog**: Graduated shedding (0% $\rightarrow$ 25% $\rightarrow$ 75% $\rightarrow$ 100%) with asymmetric Redis hysteresis (15ms cutoff, 10ms recovery floor).
80
- * **Ephemeral Quotas & K8s Eviction Defense**: Chunked watermark pruning (80% $\rightarrow$ 60% in 500-entry batches) and proactive $<10\%$ space spill pauses.
81
- * **Wildcard & Hierarchical Tag Invalidation**: Concrete generation bumps are $O(1)$; wildcard and hierarchy resolution scan matching tag metadata.
82
- * **Differential Multi-Tier Waterfall Batching**: Cascading `cache.mget` resolves L1 $\rightarrow$ L2 $\rightarrow$ Disk $\rightarrow$ DB miss fetch with zero $N+1$ queries.
83
- * **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.
84
61
 
85
62
  ---
86
63
 
87
- ## 🏆 Feature Overview
64
+ ## How it works
88
65
 
89
- | Feature | Behavior |
90
- |:---|:---|
91
- | **Storage hierarchy** | RAM → eligible disk/tmpfs spill → Redis/Valkey |
92
- | **Singleflight** | Coalesces concurrent work per process and key |
93
- | **Tag invalidation** | Concrete generation bumps; metadata scans for patterns/cascades |
94
- | **Backplane** | Pub/Sub or retained-event Redis Streams replay |
95
- | **Compression** | Zstandard with fallback; optional Brotli, gzip, LZ4, or custom compressor |
96
- | **Batch reads** | Resolves cached keys and fetches only remaining misses |
97
- | **Resource controls** | Packed-data limits, bounded disk I/O, and cgroup pressure guards |
98
- | **Encryption** | Optional AES-GCM for Node and Web Crypto edge storage |
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 App Router (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.
88
+
89
+ ---
90
+
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.
117
101
 
118
102
  ---
119
103
 
120
- ## 🗄️ Turnkey Ecosystem Integrations
104
+ ## Integrations
121
105
 
122
106
  | Integration | Import Path | Description |
123
107
  |:---|:---|:---|
@@ -127,29 +111,33 @@ const cache = CacheService.preset('enterprise-hardened', { redisHost: 'redis.int
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
113
  | **Node Hono** | `tricache/hono` | Response caching with TTL/tags, privacy guards, 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. |
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
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.
137
122
  - Dashboard access should be authenticated and private. It defaults to `readOnly: true`; administrative writes require explicit opt-in.
138
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.
139
- - Redis promotions preserve remaining TTL where supported. Custom drivers without atomic expiry reads use fallback TTLs; edge legacy JSON without expiry metadata is read without local promotion.
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.
140
125
  - `/dev/shm` reduces disk I/O but still consumes container memory. Encryption and cache configuration do not by themselves establish regulatory compliance.
141
126
 
142
127
  ---
143
128
 
144
- ## 📚 Documentation & Deep Dives
145
-
146
- * 📖 **[Documentation Portal](https://kareem411.github.io/TriCache/)** — Official VitePress guides, architecture, and API reference
147
- * 🔬 **[Architecture & Mathematical Internals](docs/architecture-internals.md)** — W-TinyLFU, CMS, Bloom filters, SigV4 signer
148
- * ☸️ **[Kubernetes SRE & Production Guide](docs/kubernetes-production-guide.md)** — `/dev/shm`, cgroups, eviction defense, readiness probes
149
- * ☁️ **[Cold-Start Cloud Snapshot Hydration](docs/cold-start-cloud-hydration.md)** — S3, Cloudflare R2, readiness gates
150
- * 📈 **[Prometheus /metrics Scraping Recipe](docs/metrics-recipe.md)** — Express / Fastify / Next.js endpoints, scrape config, and one-command local Grafana stack
151
- * 💰 **[Cloud ROI Financial Simulation](bench/cloud-roi-simulation.ts)** — Deterministic Mulberry32 Zipfian benchmark (`pnpm bench:roi`)
152
- * 📊 **[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)
153
141
 
154
142
  ---
155
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' }