Node.js — Redis: Getting started with caching

Sameem Abbas
6 min readJun 5, 2024

--

As a backend developer, the relentless pursuit of server optimization is a constant battle cry. You strive to create a robust and efficient system that can handle heavy traffic and complex tasks with ease. In this quest, you’ve likely encountered Redis, an in-memory data store that promises to be a game-changer.

This article delves into the world of Redis, exploring how it can transform your Node.js server and unlock a new level of performance, scalability, and user experience. We’ll explore how Redis’s lightning-fast speed, versatile data structures, and real-time communication capabilities can empower you to build a truly exceptional backend. So, buckle up and get ready to discover the power of Redis!

This article will be a basic setup tutorial to not make it longer than it should be. Further Redis methods will be explored in the upcoming articles.

Caching

Caching, in the context of Redis and Node.js, refers to the practice of storing frequently accessed data from your main database in a super-fast temporary storage location. This temporary location is Redis, the in-memory data store.

Think of it like this: Imagine your main database is like a giant library with all the information you need. But accessing a specific book (data) every time you need it can be slow, like waiting for the librarian to retrieve it from the stacks.

Here’s where caching with Redis comes in. It’s like having a small bookshelf next to your desk where you keep copies of the books you use most often. This way, you can grab the information you need instantly without waiting for the library (main database).

Redis

Redis, short for Remote Dictionary Server, is an open-source in-memory data store that acts like a super-charged cache and database on steroids for your Node.js server. Here’s a breakdown of its key features:

  • Blazing Speed: Unlike traditional databases that store data on disks, Redis keeps everything in RAM (your computer’s memory).
  • Cache Master: One of its most popular uses is as a cache.
  • Data Structure Powerhouse: Redis isn’t just for simple key-value pairs like “username” and “password.” It offers a variety of data structures like lists, sets, sorted sets, and hashes.
  • Real-time Communication Champion: Does your application need different parts to talk to each other instantly? Look no further than Redis! It acts as a message broker, allowing you to send messages to channels and have subscribed parts of your application receive them immediately.
  • Durability with a Twist: While data resides in RAM for ultimate speed, Redis offers persistence options.

By incorporating Redis into your Node.js backend, you can significantly improve performance, scalability, and user experience. It’s like adding a turbocharger to your server, giving it the edge it needs to handle heavy traffic and complex data operations with ease. However, it’s important to remember that Redis complements your main database, not replaces it.

Getting Started

1- Install Linux Subsystem for Windows

On your system open cmd and enter the command:

wsl — install

to install the linux subsystem for windows on your system. once the process is complete, you need to restart your system to complete the wsl setup.

2- Install redis on wsl

Once your system has completely restarted. Click on Start and open Ubuntu application. After that copy below command and paste it in ubuntu.

curl -fsSL https://packages.redis.io/gpg | sudo gpg — dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg

This will install recent stable versions of Redis from the official packages.redis.io APT repository.

Then copy and paste from below,

echo “deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main” | sudo tee /etc/apt/sources.list.d/redis.list

This command adds the official Redis repository to your system’s package list for APT (Advanced Package Tool) on Debian-based Linux distributions.

Then run:

sudo apt-get update

and then:

sudo apt-get install redis

which updates the local package lists of your system and installs the redis package using your system's package manager.

Run the redis server

Now the last step will be to run you redis server. Run the command

redis-server

and you will see a screen like this

If you donot see something like this but instead of ready to accept connections tcp, it say port already in use, You might want to restart you system.

And voila, the Redis server setup is complete.

Initializing the node.js app

Lets consider the example below

//importing necessary libraries
import express from "express";
import fetch from "node-fetch";

const PORT = process.env.PORT || 5000;

const app = express();

async 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;

res.status(200).json({
username: username,
repos: repos
});
} catch (err) {
console.error(err);
res.status(500);
}
}

app.get("/repos/list/:username", getRepos);

app.listen(5000, () => {
console.log(`App listening on port ${PORT}`);
});

The above code fetches github repositories of the username passed in the params.

Integrating Redis

Install redis library

Install the redis library by running:

npm install redis

connect your code to redis

import express from "express";
import fetch from "node-fetch";
import redis from 'redis'; //import redis library

const PORT = process.env.PORT || 5000;
const REDIS_PORT = process.env.REDIS_PORT || 6379;//6379 is the default redis port

const app = express();
const client = redis.createClient(`redis://localhost:${REDIS_PORT}`); // create a redis client instance

async 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;

res.status(200).json({
username: username,
repos: repos
});
} catch (err) {
console.error(err);
res.status(500);
}
}

app.get("/repos/list/:username", getRepos);

app.listen(5000, () => {
console.log(`App listening on port ${PORT}`);
});

Now lets manipulate data on redis server.

Manipulating Data in the Redis Cache

There are two methods I know to store data inside the redis cache:

The Straight Forward Way

this method will store your data inside the redis client.

client.set("userData", jsonString);

OR

client.set('name',
JSON.stringify({ firstname: 'Sameem', lastname: 'Abbas'})
)

Setting Data with Expiry

client.set('userData', jsonString, 'EX', 60);

OR

client.set('name', 'Max', 'EX', 60); //expiry is in seconds

Adding Expiry to Data

client.expire('name', 60);//this will add 60 secs expiry to name

Appending to Already Existing Data

client.append(‘name’, ‘{middleName : 'Developer'}’); //this will append middle name to the name object

Fetching Data From Cache

const data = await client.get("userData");

Check if the Data Exists

client.exists('name', (error, value) => {
if (value) {
console.log('Key does exist')
} else {
console.log('Key does not exist')
}
})

Deleting Data from the Cache

client.del(‘name’)

This is basic setup for redis, you can use the above functions to perform basic operations for storing and manipulating data on redis.

Setting up Redis as a caching layer in your application is a powerful way to enhance performance and scalability. By efficiently storing and retrieving frequently accessed data, Redis reduces the load on your primary database and speeds up response times. In this article, we’ve covered the basics of setting up a Redis client, connecting to a Redis server, and performing essential operations such as setting and getting data with expiration policies. With this foundational knowledge, you’re now equipped to integrate Redis into your projects, leveraging its robust features to build high-performance applications. As you grow more familiar with Redis, you can explore its advanced capabilities, such as data persistence, clustering, and scripting, to further optimize and scale your systems.

I will explore more advanced redis methods and will write another article and mention what I’ve learned.

--

--

Sameem Abbas

🌱 Aspiring developer, coding enthusiast, and perpetual learner on the tech odyssey. Let's conquer bugs! 💻. Learning to be a better Human Being✨