Add a Redis cache to your NestJS backend
Tags: webdev, node, redis, docker
Published: 2021-04-28 14:53:19

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](https://fast-modular-project.com/modules/redis-cache-nest-js)** 🙂

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](https://dev.to/fastmodularproject/web-starter-react-nestjs-mysql-3o9i).

# 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](https://docs.nestjs.com/techniques/caching) from NestJS, to adapt it to the web starter.

* You should install following packages:
```
npm install cache-manager
npm install cache-manager-redis-store
```

* You should specify your backend environments variables:
```
    export const environment = {
        ...,
        redis: {
            host: process.env.LOCAL_IP,
            port: process.env.REDIS_PORT,
            defaultTtl: 86400
        }
    };
```

* 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**](https://fast-modular-project.com/modules/redis-cache-nest-js) 🙂


# 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:
    ...
```
(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
...
```

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](https://aws.amazon.com/fr/blogs/database/latency-reduction-of-hybrid-architectures-with-amazon-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](https://fast-modular-project.com)
* Module "Scalable caching system with Redis and NestJS" is available [here](https://fast-modular-project.com/modules/redis-cache-nest-js).

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