Node.js7 min read

Working with Redis

Use Redis for caching and sessions. Learn Redis data structures.

Sarah Chen
December 19, 2025
0.0k0

Working with Redis

What is Redis?

Redis is an in-memory data store. Super fast because data lives in RAM.

Use cases:

  • Caching
  • Sessions
  • Real-time analytics
  • Pub/Sub messaging
  • Rate limiting

Setup

npm install redis
const redis = require('redis');

const client = redis.createClient({
  host: 'localhost',
  port: 6379
});

await client.connect();

Basic Operations

await client.set('key', 'value');

const value = await client.get('key');

await client.setEx('key', 3600, 'value');

await client.del('key');

const exists = await client.exists('key');

await client.incr('counter');

Caching Pattern

async function getUser(id) {
  const cacheKey = `user:${id}`;
  
  const cached = await client.get(cacheKey);
  if (cached) {
    return JSON.parse(cached);
  }
  
  const user = await User.findById(id);
  
  await client.setEx(cacheKey, 3600, JSON.stringify(user));
  
  return user;
}

Lists

await client.rPush('queue', 'task1');
await client.rPush('queue', 'task2');

const task = await client.lPop('queue');

const length = await client.lLen('queue');

Sets

await client.sAdd('tags', 'nodejs');
await client.sAdd('tags', 'redis');

const isMember = await client.sIsMember('tags', 'nodejs');

const members = await client.sMembers('tags');

Hashes

await client.hSet('user:123', 'name', 'John');
await client.hSet('user:123', 'email', 'john@example.com');

const name = await client.hGet('user:123', 'name');

const user = await client.hGetAll('user:123');

Key Takeaway

Redis is fast in-memory storage. Use for caching, sessions, queues. Data structures: strings, lists, sets, hashes. Set expiration to save memory.

#Node.js#Redis#Caching#Database