← Course Index

Redis — Caching, Sessions & Beyond

~30 min · Redis

Ref
Primary Source
Redis University — Redis for JavaScript Developers

Free official course covering Redis data structures with Node.js examples. Best structured Redis learning available. Read →

What is Redis?

Redis is an in-memory data store — a supercharged shared Map that your entire application cluster can access. It reads/writes in microseconds, supports TTL-based expiration, and persists to disk. The universal tool for: caching, sessions, rate limiting, real-time features, and lightweight queues.

💡 JS translation

Redis is like a Map that lives outside your process, survives restarts (with persistence), is shared across all server instances, and has built-in TTL for every key.

Core Data Types

TypeUse caseKey commands
StringCache values, countersSET, GET, SETEX, INCR
HashObjects with multiple fieldsHSET, HGET, HMGET, HGETALL
ListQueues, recent activityLPUSH, RPUSH, LRANGE, BRPOP
SetUnique members, tagsSADD, SISMEMBER, SMEMBERS
Sorted SetLeaderboards, rate limitingZADD, ZRANGE, ZSCORE

Using Redis with Node.js (ioredis)

npm install ioredis

import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL); // redis://redis:6379

// Cache-aside pattern
async function getUserById(userId) {
  const key = `user:${userId}`;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const user = await db.users.findById(userId);
  await redis.setex(key, 300, JSON.stringify(user)); // 5 min TTL
  return user;
}

// Invalidate on update
async function updateUser(userId, data) {
  await db.users.update(userId, data);
  await redis.del(`user:${userId}`);
}

// Rate limiting
async function rateLimit(ip, limit=100, window=60) {
  const key = `ratelimit:${ip}`;
  const count = await redis.incr(key);
  if (count === 1) await redis.expire(key, window);
  return count <= limit;
}

// Session storage (connect-redis)
import session from 'express-session';
import { RedisStore } from 'connect-redis';
app.use(session({
  store: new RedisStore({ client: redis }),
  secret: process.env.SESSION_SECRET,
  resave: false, saveUninitialized: false,
  cookie: { secure: true, maxAge: 86400000 }
}));

TTL Management

await redis.setex('key', 300, 'value');   // Set with 300s TTL
const ttl = await redis.ttl('key');        // Time remaining (-1=no expiry, -2=gone)
await redis.expire('key', 600);            // Reset TTL without changing value
await redis.del('key');                    // Delete immediately

Redis Persistence

ModeHowDurability
RDBPoint-in-time snapshot every N minutesLow — lose data since last snapshot
AOFLog every write commandHigh — can replay to any point
BothRDB + AOFBest — fast restarts + durability
# docker-compose.yml (enables AOF persistence)
redis:
  image: redis:7-alpine
  command: redis-server --appendonly yes --save 60 1

Check Your Understanding

1. You need to cache a user object for 5 minutes. Which command?
2. A user updates their profile. The Redis cache has stale data. What must your update function do?
3. For production Redis that should lose at most ~1 second of data, which persistence config?