Caching with Redis in Node.js Application

    May 17, 2019       by Pankaj Kumar
nodejs-redis.jpg

Caching is the process of storing data into a cache. A cache is a temporary data store where data is kept for later use. It is not a good approach if we go to database and query for the same data every time. So in this scenerio, we save the data in cache for the first time and retrieve data from cache inplace of database. It increases the app performance a lot.

In this article, We will discuss caching with Redis in Node.js application. For a web developer, it's very necessary to increase the performance and make the app respond faster, And for achieving this we use caching at the server end. I have already shared an article to implement memcached with nodejs and today explaing caching with Redis. 

 

What is Redis?

Official doc says - Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

 

Let's Get Started

 

Step 1: Install redis over local machine

At first, Install redis over local system with below command over ubuntu system.

sudo apt-get install redis-server

 

Step 2: Create nodejs app

Create a project folder, redis-nodejs, move to the folder over terminal and create a nodejs app with default package.json file with below command over terminal.

npm init --yes

 

Step 3: Install required packages

Now install express, redis, node-fetch npm packages with below command:

npm i express node-fetch redis 

 

Step 4: update server.js file

create a file, server.js inside project folder and put the below code inside this file:

 

 
const express = require('express');
const app = express() // create express app
 
const fetch = require("node-fetch");
const redis = require('redis');
 
 
 
const client = redis.createClient(6379); //connect redis client with local instance.
 
// echo redis errors to the console
client.on('error', (err) => {
console.log("Error " + err)
});
 
// get user list
app.get('/user-list', (req, res) => {
const todoRedisKey = 'user:userList';
// Try fetching the result from Redis first in case we have it cached
return client.get(todoRedisKey, (err, users) => {
 
// If that key exists in Redis store
if (users) {
console.log('fetching data from cache-----');
return res.json({ source: 'cache', data: JSON.parse(users) })
 
} else { // Key does not exist in Redis store
console.log('fetching data from api-----');
// Fetch directly from remote api
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(users => {
 
// Save the API response in Redis store, data expire time in 3600 seconds, it means one hour
client.setex(todoRedisKey, 3600, JSON.stringify(users))
 
// Send JSON response to client
return res.json({ source: 'api', data: users })
 
})
.catch(error => {
// log error message
console.log(error)
// send error to the client
return res.json(error.toString())
})
}
});
});
 
// start express server at 3000 port
app.listen(3000, () => {
console.log('Server listening on port: ', 3000)
});
 

 

Step 5: Run the app

Type below command over the terminal in the project folder.

node  server.js

 

Now go to the browser at and enter url: http://localhost:3000/user-list in the url. When yo will fetch the data for the first time, then data will come after calling the api and from the next request, data will fetch from the cache only. And if request time of first request 4000 ms then from the next it will take around 1000 ms.

 

Conclusion

Redis is very powerful in-memory data-store that we can use in our applications. It’s very simple to save and get data without much overhead. 

 

So in this article, We understand the implementation of Redis in Node.js application with a very basic example. Click here to find more Nodejs sample application

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

You can download complete code from here. Download Code


WHAT'S NEW

Find other similar Articles here: