Redis: A Beginner’s Guide with a Practical Demo Project

Madhura Jayashanka
Enlear Academy
Published in
7 min readMar 7, 2024

--

Introduction

Redis is an open-source, in-memory data structure store that can be used as a database, cache, and message broker. It is known for its high performance, flexibility, and wide range of data structures, making it a popular choice for building modern applications. In this article, we’ll explore what Redis is, why you should consider using it, and how it differs from other data stores with a Nodejs app demonstrating the use cases.

What is Redis?

Redis stands for Remote Dictionary Server, and it is often referred to as a data structure server because it allows you to store and manipulate data structures such as strings, hashes, lists, sets, and sorted sets. It is designed to be fast, scalable, and easy to use, making it ideal for use cases where high performance and low latency are important.

Why Redis?

There are several reasons why Redis is a popular choice for developers:

  1. Performance: Redis is incredibly fast because it stores data in memory and uses asynchronous I/O operations to persist data to disk. This makes it ideal for use cases where low latency is critical, such as real-time analytics, caching, and session storage.
  2. Data Structures: Redis supports a wide range of data structures, including strings, hashes, lists, sets, and sorted sets, allowing you to model your data in a way that makes sense for your application.
  3. Built-in Features: Redis comes with several built-in features, such as replication, clustering, and Lua scripting, that make it easy to scale and customize to fit your needs.
  4. Versatility: Redis can be used as a database, cache, or message broker, making it a versatile tool that can be used in a variety of use cases.

How Redis Differs from Other Data Stores

https://backendless.com/redis-what-it-is-what-it-does-and-why-you-should-care/
https://backendless.com/redis-what-it-is-what-it-does-and-why-you-should-care/

While there are several data stores available, Redis stands out in several ways:

  1. In-Memory Storage: Redis stores data in memory, which allows for extremely fast read and write operations. However, this also means that the amount of data you can store is limited by the amount of memory available on your server.
  2. Persistence Options: Redis offers different persistence options, including snapshots and append-only files, to ensure that your data is not lost in case of a server failure.
  3. Data Structures: Redis supports a wide range of data structures, including strings, hashes, lists, sets, and sorted sets, which allows you to model your data in a way that makes sense for your application.
  4. Built-in Features: Redis comes with a number of built-in features, such as replication, clustering, and Lua scripting, that make it easy to scale and customize to fit your needs.

Getting Started with Redis

To get started with Redis, you can download and install it on your local machine or use a cloud-based Redis service in this tutorial I am using the Redis with Docker. Once you have Redis installed, you can interact with it using the Redis CLI or one of the many client libraries available for various programming languages.

Go to Dockerhub and search for Redis.

Then, pull the Redis image:

npx nodemon app.js

Run using the below command:

docker run -d --name my-redis -p 6379:6379 redis

You can access the Redis CLI using the below command:

docker exec -it my-redis redis-cli

Useful Redis CLI Commands

Using Redis CLI, you can perform various tasks, Here are some useful commands:

  • Flush All Data: To flush all data from the Redis database, use the following command: FLUSHALL
  • Flush Specific Database: If you have multiple databases (0–15), you can flush a specific database using the following command: FLUSHDB
  • Check Database Size: To check the size of the current database, use the following command: DBSIZE
  • Check Key Existence: To check if a key exists in the current database, use the following command: EXISTS key_name
  • Delete Key: To delete a key from the current database, use the following command: DEL key_name
  • Get All Keys: To get all keys in the current database, use the following command: KEYS *

Using Redis with Node.js and Express

Here’s a simple Node.js and Express application that demonstrates how you can use Redis to cache data and reduce latency:

const express = require('express');
const axios = require('axios');
const redis = require('redis');

const app = express();
const client = redis.createClient();
const EXPIRATION_TIME = 10; // 10 seconds
client.on('error', (err) => {
console.error('Redis error:', err);
});
// API endpoint to fetch data
app.get('/photos', async (req, res) => {
try {
// Check if data is cached in Redis
client.get('photos', async (error, data) => {
if (error) throw error;
if (data) {
console.log('Data is cached in Redis');
// If data is cached, return it
res.send(JSON.parse(data));
} else {
console.log('Data is not cached in Redis');
// If data is not cached, fetch it from the internet
const response = await axios.get('https://jsonplaceholder.typicode.com/photos');
const fetchedData = response.data;
// Cache the fetched data in Redis for 10 seconds
client.setex('photos', EXPIRATION_TIME, JSON.stringify(fetchedData));
res.send(fetchedData);
}
});
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
  • It uses the client.get('photos', async (error, data) => { ... }) method to attempt to retrieve data for the key 'photos' from the Redis cache.
client.get('photos', async (error, data) => {
if (error) throw error;
if (data) {
console.log('Data is cached in Redis');
res.send(JSON.parse(data));
} else {

}
});
  • If the data is not found in the cache (if (!data) { ... }), it fetches the data from an external API (const response = await axios.get('https://jsonplaceholder.typicode.com/photos');), stores it in Redis using client.setex('photos', EXPIRATION_TIME, JSON.stringify(fetchedData));, and sends it back to the client (res.send(fetchedData);).
client.get('photos', async (error, data) => {
if (error) throw error;
if (data) {

} else {
console.log('Data is not cached in Redis');
const response = await axios.get('https://jsonplaceholder.typicode.com/photos');
const fetchedData = response.data;
client.setex('photos', EXPIRATION_TIME, JSON.stringify(fetchedData));
res.send(fetchedData);
}
});

To run this application, install the required packages:

npm i axios express nodemon redis@3.1.2

Then, start the application using Nodemon:

npx nodemon app.js

When you run the application for the first time, it will take some time to fetch data from the internet and cache it in Redis. You will see a console log indicating that “Data is not cached in Redis”.

This has taken 721ms

However, if you try accessing the /photos endpoint again within 10 seconds, you will see a console log indicating that "Data is cached in Redis".

This has taken only 32ms

This demonstrates how Redis can massively reduce latency and improve the overall performance of your Node.js applications.

GitHub Repository: https://github.com/madhurajayashanka/redis-tutorial

Feel free to clone the repository and experiment with the code to further enhance your understanding of Redis and its benefits in Node.js applications.

Conclusion

In this article, we’ve discussed what Redis is, why it’s beneficial, and how it differs from other caching solutions. We’ve also provided a step-by-step tutorial on setting up Redis with a simple Node.js and Express app to demonstrate its effectiveness in reducing latency and improving performance. By following the instructions in this article, you can easily integrate Redis into your Node.js applications and take advantage of its benefits.

References

Redis Documentation

Docker Redis Image

Redis npm package

Read More Articles by Me

Contact me

Linkedin — https://www.linkedin.com/in/madhurajayashanka/

--

--