Complete Guide on Nest JS Caching | Redis

Programming with Lakshya
7 Mar 202413:04

Summary

TLDRThis tutorial explores caching in NestJS, comparing in-memory caching to Redis for scalability and persistence. It demonstrates how to implement caching using the CacheManager package, set up Redis as a cache store, and utilize cache interceptors for automatic caching of data fetched from the database.

Takeaways

  • 📒 Caching in NestJS can be implemented in multiple ways based on the project needs, primarily through in-memory caching and Redis.
  • 📝 In-memory caching stores data directly in the application's memory, acting like a quick reference guide for fast access.
  • 🚀 In-memory caching is fast and easy to set up, ideal for small-scale applications but has limitations with larger data volumes or multiple server instances.
  • 🔄 Redis can be used for larger applications, ensuring consistency and efficiency by storing data in a dedicated data store.
  • ⚙️ Implementing caching in a NestJS application involves installing the necessary packages and configuring the CacheModule.
  • 🗂️ The CacheModule can be registered globally, making it available across the entire application, or locally within specific modules.
  • 📥 Caching data with Redis involves setting up the Redis store in the CacheModule and configuring the host and port.
  • 🔧 Caching interceptors can be used to automatically cache responses from specific routes or controllers in NestJS.
  • 🔄 Redis provides benefits such as scalability and persistence, ensuring cache data is retained even if the application restarts or crashes.
  • 📈 Using Redis for caching involves setting up a Redis container, interacting with Redis CLI, and verifying cached keys and data.

Q & A

  • What is caching in the context of a Node.js application?

    -Caching in Node.js refers to the process of storing frequently accessed data in a temporary storage area to improve the performance of an application by reducing the need to fetch the data from its original source repeatedly.

  • What is the primary advantage of in-memory caching in Node.js?

    -The primary advantage of in-memory caching is its speed. It allows for quick access to data stored directly in the application's memory, which is ideal for small-scale applications and does not require any external tools.

  • What limitations does in-memory caching have as an application grows?

    -In-memory caching may struggle to keep up as the application grows due to its inability to handle large volumes of data or maintain consistency across multiple server instances.

  • What is Redis and how does it help overcome the limitations of in-memory caching?

    -Redis is a data store that can be used for caching purposes. It helps overcome the limitations of in-memory caching by providing a shared, persistent, and scalable cache that can be accessed across different instances of an application.

  • What is the role of the 'CacheModule' in a NestJS application?

    -The 'CacheModule' in NestJS is used to set up and configure caching within the application. It allows for the registration of various caching options and settings, such as the maximum number of keys and time-to-live (TTL) for cached data.

  • What does TTL stand for in the context of caching?

    -TTL stands for 'Time To Live', which is the duration for which cached data is considered valid before it needs to be refreshed or expired.

  • How can you implement caching in a NestJS application?

    -To implement caching in a NestJS application, you need to install the required packages, import the 'CacheModule' in the AppModule, register the caching options, and then inject the cache manager into your service classes to interact with the cache.

  • What is an 'Interceptor' in NestJS and how does it relate to caching?

    -An 'Interceptor' in NestJS is a class annotated with the @Interceptor() decorator that can intercept incoming requests before they reach their respective handlers. In the context of caching, a cache interceptor can check for a cached response and return it if available, otherwise, it allows the request to proceed and caches the response for future requests.

  • How can you use Redis as a cache store in a NestJS application?

    -To use Redis as a cache store in a NestJS application, you need to install the 'cache-manager-redis-store' package and its TypeScript type definitions. Then, configure the 'CacheModule' to use Redis by setting the 'store' property to 'RedisStore' and providing the host and port of the Redis instance.

  • What is the purpose of using a Docker container for running Redis?

    -Using a Docker container for running Redis allows for easy deployment, isolation, and management of the Redis service. It ensures that the Redis cache store is separate from the application environment, promoting better resource management and consistency.

  • How can you verify if data is being cached in Redis?

    -You can verify if data is being cached in Redis by using the Redis CLI (Command Line Interface) to connect to the Redis instance and executing the 'KEYS' command to list all cached keys or the 'GET' command to retrieve the cached data for a specific key.

Outlines

00:00

📚 Introduction to Caching in Njs

This paragraph introduces the concept of caching in the context of Njs applications. It explains two primary methods of caching: in-memory caching, which is likened to a sticky note for quick access to data stored directly in the application's memory, and using a data store like Redis for larger applications or those requiring data consistency across multiple server instances. The paragraph emphasizes the speed and simplicity of in-memory caching for small-scale applications and the scalability and persistence advantages of Redis for larger applications. It also outlines the steps to implement caching in a Nest application, including installing necessary packages, setting up the cache module, and creating methods to interact with the cache manager.

05:00

🛠 Implementing Caching and Auto-Caching in Njs

In this paragraph, the tutorial continues with the practical implementation of caching within a Nest application. It describes how to set up and interact with the cache manager, including methods for setting and getting cache keys, as well as deleting and resetting the cache. The paragraph also introduces the use of cache interceptors for auto-caching data fetched from the database, demonstrating how to bind the interceptor to a controller to cache all GET routes. It further explains the process of using Redis as a cache store, including installing the necessary packages, configuring the cache module to use Redis, and verifying that data is being cached in Redis by interacting with the Redis CLI.

10:02

🔄 Utilizing Redis for Persistent Caching in Njs

The final paragraph focuses on the integration of Redis as a persistent cache store in a Nest application. It discusses the importance of using Redis to maintain cache data even when the application restarts or crashes, ensuring data consistency and availability. The tutorial guides through the process of setting up Redis as a cache store, including configuring the host and port, and troubleshooting potential type mismatch errors by ensuring the correct version of the cache manager store package is installed. The paragraph concludes with a demonstration of how data is now being cached in Redis and the improved performance observed when fetching data from the cache.

Mindmap

Keywords

💡Caching

Caching is the process of storing frequently used data in a temporary storage area to speed up future access to that data. In the context of the video, caching is a crucial technique in NestJS applications to improve performance by reducing the need to repeatedly fetch the same data from a database or other external sources. The script discusses two main types of caching: in-memory and using a data store like Redis.

💡NestJS

NestJS is a framework for building efficient, reliable, and scalable server-side applications using JavaScript or TypeScript. It is built with and for Node.js, and the video's theme revolves around implementing caching strategies within a NestJS application to enhance its performance and scalability.

💡In-memory caching

In-memory caching refers to the storage of data within the application's memory. It is depicted in the script as a quick and easy method for small-scale applications where the data is stored directly in the application's memory for rapid access. However, it has limitations when it comes to scaling and persisting data across multiple instances or after application restarts.

💡Redis

Redis is an open-source, in-memory data structure store, used as a database, cache, and message broker. In the script, Redis is introduced as a solution for caching that provides persistence, meaning cached data is not lost when the application restarts or crashes, and it supports scaling and sharing data across different instances.

💡Cache Manager

Cache Manager is a library that provides a simple way to manage cache in Node.js applications. The script mentions using the 'cache manager' package in NestJS to set up and interact with the caching mechanisms, whether it's in-memory or using an external store like Redis.

💡TTL (Time To Live)

TTL stands for 'Time To Live', which is the duration for which cached data is considered valid. In the video script, TTL is discussed as a property of the cache where the expiration time can be set in seconds or milliseconds, depending on the version of the cache manager being used.

💡Interceptor

An interceptor in NestJS is a class annotated with the @Interceptor() decorator that can intercept an outgoing request or an incoming response. The script describes using a CacheInterceptor to automatically cache the response of a request if no cached response is available, thus enhancing the efficiency of data retrieval.

💡Docker

Docker is a platform that allows developers to develop, deploy, and run applications in containers. The script mentions creating a Docker image for the NestJS application and running it in a container to demonstrate the caching functionality in a practical environment.

💡Postman

Postman is an API platform for building and using APIs. It is used in the script to test the endpoints created in the NestJS application, demonstrating how data is fetched from the cache and how new data is stored in the cache.

💡Scalability

Scalability refers to the ability of a system, network, or process to handle a growing amount of work. In the context of the video, scalability is an advantage of using Redis for caching, as it allows the application to handle an increasing load and share cached data across multiple instances.

💡Persistence

Persistence in caching refers to the ability to retain data even after the application is restarted or crashes. The script highlights Redis's persistence feature as a key advantage over in-memory caching, ensuring that cached data is not lost.

Highlights

Introduction to caching in NestJS with a focus on its importance and implementation.

Explanation of in-memory caching as a quick reference guide for small-scale applications.

Limitations of in-memory caching when scaling applications and handling large volumes of data.

Introduction of Redis as a data store for caching to ensure consistency and efficiency across multiple server instances.

Practical guide on choosing between in-memory and Redis caching based on project needs.

Step-by-step tutorial on implementing caching within a NestJS application.

Installation of required packages for caching and setting up the CacheModule in the AppModule.

Configuration of cache properties such as max keys and TTL (Time To Live).

Injection of the CacheManager instance into a class using the CacheManager token.

Creation of methods to set and get cache keys, demonstrating basic cache interactions.

Demonstration of a simple NestJS application running in a Docker container to test caching endpoints.

Use of Postman to interact with the application's caching endpoints and observe cache behavior.

Introduction of additional methods for cache management such as delete, reset, and get all keys.

Explanation of auto-caching data when fetched from the database using cache interceptors.

Setting up a new user module with an endpoint for auto-caching and demonstrating its effectiveness.

Advantages of using Redis over in-memory caching, including persistence and scalability.

Installation and configuration of Redis as a cache store in a NestJS application.

Verification of Redis cache data using the Redis CLI and the impact on application performance.

Conclusion summarizing the implementation of caching in a NestJS application and its benefits.

Transcripts

play00:00

today we'll dive into njs and Tackle an

play00:02

important topic called caching I'll

play00:04

break down caching in njs into simple

play00:06

terms and we'll show you how to

play00:07

implement it but before we start let's

play00:10

understand how caching Works in SGS we

play00:12

have multiple ways on how we can cach

play00:14

data in our application based on our

play00:16

project needs first up we have inmemory

play00:18

caching imagine it like having a sticky

play00:21

note on your desk where you quickly

play00:22

write down important info in njs the

play00:25

application stores data directly in its

play00:27

memory so when a request comes in it

play00:29

checks this fast ACC memory first before

play00:31

doing any heavy lifting it's like having

play00:33

a quick reference guide that saves a lot

play00:34

of time it is super quick for small

play00:37

scale applications and is easy to set up

play00:39

and doesn't require any external tool

play00:41

however it has limitations as your

play00:43

application grows the in-memory cache

play00:45

May struggle to keep up it's great for

play00:47

Simplicity but not always the best for

play00:49

handling large volumes of data or

play00:51

multiple server instances so in order to

play00:53

resolve this issue we can use a data

play00:55

store like RIS when your nest app needs

play00:57

to cat something it sends the data to

play00:59

radies and whenever it needs the data

play01:01

again it checks radies first it's like

play01:04

having a team wi memory ensuring

play01:06

consistency and efficiency across the

play01:08

board so which one to use in a nutshell

play01:11

if you're working on a smaller project

play01:13

where Simplicity is the key inmemory

play01:15

caching might be a go-to it's fast and

play01:18

straightforward on the other hand if

play01:19

you're dealing with a larger application

play01:21

handling a substantial amount of data or

play01:24

need to share their data across

play01:25

different instances redus could be the

play01:27

hero it brings scalability and to the

play01:30

table next let's Implement caching

play01:33

within our

play01:34

application all right let's see this in

play01:36

action I've created a simple Nest

play01:39

application for this tutorial to start

play01:41

with I'll first install the required

play01:43

packages for

play01:50

caching once the packages are installed

play01:54

next let's import cache module in app

play01:56

module

play01:57

file in Imports we can type cache

play02:01

module and import it from njs Cache

play02:04

manager package next let's import the

play02:07

register

play02:09

method this register method takes few

play02:11

optional

play02:12

properties first we have

play02:14

Max which is a maximum number of keys we

play02:17

can store in cash memory let's set it to

play02:20

100 next we have

play02:23

TTL which is the cash expiry

play02:26

time now if I open Package notice the

play02:29

version for cash manager it is five so

play02:33

if we are using cash manager of version

play02:35

four we need to Define TTL in seconds if

play02:38

it is greater than four then we need to

play02:39

Define TTL in

play02:41

milliseconds now if we want that we

play02:44

don't want our cash to expire we can set

play02:46

it to

play02:47

zero now since we have registered cache

play02:50

module let's see in memory caching so to

play02:53

interact with cash manager instance we

play02:55

need to inject it to our class using

play02:57

cash manager

play02:58

token I'll head over to app

play03:01

service I'll create a Constructor

play03:04

first then I'll inject our cash manager

play03:11

tokon which is imported from Nest cash

play03:13

manager

play03:15

package next I'll create an instance for

play03:17

a cash manager

play03:23

class which is imported from cash

play03:27

manager next I have created two methods

play03:30

to set and get cach keys set cach key

play03:33

will accept two parameters key and

play03:37

value and we'll set the key in the cache

play03:40

memory get cach key method will accept

play03:43

key as the parameter and we fetch the

play03:47

value for that key from the cach memory

play03:49

if the key does not exist in memory it

play03:51

returns null next I have created route

play03:54

for these two methods let's run our app

play03:57

first and hit these endpoints

play04:00

to run our app let's create a Docker

play04:02

Image

play04:05

First Once the image is built let's run

play04:08

it in a

play04:16

container we can see our app is running

play04:20

next let's open Postman and hit these

play04:22

end

play04:28

points

play04:30

we have set two keys first name and last

play04:33

name now let's try to get these keys

play04:36

I'll try to get first name first so I'm

play04:39

getting the data similarly let's try to

play04:42

get the last name key as

play04:45

well now let's try to get a key that we

play04:48

haven't set so far let's say

play04:52

age so in this case since we haven't set

play04:55

this key we are getting nulls data next

play04:58

I added few more methods

play05:00

to delete a cach key to reset the whole

play05:03

cach memory this will delete all the

play05:06

keys and to get all the keys in our cash

play05:09

tour also have added routes for these

play05:11

three methods as well next let's open

play05:17

Postman let's first try to get all the

play05:20

keys from our store so we have two keys

play05:23

that we created

play05:24

previously let's try to delete one of

play05:27

these Keys let's try to delete first

play05:33

name this will delete our key now if I

play05:36

try to get first name we'll get

play05:40

null similarly let's try to reset our

play05:43

cache this will clear our cache so if I

play05:48

try to get all the keys we don't have

play05:50

any key

play05:51

now this is not an ideal way how we cat

play05:54

data in our

play05:55

application we don't have to hit this

play05:57

end points every time we want to save

play05:59

data in Cache memory these endpoints

play06:02

were just for this tutorial to show how

play06:04

caching Works in SGS and how we can use

play06:06

inbu cache manager to fetch the cach

play06:09

data n provides a mechanism to autoc

play06:12

cach the data when it's fetched from DB

play06:15

let's see that in

play06:17

action I've created a new user module

play06:19

for autoc

play06:21

caching I'll create a new endpoint to

play06:23

get data and we'll try to autoc catch

play06:25

that

play06:26

data first I'll head over to app module

play06:29

in my cache modu register method I'll

play06:32

register a new property is

play06:35

global and we'll set it to

play06:37

true if you want to use cache module in

play06:40

other modules in our application we have

play06:42

to import it in those modules but since

play06:45

we set is global property to true it

play06:47

will be loaded in root module and will

play06:49

be available to use in other

play06:51

modules in my user service I've created

play06:53

a new method get users which is

play06:56

returning test users data from Json

play06:59

pleas soer

play07:00

API next let's create an endpoint for

play07:02

this

play07:03

method in my user controller I've

play07:06

created a get endpoint to get all

play07:09

users now if we want to cache data for

play07:11

this route we can bind cache Interceptor

play07:13

here so after our get decorator let's

play07:18

import use interceptors decorator which

play07:21

excepts an Interceptor let's add cach

play07:24

Interceptor which is important from Nest

play07:27

cash manager package what it does is it

play07:30

intercepts the incoming requests before

play07:32

they reach their respective

play07:33

handlers it checks if there is a cach

play07:36

response available for the request if

play07:38

there is it Returns the cach response

play07:40

instead of forwarding the request to the

play07:42

Handler if there isn't a cach response

play07:45

the Interceptor allows the request to

play07:46

proceed to the Handler and once the

play07:48

request is generated it caches it for

play07:50

future requests now if you want to cach

play07:52

all routes in this controller we can B

play07:54

cache Interceptor at controller level so

play07:57

if we remove it from here and add it

play07:59

after for controller decorator in this

play08:01

way it will cach all get routes within

play08:04

this controller next let's head over to

play08:06

postman and hit this

play08:11

endpoint we can see that we don't have

play08:13

any keys in Cache

play08:16

memory now if I hit this endpoint first

play08:19

time it will take some time to fetch

play08:22

data we can see that it took 97

play08:26

milliseconds to fetch users data but if

play08:30

we hit endpoint again we can see it f

play08:32

data in a very less time because this

play08:35

time it Fest data from cach memory now

play08:37

if we see the cache key again we can see

play08:40

that it takes the route as key since we

play08:42

didn't set any key explicitly for this

play08:44

route I'll head over to vs code

play08:47

again and my user controller after I've

play08:50

defined the get

play08:52

aurator i'll import the cach key

play08:55

aurator and here I'll Define the key for

play08:58

this route

play09:00

let's name it users now the next time I

play09:02

hit this endpoint it will store the

play09:04

value for this route against the users's

play09:07

key so far so good if we can cache a

play09:11

data in inbuilt Cache memory then why do

play09:14

we need third party stores like radius

play09:16

the reason is inmemory cache will reset

play09:19

every time our Nest application is

play09:21

restarted or even crashed so we need a

play09:23

store like redes to store cash data so

play09:26

that even if our app is crashed or even

play09:28

restarted we don't lose our cash data

play09:31

although this is not the only reason to

play09:32

use redis there are many other

play09:34

advantages as well of using redis like

play09:37

its scalability persistence Etc next

play09:41

let's add ready store in our Nest

play09:43

application now in order to use redis we

play09:45

need to install two more packages cash

play09:48

manager red store package allows us to

play09:50

use redis as a cash store with cash

play09:58

manager

play09:59

next we need to install this package

play10:02

which provides typescript type

play10:03

definitions for cash manager at store

play10:05

package we need to install it as a

play10:07

developer

play10:09

dependency once both packages are

play10:11

installed we can head over to app module

play10:14

and import our package then in a

play10:17

register method we can add another

play10:18

property called store and point it to

play10:21

ready store by default it points to in

play10:23

memory store then we need to add

play10:28

host and Port of our red store so Port

play10:32

is by default

play10:33

6379 and for host since we are running

play10:36

redes in Docker we need to define the

play10:39

container

play10:39

IP so first let's head over to Docker

play10:43

and check if our radius image is running

play10:46

then let's open our terminal and type

play10:49

Docker PS this will list down our

play10:51

running

play10:52

containers then copy the container ID

play10:54

for Rus and type talker inspect

play11:02

and then paste this

play11:04

ID we'll get the IP address for our

play11:06

container let's copy

play11:08

this and paste here now we are getting

play11:11

an error for store property it says that

play11:15

there is a type mismatch for the

play11:17

property that means it is expecting a

play11:20

value that we are not providing so if we

play11:23

head over to package

play11:25

J we can see that we have installed the

play11:27

latest version for manager at store

play11:30

which is version three we need to decate

play11:32

this version and provide version two

play11:34

here so let's open

play11:38

Terminal let's clear it first and

play11:41

uninstall our

play11:42

package then let's install version two

play11:45

for this

play11:48

package so this error should be gone now

play11:51

now once we have set up our ready store

play11:53

let's hit the endpoint again and see if

play11:55

data is being cached in radi or not

play11:58

let's open open Docker first then in

play12:01

containers click on this red is

play12:03

container go to

play12:05

execute Tab and type redis hyphen CLI to

play12:11

interact with the radius CLI then type

play12:13

Keys Asis to list down all the keys we

play12:17

can see that there's no key currently in

play12:19

redish then open Postman and hit the

play12:23

endpoint

play12:25

again we got the data and it took about

play12:28

700 milliseconds to fetch the

play12:31

data let's see if we got the key in

play12:33

radius or not let's type key asri again

play12:36

and we can see that we now have users

play12:39

key in redis if you want to get the data

play12:41

we can type get and then users and we

play12:44

can see that we have our cach

play12:46

data now if I hit the endpoint

play12:49

again it took just 14 milliseconds to F

play12:52

the data now because it f the data from

play12:55

ready cash and that's it with just a few

play12:58

lines of code we have implemented

play12:59

caching in our Nest application thanks

play13:01

for tuning in I'll see you in the next

play13:03

video

Rate This

5.0 / 5 (0 votes)

Etiquetas Relacionadas
NestJSCachingIn-MemoryRedisData StorePerformanceTutorialCache ManagerDockerRedis Store
¿Necesitas un resumen en inglés?