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.
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.
At first, Install redis over local system with below command over ubuntu system.
sudo apt-get install redis-server
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
Now install express, redis, node-fetch npm packages with below command:
npm i express node-fetch redis
create a file, server.js inside project folder and put the below code inside this file:
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.
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.