Loading
Portfolio
Rayden Li
Redis · NestJS
Redis is an in-memory data store that is especially useful in NestJS applications for caching, distributed state, background jobs, rate limiting, and real-time features. In a typical NestJS backend, Redis complements your primary database by handling fast, temporary, or shared operational data.
NestJS applications are often deployed as multiple instances behind a load balancer. In that setup, in-memory data stored inside one Node.js process is not visible to other instances. Redis provides a shared, fast data layer that all NestJS instances can access.
| Need | Redis role in NestJS |
|---|---|
| Reduce database load | Cache expensive queries and API responses |
| Support multiple app instances | Share sessions, cache, locks, and counters |
| Handle slow operations | Queue background jobs with BullMQ |
| Protect APIs | Implement rate limiting and throttling |
| Coordinate services | Publish/subscribe events and distributed locks |
| Improve user experience | Store temporary data such as OTPs, carts, and presence |
The most common Redis use case is caching data that is expensive to compute or frequently requested.
Examples:
NestJS supports Redis through @nestjs/cache-manager and a Redis adapter such as @keyv/redis. The cache can be used manually with get(), set(), and del(), or automatically for HTTP responses using CacheInterceptor. [web:16]
@Injectable()
export class ProductService {
constructor(
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
private readonly productRepository: ProductRepository,
) {}
async getProduct(id: string) {
const cacheKey = `product:${id}`;
const cached = await this.cacheManager.get(cacheKey);
if (cached) {
return cached;
}
const product = await this.productRepository.findById(id);
await this.cacheManager.set(cacheKey, product, 60_000);
return product;
}
}
Do not cache mutating operations. NestJS documentation specifically warns that business operations should not be cached; caching is appropriate for data queries. [web:16]
For read-heavy REST APIs, Redis can cache entire controller responses.
@Controller('products')
@UseInterceptors(CacheInterceptor)
export class ProductController {
@Get()
findAll() {
return this.productService.findAll();
}
}
By default, NestJS caches GET endpoints and generates a cache key from the request URL. You can customize the key and TTL using @CacheKey() and @CacheTTL(). [web:16]
@Get(':id')
@CacheKey('product-detail')
@CacheTTL(30_000)
findOne(@Param('id') id: string) {
return this.productService.findOne(id);
}
This is useful for public or semi-public endpoints such as catalogs, blog posts, categories, and reference data.
Redis is commonly used to store user sessions in a horizontally scaled NestJS application.
Typical use cases:
Instead of storing session data in each Node.js process, Redis lets every NestJS instance validate the same session.
await redis.set(
`session:${sessionId}`,
JSON.stringify(session),
'EX',
60 * 60 * 24,
);
This pattern works well when you run multiple containers or pods behind Kubernetes, Google Cloud Run, AWS ECS, or a traditional load balancer.
Redis is ideal for rate limiting because counters can be shared across all application instances.
Use cases:
A simple fixed-window implementation:
async checkRateLimit(userId: string) {
const key = `rate-limit:${userId}`;
const limit = 100;
const windowSeconds = 60;
const current = await redis.incr(key);
if (current === 1) {
await redis.expire(key, windowSeconds);
}
if (current > limit) {
throw new HttpException('Too Many Requests', 429);
}
}
For production, use atomic Redis commands or a Lua script to avoid race conditions when traffic is high.
Redis is the backing store for BullMQ, which is the recommended modern queue library for NestJS background processing. NestJS provides official integration through @nestjs/bullmq. [web:19]
Common job types:
@Module({
imports: [
BullModule.forRoot({
connection: {
host: process.env.REDIS_HOST,
port: Number(process.env.REDIS_PORT),
},
}),
BullModule.registerQueue({
name: 'email',
}),
],
})
export class EmailModule {}
@Injectable()
export class EmailService {
constructor(
@InjectQueue('email') private readonly emailQueue: Queue,
) {}
async sendWelcomeEmail(userId: string) {
await this.emailQueue.add(
'welcome',
{ userId },
{
attempts: 3,
backoff: {
type: 'exponential',
delay: 1_000,
},
},
);
}
}
BullMQ jobs are persisted in Redis, support delayed execution, retries, priorities, and distributed workers. [web:19][web:23]
Queues help NestJS handle traffic spikes, prevent long-running work from blocking the event loop, and provide reliable communication between services. [web:19]
Redis-backed queues are useful when work should happen later rather than immediately.
Examples:
await this.orderQueue.add(
'expire-order',
{ orderId },
{ delay: 30 * 60 * 1000 },
);
BullMQ supports delayed jobs, retries with backoff, priorities, and repeatable or scheduled jobs. [web:19][web:23]
When multiple NestJS instances may perform the same operation at the same time, Redis can provide a distributed lock.
Use cases:
const lockKey = `lock:payment:${paymentId}`;
const acquired = await redis.set(lockKey, '1', 'EX', 30, 'NX');
if (!acquired) {
throw new ConflictException('Payment is already being processed');
}
try {
await this.paymentService.process(paymentId);
} finally {
await redis.del(lockKey);
}
Use a lock TTL and a safe release strategy so that a crashed instance does not leave the lock permanently held.
Redis Pub/Sub can distribute events between NestJS instances or services.
Use cases:
await redis.publish(
'product-updated',
JSON.stringify({ productId, status: 'published' }),
);
For critical event workflows, consider Redis Streams or a dedicated message broker such as Kafka or RabbitMQ. Pub/Sub is best when delivery guarantees are not strict.
Redis TTLs make it a strong fit for short-lived data.
Examples:
await redis.set(
`otp:${userId}`,
otp,
'EX',
300,
);
After five minutes, Redis automatically removes the OTP, eliminating the need for a cleanup job.
Redis data structures are efficient for counters and ranked data.
| Redis structure | NestJS use case |
|---|---|
INCR / DECR | View counts, likes, inventory counters |
| Sorted sets | Leaderboards, trending products, ranking |
| Sets | Unique visitors, tags, followers |
| Hashes | User profile snapshots, feature flags |
| Lists | Recent activity feeds |
| Streams | Event logs and consumer groups |
await redis.zincrby('products:trending', 1, productId);
This is useful for dashboards, real-time popularity lists, and lightweight analytics where writing every event directly to the primary database would be too expensive.
A practical NestJS + Redis architecture often looks like this:
Client
|
NestJS API instances
|
+-- PostgreSQL / MySQL / MongoDB -> source of truth
|
+-- Redis
|-- Cache
|-- Sessions
|-- Rate limits
|-- Distributed locks
+-- BullMQ queues
|
+-- Worker instances
Keep your relational or document database as the source of truth. Redis should hold data that is temporary, derived, shared, or performance-critical.
Avoid using Redis as the primary database when:
Redis is excellent for speed and coordination, but it should usually not replace your main database.
user:{id}:profile or cache:product:{id}.Redis is most valuable in NestJS when your application needs shared state, low-latency reads, background processing, or protection against excessive traffic. Start with caching and queues, then add sessions, rate limiting, distributed locks, and Pub/Sub as your application scales.