Appearance
Redis Cache Service
A shared caching layer backed by ioredis. Any module can inject it to read/write cached values or perform pattern-based invalidation.
Interface
typescript
interface IRedisCacheService {
write<T>(key: string, value: T, ttlSeconds: number): Promise<void>;
read<T>(key: string): Promise<T | null>;
invalidate(key: string): Promise<void>;
invalidateByPattern(pattern: string): Promise<void>;
getClient(): Redis;
}| Method | Description |
|---|---|
write | JSON-serializes the value and stores it with SET ... EX. |
read | Returns the parsed value or null if the key does not exist. |
invalidate | Deletes a single key (DEL). |
invalidateByPattern | Uses SCAN + DEL in batches of 100 (never KEYS). |
getClient | Returns the raw ioredis client for advanced operations (e.g., Lua scripts). |
Telemetry Lifecycle
RedisCacheServiceno longer owns Redis metrics timing, error handling, or prefix parsing.RedisMetricsService.recordOperation(...)wraps the Redis callback, measures duration, records operation errors, and resolves the key prefix internally.- The callback receives telemetry helpers for read-specific signals:
typescript
await this.redisMetricsService.recordOperation({
operation: 'get',
key,
execute: async (telemetry) => {
const raw = await this.client.get(key);
if (raw === null) {
telemetry.recordCacheMiss();
return null;
}
telemetry.recordCacheHit();
return JSON.parse(raw) as T;
},
});- Pattern invalidation passes
keyKind: 'pattern'so the metrics service can derive the prefix from values likesession:*without duplicating parsing logic in the cache service.
Injection
typescript
import { RedisCacheServiceKey } from '@api/shared/application/services/redis-cache.service.interface';
import type { IRedisCacheService } from '@api/shared/application/services/redis-cache.service.interface';
constructor(
@Inject(RedisCacheServiceKey)
private readonly cache: IRedisCacheService,
) {}Environment Variables
| Variable | Required | Default | Description |
|---|---|---|---|
REDIS_HOST | Yes | — | Redis server hostname |
REDIS_PORT | No | 6379 | Redis server port |
REDIS_PASSWORD | Yes | — | Redis authentication password |
Lifecycle
OnModuleInit: Connects to Redis and sends aPINGto verify connectivity.OnModuleDestroy: Gracefully closes the connection withQUIT.