Skip to content

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;
}
MethodDescription
writeJSON-serializes the value and stores it with SET ... EX.
readReturns the parsed value or null if the key does not exist.
invalidateDeletes a single key (DEL).
invalidateByPatternUses SCAN + DEL in batches of 100 (never KEYS).
getClientReturns the raw ioredis client for advanced operations (e.g., Lua scripts).

Telemetry Lifecycle

  • RedisCacheService no 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 like session:* 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

VariableRequiredDefaultDescription
REDIS_HOSTYesRedis server hostname
REDIS_PORTNo6379Redis server port
REDIS_PASSWORDYesRedis authentication password

Lifecycle

  • OnModuleInit: Connects to Redis and sends a PING to verify connectivity.
  • OnModuleDestroy: Gracefully closes the connection with QUIT.