logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Caching in NestJS with Redis

author
Generated by
ProCodebase AI

10/12/2024

NestJS

Sign in to read full article

When it comes to building modern web applications, performance often dictates user experience. One effective way to enhance performance is by using caching techniques to minimize database queries and decrease load times. In this blog, we will see how to leverage Redis as a caching layer in a NestJS application.

What is Redis?

Redis is an open-source, in-memory data structure store that functions as a database, cache, and message broker. Its high performance, persistence options, and support for complex data types make it a popular choice in many web applications.

Why Use Caching?

Caching can dramatically improve response times by reducing the need to fetch data from a database on every request. It is particularly useful for read-heavy applications where the data doesn’t change frequently.

Benefits of Caching:

  • Improved Performance: Decrease the response time for fetching data.
  • Reduces Database Load: Fewer database queries mean decreased strain on your database.
  • Scalability: Allows your application to handle more requests efficiently.

Setting Up Redis

Before diving into the integration with NestJS, the first step is to install Redis on your system. You can download it from the official Redis website or install it using a package manager like brew for macOS:

brew install redis

Once installed, you can start the Redis server:

redis-server

You can verify if it’s running by executing:

redis-cli ping

If the server is running correctly, you will see a response of PONG.

Integrating Redis with NestJS

With Redis up and running, we can now focus on integrating it into our NestJS application.

Step 1: Set Up Your NestJS Project

If you haven’t already created a NestJS project, you can do so using the Nest CLI:

npm i -g @nestjs/cli nest new nest-redis-cache cd nest-redis-cache

Step 2: Install Redis Packages

To connect and interact with Redis, install the ioredis package, which is a robust Redis client for Node.js:

npm install ioredis @nestjs/cache

Step 3: Configure Caching Module

Now that we have installed the necessary packages, let’s configure the caching module in our NestJS application. Open up the app.module.ts file and modify it as follows:

import { Module, CacheModule } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import * as redisStore from 'cache-manager-redis-store'; @Module({ imports: [ CacheModule.register({ store: redisStore, url: 'redis://localhost:6379', }), ], controllers: [AppController], providers: [AppService], }) export class AppModule {}

Step 4: Create a Service with Caching

Let’s create a simple service that utilizes caching to store data fetched from an external API. Create a new file named app.service.ts and implement the following:

import { Injectable, Cacheable } from '@nestjs/common'; import { Cache } from 'cache-manager'; import { InjectCache } from '@nestjs/cache-manager'; @Injectable() export class AppService { constructor(@InjectCache() private readonly cacheManager: Cache) {} @Cacheable({ key: 'data', ttl: 60 // cache this data for 60 seconds }) async getExternalData(): Promise<any> { // Mimic an external API call const data = await this.fetchDataFromAPI(); return data; } private async fetchDataFromAPI(): Promise<any> { // Simulated delay for fetching data return new Promise(resolve => { setTimeout(() => { resolve({ message: 'Hello from external API!' }); }, 2000); }); } }

In this example, when getExternalData is called the first time, it will take 2 seconds to return data fetched from our simulated API. However, subsequent calls within 60 seconds will return the cached result instantaneously.

Step 5: Use the Service in Your Controller

Finally, let’s expose this cached service through a controller. In your app.controller.ts:

import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get('data') async getData() { return await this.appService.getExternalData(); } }

Testing the Cache

Start your NestJS application:

npm run start

Now, navigate to http://localhost:3000/data in your browser. The first request will take around 2 seconds. If you refresh the page within 60 seconds, you should see the response come nearly instantaneously, demonstrating the caching in action.

Conclusion

In this blog, we walked through using Redis for caching with a NestJS application. The caching strategies help improve performance significantly and reduce the load on your database. With just a few lines of code, we incorporated Redis caching effectively, leading to more efficient data handling for our applications.

Happy coding!

Popular Tags

NestJSRedisCaching

Share now!

Like & Bookmark!

Related Collections

  • NestJS Mastery: Modern Backend Development

    10/12/2024 | NestJS

Related Articles

  • Dependency Injection in NestJS

    10/12/2024 | NestJS

  • Controllers and Routing in NestJS

    10/12/2024 | NestJS

  • Understanding Modules in NestJS

    10/12/2024 | NestJS

  • Understanding Services and Providers in NestJS

    10/12/2024 | NestJS

  • Performance Optimization in NestJS Applications

    10/12/2024 | NestJS

  • Validation with Class Validator and Class Transformer in NestJS

    10/12/2024 | NestJS

  • Understanding Interceptors in NestJS

    10/12/2024 | NestJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design