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)
- RedisClient: Raw
ioredisinstance, provided by a FactoryProvider Pattern. - RedisRepository: Injectable class implementing
OnModuleDestroyfor connection cleanup. Provides generic methods (get,set,delete,setWithExpiry) with automatic key prefixing via Redis Prefix Key Naming. - RedisService: Domain-specific service (e.g.,
ProductServicefor 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)