Redis Introduction - Caching and Session Management

intermediate | 45 min read | 2024.12.24

What You’ll Learn in This Tutorial

✓ Redis installation and basic operations
✓ Data types and commands
✓ Caching patterns
✓ Session management
✓ Node.js integration

Step 1: Setup

# macOS
brew install redis
brew services start redis

# Ubuntu
sudo apt install redis-server
sudo systemctl start redis

# Connection check
redis-cli ping
# PONG

Step 2: Basic Commands

# Strings
SET name "Alice"
GET name
SETEX token 3600 "abc123"  # With expiration

# Hash
HSET user:1 name "Alice" email "alice@example.com"
HGET user:1 name
HGETALL user:1

# List
LPUSH queue "task1"
RPUSH queue "task2"
LPOP queue

# Set
SADD tags "javascript" "typescript"
SMEMBERS tags

# Sorted Set
ZADD ranking 100 "alice" 85 "bob"
ZRANGE ranking 0 -1 WITHSCORES

Step 3: Node.js Integration

// npm install ioredis
import Redis from 'ioredis';

const redis = new Redis();

// Cache function
async function getWithCache<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttl: number = 3600
): Promise<T> {
  const cached = await redis.get(key);
  if (cached) {
    return JSON.parse(cached);
  }

  const data = await fetcher();
  await redis.setex(key, ttl, JSON.stringify(data));
  return data;
}

// Usage example
const user = await getWithCache(
  `user:${userId}`,
  () => db.user.findById(userId),
  600
);

Step 4: Session Management

import session from 'express-session';
import RedisStore from 'connect-redis';
import Redis from 'ioredis';

const redis = new Redis();

app.use(session({
  store: new RedisStore({ client: redis }),
  secret: 'your-secret',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 86400000 }
}));

Step 5: Caching Strategies

// Cache-Aside
async function getUser(id: number) {
  const cacheKey = `user:${id}`;
  let user = await redis.get(cacheKey);

  if (!user) {
    user = await db.user.findById(id);
    await redis.setex(cacheKey, 3600, JSON.stringify(user));
  }

  return JSON.parse(user);
}

// Cache invalidation
async function updateUser(id: number, data: any) {
  await db.user.update(id, data);
  await redis.del(`user:${id}`);
}

Summary

Redis is a fast in-memory data store, ideal for caching and session management. Improve performance with proper TTL settings and invalidation strategies.

← Back to list