Skip to main content

Command Palette

Search for a command to run...

πŸš€ Redis Caching in Node.js: Beginner to Advanced Guide

Published
β€’4 min read
πŸš€ Redis Caching in Node.js: Beginner to Advanced Guide
P

MERN STACK DEVELOPER

In today’s fast-paced applications, speed is everything. Whether it’s fetching user profiles, showing real-time counters, or maintaining a leaderboard, users expect instant responses. One of the best tools for this job is Redis.

Redis (Remote Dictionary Server) is an open-source, in-memory data store that works as a cache, message broker, and lightweight NoSQL database. Thanks to its in-memory architecture, Redis can perform millions of read/write operations per second with extremely low latency.

1. Getting Started with Redis

Before using Redis in Node.js, make sure Redis is installed and running.

Common Redis Commands:

# Stop Redis server
sudo systemctl stop redis-server  

# Start Redis server
sudo systemctl start redis-server  

# Run Redis server manually
redis-server

Redis runs on port 6379 by default. Once it’s running, we can connect it to Node.js.

2. Creating a Redis Client in Node.js

We’ll use the official redis npm package.

Install the package:

npm install redis

Connecting to Redis:

const redis = require("redis");

const client = redis.createClient({
  url: "redis://localhost:6379",
});

client.on("error", (err) => {
  console.log("Redis Client Error", err);
});

const connectRedis = async () => {
  try {
    await client.connect();
    console.log("Redis connected");
  } catch (error) {
    console.log("Redis connection error", error);
  } finally {
    await client.quit();
    console.log("Redis disconnected");
  }
};

connectRedis();

Explanation:

  • createClient() β†’ Creates a Redis client instance.

  • client β†’ Object used to send commands.

  • on("error") β†’ Handles errors.

  • connect() β†’ Opens connection to Redis server.

  • quit() β†’ Closes connection gracefully.

3. Basic Redis Operations

Let’s look at some common caching operations.

await client.set("name", "prathamesh");
console.log(await client.get("name")); // prathamesh

await client.set("name", "pichkate");
console.log(await client.get("name")); // pichkate

await client.del("name");
console.log(await client.get("name")); // null

await client.set("count", 100);
console.log(await client.incr("count")); // 101
console.log(await client.incr("count")); // 102
console.log(await client.decr("count")); // 101

πŸ‘‰ Redis makes it super easy to store, retrieve, update, and delete data.

4. Working with Redis Data Types

Redis is not just about simple key-value pairs. It supports multiple data structures that make it powerful.

βœ… 4.1 Strings (GET, SET, MSET, MGET)

await client.mSet([
  "user:name", "Prathamesh",
  "user:age", "30",
  "user:place", "Pune"
]);

const [name, age, place] = await client.mGet([
  "user:name", "user:age", "user:place"
]);

console.log(name, age, place); // Prathamesh 30 Pune

βœ” Useful for simple values and caching JSON strings.

βœ… 4.2 Lists (LPUSH, LRANGE, LPOP, RPOP)

await client.lPush("users", ["Alice", "Bob", "Charlie"]);
const allUsers = await client.lRange("users", 0, -1);
console.log(allUsers); // [ 'Charlie', 'Bob', 'Alice' ]

const removed = await client.lPop("users", 2);
console.log("Removed:", removed);

βœ” Useful for queues, task lists, or messaging systems.

βœ… 4.3 Sets (SADD, SMEMBERS, SREM)

await client.sAdd("tags", ["node", "redis", "backend"]);
const tags = await client.sMembers("tags");
console.log(tags); // [ 'node', 'redis', 'backend' ]

βœ… 4.4 Sorted Sets (ZADD, ZRANGE, ZRANK)

await client.zAdd("cart", [
  { score: 100, value: "Cart1" },
  { score: 150, value: "Cart2" },
  { score: 10, value: "Cart3" }
]);

console.log(await client.zRange("cart", 0, -1));
console.log(await client.zRangeWithScores("cart", 0, -1));
console.log(await client.zRank("cart", "Cart1"));

βœ” Perfect for leaderboards, ranking systems, and scoring.

βœ… 4.5 Hashes (HSET, HGET, HGETALL, HDEL)

await client.hSet("product:1", {
  name: "Product 1",
  description: "The product 1 is listed",
  rating: "5",
});

console.log(await client.hGet("product:1", "rating")); 
console.log(await client.hGetAll("product:1"));

await client.hDel("product:1", "rating");
console.log(await client.hGetAll("product:1"));

βœ” Ideal for storing structured data like user profiles or product details.

5. Advanced Redis Usage

Redis can do more than just store data:

  • Pub/Sub β†’ For building real-time notifications or chat systems.

  • Streams β†’ For log processing and event sourcing.

  • TTL (Time-To-Live) β†’ Expire keys after a certain time (perfect for caching).

await client.set("session:user1", "active", { EX: 60 }); // expires in 60s
  • Transactions β†’ Run multiple commands atomically.

  • Lua Scripting β†’ Run custom logic inside Redis.

6. redis vs ioredis

Featureredis (Official)ioredis
Ease of useSimple, lightweightSlightly more complex
PerformanceGood for standaloneOptimized for clusters
Cluster supportLimitedFull cluster + Sentinel support
Reconnection handlingBasicAdvanced, automatic retries
Promises supportYesYes
Best forSmall/medium apps, learningLarge-scale, production, enterprise

πŸ‘‰ If you’re learning or building a small project β†’ use redis.
πŸ‘‰ If you’re deploying in production with clusters β†’ use ioredis.

Example with ioredis:

const Redis = require("ioredis");
const redis = new Redis(); // localhost:6379

redis.set("foo", "bar");
redis.get("foo").then((result) => console.log(result)); // bar

7. Real-World Use Cases of Redis

Redis is widely used in production for:

  • Caching API responses β†’ Reduce DB queries, improve performance.

  • Session storage β†’ Store user sessions in distributed apps.

  • Leaderboards & rankings β†’ Gaming apps, scoring systems.

  • Rate limiting β†’ Control API requests per user.

  • Message queues β†’ Use lists/streams for background jobs.

🎯 Conclusion

Redis is not just a cache β€” it’s a high-performance in-memory data store with powerful features.

We explored:
βœ… Basic setup and commands
βœ… Node.js integration with redis client
βœ… Data structures (Strings, Lists, Sets, Sorted Sets, Hashes)
βœ… Advanced concepts like TTL, Pub/Sub
βœ… Difference between redis and ioredis
βœ… Real-world use cases

With this foundation, you can confidently use Redis in your Node.js applications, from simple caching to enterprise-scale data processing. πŸš€