A beginner's guide to REDIS cache.
Tags: redis, node, database, tutorial
Published: 2022-02-15 18:38:46

##What is caching
Caching is an intermediary stage to provide an abstract storage mechanism to support your backend. It enables efficient data extraction which are optimized to reduce the response time of your server. In simple terms, we store data in a temporary location so that the data can be easily accessed with minimal retrieval cost. It also reduces the bandwidth of data sent over the network thus making your application fast and user-friendly. Once a certain piece of data is obtained after several computations, it is stored in cache and we can directly access it the next time we need it skipping the additional cost of computation.

##Factors to decide when to involve cache in your backend
 
1. **Data chunk being used frequently**
Caching makes sense only if you use a computated chunk of data very frequently. If this is not the case, caching wouldn't make any sense as a new set of data always has to be calculated and stored in cache. 

2. **Deciding your TTL**
TTL is the time in seconds after which your key inside cache will get expired. It is of utmost importance that you have to decide the optimal time after which you want to update/remove the key from cache. The logic to maintain an up-to-date cache plays an important part in both your response time and more importantly not providing stale data in your response.

##How does REDIS cache work
Redis stands for REmote DIctionary Server. It has the ability to store and manipulate high-level data types. It is an in-memory database, its data access operations are faster than any other disk-based database, which makes Redis the perfect choice for caching. Its key-value data storage system is another plus because it makes storage and retrieval much simpler. Using Redis, we can store and retrieve data in the cache using the SET and GET methods, respectively (just like Hashmap in java or dictionary in python).

##Setting up Redis
We will be discussing about implementing Redis for a typical NodeJS server. To start with, we need to install redis node client. Also make sure that Redis is installed and running in your local. To find how to install and spin up redis do checkout [here](https://redis.io/topics/quickstart). 

##Working with Redis in Node layer
Using Redis is very simple. For any route receiving requests, we need to check if the route has cache enabled or not. If enabled we need to find if the data for requested key exists in the cache. If it exists, then without any database operation, we directly return it from the middleware itself. If not, then we compute that data and before returning it we also store in key-pair format in the Redis cache. The key used to store the data can be any custom string which can be formed using several parameters of your request. 
```
const logger = require('winston-logger')
const CONFIG = require('configs/config')
const { redis: redisClient } = require('redis-client')
const axios = require('axios')

const getData = async (_, args, ctx) => {
  try {
    let { data: { slug, query } } = args

    //creating unique key based on slug
    let cacheName = `MEDIA_PAGE_COLLECTION-${slug}`
    let cacheData = await redisClient.get(cacheName)
    if (cacheData) {
      let data = JSON.parse(cacheData)
      return {
        data
      }
    } else {
      let url = `${CONFIG.contentful.baseUrl}/spaces/${CONFIG.contentful.spaceId}/environments/${CONFIG.contentful.environment}`

      let response = await axios({
        url,
        method: 'POST',
        headers: { 'Authorization': `Bearer ${CONFIG.accessToken}`},
        customQuery: {
          query
        }
      })
      data = response.data

      await redisClient.setex(cacheName, 43200, JSON.stringify(data))

      return {
        data
      }
    }
  } catch (error) {
    logger.error('ERROR WHILE FETCHING data >>>', error)
    return error
  }
}
```
The above code is an example of how to implement Redis-cache. Firstly we check if data exists or not. If does not exist then we then create a key dynamically store the data against the key. While storing the data, we have provided 3 parameters. First is the key for which the data has to be stored. Second is the TTL for which the data should be stored in the cache and the third parameter is the content. After the TTL, the key-value pair expires.
I have also attached a basic flow chart to demonstrate the basic functionality of how a typical cache works. 

![Work Flow of Redis Cache](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tf3gfv8aliiatxs1k98p.png)

To install and use Redis for a node server checkout [here](https://www.npmjs.com/package/redis)