0
0
NestJSframework~5 mins

Cache stores (memory, Redis) in NestJS

Choose your learning style9 modes available
Introduction

Cache stores help your app remember data temporarily to make it faster. Memory cache keeps data inside the app, Redis cache stores data outside the app for sharing.

You want to speed up repeated data requests without hitting the database every time.
You need to share cached data between multiple app servers.
You want to reduce load on slow or expensive data sources.
You want to store session or user data temporarily.
You want to improve app response time for common queries.
Syntax
NestJS
import { CacheModule } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';

// For memory cache
CacheModule.register({
  ttl: 5, // seconds
  max: 100, // max items
});

// For Redis cache
CacheModule.register({
  store: redisStore,
  host: 'localhost',
  port: 6379,
  ttl: 10,
});

Memory cache stores data inside your app process, so it resets when app restarts.

Redis cache stores data outside your app, so it can be shared and persists across restarts.

Examples
This sets up a simple memory cache with a 10-second time-to-live.
NestJS
import { CacheModule } from '@nestjs/common';

@Module({
  imports: [CacheModule.register({ ttl: 10 })],
})
export class AppModule {}
This configures Redis as the cache store with a 20-second expiration.
NestJS
import { CacheModule } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';

@Module({
  imports: [
    CacheModule.register({
      store: redisStore,
      host: 'localhost',
      port: 6379,
      ttl: 20,
    }),
  ],
})
export class AppModule {}
Sample Program

This example creates a simple controller with a counter. The CacheInterceptor caches the response for 5 seconds using Redis. If you call the /count endpoint multiple times within 5 seconds, it returns the same count without increasing.

NestJS
import { Controller, Get, CacheInterceptor, UseInterceptors } from '@nestjs/common';
import { CacheModule, Module } from '@nestjs/common';
import * as redisStore from 'cache-manager-redis-store';

@Controller()
@UseInterceptors(CacheInterceptor)
export class AppController {
  private counter = 0;

  @Get('count')
  getCount() {
    this.counter++;
    return { count: this.counter };
  }
}

@Module({
  imports: [
    CacheModule.register({
      store: redisStore,
      host: 'localhost',
      port: 6379,
      ttl: 5,
    }),
  ],
  controllers: [AppController],
})
export class AppModule {}
OutputSuccess
Important Notes

Memory cache is easy to set up but only works for single app instances.

Redis cache requires Redis server running but supports multiple app instances sharing cache.

Always set a TTL (time-to-live) to avoid stale data.

Summary

Cache stores speed up apps by saving data temporarily.

Memory cache is simple but local to one app instance.

Redis cache is shared and persistent, good for multiple servers.