Skip to main content

Redis Caching Architecture

Caching strategy using Redis for performance optimization.

Configuration​

REDIS_URL=redis://localhost:6379
REDIS_HOST=localhost
REDIS_PORT=6379

Cache Layers​

NestJS Cache Integration​

import { CacheModule } from "@nestjs/cache-manager";
import * as redisStore from "cache-manager-redis-store";

@Module({
imports: [
CacheModule.register({
store: redisStore,
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
ttl: 300, // 5 minutes default
}),
],
})
export class AppModule {}

Using Cache​

Controller-Level​

@UseInterceptors(CacheInterceptor)
@CacheTTL(600)
@Get()
async findAll() {
return this.employeeService.findAll();
}

Service-Level​

@Injectable()
export class EmployeeService {
constructor(@Inject(CACHE_MANAGER) private cache: Cache) {}

async findById(id: string): Promise<Employee> {
const cacheKey = `employee:${id}`;
let employee = await this.cache.get<Employee>(cacheKey);

if (!employee) {
employee = await this.repository.findOne({ where: { id } });
await this.cache.set(cacheKey, employee, 600);
}

return employee;
}
}

Cache Invalidation​

// Invalidate on update
async update(id: string, dto: UpdateDTO): Promise<Employee> {
const result = await this.repository.save({ id, ...dto });
await this.cache.del(`employee:${id}`);
await this.cache.del('employee:list');
return result;
}

Cache Key Patterns​

PatternTTLInvalidation
employee:{id}10minOn update/delete
employee:list:{orgId}5minOn any employee change
task:count:{projectId}2minOn task change
permission:{userId}30minOn role change
config:{tenantId}60minOn config change