Cache frequently read results

12.6.0

Save a result for a short time to reduce repeated work. Set a clear rule for when to read fresh data.

On this page

Read the cache first, then the database

Install @nestjs/cache-manager and cache-manager, then register CacheModule. Inject CACHE_MANAGER in the service. The default store is in memory. Here the key identifies the shop and the result stays cached for 30,000 milliseconds.

// Inside the service with CACHE_MANAGER and a product repository injected
async list(shopId: number) {
  const key = "products:shop:" + shopId;
  const cached = await this.cache.get<Product[]>(key);
  if (cached != null) return cached;

  const products = await this.repository.list(shopId);
  await this.cache.set(key, products, 30_000);
  return products;
}

Remove old entries after a write

Delete the matching key after the database commit so the next read can load fresh data. An in-flight read can still refill a stale entry, so use a short TTL and choose a stronger design for data that needs immediate consistency. For several Nest processes, choose a shared store if they need to share cached values.

await this.repository.updateQuantity(shopId, productId, quantity);
await this.cache.del("products:shop:" + shopId);

Official references