0
0
NestJSframework~5 mins

Why caching reduces response latency in NestJS

Choose your learning style9 modes available
Introduction

Caching stores data temporarily so your app can get it faster next time. This makes your app respond quicker and feel smoother.

When your app fetches the same data many times, like user profiles or product lists.
When you want to reduce waiting time for users on slow or busy servers.
When you want to lower the load on your database or external services.
When you want to improve performance for repeated requests in a short time.
When you want to save bandwidth by not fetching unchanged data repeatedly.
Syntax
NestJS
import { CacheModule, Module } from '@nestjs/common';

@Module({
  imports: [CacheModule.register({ ttl: 5 })], // ttl is time to live in seconds
})
export class AppModule {}

ttl means how long the data stays in cache before it is refreshed.

CacheModule helps NestJS store and retrieve cached data easily.

Examples
This example caches the response of the findAll method so repeated calls return cached data quickly.
NestJS
import { CacheInterceptor, Controller, Get, UseInterceptors } from '@nestjs/common';

@Controller('items')
@UseInterceptors(CacheInterceptor)
export class ItemsController {
  @Get()
  findAll() {
    return ['item1', 'item2', 'item3'];
  }
}
Here, cache entries expire after 10 seconds, so data refreshes regularly.
NestJS
import { CacheModule, Module } from '@nestjs/common';

@Module({
  imports: [CacheModule.register({ ttl: 10 })],
})
export class AppModule {}
Sample Program

This NestJS app counts visitors but caches the greeting for 30 seconds. So, repeated requests within 30 seconds show the same visitor number, making responses faster.

NestJS
import { CacheModule, CacheInterceptor, Controller, Get, Module, UseInterceptors } from '@nestjs/common';

@Controller('greet')
@UseInterceptors(CacheInterceptor)
export class GreetController {
  private count = 0;

  @Get()
  sayHello() {
    this.count++;
    return `Hello! You are visitor number ${this.count}`;
  }
}

@Module({
  imports: [CacheModule.register({ ttl: 30 })],
  controllers: [GreetController],
})
export class AppModule {}
OutputSuccess
Important Notes

Caching improves speed but cached data might be outdated until refreshed.

Choose cache duration (ttl) wisely based on how fresh your data needs to be.

Use caching for data that does not change every second to get the best benefit.

Summary

Caching stores data temporarily to speed up repeated requests.

It reduces the time your app waits for data from slow sources.

In NestJS, CacheModule and CacheInterceptor make caching easy to add.