Caching in NestJS: In-Memory Stores to Multi-Tier Redis & Custom Tracking

Shaishab Roy
Published 12 days ago

Discover curated collections of blog posts

Shaishab Roy
Published 12 days ago


Strategic Writer
A technology and business leader with a strong focus on digital transformation, software delivery, and strategic growth. Experienced in leading JavaScript-focused teams, driving business development initiatives, and building innovative SaaS products. Passionate about AI-powered solutions, product development, stakeholder management, and creating scalable digital platforms. Skilled at bridging the gap between business objectives and technology execution while fostering collaboration across clients, teams, and partners.
Get personalized recommendations based on your reading history and interests. Visit the member dashboard to see blogs tailored just for you.
Every modern web application eventually hits the exact same performance wall: your database starts choking on repetitive read queries, response latencies creep up from 20 milliseconds to 800 milliseconds, and expensive third-party API calls drain both speed and budget. When your modular NestJS backend is repeatedly calculating the same dashboard analytics or querying unchanged product catalogs, your CPU is doing redundant work.
In this comprehensive engineering guide, we break down how to implement high-performance caching in a modular NestJS architecture. Drawing directly from production patterns we apply in projects like CodeOps AI, we will move from basic in-memory caching to declarative route interceptors, custom cache tracking for user-specific data, manual service-level key management, and multi-tier Redis architectures powered by Keyv—all standardized on Yarn.
In-Memory vs. Distributed Stores: Understand how NestJS uses @nestjs/cache-manager and Keyv under the hood, and the critical differences in object reference vs. JSON serialization.
Declarative Auto-Caching: Leverage CacheInterceptor, @CacheKey(), and @CacheTTL() at global, controller, and route levels without cluttering business logic.
Custom Cache Tracking (trackBy): Extend CacheInterceptor to solve the 'shared cache leak' problem by isolating cached responses per authenticated user or tenant header.
Programmatic Service-Level Caching: Inject CACHE_MANAGER directly into domain services for granular key control, explicit invalidation, and clean controller separation.
To see why a single caching strategy is never enough, consider a typical modular e-commerce or SaaS platform:
Scenario A — Public Product Catalog (GET /products): Thousands of visitors view the exact same product list every minute. Inventory prices rarely change second-by-second. Caching this endpoint for 60 seconds cuts database read load by 95%.
Scenario B — Authenticated User Dashboard (GET /users/me/profile): Every user hits the exact same URL path (/users/me/profile), differentiated only by their Authorization Bearer token or x-tenant-id header. If you naively apply default URL-based caching here, User B will receive User A's cached profile! We need custom tracking (trackBy) to isolate cache keys per user.
Scenario C — Active Cache Invalidation on Write (PATCH /products/:id): When an admin updates a product's price, waiting 60 seconds for TTL expiration shows stale prices. We need programmatic CACHE_MANAGER access inside our service to immediately invalidate (del()) the stale key.
Caching Approach | Best Use Case | Key Generation | Invalidation Control |
CacheInterceptor (Default) | Public GET endpoints (e.g., catalogs, static configs). | Automatic via HTTP Request URL. | Time-based (TTL expiration only). |
Custom HttpCacheInterceptor | User-specific or multi-tenant GET endpoints. | Custom trackBy() using Headers / User ID. | Time-based (TTL expiration). |
Programmatic CACHE_MANAGER | Complex service queries, writes & mutations. | Explicit developer-defined keys. | Immediate manual del() / clear(). |
Multi-Tier (Memory + Redis) | High-traffic production nodes needing persistence. | Automatic or custom keys via Keyv. | Shared across instances + L1 LRU. |
NestJS provides a unified caching abstraction via @nestjs/cache-manager, which wraps cache-manager and Keyv under the hood. Let's install the required packages using Yarn:
# Install NestJS cache manager and underlying cache-manager engine
yarn add @nestjs/cache-manager cache-managerTo enable in-memory caching across your modular application, register CacheModule inside your root AppModule. Setting isGlobal: true ensures you don't have to repeatedly import CacheModule into every feature module:
// src/app.module.ts
import { Module } from '@nestjs/common';
import { CacheModule } from '@nestjs/cache-manager';
import { ProductsModule } from './products/products.module';
@Module({
imports: [
CacheModule.register({
isGlobal: true,
ttl: 30000, // Default Time-To-Live: 30 seconds (in milliseconds)
}),
ProductsModule,
],
})
export class AppModule {}Critical Memory Reference Gotcha (v6/v7 Behavior)
The default in-memory store keeps a direct reference to the JavaScript object passed to set(), rather than cloning it. If you mutate a retrieved object in your code, you also mutate the cached entry! Treat cached objects as immutable, or clone them before modification. External Keyv stores (like Redis) serialize values to JSON instead—meaning class instances return as plain objects and Date objects return as ISO strings.
For read-heavy public endpoints like our product catalog, you don't need to write a single line of cache-lookup logic inside your service. Simply bind CacheInterceptor to the controller or route handler:
// src/products/products.controller.ts
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor, CacheKey, CacheTTL } from '@nestjs/cache-manager';
import { ProductsService } from './products.service';
@Controller('products')
@UseInterceptors(CacheInterceptor) // Automatically caches GET responses
export class ProductsController {
constructor(private readonly productsService: ProductsService) {}
@Get()
@CacheKey('all_products_catalog') // Overrides URL-based key
@CacheTTL(60000) // Overrides module default TTL to 60 seconds
async findAll() {
// This database call only executes on a cache miss!
return this.productsService.findAll();
}
}You can also bind CacheInterceptor globally across your entire application via APP_INTERCEPTOR in AppModule, and selectively override TTLs on specific controllers or methods using @CacheTTL().
Three Strict Rules for CacheInterceptor
1. GET Endpoints Only: By default, CacheInterceptor only caches HTTP GET requests (unless bypassed with an explicit @CacheKey() on a handler).
2. No Native @Res() Injection: Routes that inject the platform-specific response object (@Res()) bypass Nest's response lifecycle and cannot use CacheInterceptor.
3. Not for GraphQL Field Resolvers: In GraphQL apps, interceptors execute per field resolver, making CacheInterceptor unsuitable for GraphQL.
By default, CacheInterceptor uses the HTTP request URL (e.g., /users/me/profile) as the cache key. While this works great for public endpoints, it creates a critical security and data-integrity bug for personalized endpoints.
Imagine Alice sends GET /users/me/profile with Authorization: Bearer token_alice. NestJS caches Alice's profile under the key /users/me/profile. Two seconds later, Bob sends GET /users/me/profile with Authorization: Bearer token_bob. Because the URL path is identical, CacheInterceptor serves Alice's private profile to Bob!
To fix this, subclass CacheInterceptor and override the trackBy(context: ExecutionContext) method. By inspecting the incoming request headers or authenticated user object attached by your AuthGuard, you can construct a composite cache key that isolates each user's cache:
// src/common/interceptors/user-cache.interceptor.ts
import { ExecutionContext, Injectable } from '@nestjs/common';
import { CacheInterceptor } from '@nestjs/cache-manager';
import { Request } from 'express';
@Injectable()
export class UserHttpCacheInterceptor extends CacheInterceptor {
trackBy(context: ExecutionContext): string | undefined {
const request = context.switchToHttp().getRequest<Request>();
// 1. Only cache GET requests
if (request.method !== 'GET') {
return undefined; // Returning undefined bypasses caching completely
}
// 2. Extract user ID (populated by AuthGuard) or Authorization/Tenant header
const userId = (request as any).user?.id;
const tenantId = request.headers['x-tenant-id'] || 'default';
// 3. Construct an isolated, deterministic cache key
if (userId) {
return `tenant:${tenantId}:user:${userId}:url:${request.originalUrl}`;
}
// 4. Fallback to standard URL tracking for unauthenticated public routes
return super.trackBy(context);
}
}Now, when Alice and Bob call /users/me/profile, their responses are stored under distinct keys (tenant:acme:user:alice:url:/users/me/profile vs. tenant:acme:user:bob:url:/users/me/profile), eliminating cross-user data leaks while preserving full caching speed.
Declarative interceptors excel at read-only endpoints, but real-world applications must invalidate stale data immediately when records are created, updated, or deleted. Furthermore, caching inside the service layer keeps controllers thin and makes business logic easier to unit test.
Inject CACHE_MANAGER into your domain service to gain full control over get(), set(), del(), and clear():
// src/products/products.service.ts
import { Inject, Injectable, NotFoundException } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { UpdateProductDto } from './dto/update-product.dto';
@Injectable()
export class ProductsService {
private readonly ALL_PRODUCTS_KEY = 'catalog:products:all';
constructor(
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
// private readonly productRepository: ProductRepository,
) {}
async findAll() {
// 1. Check cache first (Note: cache-manager v7 returns undefined on miss; v6 returned null)
const cachedProducts = await this.cacheManager.get(this.ALL_PRODUCTS_KEY);
if (cachedProducts) {
return cachedProducts;
}
// 2. Cache miss: Query database
const products = await this.fetchFromDatabase();
// 3. Store in cache with 60-second TTL (in milliseconds; pass 0 for never-expiring)
await this.cacheManager.set(this.ALL_PRODUCTS_KEY, products, 60000);
return products;
}
async updateProduct(id: string, dto: UpdateProductDto) {
const updated = await this.updateInDatabase(id, dto);
if (!updated) throw new NotFoundException('Product not found');
// 4. Active Invalidation: Immediately purge stale cache keys on write!
await this.cacheManager.del(this.ALL_PRODUCTS_KEY);
await this.cacheManager.del(`catalog:product:${id}`);
return updated;
}
private async fetchFromDatabase() {
return [{ id: '1', name: 'Mechanical Keyboard', price: 149 }];
}
private async updateInDatabase(id: string, dto: UpdateProductDto) {
return { id, ...dto };
}
}Notice how clean ProductsController becomes when caching lives in the service layer—no @CacheKey() or @UseInterceptors(CacheInterceptor) decorators are needed on the controller methods.
In-memory caching is blazingly fast, but it resets every time your server restarts and isn't shared if you run multiple Node.js worker instances behind a load balancer. Because cache-manager uses Keyv under the hood, you can configure a multi-tier store combining a fast local L1 in-memory LRU cache with a persistent L2 Redis store:
# Install Keyv Redis adapter and Cacheable in-memory LRU store
yarn add @keyv/redis keyv cacheableUsing CacheModule.registerAsync(), we can inject ConfigService to read our Redis connection string dynamically and configure both stores:
// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { CacheModule } from '@nestjs/cache-manager';
import { createKeyv } from '@keyv/redis';
import { Keyv } from 'keyv';
import { KeyvCacheableMemory } from 'cacheable';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
CacheModule.registerAsync({
isGlobal: true,
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
const redisUrl = configService.get<string>('REDIS_URL', 'redis://localhost:6379');
const redisStore = createKeyv(redisUrl);
// CRITICAL: Attach an error listener so Redis network hiccups don't crash Node.js
redisStore.on('error', (err) => {
console.error('[Redis Cache Store Error]:', err.message);
});
return {
stores: [
// Primary L1 Store: Ultra-fast local in-memory LRU (max 5,000 items, 60s TTL)
new Keyv({
store: new KeyvCacheableMemory({ ttl: 60000, lruSize: 5000 }),
}),
// Secondary L2 Store: Shared distributed Redis persistence
redisStore,
],
};
},
}),
],
})
export class AppModule {}Mandatory Redis Safety Listener
Always attach an .on('error', ...) event handler to your Redis Keyv instance. If Redis temporarily disconnects, Keyv emits an 'error' event—and in Node.js, an unhandled EventEmitter error will crash your entire application process.
Developers often confuse application caching with function memoization. While both eliminate redundant work, they operate at different architectural layers:
Feature | Application Caching (CacheModule / Redis) | Function Memoization (fast-memoize / memoizee) |
Primary Scope | I/O bound operations: DB queries, external APIs, HTTP responses. | CPU bound pure functions: complex math, tax/pricing formulas. |
Storage Layer | In-memory store or external distributed store (Redis). | Local function closure memory inside a single Node process. |
Expiration & Eviction | Time-based TTL, LRU max-size limits, manual del() invalidation. | Typically lives for process lifetime unless bounded by custom cache size. |
If you want service-level caching without repeating cacheManager.get() and cacheManager.set() boilerplate inside every method, you can build a clean custom @Cacheable() TypeScript method decorator:
// src/common/decorators/cacheable.decorator.ts
import { Inject } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
export function Cacheable(keyPrefix: string, ttlMs = 30000) {
const injectCache = Inject(CACHE_MANAGER);
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
// Automatically inject CACHE_MANAGER onto the class instance if not already present
injectCache(target, 'cacheManager');
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
const cacheManager: Cache = (this as any).cacheManager;
const cacheKey = `${keyPrefix}:${JSON.stringify(args)}`;
try {
const cached = await cacheManager?.get(cacheKey);
if (cached !== undefined && cached !== null) {
return cached;
}
} catch (err) {
console.warn(`Cache read failed for ${cacheKey}, falling back to source:`, err);
}
// Execute original service method on cache miss
const result = await originalMethod.apply(this, args);
try {
await cacheManager?.set(cacheKey, result, ttlMs);
} catch (err) {
console.warn(`Cache write failed for ${cacheKey}:`, err);
}
return result;
};
return descriptor;
};
}With this decorator in place, any service method becomes self-caching with built-in graceful fallback if the cache store is temporarily unreachable:
@Injectable()
export class SettingsService {
@Cacheable('system:settings', 60000)
async getWorkspaceSettings(workspaceId: string) {
// Runs only on cache miss; arguments are automatically hashed into the key!
return this.fetchSettingsFromDb(workspaceId);
}
}Verify your caching implementation, type safety, and Redis integration under Yarn:
# Start NestJS in watch mode to verify cache hit/miss latencies
yarn start:dev
# Run unit tests mocking CACHE_MANAGER
yarn test
# Run end-to-end tests verifying HTTP Cache-Control and TTL expiration
yarn test:e2eJoin the Discussion & Share Your Feedback
We'd love to hear your thoughts on this caching architecture! How are you handling cache invalidation and user-specific keys in your NestJS projects? Drop your feedback, questions, or experiences in the comment section below.
Effective caching transforms a sluggish, database-bound API into a responsive, scalable system. By combining declarative CacheInterceptor endpoints for public data, custom trackBy() interceptors for authenticated user routes, programmatic CACHE_MANAGER invalidation on writes, and resilient multi-tier Redis stores via Keyv, you gain complete control over your modular NestJS application's performance.
Remember: always measure before caching, avoid caching mutating operations, and treat cache invalidation as a first-class citizen in your service design.
Comments