API with NestJS #24. Cache with Redis. Running the app in a Node.js cluster

JavaScript NestJS TypeScript

This entry is part 24 of 121 in the API with NestJS

Redis is a fast and reliable key-value store. It keeps the data in its memory, although Redis, by default, writes the data to the file system at least every 2 seconds.

In the previous part of this series, we’ve used a cache stored in our application’s memory. While it is simple and efficient, it has its downsides. With applications where performance and availability are crucial, we often run multiple instances of our API. With that, the incoming traffic is load-balanced and redirected to multiple instances.

Unfortunately, keeping the cache within the memory of the application means that multiple instances of our API do not share the same cache. Also, restarting the API means losing the cache. Because of all of that, it is worth looking into Redis.

Setting up Redis

Within this series, we’ve used Docker Compose to set up our architecture. It is also very straightforward to set up Redis with Docker. By default, Redis works on port .

docker-compose.yml

To connect Redis to NestJS, we also need the library.

Unfortunately, this library is not prepared to work with TypeScript. To deal with that, we can create our own declaration file.

cacheManagerRedisStore.d.ts

To connect to Redis, we need two new environment variables: the host and the port.

app.module.ts

.env

Once we do all of the above, we can use it to establish a connection with Redis.

posts.module.ts

Managing our Redis server with an interface

As we use our app, we might want to look into our Redis data storage. A straightforward way to do that would be to set up Redis Commander through Docker Compose.

docker-compose.yml

With above we make sure that redis has been started before running Redis Commander

Running Redis Commander in such a way creates a web user interface that we can see at http://localhost:8081/.

Thanks to the way we set up the cache in the previous part of this series, we can now have multiple cache keys for the endpoint.

Running multiple instances of NestJS

JavaScript is single-threaded in nature. Although that’s the case, in the tenth article of the Node.js TypeScript series, we’ve learned that Node.js is capable of performing multiple tasks at a time. Aside from the fact that it runs input and output operations in separate threads, Node.js allows us to create multiple processes.

To prevent heavy traffic from putting a strain on our API, we can also launch a cluster of Node.js processes. Such child processes share server ports and work under the same address. With that, the cluster works as a load balancer.

With Node.js we can also use Worker Threads. To read more about it, check out Node.js TypeScript #12. Introduction to Worker Threads with TypeScript

runInCluster.ts

In the example above, our main process creates a child process for each core in our CPU. By default, Node.js uses the round-robin approach in which the master process listens on the port we’ve opened. It accepts incoming connections and distributes them across all of the processes in our cluster. Round-robin is a default policy on all platforms except Windows.

If you want to read more about the cluster and how to change the scheduling policy, check out Node.js TypeScript #11. Harnessing the power of many processes using a cluster

To use the above logic, we need to supply it with our function. A fitting place for that would be the file:

main.ts

On Linux, we can easily check how many processes our cluster spawns with :

Summary

In this article, we added to the topic of caching by using Redis. One of its advantages is that the Redis cache can be shared across multiple instances of our application. To experience it, we’ve used the Node.js cluster to spawn multiple processes containing our API. The Node.js delegates the incoming requests to various processes, balancing the load.

Series Navigation<< API with NestJS #23. Implementing in-memory cache to increase the performanceAPI with NestJS #25. Sending scheduled emails with cron and Nodemailer >>
Subscribe
Notify of
guest
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
bill
bill
3 years ago

thank you for these articles, these articles have been very helpful for learning✌

kurotyann9696
2 years ago

> Unfortunately, this library is not prepared to work with TypeScript. To deal with that, we can create our own declaration file.

Currently, @types/cache-manager-redis-store is available.
https://www.npmjs.com/package/@types/cache-manager-redis-store?activeTab=readme

Last edited 2 years ago by kurotyann9696
Shamim
2 years ago

cluster.isMaster is deprecated, I think it should be isPrimary. Also showing cluster undefined typing issue on (* as cluster)

Duy
Duy
2 years ago

thanks a lot. this series are very useful.

Vlad
2 years ago

Amazing article! I really enjoyed reading your API with NestJs series.

I wrote an article about caching with Redis long ago, with Typescript support for the cache module!
https://www.codewithvlad.com/blog/nestjs-caching-with-redis