tricache 0.1.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.
- package/LICENSE +21 -0
- package/README.md +438 -0
- package/dist/index.cjs +1784 -0
- package/dist/index.d.cts +718 -0
- package/dist/index.d.ts +718 -0
- package/dist/index.js +1741 -0
- package/package.json +64 -0
- package/src/cache-service.ts +866 -0
- package/src/disk-tier.ts +300 -0
- package/src/encryption.ts +340 -0
- package/src/index.ts +36 -0
- package/src/smart-memory-cache.ts +472 -0
- package/src/types.ts +317 -0
- package/src/wasm/bloom-filter-wasm.ts +117 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 tricache contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
# tricache ⚡
|
|
2
|
+
|
|
3
|
+
[](https://github.com/Kareem411/tricache/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/tricache)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
[](https://nodejs.org)
|
|
7
|
+
[](https://www.typescriptlang.org)
|
|
8
|
+
|
|
9
|
+
**Stop paying for slow.** tricache is a three-tier Node.js cache that serves **1.4 million reads/second** from RAM, spills cold entries to NVMe instead of dropping them on the floor, and fans out invalidations across your entire fleet in real time — all behind a single `npm install`.
|
|
10
|
+
|
|
11
|
+
Built for production from day one: adaptive LFU×LRU×priority eviction, AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, thundering-herd prevention, OOM guard, cold-start snapshots, and Prometheus metrics. Zero required configuration.
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
Request
|
|
15
|
+
│
|
|
16
|
+
▼
|
|
17
|
+
L1 — SmartMemoryCache (in-process RAM, 200 MB default, adaptive LFU×LRU×priority eviction)
|
|
18
|
+
│ miss
|
|
19
|
+
▼
|
|
20
|
+
L1.5 — DiskTier (NVMe spill, 500 MB default, 2–100 µs, holds evicted L1 entries)
|
|
21
|
+
│ miss
|
|
22
|
+
▼
|
|
23
|
+
L2 — Redis / Valkey (distributed, production-only by default, pub/sub invalidation)
|
|
24
|
+
│ miss
|
|
25
|
+
▼
|
|
26
|
+
fetchFn() (your database / API call — fires exactly once per key under load)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## ✨ Features
|
|
32
|
+
|
|
33
|
+
| Feature | Detail |
|
|
34
|
+
|---|---|
|
|
35
|
+
| **Adaptive eviction** | LFU × LRU × priority score; reservoir-sampled O(1) hot path; category limits prevent any prefix monopolising RAM |
|
|
36
|
+
| **WASM Bloom filter** | 562-byte binary inlined as Base64 — O(k=7) guaranteed-miss detection, no filesystem access, pure-JS fallback |
|
|
37
|
+
| **msgpackr serialization** | All entries packed with msgpackr — uniform binary format, no JSON at any payload size |
|
|
38
|
+
| **Stale-While-Revalidate** | Serve stale instantly, revalidate in background — zero added latency on cache hit |
|
|
39
|
+
| **Thundering-herd prevention** | Inflight `Promise` registry — only one `fetchFn` call per key regardless of concurrency |
|
|
40
|
+
| **Pub/sub invalidation backplane** | Redis pub/sub channel propagates deletes across all instances in real time |
|
|
41
|
+
| **OOM guard** | Polls `heapUsed/heapTotal` on a timer; emergency-evicts coldest L1 entries before the process crashes |
|
|
42
|
+
| **Cold-start snapshot** | L1 serialised to disk on `SIGTERM`/`SIGINT`, reloaded on next startup — warm cache, cold process |
|
|
43
|
+
| **AES-256-GCM encryption** | L2 (Redis) values, disk spill files, and snapshots encrypted at rest |
|
|
44
|
+
| **Prometheus metrics** | `cache.metrics()` + `CacheService.toPrometheusText()` — drop into any `/metrics` endpoint |
|
|
45
|
+
| **Distributed counter** | `cache.increment()` backed by Redis `INCR` for distributed rate limiting |
|
|
46
|
+
| **Pluggable logger** | Bring your own `pino`, `winston`, etc. |
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## 📦 Install
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
npm install tricache
|
|
54
|
+
# or
|
|
55
|
+
pnpm add tricache
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## 🚀 Quick start
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
import { CacheService, CachePriority } from 'tricache';
|
|
64
|
+
|
|
65
|
+
// Get (or create) the process-level singleton
|
|
66
|
+
const cache = CacheService.create({
|
|
67
|
+
redisHost: 'my-redis.example.com', // omit or set NODE_ENV!=production to disable L2
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
// Get-or-fetch with a 5-minute TTL
|
|
71
|
+
const user = await cache.get(
|
|
72
|
+
`user:${userId}`,
|
|
73
|
+
() => db.users.findById(userId),
|
|
74
|
+
300,
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
// Explicit set
|
|
78
|
+
await cache.set(`user:${userId}`, user, 300);
|
|
79
|
+
|
|
80
|
+
// Delete one key
|
|
81
|
+
await cache.delete(`user:${userId}`);
|
|
82
|
+
|
|
83
|
+
// Delete by glob pattern
|
|
84
|
+
await cache.delete(`user:${userId}:*`);
|
|
85
|
+
|
|
86
|
+
// Stale-While-Revalidate: serve stale for up to 30 s while refreshing in background
|
|
87
|
+
const dashboard = await cache.get(
|
|
88
|
+
`dashboard:${orgId}`,
|
|
89
|
+
() => analytics.buildDashboard(orgId),
|
|
90
|
+
300,
|
|
91
|
+
{ swr: 30 },
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
// Distributed rate-limiting counter
|
|
95
|
+
const hits = await cache.increment(`ratelimit:${ip}`, 60 /* TTL seconds */);
|
|
96
|
+
|
|
97
|
+
// Prometheus metrics
|
|
98
|
+
const snap = cache.metrics();
|
|
99
|
+
console.log(CacheService.toPrometheusText(snap));
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## ⚙️ Configuration
|
|
105
|
+
|
|
106
|
+
All options are optional — sensible defaults apply.
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
CacheService.create({
|
|
110
|
+
// ── Namespace ─────────────────────────────────────────────────────────
|
|
111
|
+
// Isolates keys, disk dir, snapshot file, and Redis backplane channel.
|
|
112
|
+
// Two instances with different namespaces are fully independent.
|
|
113
|
+
namespace: 'my-app',
|
|
114
|
+
|
|
115
|
+
// ── Logger ────────────────────────────────────────────────────────────
|
|
116
|
+
logger: pinoLogger, // default: console warn/error only
|
|
117
|
+
|
|
118
|
+
// ── L1 (in-memory) ───────────────────────────────────────────────────
|
|
119
|
+
l1MaxBytes: 200 * 1024 * 1024, // 200 MB total RAM cap (default)
|
|
120
|
+
l1MaxEntries: 2_000, // max entries in L1 (default)
|
|
121
|
+
categoryLimits: {
|
|
122
|
+
// per-prefix limits — keys are matched by startsWith()
|
|
123
|
+
'user:': { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 },
|
|
124
|
+
'analytics:': { maxEntries: 100, maxSizeBytes: 20 * 1024 * 1024 },
|
|
125
|
+
'default': { maxEntries: 1000, maxSizeBytes: 100 * 1024 * 1024 },
|
|
126
|
+
},
|
|
127
|
+
|
|
128
|
+
// ── L1.5 (disk spill) ────────────────────────────────────────────────
|
|
129
|
+
diskCacheDir: '/tmp/my-app-cache', // default: os.tmpdir()/tricache-disk
|
|
130
|
+
diskMaxBytes: 500 * 1024 * 1024, // 500 MB (default)
|
|
131
|
+
diskEntryMaxBytes: 10 * 1024 * 1024, // 10 MB per entry (default)
|
|
132
|
+
|
|
133
|
+
// ── L2 (Redis / Valkey) ──────────────────────────────────────────────
|
|
134
|
+
redisHost: 'my-redis.example.com', // or REDIS_HOST env var
|
|
135
|
+
redisPort: 6379,
|
|
136
|
+
redisTls: true, // default: true when NODE_ENV=production
|
|
137
|
+
disableRedis: false, // default: true when NODE_ENV!=production
|
|
138
|
+
|
|
139
|
+
// ── Invalidation backplane ───────────────────────────────────────────
|
|
140
|
+
// Redis pub/sub channel that propagates deletes to all instances.
|
|
141
|
+
// Enabled by default when Redis is active.
|
|
142
|
+
invalidationBackplane: true,
|
|
143
|
+
|
|
144
|
+
// ── OOM guard ────────────────────────────────────────────────────────
|
|
145
|
+
oomProtection: true, // enabled by default
|
|
146
|
+
oomHeapThreshold: 0.85, // evict when heapUsed/heapTotal > 85 %
|
|
147
|
+
oomCheckIntervalMs: 10_000, // poll every 10 s
|
|
148
|
+
oomEvictPercent: 0.20, // evict coldest 20 % of L1 per trigger
|
|
149
|
+
|
|
150
|
+
// ── Encryption ───────────────────────────────────────────────────────
|
|
151
|
+
// base64-encoded 32-byte key; or set CACHE_ENCRYPTION_KEY env var.
|
|
152
|
+
// node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
153
|
+
encryptionKey: process.env.CACHE_ENCRYPTION_KEY,
|
|
154
|
+
|
|
155
|
+
// ── Cold-start snapshot ──────────────────────────────────────────────
|
|
156
|
+
snapshotPath: '/tmp/my-app-cache-snapshot.msgpack',
|
|
157
|
+
snapshotMaxAgeMs: 2 * 60 * 60 * 1000, // 2 hours (default)
|
|
158
|
+
forbiddenSnapshotPrefixes: ['auth:', 'session:', 'mfa:', 'rate_limit:'],
|
|
159
|
+
|
|
160
|
+
// ── Metrics callback ─────────────────────────────────────────────────
|
|
161
|
+
metricsIntervalMs: 60_000, // emit every 60 s (default)
|
|
162
|
+
onMetrics: (m) => myMonitoring.record(m), // optional push callback
|
|
163
|
+
});
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### Environment variables
|
|
167
|
+
|
|
168
|
+
| Variable | Purpose |
|
|
169
|
+
|---|---|
|
|
170
|
+
| `REDIS_HOST` | Redis/Valkey hostname (used when `redisHost` option is not set) |
|
|
171
|
+
| `CACHE_ENCRYPTION_KEY` | Base64-encoded 32-byte AES-256-GCM key |
|
|
172
|
+
| `NODE_ENV` | When `!== 'production'`, L2 Redis and TLS are disabled by default |
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
## 📖 API reference
|
|
177
|
+
|
|
178
|
+
### `CacheService.create(options?)` → `CacheService`
|
|
179
|
+
|
|
180
|
+
Returns the process-level singleton. Options are only applied on the **first** call per namespace — subsequent calls return the existing instance.
|
|
181
|
+
|
|
182
|
+
### `CacheService.reset(options?)` → `CacheService`
|
|
183
|
+
|
|
184
|
+
Destroys the existing singleton and creates a fresh one. Useful in tests.
|
|
185
|
+
|
|
186
|
+
### `cache.get<T>(key, fetchFn, ttlSeconds?, opts?)` → `Promise<T>`
|
|
187
|
+
|
|
188
|
+
Get from cache or call `fetchFn` on a miss. The inflight map ensures `fetchFn` fires at most once per key regardless of concurrency.
|
|
189
|
+
|
|
190
|
+
| Parameter | Type | Default | Description |
|
|
191
|
+
|---|---|---|---|
|
|
192
|
+
| `key` | `string` | — | Cache key |
|
|
193
|
+
| `fetchFn` | `() => Promise<T>` | — | Called on a miss; result is cached |
|
|
194
|
+
| `ttlSeconds` | `number` | `300` | Hard TTL in seconds |
|
|
195
|
+
| `opts.swr` | `number` | `0` | Stale-While-Revalidate grace seconds |
|
|
196
|
+
| `opts.priority` | `CachePriority` | auto-inferred | Eviction priority override |
|
|
197
|
+
|
|
198
|
+
### `cache.set<T>(key, data, ttlSeconds?, priority?)` → `Promise<void>`
|
|
199
|
+
|
|
200
|
+
Writes to L1 and (in production) L2. Publishes an invalidation to the backplane.
|
|
201
|
+
|
|
202
|
+
### `cache.delete(key)` → `Promise<void>`
|
|
203
|
+
|
|
204
|
+
Deletes one exact key or a glob pattern (`user:abc:*`). Propagates to disk, Redis, and all backplane peers.
|
|
205
|
+
|
|
206
|
+
### `cache.increment(key, ttlSeconds?)` → `Promise<number>`
|
|
207
|
+
|
|
208
|
+
Redis `INCR` — atomically increments a counter, setting TTL on first write. Returns `0` when Redis is disabled (safe for dev).
|
|
209
|
+
|
|
210
|
+
### `cache.metrics()` → `CacheMetrics`
|
|
211
|
+
|
|
212
|
+
Returns a full metrics snapshot including hit rates, bloom filter stats, backplane counters, OOM eviction history, and tier sizes.
|
|
213
|
+
|
|
214
|
+
### `CacheService.toPrometheusText(metrics, prefix?)` → `string`
|
|
215
|
+
|
|
216
|
+
Converts a `CacheMetrics` snapshot to Prometheus text exposition format. Paste into your `/metrics` route.
|
|
217
|
+
|
|
218
|
+
```typescript
|
|
219
|
+
app.get('/metrics', (_req, res) => {
|
|
220
|
+
res.type('text/plain').send(CacheService.toPrometheusText(cache.metrics()));
|
|
221
|
+
});
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
### `cache.stats()` → `{ l1, disk }`
|
|
225
|
+
|
|
226
|
+
Lightweight L1 and disk stats without the full metrics breakdown.
|
|
227
|
+
|
|
228
|
+
### `cache.writeSnapshot()` / `cache.loadSnapshot()`
|
|
229
|
+
|
|
230
|
+
Manual snapshot control. Called automatically on `SIGTERM`/`SIGINT` — only needed when you manage shutdown yourself.
|
|
231
|
+
|
|
232
|
+
### `cache.destroy()` → `Promise<void>`
|
|
233
|
+
|
|
234
|
+
Closes the Redis connection, unsubscribes the backplane, and stops all background timers.
|
|
235
|
+
|
|
236
|
+
---
|
|
237
|
+
|
|
238
|
+
## 🎯 Priority levels
|
|
239
|
+
|
|
240
|
+
```typescript
|
|
241
|
+
import { CachePriority } from 'tricache';
|
|
242
|
+
|
|
243
|
+
CachePriority.LOW // 1 — analytics, reports — evicted first
|
|
244
|
+
CachePriority.NORMAL // 2 — general application data (default)
|
|
245
|
+
CachePriority.HIGH // 3 — user profiles, config — evicted last
|
|
246
|
+
CachePriority.CRITICAL // 4 — never evicted while valid (auth tokens, sessions)
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
Priority is **auto-inferred** from the key when not specified:
|
|
250
|
+
|
|
251
|
+
| Key contains | Inferred priority |
|
|
252
|
+
|---|---|
|
|
253
|
+
| `auth:` or `session:` | `CRITICAL` |
|
|
254
|
+
| `user:`, `org:`, or `profile:` | `HIGH` |
|
|
255
|
+
| `analytics:`, `report:`, or `stats:` | `LOW` |
|
|
256
|
+
| anything else | `NORMAL` |
|
|
257
|
+
|
|
258
|
+
---
|
|
259
|
+
|
|
260
|
+
## 🧠 Eviction algorithm
|
|
261
|
+
|
|
262
|
+
L1 eviction uses **reservoir sampling** — an O(n) single pass samples 16 candidates, then sorts only those 16 (O(1)). Each candidate is scored:
|
|
263
|
+
|
|
264
|
+
```
|
|
265
|
+
score = priority × 1000 + min(hits, 100) × 10 + ttlRemaining/60s − age/60s
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
- Higher score = kept longer
|
|
269
|
+
- `CRITICAL` entries are excluded from sampling while valid
|
|
270
|
+
- When a category limit is breached, entries from that category receive a score penalty
|
|
271
|
+
|
|
272
|
+
---
|
|
273
|
+
|
|
274
|
+
## 🪵 Pluggable logger
|
|
275
|
+
|
|
276
|
+
Bring your own structured logger — tricache doesn't care if it's `pino`, `winston`, or `console`.
|
|
277
|
+
|
|
278
|
+
```typescript
|
|
279
|
+
import pino from 'pino';
|
|
280
|
+
const logger = pino();
|
|
281
|
+
|
|
282
|
+
CacheService.create({
|
|
283
|
+
logger: {
|
|
284
|
+
debug: (msg, meta) => logger.debug(meta ?? {}, msg),
|
|
285
|
+
info: (msg, meta) => logger.info(meta ?? {}, msg),
|
|
286
|
+
warn: (msg, meta) => logger.warn(meta ?? {}, msg),
|
|
287
|
+
error: (msg, meta, err) => logger.error({ ...(meta ?? {}), err }, msg),
|
|
288
|
+
},
|
|
289
|
+
});
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
---
|
|
293
|
+
|
|
294
|
+
## 🔐 Encryption
|
|
295
|
+
|
|
296
|
+
AES-256-GCM for L2 (Redis) values, disk spill files, and cold-start snapshots. Three modes are available via `encryptionMode`:
|
|
297
|
+
|
|
298
|
+
| Mode | Key length | Notes |
|
|
299
|
+
|---|---|---|
|
|
300
|
+
| `aes-256-gcm` | 32 bytes | **Default.** Authenticated encryption (AEAD). |
|
|
301
|
+
| `aes-128-gcm` | 16 bytes | ~15% faster than AES-256. Same AEAD guarantees. |
|
|
302
|
+
| `aes-128-ctr` | 16 bytes | Fastest cipher mode. AES-NI keystream, no auth tag. Use when integrity is guaranteed elsewhere (TLS, HMAC). |
|
|
303
|
+
| `xor` | any (≥ 16 bytes recommended) | **NOT cryptographic.** XOR obfuscation only. Dev/non-sensitive data. |
|
|
304
|
+
|
|
305
|
+
**Key generation:**
|
|
306
|
+
|
|
307
|
+
```bash
|
|
308
|
+
# AES-256 (32 bytes)
|
|
309
|
+
node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
310
|
+
|
|
311
|
+
# AES-128 / AES-128-CTR (16 bytes)
|
|
312
|
+
node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
|
|
313
|
+
|
|
314
|
+
# XOR — any length, minimum 16 bytes recommended
|
|
315
|
+
node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
```typescript
|
|
319
|
+
// AES-256-GCM (default)
|
|
320
|
+
CacheService.create({ encryptionKey: '<base64-32-bytes>' });
|
|
321
|
+
|
|
322
|
+
// AES-128-GCM
|
|
323
|
+
CacheService.create({ encryptionKey: '<base64-16-bytes>', encryptionMode: 'aes-128-gcm' });
|
|
324
|
+
|
|
325
|
+
// AES-128-CTR (fastest cipher, no auth tag)
|
|
326
|
+
CacheService.create({ encryptionKey: '<base64-16-bytes>', encryptionMode: 'aes-128-ctr' });
|
|
327
|
+
|
|
328
|
+
// XOR obfuscation (NOT cryptographic — dev/non-sensitive only)
|
|
329
|
+
CacheService.create({ encryptionKey: '<base64-key>', encryptionMode: 'xor' });
|
|
330
|
+
|
|
331
|
+
// or use the env var: CACHE_ENCRYPTION_KEY=<base64-key>
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
| Mode | Redis format | Disk / snapshot format |
|
|
335
|
+
|---|---|---|
|
|
336
|
+
| `aes-256-gcm` | `enc:v1:<base64(IV[12]\|Tag[16]\|CT)>` | `TRIC1ENC\|IV[12]\|Tag[16]\|CT[N]` |
|
|
337
|
+
| `aes-128-gcm` | `a128:v1:<base64(IV[12]\|Tag[16]\|CT)>` | `TRIC1128\|IV[12]\|Tag[16]\|CT[N]` |
|
|
338
|
+
| `aes-128-ctr` | `ctr:v1:<base64(IV[16]\|CT)>` | `TRIC1CTR\|IV[16]\|CT[N]` |
|
|
339
|
+
| `xor` | `xor:v1:<base64(key⊕data)>` | `TRIC1XOR\|key⊕data[N]` |
|
|
340
|
+
|
|
341
|
+
Existing plaintext values are read transparently during key rotation.
|
|
342
|
+
|
|
343
|
+
---
|
|
344
|
+
|
|
345
|
+
## ⚡ WASM Bloom filter
|
|
346
|
+
|
|
347
|
+
A 100,000-bit filter with k=7 hash probes:
|
|
348
|
+
|
|
349
|
+
- At the default `l1MaxEntries: 2,000` — false-positive rate ≈ **0.01%**
|
|
350
|
+
- At rated capacity (~18,000 entries) — false-positive rate ≈ **1%**
|
|
351
|
+
- The filter rebuilds automatically when stale bits from deleted/expired entries accumulate
|
|
352
|
+
|
|
353
|
+
Mechanics:
|
|
354
|
+
- `mightContain(key) === false` → **guaranteed miss** — the Map lookup is skipped entirely
|
|
355
|
+
- `mightContain(key) === true` → probable hit — the Map is checked to confirm
|
|
356
|
+
|
|
357
|
+
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.
|
|
358
|
+
|
|
359
|
+
---
|
|
360
|
+
|
|
361
|
+
## 📊 Performance
|
|
362
|
+
|
|
363
|
+
Measured on a single Node.js thread (no `await` on synchronous paths):
|
|
364
|
+
|
|
365
|
+
**L1 SmartMemoryCache**
|
|
366
|
+
|
|
367
|
+
| Operation | Throughput | Latency | Notes |
|
|
368
|
+
|---|---|---|---|
|
|
369
|
+
| `get` — hot hit (8K entries) | 1.24 M/s | 807 ns | bloom → Map lookup |
|
|
370
|
+
| `get` — cold miss | 7.32 M/s | 137 ns | bloom gates → early return |
|
|
371
|
+
| `set` — tiny payload | 1.03 M/s | 974 ns | pack() + Map.set + bloom.add |
|
|
372
|
+
| `set` — small payload (≈ 512 B) | 519 K/s | 1.93 µs | pack() same unified path, larger payload |
|
|
373
|
+
| `set` — large payload (≥ 512 B) | 225 K/s | 4.44 µs | pack() larger payload |
|
|
374
|
+
| `set` — CRITICAL priority | 693 K/s | 1.44 µs | same set path; skipped in eviction sort |
|
|
375
|
+
| `delete` — exact key | 3.08 M/s | 325 ns | Map.delete |
|
|
376
|
+
| `deletePattern` — glob wildcard | 7.1 K/s | 141 µs | O(n) Map scan |
|
|
377
|
+
|
|
378
|
+
**CacheService (end-to-end)**
|
|
379
|
+
|
|
380
|
+
| Operation | Throughput | Latency | Notes |
|
|
381
|
+
|---|---|---|---|
|
|
382
|
+
| `get` — L1 warm hit | 1.39 M/s | 720 ns | inflight check → l1.get |
|
|
383
|
+
| `get` — SWR stale serve | 1.34 M/s | 744 ns | serves stale; revalidates async |
|
|
384
|
+
| `get` — miss + fetchFn | 17.8 K/s | 56.2 µs | Promise microtask + l1.set |
|
|
385
|
+
| `set` | 28.3 K/s | 35.3 µs | l1.set + disk.save (fire-and-forget) |
|
|
386
|
+
| `delete` — exact key | 29.7 K/s | 33.6 µs | l1.delete + disk.delete + backplane |
|
|
387
|
+
| `delete` — glob `*` | 723 K/s | 1.38 µs | l1.deletePattern O(n) + disk glob |
|
|
388
|
+
|
|
389
|
+
**Encryption** (IV pool, pre-allocated output buffers)
|
|
390
|
+
|
|
391
|
+
| Mode | Payload | Encrypt | Decrypt |
|
|
392
|
+
|---|---|---|---|
|
|
393
|
+
| AES-256-GCM | 64 B | 129 K/s / 7.78 µs | 147 K/s / 6.80 µs |
|
|
394
|
+
| AES-256-GCM | 512 B | 120 K/s / 8.33 µs | 103 K/s / 9.72 µs |
|
|
395
|
+
| AES-256-GCM | 4 KB | 56.3 K/s / 17.8 µs | 46.3 K/s / 21.6 µs |
|
|
396
|
+
| AES-128-GCM | 64 B | 116 K/s / 8.66 µs | 153 K/s / 6.55 µs |
|
|
397
|
+
| AES-128-GCM | 512 B | 125 K/s / 7.99 µs | 141 K/s / 7.12 µs |
|
|
398
|
+
| AES-128-GCM | 4 KB | 58.6 K/s / 17.1 µs | 55.1 K/s / 18.2 µs |
|
|
399
|
+
| AES-128-CTR | 64 B | 142 K/s / 7.02 µs | 194 K/s / 5.15 µs |
|
|
400
|
+
| AES-128-CTR | 512 B | 181 K/s / 5.54 µs | 190 K/s / 5.25 µs |
|
|
401
|
+
| AES-128-CTR | 4 KB | 85.5 K/s / 11.7 µs | 60.0 K/s / 16.7 µs |
|
|
402
|
+
| XOR _(obfuscation only)_ | 64 B | 2.34 M/s / 428 ns | 1.88 M/s / 531 ns |
|
|
403
|
+
| XOR _(obfuscation only)_ | 512 B | 549 K/s / 1.82 µs | 893 K/s / 1.12 µs |
|
|
404
|
+
| XOR _(obfuscation only)_ | 4 KB | 102 K/s / 9.86 µs | 181 K/s / 5.51 µs |
|
|
405
|
+
|
|
406
|
+
> AES and XOR string-path numbers shown (Redis L2). Buffer path (disk/snapshot) is 5–20% faster — no base64 overhead.
|
|
407
|
+
> AES-128-GCM is 5–50% faster than AES-256-GCM depending on payload (gap widens at mid-range sizes on AES-NI hardware).
|
|
408
|
+
> 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.
|
|
409
|
+
> 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.
|
|
410
|
+
|
|
411
|
+
Run `pnpm bench` for a full breakdown including bloom filter cost, compression trade-offs, eviction pressure, concurrency, and a realistic 80/15/5 read/miss/write workload.
|
|
412
|
+
|
|
413
|
+
---
|
|
414
|
+
|
|
415
|
+
## 🤝 Contributing
|
|
416
|
+
|
|
417
|
+
Bug reports and pull requests are welcome!
|
|
418
|
+
|
|
419
|
+
1. Fork the repo and create a feature branch
|
|
420
|
+
2. Run `pnpm test` — all tests must pass
|
|
421
|
+
3. Run `pnpm bench` if you touch a hot path and include before/after numbers in your PR
|
|
422
|
+
4. Open your PR against `master`
|
|
423
|
+
|
|
424
|
+
> 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.
|
|
425
|
+
|
|
426
|
+
---
|
|
427
|
+
|
|
428
|
+
## 🛡️ Security
|
|
429
|
+
|
|
430
|
+
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.
|
|
431
|
+
|
|
432
|
+
For encryption key generation and rotation best practices, see the [Encryption](#-encryption) section.
|
|
433
|
+
|
|
434
|
+
---
|
|
435
|
+
|
|
436
|
+
## 📄 License
|
|
437
|
+
|
|
438
|
+
MIT
|