An introduction to Caching with Redis in Node.js application

An introduction to Caching with Redis in Node.js application
Caching is the process of storing data into a cache. In this article, We will discuss caching with Redis in Node.js application.

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.

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.

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 Node.js application

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 Node.js application

Type below command over terminal in 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

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Learn More

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Node.js: The Complete Guide to Build RESTful APIs (2018)

Database Caching With Redis and Java

Using Redis Cache with Nodejs to make application super fast

Top 10 Node.js Frameworks

How To Build a Node.js Application with Docker

An introduction to Web Development with Rust for Node.js Developers

Originally published on https://jsonworld.com