How to integrate REDIS into Nodejs API!πŸš€πŸ”₯

Β·

3 min read

In my previous article, we learnt about the theory part of web-caching and Redis. It's recommended to go through it once, to get the concepts part!

I dare you to go through it and understand it before diving into the code!

If you have already gone through it, Fighter! Let's talk code now. πŸ§‘β€πŸ’»


Let's get our hands dirty!

We are going to make a nodejs API, which will be fetching data from reqres.in. We will observe how integrating Redis will help in reducing the response time! Let's get started!!

Initialize the project and install dependencies

For initializing:

npm init -y

We will be needing: Redis(Obviously!), express, axios, response-time

npm install redis express response-time axios

response-time dependency will help in displaying the time taken to fetch and send the requested data. Node modules folder will be created once all the dependencies are installed. Installed dependencies are listed in package.json.


API without Redis

Create a file named index.js.

The below-given code simply fetches user details from the reqres.in! Paste it into your VSCode/any other code editor in the index.js file, that you just created. Make sure all the dependencies are installed mentioned above.

const express = require('express');
const axios = require('axios');
const redis = require('redis');
const responseTime = require('response-time');


const app = express();

// response time for request to be handled
app.use(responseTime());

app.get('/users', async (req, res, next) => {
    try {
     const response = await axios.get('https://reqres.in/api/users?page=1');
     res.send(response.data);

    } catch (error) {
        res.send(error.message)
    }
});

app.listen(6969, () => {
    console.log("App is ruuning on port 6969 πŸš€");
})

Start your server by:

nodemon index.js

We will hit a GET request on the route given in the code. I am using a VSCode extension called REST client, for testing my endpoints. Let's hit the route and observe the output!

Observation:

Response-Time: 351.067ms


API with Redis

We have finally set up Redis in our API. I have mentioned the explanations as comments in the code below.

const express = require('express');
const axios = require('axios');
const redis = require('redis');
const responseTime = require('response-time');


const app = express();

// response time for request to be handled
app.use(responseTime());

// setting up redis
const client = redis.createClient({
    host: '127.0.0.1',
    port: 6379,
});
client.connect().catch(console.error)


app.get('/users', async (req, res, next) => {
    try {
//We are checeking if requested data is present in redis cache memory or not.
     const cacheResponse = await client.get('users');
//if its present then, send it to the client directly
     if(cacheResponse){

        console.log("using cached data");
        res.send(JSON.parse(cacheResponse));
        return
     }
/*
if its not present in redis cache, then send a request to the server, 
get the requested data and :
    1. Store it in cache for future requests
    2. Send it to the user 
*/
 const response = await axios.get('https://reqres.in/api/users?page=1');

//we are saving the data in cache, for 5 seconds.    
 const saveResult = await client.setEx('users', 5, JSON.stringify(response.data));

     console.log("New Data Cached", saveResult);
     res.send(response.data);
    } catch (error) {
        res.send(error.message)
    }
});

//port no: 6969
app.listen(6969, () => {
    console.log("App is ruuning on port 6969 πŸš€");
});

Start the server, hit the route and let's watch the magic happen! πŸͺ„πŸ”₯

  1. The requested data is not present in the cache currently, so first it saves the data in the cache and then sends it to the user.

Now, hit the route again, keeping in mind that data is present in the cache now!

Observation:

Response Time: 3.133ms (~99% reduction πŸ”₯)

So that's how my friends, REDIS does its magic. AWS also provides web caching through their service named, AWS CloudFront ( Article coming soon! πŸ—Ώ )


Congratulations you just optimized your API!πŸ—ΏπŸ—Ώ

Hope you had a wonderful read and implemented with me too!

Do like and share if you learnt something new. Cheers!

Β