A detailed walkthrough of setting up a Redis client in NestJS using the ioredis library with a FactoryProvider pattern and a layered architecture (client → repository → service). Covers caching and short-lived data storage with prefix-based key naming.
Key takeaways
- Uses a FactoryProvider (
redisClientFactory) with injection token'RedisClient'to create a singletonioredisinstance, reading host/port from environment variables. - Introduces a RedisRepository layer that abstracts the Redis client and supports key prefixing (e.g.,
prefix:key), enabling folder-like organization in RedisInsight. - The repository implements
OnModuleDestroyto disconnect the Redis client on application shutdown (triggered byapp.close()orenableShutdownHooks). - A RedisService wraps the repository and provides domain-specific methods (e.g.,
saveProduct,getResetToken), handling JSON serialization and TTL management. - Demonstrates two real-world use cases: caching product data for 1 day, and storing password reset tokens for 10 minutes.
- Uses
RedisPrefixEnumto define data store names as enum values, avoiding hardcoded prefix strings.
Entities and concepts
- Redis
- ioredis
- NestJS
- Cache-aside Pattern
- Redis Prefix Key Naming
- Redis Repository Pattern
- FactoryProvider Pattern
Connections to existing knowledge
This article represents the most architecturally complete direct-ioredis approach among the ingested sources. It shares the same basic pattern as the Medium guide and the bytegoblin tutorial, but adds the FactoryProvider + Repository + Service layering. It contrasts with the cache-manager approach in How to add Redis cache to a NestJS app, which uses NestJS’s built-in CacheModule and CacheInterceptor instead of a hand-rolled Redis service. The bytegoblin article incorrectly references an @nestjs/redis package that does not exist; this article correctly uses ioredis directly. A second Medium article by Dip Ghosh follows the same manual ioredis pattern with a real-world case study: caching hero products reduced DB queries from hundreds of thousands to a few hundred per day (90% reduction) during a sale event.