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

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
| Feature | redis (Official) | ioredis |
| Ease of use | Simple, lightweight | Slightly more complex |
| Performance | Good for standalone | Optimized for clusters |
| Cluster support | Limited | Full cluster + Sentinel support |
| Reconnection handling | Basic | Advanced, automatic retries |
| Promises support | Yes | Yes |
| Best for | Small/medium apps, learning | Large-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. π


