DEV Community

Cover image for Add a Redis cache to your NestJS backend
Leonidas Costas
Leonidas Costas

Posted on • Edited on • Originally published at fast-modular-project.com

Add a Redis cache to your NestJS backend

Hi Sparta!

In this article I will share with you how to use Redis as scalable cache system in your NestJS backend.

The full source code and the documentation is available here 🙂

This cache system module will be added top of the React/Node/MySQL starter. This starter has already been presented to you in this article.

Redis in 3 words

Redis is an open source in-memory data structure store, that can be used either as a cache, either as a database, or a message broker (like JMS or RabbitMQ). Even in critical applications, Redis is used in production as it provides a high availability via the Redis Sentinels and a automatic partitioning thanks to the Redis Cluster.

Configure your NestJS backend to use Redis

This section is an overhead on top for the official documentation from NestJS, to adapt it to the web starter.

  • You should install following packages:
npm install cache-manager
npm install cache-manager-redis-store
Enter fullscreen mode Exit fullscreen mode
  • You should specify your backend environments variables:
    export const environment = {
        ...,
        redis: {
            host: process.env.LOCAL_IP,
            port: process.env.REDIS_PORT,
            defaultTtl: 86400
        }
    };
Enter fullscreen mode Exit fullscreen mode
  • You should now create a NestJS module MyRedisCacheModule with it's service MyRedisCacheService to interact with your cache through the cache-manager.

set: allows you to set a cached value.

get: allows to retrieve the value (will be undefined when TTL expired).

del: allows you to deleted a stored key.

The controller and the service:

  • gets a cached value in Redis
  • stores a value in Redis
  • deletes a stored key

The controller and service are available here 🙂

Setup Redis for dev environment

  • The initial starter's docker-compose file launches our local databases (with a volume attached), our backend and our frontend. We'll modify it to also launch a redis server locally when starting our web app with docker-compose up.
services:
  db:
    ...

  back:
    ...

  cache:
    image: "redis:alpine"
    ports:
      - ${REDIS_PORT}:${REDIS_PORT}
    env_file: ./.env

  front:
    ...
Enter fullscreen mode Exit fullscreen mode

(optional) to specify a password for this service you can add command: redis-server --requirepass yourpassword in the docker-compose.yaml and add also the password in your backend redisStore: auth_pass: 'password'.

  • The environments variables in .env are loaded by docker when launching your app with docker-compose up. You'll to add to this file the redis port you wanna use:
...
REDIS_PORT = 6379
...
Enter fullscreen mode Exit fullscreen mode

Your redis cache system is now alive locally 🙂
You can test the test endpoints created in last section with Postman!

You want to use a cache system in production ? Let's jump to the next section.

Setup Redis for prod environment

From your code point of view, you'll only need to adapt your environment variables to route to a production AWS ElastiCache. For your Redis instance, the non clustered mode should be enough if not dealing with a large volume of datas. The best documentation to be read for this step is the great one provided by AWS for ElastiCache.

Conclusion

I hope this module will help you saving some time while trying to optimize your backend performance with a Redis cache. If you have any question, I'll be present as usual in the comment section!

Links:

  • The platform sharing the starter and it's modules: Fast Modular Project
  • Module "Scalable caching system with Redis and NestJS" is available here.

Do not hesitate to pin and like if you appreciated the article ❤️

Top comments (0)