@nathapp/nestjs-cache 2.1.0-rc.0 → 2.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.
Files changed (95) hide show
  1. package/CLAUDE.md +149 -0
  2. package/README.md +330 -420
  3. package/TODO.md +56 -0
  4. package/dist/enum/strategy.enum.js.map +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/index.js.map +1 -1
  8. package/dist/inteceptor/index.d.ts +1 -2
  9. package/dist/inteceptor/index.js +1 -2
  10. package/dist/inteceptor/index.js.map +1 -1
  11. package/dist/interceptor/cache-invalidate.interceptor.js.map +1 -0
  12. package/dist/{inteceptor → interceptor}/cache.interceptor.js +9 -3
  13. package/dist/interceptor/cache.interceptor.js.map +1 -0
  14. package/dist/interceptor/index.d.ts +2 -0
  15. package/dist/interceptor/index.js +19 -0
  16. package/dist/interceptor/index.js.map +1 -0
  17. package/dist/interface/cache-invalidate.interface.d.ts +8 -0
  18. package/dist/interface/enhanced-cache-options.interface.d.ts +16 -0
  19. package/dist/interface/health.interface.d.ts +19 -0
  20. package/dist/interface/health.interface.js +3 -0
  21. package/dist/interface/health.interface.js.map +1 -0
  22. package/dist/interface/index.d.ts +2 -0
  23. package/dist/interface/index.js +2 -0
  24. package/dist/interface/index.js.map +1 -1
  25. package/dist/interface/metrics.interface.d.ts +17 -0
  26. package/dist/interface/metrics.interface.js +3 -0
  27. package/dist/interface/metrics.interface.js.map +1 -0
  28. package/dist/module/cache-invalidate.provider.js +5 -0
  29. package/dist/module/cache-invalidate.provider.js.map +1 -1
  30. package/dist/module/cache-module.interface.d.ts +1 -0
  31. package/dist/module/cache.module.d.ts +2 -1
  32. package/dist/module/cache.module.js +7 -3
  33. package/dist/module/cache.module.js.map +1 -1
  34. package/dist/module/cache.provider.js +69 -1
  35. package/dist/module/cache.provider.js.map +1 -1
  36. package/dist/provider/cacheable.provider.d.ts +3 -0
  37. package/dist/provider/cacheable.provider.js +120 -35
  38. package/dist/provider/cacheable.provider.js.map +1 -1
  39. package/dist/service/cache-invalidate.factory.js.map +1 -1
  40. package/dist/service/cache-invalidate.manager.d.ts +4 -3
  41. package/dist/service/cache-invalidate.manager.js +8 -5
  42. package/dist/service/cache-invalidate.manager.js.map +1 -1
  43. package/dist/service/cache-manager.d.ts +39 -8
  44. package/dist/service/cache-manager.js +579 -71
  45. package/dist/service/cache-manager.js.map +1 -1
  46. package/dist/service/cache-provider.js +3 -6
  47. package/dist/service/cache-provider.js.map +1 -1
  48. package/dist/service/cache-tag-registry.d.ts +30 -0
  49. package/dist/service/cache-tag-registry.js +100 -0
  50. package/dist/service/cache-tag-registry.js.map +1 -0
  51. package/dist/service/index.d.ts +1 -0
  52. package/dist/service/index.js +1 -0
  53. package/dist/service/index.js.map +1 -1
  54. package/dist/service/redis-cache-invalidate.manager.d.ts +9 -1
  55. package/dist/service/redis-cache-invalidate.manager.js +107 -55
  56. package/dist/service/redis-cache-invalidate.manager.js.map +1 -1
  57. package/dist/service/redis-pattern-invalidation.js +4 -0
  58. package/dist/service/redis-pattern-invalidation.js.map +1 -1
  59. package/dist/utils/cache-key.utils.d.ts +3 -0
  60. package/dist/utils/cache-key.utils.js +34 -2
  61. package/dist/utils/cache-key.utils.js.map +1 -1
  62. package/dist/utils/config-validation.d.ts +2 -0
  63. package/dist/utils/config-validation.js +57 -0
  64. package/dist/utils/config-validation.js.map +1 -0
  65. package/dist/utils/deprecation.d.ts +1 -0
  66. package/dist/utils/deprecation.js +13 -2
  67. package/dist/utils/deprecation.js.map +1 -1
  68. package/dist/utils/index.d.ts +3 -0
  69. package/dist/utils/index.js +3 -0
  70. package/dist/utils/index.js.map +1 -1
  71. package/dist/utils/redis-uri.utils.d.ts +9 -0
  72. package/dist/utils/redis-uri.utils.js +62 -0
  73. package/dist/utils/redis-uri.utils.js.map +1 -0
  74. package/dist/utils/validation.d.ts +10 -0
  75. package/dist/utils/validation.js +39 -0
  76. package/dist/utils/validation.js.map +1 -0
  77. package/docker-compose.e2e.yml +16 -0
  78. package/docs/CACHEOBLESYNC-MIGRATION-PLAN.md +55 -0
  79. package/docs/CODE-REVIEW-2026-02-10-v2.md +134 -0
  80. package/docs/CODE-REVIEW-2026-02-10.md +142 -0
  81. package/docs/CODE_REVIEW.md +356 -0
  82. package/docs/FINAL-CODE-REVIEW-2026-02-10.md +312 -0
  83. package/docs/IMPLEMENTATION_PLAN.md +1045 -0
  84. package/docs/IMPLEMENTATION_PLAN_V2.md +201 -0
  85. package/docs/IMPLEMENTATION_PLAN_V3.md +169 -0
  86. package/docs/IMPLEMENTATION_TASKS.md +1090 -0
  87. package/docs/PHASE3_COVERAGE_TASKS.md +266 -0
  88. package/docs/TAG-BASED-INVALIDATION-PLAN.md +367 -0
  89. package/docs/UNIFIED-INVALIDATE-PLAN.md +229 -0
  90. package/package.json +11 -4
  91. package/dist/inteceptor/cache-invalidate.interceptor.js.map +0 -1
  92. package/dist/inteceptor/cache.interceptor.js.map +0 -1
  93. /package/dist/{inteceptor → interceptor}/cache-invalidate.interceptor.d.ts +0 -0
  94. /package/dist/{inteceptor → interceptor}/cache-invalidate.interceptor.js +0 -0
  95. /package/dist/{inteceptor → interceptor}/cache.interceptor.d.ts +0 -0
package/README.md CHANGED
@@ -1,63 +1,33 @@
1
1
  # @nathapp/nestjs-cache
2
2
 
3
- Enterprise-grade caching library for NestJS applications with support for multiple caching strategies, TTL shorthands, and multi-tier caching.
3
+ Enterprise-grade caching module for NestJS with multi-tier storage, tag-based invalidation, and distributed synchronization.
4
+
5
+ Built on top of [Cacheable](https://cacheable.org) and [Keyv](https://keyv.org) for high-performance L1/L2 caching.
4
6
 
5
7
  ## Features
6
8
 
7
- - 🚀 **Multiple Caching Strategies**
8
- - Memory (In-memory LRU cache)
9
- - Distributed (Redis/Valkey)
10
- - Multi-Tier (L1 Memory + L2 Redis)
11
- - Legacy (@nestjs/cache-manager compatibility)
12
-
13
- - 🎯 **Zero Breaking Changes**
14
- - Drop-in replacement for @nestjs/cache-manager
15
- - Opt-in migration path
16
- - Full backward compatibility
17
-
18
- - ⚡ **Performance Optimized**
19
- - Non-blocking cache operations
20
- - Background refresh capabilities
21
- - Efficient SCAN-based pattern invalidation
22
- - LRU eviction for memory management
23
-
24
- - 🔧 **Developer Experience**
25
- - TTL shorthand notation (`'1m'`, `'1h'`, `'1d'`)
26
- - Type-safe cache keys
27
- - Cache statistics and monitoring
28
- - Pattern-based invalidation
9
+ - **Multiple strategies**: Memory, Distributed (Redis), Multi-Tier (L1 + L2), Legacy
10
+ - **Tag-based invalidation**: O(m) bulk cache clearing using Redis Sets
11
+ - **Distributed sync**: Automatic cross-instance cache synchronization via CacheableSync
12
+ - **Unified API**: Single `invalidate()` method with mode overloads (`key`, `pattern`, `tag`)
13
+ - **Redis URI support**: Parse `redis://` and `rediss://` URIs into connection objects
14
+ - **Metrics hooks**: Monitor hits, misses, sets, deletes, and errors
15
+ - **Health checks**: Built-in health check interface
16
+ - **Namespace support**: Isolated cache namespaces with auto-prefixed tags
17
+ - **Graceful degradation**: Fallback to memory when Redis is unavailable (MULTI_TIER)
18
+ - **Non-blocking mode**: Background L2 updates for low-latency responses
29
19
 
30
20
  ## Installation
31
21
 
32
22
  ```bash
33
- # For enhanced mode (MEMORY, DISTRIBUTED, or MULTI_TIER)
34
- npm install @nathapp/nestjs-cache cacheable @keyv/redis @qified/redis
35
-
36
- # For legacy mode only
37
- npm install @nathapp/nestjs-cache @nestjs/cache-manager cache-manager
23
+ npm install @nathapp/nestjs-cache cacheable @keyv/redis
24
+ # For distributed sync (MULTI_TIER with multiple instances):
25
+ npm install @qified/redis
38
26
  ```
39
27
 
40
28
  ## Quick Start
41
29
 
42
- ### Legacy Mode (Default)
43
-
44
- ```typescript
45
- import { Module } from '@nestjs/common';
46
- import { CacheModule } from '@nathapp/nestjs-cache';
47
-
48
- @Module({
49
- imports: [
50
- CacheModule.register({
51
- // No strategy specified = LEGACY mode
52
- // Works exactly as before with @nestjs/cache-manager
53
- isGlobal: true,
54
- }),
55
- ],
56
- })
57
- export class AppModule {}
58
- ```
59
-
60
- ### Memory Cache
30
+ ### Memory Strategy (Single Instance)
61
31
 
62
32
  ```typescript
63
33
  import { CacheModule, CacheStrategy } from '@nathapp/nestjs-cache';
@@ -67,138 +37,68 @@ import { CacheModule, CacheStrategy } from '@nathapp/nestjs-cache';
67
37
  CacheModule.register({
68
38
  strategy: CacheStrategy.MEMORY,
69
39
  memory: {
70
- lruSize: 1000, // Maximum items in LRU cache
71
- ttl: '1h', // Time-to-live (supports shorthand)
72
- checkPeriod: 60000, // Check for expired items every 60s
40
+ lruSize: 1000,
41
+ ttl: '5m',
73
42
  },
74
- isGlobal: true,
75
43
  }),
76
44
  ],
77
45
  })
78
46
  export class AppModule {}
79
47
  ```
80
48
 
81
- ### Distributed Cache (Redis/Valkey)
49
+ ### Distributed Strategy (Redis Only)
82
50
 
83
51
  ```typescript
84
- import { CacheModule, CacheStrategy } from '@nathapp/nestjs-cache';
85
-
86
- @Module({
87
- imports: [
88
- CacheModule.register({
89
- strategy: CacheStrategy.DISTRIBUTED,
90
- distributed: {
91
- url: 'redis://localhost:6379/0', // Full Redis URL
92
- // OR use individual options:
93
- // host: 'localhost',
94
- // port: 6379,
95
- // password: 'secret',
96
- // db: 0,
97
- ttl: '1h',
98
- keyPrefix: 'myapp:',
99
- },
100
- isGlobal: true,
101
- }),
102
- ],
52
+ CacheModule.register({
53
+ strategy: CacheStrategy.DISTRIBUTED,
54
+ distributed: {
55
+ host: 'localhost',
56
+ port: 6379,
57
+ ttl: '10m',
58
+ },
103
59
  })
104
- export class AppModule {}
105
60
  ```
106
61
 
107
- ### Multi-Tier Cache (L1 + L2)
108
-
109
- Multi-tier caching provides the best of both worlds: fast in-memory cache (L1) with Redis persistence (L2).
62
+ ### Multi-Tier Strategy (L1 Memory + L2 Redis)
110
63
 
111
64
  ```typescript
112
- import { CacheModule, CacheStrategy } from '@nathapp/nestjs-cache';
113
-
114
- @Module({
115
- imports: [
116
- CacheModule.register({
117
- strategy: CacheStrategy.MULTI_TIER,
118
- memory: {
119
- lruSize: 500,
120
- ttl: '5m', // L1 cache for 5 minutes (fast access)
121
- },
122
- distributed: {
123
- url: 'redis://localhost:6379/0',
124
- ttl: '1h', // L2 cache for 1 hour (persistent)
125
- keyPrefix: 'myapp:',
126
- },
127
- nonBlocking: true, // Don't block on cache misses
128
- refreshThreshold: 0.2, // Refresh when 20% TTL remaining
129
- isGlobal: true,
130
- }),
131
- ],
65
+ CacheModule.register({
66
+ strategy: CacheStrategy.MULTI_TIER,
67
+ memory: {
68
+ lruSize: 500,
69
+ ttl: '1m',
70
+ },
71
+ distributed: {
72
+ url: 'redis://localhost:6379',
73
+ ttl: '10m',
74
+ },
132
75
  })
133
- export class AppModule {}
134
- ```
135
-
136
- **How Multi-Tier Works:**
137
- 1. **Cache Hit (L1)**: Value returned immediately from memory
138
- 2. **Cache Miss (L1), Hit (L2)**: Value fetched from Redis and populated to L1
139
- 3. **Cache Miss (Both)**: Value computed, stored in both L1 and L2
140
- 4. **Background Refresh**: Values automatically refreshed before expiration
141
-
142
- ## Configuration Options
143
-
144
- ### Cache Strategies
145
-
146
- | Strategy | Description | Use Case |
147
- |----------|-------------|----------|
148
- | `LEGACY` | Uses @nestjs/cache-manager | Existing apps, no migration needed |
149
- | `MEMORY` | In-memory LRU cache | Single-instance apps, fast access |
150
- | `DISTRIBUTED` | Redis/Valkey cache | Multi-instance apps, shared cache |
151
- | `MULTI_TIER` | L1 (memory) + L2 (Redis) | High-performance, multi-instance apps |
152
-
153
- ### TTL Shorthand Notation
154
-
155
- Enhanced mode supports convenient TTL notation:
156
-
157
- ```typescript
158
- ttl: '30s' // 30 seconds
159
- ttl: '5m' // 5 minutes
160
- ttl: '1h' // 1 hour
161
- ttl: '7d' // 7 days
162
- ttl: 300000 // 300,000 milliseconds (also supported)
163
76
  ```
164
77
 
165
- ### Memory Cache Options
78
+ ### Redis URI Configuration
166
79
 
167
80
  ```typescript
168
- interface MemoryCacheOptions {
169
- lruSize?: number; // Max items in cache (default: 1000)
170
- ttl?: number | string; // Time-to-live (supports shorthand)
171
- checkPeriod?: number; // Expired item check interval (default: 60000ms)
172
- }
173
- ```
174
-
175
- ### Distributed Cache Options
176
-
177
- ```typescript
178
- interface DistributedCacheOptions {
179
- url?: string; // Full Redis URL (takes precedence)
180
- host?: string; // Redis host (default: 'localhost')
181
- port?: number; // Redis port (default: 6379)
182
- password?: string; // Redis password
183
- db?: number; // Redis database number (default: 0)
184
- ttl?: number | string; // Time-to-live (supports shorthand)
185
- keyPrefix?: string; // Key prefix for all cache keys
186
- }
81
+ CacheModule.register({
82
+ strategy: CacheStrategy.DISTRIBUTED,
83
+ distributed: {
84
+ url: 'redis://username:password@redis.example.com:6379/0',
85
+ ttl: '10m',
86
+ },
87
+ })
187
88
  ```
188
89
 
189
- ### Enhanced Options
90
+ Individual fields override URI-parsed values:
190
91
 
191
92
  ```typescript
192
- interface EnhancedOptions {
193
- nonBlocking?: boolean; // Enable non-blocking operations (default: false)
194
- refreshThreshold?: number; // Refresh threshold ratio 0-1 (default: 0.2)
195
- isGlobal?: boolean; // Register as global module (default: false)
93
+ distributed: {
94
+ url: 'redis://localhost:6379',
95
+ port: 6380, // Overrides port from URI
196
96
  }
197
97
  ```
198
98
 
199
99
  ## Usage
200
100
 
201
- ### Basic Operations
101
+ ### Basic Cache Operations
202
102
 
203
103
  ```typescript
204
104
  import { Injectable } from '@nestjs/common';
@@ -206,373 +106,383 @@ import { CacheManager } from '@nathapp/nestjs-cache';
206
106
 
207
107
  @Injectable()
208
108
  export class UserService {
209
- constructor(private cacheManager: CacheManager) {}
109
+ constructor(private readonly cache: CacheManager) {}
210
110
 
211
111
  async getUser(id: string) {
212
- // Get or set pattern
213
- return this.cacheManager.get(
214
- ['user', id],
215
- async () => {
216
- // Fetch from database if not cached
217
- return this.database.findUser(id);
218
- },
219
- '1h' // Cache for 1 hour
112
+ // Get with resolver (cache-aside pattern)
113
+ return this.cache.get(
114
+ ['USER', id],
115
+ async () => this.userRepository.findById(id),
116
+ 60000, // TTL in ms
220
117
  );
221
118
  }
222
119
 
223
- async updateUser(id: string, data: any) {
224
- await this.database.updateUser(id, data);
225
-
226
- // Invalidate cache
227
- await this.cacheManager.invalidate(['user', id]);
228
- }
229
-
230
- async getOnly(id: string) {
231
- // Get only (no fallback)
232
- return this.cacheManager.getOnly(['user', id]);
233
- }
234
-
235
- async set(id: string, user: any) {
236
- // Set explicitly
237
- await this.cacheManager.set(['user', id], user, '30m');
120
+ async updateUser(id: string, data: UpdateUserDto) {
121
+ await this.userRepository.update(id, data);
122
+ // Invalidate cached user
123
+ await this.cache.invalidate(['USER', id]);
238
124
  }
239
125
  }
240
126
  ```
241
127
 
242
- ### Multiple Operations
128
+ ### Tag-Based Invalidation
243
129
 
244
- ```typescript
245
- // Multiple get
246
- const users = await this.cacheManager.mget(['user:1', 'user:2', 'user:3']);
247
-
248
- // Multiple set
249
- await this.cacheManager.mset([
250
- { key: 'user:1', value: user1, ttl: '1h' },
251
- { key: 'user:2', value: user2, ttl: '1h' },
252
- { key: 'user:3', value: user3, ttl: '1h' },
253
- ]);
254
- ```
255
-
256
- ### Pattern-Based Invalidation
130
+ Tags allow efficient bulk invalidation of related cache entries. Instead of scanning the entire keyspace (O(n)), tags use Redis Sets for O(m) complexity where m = number of tagged keys.
257
131
 
258
132
  ```typescript
259
- // Invalidate all user caches (fast SCAN-based)
260
- await this.cacheManager.invalidateByPattern('user:*');
261
-
262
- // Count keys before deleting
263
- const invalidator = new RedisPatternInvalidation(cacheable);
264
- const count = await invalidator.countByPattern('session:*');
265
- console.log(`About to delete ${count} keys`);
133
+ @Injectable()
134
+ export class PostService {
135
+ constructor(private readonly cache: CacheManager) {}
136
+
137
+ async getPost(userId: string, postId: string) {
138
+ return this.cache.get(
139
+ ['USER', userId, 'POST', postId],
140
+ async () => this.postRepository.findOne(postId),
141
+ { tags: ['USER:' + userId + ':POSTS', 'USER:' + userId] },
142
+ );
143
+ }
266
144
 
267
- // Delete multiple patterns
268
- await invalidator.deleteByPatterns(['user:*', 'session:*', 'cache:*']);
269
- ```
145
+ async setPost(userId: string, postId: string, data: Post) {
146
+ await this.cache.set(
147
+ ['USER', userId, 'POST', postId],
148
+ data,
149
+ 60000,
150
+ { tags: ['USER:' + userId + ':POSTS', 'USER:' + userId] },
151
+ );
152
+ }
270
153
 
271
- ### Cache Statistics
154
+ async deleteAllUserPosts(userId: string) {
155
+ // Invalidate all posts for a user in one call (O(m))
156
+ await this.cache.invalidate(
157
+ ['USER', userId, 'POSTS'],
158
+ { mode: 'tag' },
159
+ );
160
+ }
272
161
 
273
- ```typescript
274
- // Get cache statistics (enhanced mode only)
275
- const stats = await this.cacheManager.getStats();
276
- console.log('Cache stats:', stats);
277
- // Output: { hits: 1500, misses: 300, keys: 250 }
278
-
279
- // Check cache mode
280
- if (this.cacheManager.isEnhancedMode()) {
281
- console.log('Using cacheable (enhanced mode)');
282
- } else {
283
- console.log('Using cache-manager (legacy mode)');
162
+ async deleteAllUserData(userId: string) {
163
+ // Invalidate everything for a user
164
+ await this.cache.invalidate(
165
+ ['USER', userId],
166
+ { mode: 'tag' },
167
+ );
168
+ }
284
169
  }
285
170
  ```
286
171
 
287
- ### Cache Invalidation Strategies
172
+ ### `get()` Overloads
288
173
 
289
174
  ```typescript
290
- // Invalidate single key
291
- await this.cacheManager.invalidate(['user', '123']);
292
-
293
- // Invalidate by group (pattern)
294
- await this.cacheManager.invalidate(['user', '*'], true);
295
-
296
- // Multiple invalidations
297
- await this.cacheManager.mInvalidate([
298
- { cacheKeysParts: ['user', '1'] },
299
- { cacheKeysParts: ['user', '2'] },
300
- { cacheKeysParts: ['session', '*'], group: true },
301
- ]);
302
- ```
175
+ // Basic get (returns cached value or null)
176
+ const value = await cache.get<User>(['USER', '123']);
303
177
 
304
- ## Advanced Configuration
178
+ // Get with resolver (cache-aside)
179
+ const user = await cache.get(['USER', '123'], () => fetchUser('123'));
305
180
 
306
- ### Async Configuration
181
+ // Get with resolver and explicit TTL
182
+ const user = await cache.get(['USER', '123'], () => fetchUser('123'), 60000);
307
183
 
308
- ```typescript
309
- import { ConfigService } from '@nestjs/config';
184
+ // Get with resolver and tags (default 300s TTL)
185
+ const user = await cache.get(['USER', '123'], () => fetchUser('123'), {
186
+ tags: ['USER:123'],
187
+ });
310
188
 
311
- @Module({
312
- imports: [
313
- CacheModule.registerAsync({
314
- inject: [ConfigService],
315
- useFactory: (config: ConfigService) => ({
316
- strategy: config.get('CACHE_STRATEGY') as CacheStrategy,
317
- memory: {
318
- lruSize: config.get('CACHE_LRU_SIZE', 1000),
319
- ttl: config.get('CACHE_MEMORY_TTL', '5m'),
320
- },
321
- distributed: {
322
- url: config.get('REDIS_URL'),
323
- ttl: config.get('CACHE_REDIS_TTL', '1h'),
324
- keyPrefix: config.get('CACHE_KEY_PREFIX', 'app:'),
325
- },
326
- nonBlocking: config.get('CACHE_NON_BLOCKING', true),
327
- refreshThreshold: config.get('CACHE_REFRESH_THRESHOLD', 0.2),
328
- isGlobal: true,
329
- }),
330
- }),
331
- ],
332
- })
333
- export class AppModule {}
189
+ // Get with resolver, TTL, and tags
190
+ const user = await cache.get(['USER', '123'], () => fetchUser('123'), 60000, {
191
+ tags: ['USER:123'],
192
+ });
334
193
  ```
335
194
 
336
- ### Environment Variables
195
+ ### Unified `invalidate()` API
337
196
 
338
- ```bash
339
- # Cache strategy
340
- CACHE_STRATEGY=MULTI_TIER
197
+ ```typescript
198
+ // Exact key deletion (default)
199
+ await cache.invalidate(['USER', '123']);
341
200
 
342
- # Memory cache
343
- CACHE_LRU_SIZE=1000
344
- CACHE_MEMORY_TTL=5m
201
+ // Explicit mode: exact key
202
+ await cache.invalidate(['USER', '123'], { mode: 'key' });
345
203
 
346
- # Redis cache
347
- REDIS_URL=redis://localhost:6379/0
348
- CACHE_REDIS_TTL=1h
349
- CACHE_KEY_PREFIX=myapp:
204
+ // Tag-based invalidation (O(m))
205
+ await cache.invalidate(['USER:123:POSTS'], { mode: 'tag' });
350
206
 
351
- # Performance options
352
- CACHE_NON_BLOCKING=true
353
- CACHE_REFRESH_THRESHOLD=0.2
207
+ // Backward compatibility: group=true now maps to tag mode
208
+ await cache.invalidate(['USER', '123'], true);
354
209
  ```
355
210
 
356
- ### Custom Key Resolution
211
+ ### Batch Invalidation
357
212
 
358
213
  ```typescript
359
- // Array keys are joined with ':'
360
- this.cacheManager.resolveKey(['user', '123', 'profile']);
361
- // Returns: 'user:123:profile'
362
-
363
- // String keys are used as-is
364
- this.cacheManager.resolveKey('custom-key');
365
- // Returns: 'custom-key'
214
+ await cache.mInvalidate([
215
+ { cacheKey: ['USER', '123'], mode: 'key' },
216
+ { cacheKey: ['USER:456:POSTS'], mode: 'tag' },
217
+ { cacheKey: ['SESSION:789'], mode: 'key' },
218
+ ]);
366
219
  ```
367
220
 
368
- ## Migration Guide
221
+ ### Namespaced Cache
369
222
 
370
- See [MIGRATION.md](./MIGRATION.md) for detailed migration instructions from @nestjs/cache-manager to the new cacheable-based implementation.
223
+ ```typescript
224
+ const postCache = cache.namespace('POSTS');
371
225
 
372
- ### Migration Path Summary
226
+ // All keys are auto-prefixed: POSTS:123
227
+ await postCache.set(['123'], postData, 60000, {
228
+ tags: ['AUTHOR:456'], // Stored as POSTS:AUTHOR:456
229
+ });
373
230
 
374
- 1. **No Changes Required**: Continue using legacy mode (default)
375
- 2. **Test in Development**: Switch to `MEMORY` strategy
376
- 3. **Production Migration**: Move to `DISTRIBUTED` or `MULTI_TIER`
377
- 4. **Optimize**: Enable `nonBlocking` and tune `refreshThreshold`
231
+ // Invalidate within namespace
232
+ await postCache.invalidate(['AUTHOR:456'], { mode: 'tag' });
378
233
 
379
- ## Performance Best Practices
234
+ // Invalidate all keys in namespace
235
+ await postCache.invalidateAll();
236
+ ```
380
237
 
381
- ### Multi-Tier Strategy
238
+ ### Metrics
382
239
 
383
240
  ```typescript
384
241
  CacheModule.register({
385
- strategy: CacheStrategy.MULTI_TIER,
386
- memory: {
387
- lruSize: 500, // Smaller L1 for hot data
388
- ttl: '5m', // Short L1 TTL
389
- },
390
- distributed: {
391
- ttl: '1h', // Longer L2 TTL
242
+ strategy: CacheStrategy.DISTRIBUTED,
243
+ distributed: { host: 'localhost', port: 6379 },
244
+ metrics: {
245
+ onCacheHit: (ctx) => console.log(`HIT ${ctx.key} ${ctx.durationMs}ms`),
246
+ onCacheMiss: (ctx) => console.log(`MISS ${ctx.key}`),
247
+ onCacheSet: (ctx) => console.log(`SET ${ctx.key} ttl=${ctx.ttl}`),
248
+ onCacheDelete: (ctx) => console.log(`DEL ${ctx.key}`),
249
+ onCacheError: (ctx) => console.error(`ERR ${ctx.key}`, ctx.error),
392
250
  },
393
- nonBlocking: true, // Critical for performance
394
- refreshThreshold: 0.2, // Proactive refresh
395
251
  })
396
252
  ```
397
253
 
398
- ### Non-Blocking Operations
399
-
400
- When `nonBlocking: true`:
401
- - Cache misses don't block request processing
402
- - Stale data served while refresh happens in background
403
- - Significantly improves response times under load
404
-
405
- ### Pattern Invalidation
254
+ ### Health Check
406
255
 
407
256
  ```typescript
408
- // ❌ Slow: Uses Redis KEYS command (blocks server)
409
- await this.cacheManager.invalidate(['user', '*'], true);
410
-
411
- // ✅ Fast: Uses Redis SCAN command (non-blocking)
412
- await this.cacheManager.invalidateByPattern('user:*');
257
+ const health = await cache.isHealthy();
258
+ // {
259
+ // healthy: true,
260
+ // timestamp: Date,
261
+ // connections: [
262
+ // { name: 'memory', status: 'connected' },
263
+ // { name: 'redis', status: 'connected', latencyMs: 2 }
264
+ // ],
265
+ // stats: { ... }
266
+ // }
413
267
  ```
414
268
 
415
- ### TTL Strategy
269
+ ### Distributed Synchronization (CacheableSync)
416
270
 
417
- ```typescript
418
- // Hot data: Short L1, longer L2
419
- memory: { ttl: '5m' },
420
- distributed: { ttl: '1h' },
271
+ For multi-instance deployments using `MULTI_TIER`, cache synchronization is **automatically enabled**. When one instance sets or deletes a key, all other instances update their L1 (memory) caches via Redis Pub/Sub.
421
272
 
422
- // Cold data: No L1, long L2
423
- memory: { ttl: '1m' },
424
- distributed: { ttl: '24h' },
425
-
426
- // Session data: Equal TTLs
427
- memory: { ttl: '30m' },
428
- distributed: { ttl: '30m' },
273
+ ```typescript
274
+ CacheModule.register({
275
+ strategy: CacheStrategy.MULTI_TIER,
276
+ memory: { ttl: '1m' },
277
+ distributed: { host: 'localhost', port: 6379, ttl: '10m' },
278
+ // sync is enabled by default for MULTI_TIER
279
+ // To disable: sync: { enabled: false }
280
+ })
429
281
  ```
430
282
 
431
- ## Troubleshooting
432
-
433
- ### Module Not Found: 'cacheable'
283
+ To use a custom namespace for sync isolation:
434
284
 
435
- Install required dependencies:
436
- ```bash
437
- npm install cacheable @keyv/redis @qified/redis
285
+ ```typescript
286
+ sync: {
287
+ enabled: true,
288
+ namespace: 'my-service',
289
+ }
438
290
  ```
439
291
 
440
- ### Redis Connection Issues
292
+ ### Tag Configuration
441
293
 
442
294
  ```typescript
443
- // Test connection
444
- distributed: {
445
- url: process.env.REDIS_URL,
446
- // Add connection retry logic in your ConfigService
447
- }
295
+ CacheModule.register({
296
+ strategy: CacheStrategy.DISTRIBUTED,
297
+ distributed: { host: 'localhost', port: 6379 },
298
+ tags: {
299
+ enabled: true, // default: true when Redis available
300
+ tagPrefix: '_TAG:', // prefix for tag sets in Redis
301
+ tagTtl: 86400, // tag set TTL in seconds (24h)
302
+ maxTagsPerKey: 10, // max tags per cache entry
303
+ maxKeysPerTag: 10000, // safety limit per tag set
304
+ },
305
+ })
448
306
  ```
449
307
 
450
- ### Cache Not Working
308
+ ## Cache Interceptor
309
+
310
+ Automatically cache HTTP responses:
451
311
 
452
312
  ```typescript
453
- // Verify cache mode
454
- if (this.cacheManager.isEnhancedMode()) {
455
- const stats = await this.cacheManager.getStats();
456
- console.log('Cache is working:', stats);
457
- } else {
458
- console.log('Using legacy mode');
313
+ import { CacheInterceptor, CacheReqOptions } from '@nathapp/nestjs-cache';
314
+
315
+ @Controller('users')
316
+ @UseInterceptors(CacheInterceptor)
317
+ export class UserController {
318
+ @Get(':id')
319
+ @CacheReqOptions({ ttl: 60000 })
320
+ getUser(@Param('id') id: string) {
321
+ return this.userService.findById(id);
322
+ }
459
323
  }
460
324
  ```
461
325
 
462
- ### Pattern Invalidation Not Working
326
+ ## Strategies Comparison
463
327
 
464
- Ensure you're using `DISTRIBUTED` or `MULTI_TIER` strategy with a valid Redis connection.
328
+ | Feature | MEMORY | DISTRIBUTED | MULTI_TIER | LEGACY |
329
+ |---------|--------|------------|------------|--------|
330
+ | L1 (Memory) | ✅ | ❌ | ✅ | ✅ |
331
+ | L2 (Redis) | ❌ | ✅ | ✅ | ❌ |
332
+ | Tag Invalidation | ❌ | ✅ | ✅ | ⚠️ Limited |
333
+ | Cross-Instance Sync | N/A | N/A | ✅ Auto | ❌ |
334
+ | Graceful Degradation | N/A | ✅ | ✅ | N/A |
335
+ | Non-Blocking | N/A | N/A | ✅ | N/A |
336
+ | Recommended | Dev/Test | Single Redis | **Production** | Migration only |
465
337
 
466
- ## API Reference
338
+ ## Migration from Legacy
467
339
 
468
- ### CacheManager Methods
469
-
470
- | Method | Description | Mode |
471
- |--------|-------------|------|
472
- | `get(key, resolver?, ttl?)` | Get or set cache value | Both |
473
- | `getOnly(key)` | Get cache value only | Both |
474
- | `set(key, value, ttl?)` | Set cache value | Both |
475
- | `mget(keys)` | Get multiple values | Both |
476
- | `mset(items)` | Set multiple values | Both |
477
- | `invalidate(key, group?)` | Invalidate cache | Both |
478
- | `mInvalidate(items)` | Invalidate multiple keys | Both |
479
- | `invalidateByPattern(pattern)` | Efficient pattern invalidation | Enhanced |
480
- | `reset()` | Clear all cache | Both |
481
- | `keys()` | Get all cache keys | Legacy only |
482
- | `getStats()` | Get cache statistics | Enhanced only |
483
- | `isEnhancedMode()` | Check cache mode | Both |
484
-
485
- ### RedisPatternInvalidation Methods
340
+ ### Before (Legacy)
486
341
 
487
- | Method | Description |
488
- |--------|-------------|
489
- | `deleteByPattern(pattern, batchSize?)` | Delete keys matching pattern |
490
- | `deleteByPatterns(patterns, batchSize?)` | Delete multiple patterns |
491
- | `countByPattern(pattern, batchSize?)` | Count keys without deleting |
342
+ ```typescript
343
+ import { CacheModule } from '@nathapp/nestjs-cache';
492
344
 
493
- ## Examples
345
+ CacheModule.register({
346
+ // No strategy = LEGACY by default
347
+ ttl: 300,
348
+ })
349
+ ```
494
350
 
495
- ### E-commerce Application
351
+ ### After (Enhanced)
496
352
 
497
353
  ```typescript
498
- @Module({
499
- imports: [
500
- CacheModule.register({
501
- strategy: CacheStrategy.MULTI_TIER,
502
- memory: {
503
- lruSize: 1000,
504
- ttl: '10m', // Product catalog hot data
505
- },
506
- distributed: {
507
- url: process.env.REDIS_URL,
508
- ttl: '1h', // Shared across instances
509
- keyPrefix: 'shop:',
510
- },
511
- nonBlocking: true,
512
- isGlobal: true,
513
- }),
514
- ],
354
+ import { CacheModule, CacheStrategy } from '@nathapp/nestjs-cache';
355
+
356
+ CacheModule.register({
357
+ strategy: CacheStrategy.MULTI_TIER,
358
+ memory: { lruSize: 1000, ttl: '5m' },
359
+ distributed: { host: 'localhost', port: 6379, ttl: '10m' },
515
360
  })
516
- export class AppModule {}
517
361
  ```
518
362
 
519
- ### Microservices Architecture
363
+ The `CacheManager` API is backward compatible — `get()`, `set()`, `invalidate()` all work the same way with enhanced strategies.
364
+
365
+ ---
366
+
367
+ ## Deprecated APIs
368
+
369
+ > ⚠️ The following APIs are deprecated and will be removed in a future major release. Please migrate to the recommended alternatives.
370
+
371
+ ### `InvalidateStrategy.BROKER`
372
+
373
+ **Deprecated.** Cross-instance cache invalidation is now handled by `CacheableSync` (built into `Cacheable`).
520
374
 
521
375
  ```typescript
522
- // Service A (Product Service)
376
+ // ❌ Deprecated
523
377
  CacheModule.register({
524
- strategy: CacheStrategy.DISTRIBUTED,
525
- distributed: {
526
- url: process.env.REDIS_URL,
527
- ttl: '30m',
528
- keyPrefix: 'product-svc:',
378
+ invalidate: {
379
+ strategy: InvalidateStrategy.BROKER,
380
+ transport: Transport.REDIS,
381
+ options: { host: 'localhost', port: 6379 },
529
382
  },
530
383
  })
531
384
 
532
- // Service B (User Service)
385
+ // ✅ Replacement — use MULTI_TIER strategy (sync is automatic)
533
386
  CacheModule.register({
534
387
  strategy: CacheStrategy.MULTI_TIER,
535
- memory: { lruSize: 500, ttl: '5m' },
536
- distributed: {
537
- url: process.env.REDIS_URL,
538
- ttl: '1h',
539
- keyPrefix: 'user-svc:',
540
- },
388
+ distributed: { host: 'localhost', port: 6379 },
541
389
  })
542
390
  ```
543
391
 
544
- ### High-Traffic API
392
+ ### `CacheInvalidateManager` / `RedisCacheInvalidateManager`
393
+
394
+ **Deprecated.** These classes are replaced by `CacheableSync` for enhanced strategies. They remain functional only for `CacheStrategy.LEGACY`.
395
+
396
+ ### `invalidateByTag()` / `invalidateByTags()`
397
+
398
+ **Deprecated.** Use the unified `invalidate()` API with `{ mode: 'tag' }` instead.
545
399
 
546
400
  ```typescript
547
- CacheModule.register({
548
- strategy: CacheStrategy.MULTI_TIER,
549
- memory: {
550
- lruSize: 2000, // Large L1 for high traffic
551
- ttl: '1m', // Short L1, frequent refresh
552
- },
553
- distributed: {
554
- url: process.env.REDIS_URL,
555
- ttl: '10m',
556
- keyPrefix: 'api:',
557
- },
558
- nonBlocking: true,
559
- refreshThreshold: 0.3, // Early refresh for availability
560
- isGlobal: true,
561
- })
401
+ // ❌ Deprecated
402
+ await cache.invalidateByTag('USER:123:POSTS');
403
+ await cache.invalidateByTags(['USER:123:POSTS', 'USER:456:POSTS']);
404
+
405
+ // ✅ Replacement
406
+ await cache.invalidate(['USER:123:POSTS'], { mode: 'tag' });
407
+ await cache.mInvalidate([
408
+ { cacheKey: ['USER:123:POSTS'], mode: 'tag' },
409
+ { cacheKey: ['USER:456:POSTS'], mode: 'tag' },
410
+ ]);
562
411
  ```
563
412
 
564
- ## Contributing
413
+ ### `invalidateByPattern()`
565
414
 
566
- Contributions are welcome! Please read the contributing guidelines before submitting PRs.
415
+ **Deprecated.** Pattern-based invalidation uses O(n) SCAN which doesn't scale. Use tag-based invalidation instead.
567
416
 
568
- ## License
417
+ ```typescript
418
+ // ❌ Deprecated — O(n) keyspace scan
419
+ await cache.invalidateByPattern('USER:123:*');
420
+
421
+ // ✅ Replacement — O(m) tag-based
422
+ // First, set entries with tags:
423
+ await cache.set(['USER', '123', 'POST', '1'], data, 60000, {
424
+ tags: ['USER:123:POSTS'],
425
+ });
426
+ // Then invalidate by tag:
427
+ await cache.invalidate(['USER:123:POSTS'], { mode: 'tag' });
428
+ ```
429
+
430
+ > **Note:** If `invalidateByPattern()` is called and a tag registry is available, it will automatically redirect to tag-based invalidation with a deprecation warning.
431
+
432
+ ### `buildRedisUrl()`
433
+
434
+ **Deprecated.** Use `resolveRedisConnection()` to parse URIs into connection objects instead of building URL strings.
435
+
436
+ ```typescript
437
+ // ❌ Deprecated
438
+ const url = buildRedisUrl({ host: 'localhost', port: 6379 });
439
+
440
+ // ✅ Replacement
441
+ const connection = resolveRedisConnection({ host: 'localhost', port: 6379 });
442
+ ```
443
+
444
+ ### `dipatch()` (typo alias)
445
+
446
+ **Deprecated.** Use the correctly spelled `dispatch()` method.
569
447
 
570
- ISC License
448
+ ### `lib/inteceptor/` (typo directory)
571
449
 
572
- ## Support
450
+ **Deprecated.** Imports from `lib/inteceptor/` still work via barrel re-export but the implementation has moved to `lib/interceptor/`.
573
451
 
574
- For issues, questions, or feature requests, please create an issue in the repository.
452
+ ### `CacheStrategy.LEGACY`
575
453
 
576
- ## Credits
454
+ **Deprecated.** The legacy strategy using `@nestjs/cache-manager` is maintained for backward compatibility but will be removed in a future major release. Migrate to `MEMORY`, `DISTRIBUTED`, or `MULTI_TIER`.
455
+
456
+ ---
457
+
458
+ ## API Reference
459
+
460
+ ### `CacheManager`
461
+
462
+ | Method | Description |
463
+ |--------|-------------|
464
+ | `get<T>(keys, resolver?, ttlOrOptions?, options?)` | Get or resolve+cache a value |
465
+ | `getOnly<T>(keys)` | Get without resolver |
466
+ | `set<T>(keys, value, ttl?, options?)` | Set a value with optional tags |
467
+ | `mset<T>(list)` | Set multiple values |
468
+ | `mget(keys)` | Get multiple values |
469
+ | `invalidate(key, options?)` | Unified invalidation (key/pattern/tag modes) |
470
+ | `mInvalidate(list)` | Batch invalidation with mixed modes |
471
+ | `reset()` | Clear all cache entries |
472
+ | `touch(keys, ttl?)` | Extend TTL of a cached item |
473
+ | `namespace(name)` | Create a namespaced cache manager |
474
+ | `isHealthy()` | Health check |
475
+ | `getStats()` | Cache statistics (enhanced mode) |
476
+ | `isEnhancedMode()` | Check if using cacheable |
477
+ | `resolveKey(keyParts)` | Resolve key parts to string |
478
+
479
+ ### `CacheModule`
480
+
481
+ | Method | Description |
482
+ |--------|-------------|
483
+ | `register(options)` | Synchronous registration |
484
+ | `registerAsync(options)` | Async registration with factory |
485
+
486
+ ## License
577
487
 
578
- Developed by William Khoo for the Nathapp ecosystem.
488
+ See the root monorepo license.