Redis

In-Memory Key-Value Store — Cache, Sessions, Queues

Redis

Redis is the standard cache and shared-state store for Node apps.

4 min read Level 2/5 #nodejs#redis#cache
What you'll learn
  • Connect with ioredis
  • Use Redis as a cache
  • Know the other patterns (sessions, locks, queues)

Redis is an in-memory data structure store. Microsecond reads. The standard for: caching, sessions, rate limits, queues, pub/sub, distributed locks.

Install + Connect

npm install ioredis
import { Redis } from "ioredis";

const redis = new Redis(process.env.REDIS_URL);
// redis://default:password@host:6379

await redis.set("hello", "world");
const value = await redis.get("hello");
console.log(value);   // "world"

await redis.quit();

As a Cache

The most common use: avoid hitting a slow DB:

async function getUser(id) {
  const key = `user:${id}`;

  // try cache first
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  // miss — hit the DB
  const user = await db.users.findById(id);

  // cache for 60s
  await redis.set(key, JSON.stringify(user), "EX", 60);

  return user;
}

EX 60 = expire in 60 seconds.

Atomic Counters

await redis.incr("page:views");
await redis.incrby("user:42:credits", 10);

Use for: page views, rate limits, score boards.

Hash, List, Set

// hash — like a map
await redis.hset("user:42", "name", "Ada", "email", "ada@example.com");
const name = await redis.hget("user:42", "name");

// list — ordered
await redis.rpush("queue", "job1", "job2");
const job = await redis.lpop("queue");

// set — unique members
await redis.sadd("online", "user:42");
const isOnline = await redis.sismember("online", "user:42");

Pub/Sub

const subscriber = new Redis();
subscriber.subscribe("notifications");
subscriber.on("message", (channel, msg) => {
  console.log(`[${channel}] ${msg}`);
});

const publisher = new Redis();
await publisher.publish("notifications", "hello!");

Useful for cross-server eventing.

Patterns You’ll Build With It

  • Cache — bypass slow DB reads
  • Sessions — share session state across Node instances
  • Rate limiting — distributed counters
  • Distributed locks — coordinate work across servers
  • Job queues — BullMQ stores its queues in Redis
  • Real-time — pub/sub for WebSocket broadcasts

Hosting

Local: docker run -p 6379:6379 redis:7. Production: Upstash (serverless), Redis Cloud, ElastiCache.

MongoDB →