Redis Caching with NodeJs

Pratik Kumar
4 min readJun 7, 2020

This article will explain how Redis cache works with a simple nodejs application so that we can improve our application speed and performance.

In this article, we will build an application that will call GitHub API to extract the number of the repository of the particular user and save it into the cache. after that when we call the same endpoint, it will extract the data from the cache instead of calling the GitHub API again.

What is Caching?

caching is a process of storing the data in cache memory for later use. cache temporarily stores the data so that future requests for that data can be served faster.

Setting Up An Express Server:

To start a Node.js project we need to run “npm init -yin your project folder. this will create a basic package.json file with all of the default values filled in for you. after that, we need to install express by running “npm install express”. In last we need to create an app.js file with the following code.

'use strict';
const Express = require('express')
const Port = process.env.port || 5000;
const App = Express();
// Start the Server
App.listen(Port, ()=>{
console.log(`server running on port ${Port}`)
})

This app.js file will set up the server at 5000 port. After that run node app.js to start the application and if everything worked you should see a message in the console saying server running on port 5000.

This is the basic setup for our application. whenever we make changes in an application we need to restart your server in the console to see the changes take effect.

setting up Redis environment:

In console run “npm install node-fetch redis” to install Redis and node-fetch
and add the following code then app.js will look like that

'use strict';
const Express = require('express')
const Fetch = require('node-fetch') // to fetch the data
const Redis = require('redis')
const Port = process.env.port || 5000;
// set the redis port
const Redis_Port = process.env.port || 6379;
const App = Express();
// redis client
const Client = Redis.createClient(Redis_Port)
// Start the Server
App.listen(Port, ()=>{
console.log(`server running on port ${Port}`)
})

Implementation of the endpoint:

we will implement the API that will call the GitHub API to fetch the number of repo of given API. add this code into app.js file

// set setResponseasync function setResponse(username, repos) {
return `${username} has ${repos} Github repos`
}
// Make request github for dataasync function getRepos(req, res, next) {
try{
console.log('Fetching data.....')
const { username } = req.params;
const response = await Fetch(`https://api.github.com/users/${username}`);
const data = await response.json();
const repos = data.public_repos;
// set data to redis
Client.setex(username, 3600, repos);
setResponse(username, repos).then((value) => {
res.send(value)
})
} catch(err) {
console.log(err);
res.status(500);
}
}
App.get('/repos/:username', cache, getRepos);

that API is returning the number of repos of a given username

Implementation of cache middleware:

after implementation of the cache middleware, the API first look data into the cache middleware if data is not in cache then it will fetch from GitHub API

add this code into app.js

//cache middlewarefunction cache(req, res, next) {
const { username } = req.params;
Client.get(username, (err, data)=> {
if(err) throw err;
if(data !== null) {
setResponse(username, data).then(res).then((result =>{
res.send(result)
})
}else {
next();
}
})
}

first request:

the first request takes 48ms to fetch the data

second request:

the second request takes 14 ms to fetch the data because it fetches the data from the cache rather than calling the GitHub API

Conclusion:

So, Redis reduces the networks calls means rather than calling every time to the database or any third-party API it fetches data from the cache to reduce the response time.
you can clone the above-implemented code from ‘ https://github.com/pratik-iiitkalyani/Redis-Cache-with-NodeJs.

--

--