캐싱 전략(Redis)
Redis를 사용하여 다양한 캐싱 전략을 구현하고 데이터베이스 부하를 줄여 API 응답 시간을 개선합니다.
캐싱 전략(Redis)은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 6개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 6개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Boosting API Performance with Caching
Welcome to Caching Strategies with Redis! In this lesson, we'll explore how to drastically improve your NestJS API's performance and responsiveness.
Caching is a technique where frequently accessed data is stored temporarily in a faster-access memory layer. This helps avoid repeated, expensive operations like database queries or complex computations.
Why Caching Matters
Imagine an API endpoint that fetches popular products. Every time a user requests this data, your server might perform a database query, which can be slow and resource-intensive.
- Reduced Latency: Users get data faster.
- Lower Database Load: Your database works less, preventing bottlenecks.
- Improved Scalability: Your application can handle more users without slowing down.
Caching acts as a buffer, serving data quickly from memory instead of always hitting the primary data source.
Meet Redis: Your In-Memory Cache
Redis (Remote Dictionary Server) is a popular open-source, in-memory data structure store. It's often used as a database, cache, and message broker.
- Speed: Redis stores data in RAM, making read/write operations incredibly fast.
- Versatility: It supports various data structures like strings, hashes, lists, sets, and more.
- Persistence: While primarily in-memory, Redis can persist data to disk for durability.
For caching, Redis's speed and simple key-value model make it an ideal choice.
Redis Basics: Key-Value Operations
Redis stores data as simple key-value pairs. You assign a unique key to a piece of data, then use that key to retrieve it later. Here's how it looks conceptually using the Redis CLI:
# Connect to Redis CLI
redis-cli
# Store a value with a key
SET myapi:users:123 '{"name":"Alice"}'
# Retrieve the value using its key
GET myapi:users:123
# Set a value with an expiration time (10 seconds)
SETEX myapi:temp:data 10 'Expires Soon'NestJS CacheModule Setup
NestJS provides a flexible CacheModule to integrate various caching solutions. To use Redis, we'll install @nestjs/cache-manager and cache-manager-redis-store.
First, install the packages:
npm install @nestjs/cache-manager cache-manager-redis-store cache-managerThen, configure your AppModule to use Redis:
import { Module, CacheModule } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';
@Module({
imports: [
CacheModule.register({
store: redisStore,
host: 'localhost',
port: 6379,
ttl: 300 // default time-to-live in seconds
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
Automatic Caching with CacheInterceptor
For simple GET endpoints, NestJS offers the CacheInterceptor. This interceptor automatically caches the response of a method and serves it from the cache on subsequent requests.
You can apply it globally or to specific controllers/methods using decorators:
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor, CacheKey, CacheTTL } from '@nestjs/cache-manager';
@Controller('products')
@UseInterceptors(CacheInterceptor) // Apply to all methods in this controller
export class ProductsController {
@Get()
@CacheKey('all_products') // Unique key for this cache entry
@CacheTTL(60) // Cache for 60 seconds (overrides module default)
async findAll() {
// In a real app, this would fetch from a database
console.log('Fetching all products from DB...');
return [{ id: 1, name: 'Laptop' }, { id: 2, name: 'Mouse' }];
}
}Understanding CacheKey and CacheTTL
When using CacheInterceptor, two key decorators help you control caching:
@CacheKey('your_key_name'): This decorator defines the unique key under which the response data will be stored in Redis. If not provided, NestJS generates one based on the request path.@CacheTTL(seconds): This sets the Time-To-Live for the cached entry in seconds. After this duration, the cached data expires and will be re-fetched from the original source. If omitted, it uses the defaultttlfromCacheModule.register().
These allow you to fine-tune how long specific data remains cached.
Manual Caching with CacheManager
Sometimes, you need more control than what CacheInterceptor offers, for example, caching parts of a response or invalidating cache entries programmatically.
You can inject the CacheManager service and use its methods directly:
import { Controller, Get, Post, Inject, Param } from '@nestjs/common';
import { Cache } from 'cache-manager';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
@Controller('users')
export class UsersController {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
@Get(':id')
async findOne(@Param('id') id: string) {
const cacheKey = `user_${id}`;
const cachedUser = await this.cacheManager.get(cacheKey);
if (cachedUser) {
console.log('Serving from cache!');
return cachedUser;
}
// Simulate fetching from DB
const user = { id, name: `User ${id}`, email: `user${id}@example.com` };
await this.cacheManager.set(cacheKey, user, 600); // Cache for 10 mins
console.log('Serving from DB and caching...');
return user;
}
@Post('clear-all')
async clearAllCache() {
await this.cacheManager.reset(); // Clear all cache entries
return 'Cache cleared!';
}
}Cache Invalidation Strategies
A critical aspect of caching is ensuring data freshness. Stale data can lead to incorrect information being served.
- Time-To-Live (TTL): The simplest strategy, data expires automatically after a set time.
- Cache-Aside: Application code explicitly fetches from cache, then DB if not found, and updates cache.
- Write-Through: Data is written to cache and then to the database simultaneously.
- Write-Back: Data is written to cache, then asynchronously written to the database.
- Event-Driven Invalidation: When data changes in the database, an event is triggered to invalidate or update the corresponding cache entry.
Choosing the right strategy depends on your application's consistency requirements.
Quick Check: Caching Benefits
Consider a NestJS API endpoint that frequently fetches a list of popular products from a database. This database call is slow due to complex joins and large data volumes.
Caching with Redis: Recap
Great job! You've learned the fundamentals of caching with Redis in NestJS:
- Caching significantly boosts API performance, reduces database load, and improves scalability.
- Redis is an excellent choice for an in-memory cache due to its speed and versatility.
- NestJS's
CacheModulesimplifies Redis integration usingcache-manager-redis-store. - You can use the
@CacheInterceptorwith@CacheKeyand@CacheTTLfor automatic caching on controller methods. - For more control, inject
CACHE_MANAGERto manually interact with Redis. - Understanding cache invalidation strategies is crucial for maintaining data freshness.
Start implementing caching to make your NestJS applications blazing fast!
자주 묻는 질문
“캐싱 전략(Redis)” 강의는 무료인가요?
네 — “캐싱 전략(Redis)” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 6개의 강의가 포함되어 있습니다.
“캐싱 전략(Redis)”에서 뭘 배우나요?
Redis를 사용하여 다양한 캐싱 전략을 구현하고 데이터베이스 부하를 줄여 API 응답 시간을 개선합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 1번째 강의입니다.
“캐싱 전략(Redis)” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.