The Redis Repository Pattern is a design pattern for NestJS Redis integration that inserts a repository abstraction layer between the raw Redis client and domain services. It encapsulates Redis-specific operations (key prefixing, serialization, connection lifecycle) behind a clean interface.

Three-layer architecture

RedisClient (ioredis) → RedisRepository → RedisService (domain)
  1. RedisClient: Raw ioredis instance, provided by a FactoryProvider Pattern.
  2. RedisRepository: Injectable class implementing OnModuleDestroy for connection cleanup. Provides generic methods (get, set, delete, setWithExpiry) with automatic key prefixing via Redis Prefix Key Naming.
  3. RedisService: Domain-specific service (e.g., ProductService for caching) that uses the repository and handles business logic like JSON serialization and TTL decisions.

Rationale

  • Decouples domain code from Redis API changes
  • Centralizes connection lifecycle management
  • Makes testing easier (mock the repository, not Redis)