Skip to the content

Lesson 205 of 296

Redis caching and WebSockets

What you will learn

  • What Redis is and its main data types
  • The cache-aside pattern
  • Cache invalidation, TTLs and stampedes
  • Other uses of Redis
  • Real-time options: polling, Server-Sent Events, WebSockets
  • WebSockets in Node.js and scaling them
On this page

Redis

Redis is an in-memory data store: it keeps data in RAM, so reads and writes take well under a millisecond. It is used as a cache, session store, queue backend, rate limiter and message broker. (Valkey is an open-source fork of Redis created in 2024, supported by AWS and others; the commands are the same.)

Data typeExample useCommands
StringCached JSON, countersSET, GET, INCR, EXPIRE
HashAn object with fieldsHSET, HGET, HGETALL
ListA simple queue, recent itemsLPUSH, RPOP, LRANGE
SetUnique members (online users)SADD, SISMEMBER
Sorted setLeaderboards, time-ordered data, rate limit windowsZADD, ZRANGE, ZREMRANGEBYSCORE
StreamAn append-only event log with consumer groupsXADD, XREADGROUP

TTL (time to live): every key can expire automatically: SET product:42 "{...}" EX 300 lives for 300 seconds.

The cache-aside pattern

The most common caching pattern ("lazy loading"):

  1. Look in the cache.
  2. Hit: return it.
  3. Miss: load from the database, store it in the cache with a TTL, return it.
TypeScript
export interface KeyValueCache {
  get(key: string): Promise<string | null>;
  set(key: string, value: string, ttlSeconds: number): Promise<void>;
  del(key: string): Promise<void>;
}

export class CacheAside {
  private inFlight = new Map<string, Promise<unknown>>();

  constructor(private readonly cache: KeyValueCache) {}

  async getOrLoad<T>(key: string, ttlSeconds: number, load: () => Promise<T>): Promise<T> {
    const cached = await this.cache.get(key);
    if (cached !== null) return JSON.parse(cached) as T;

    const existing = this.inFlight.get(key);
    if (existing) return existing as Promise<T>;

    const promise = (async () => {
      try {
        const value = await load();
        const jitter = Math.floor(Math.random() * ttlSeconds * 0.1);
        await this.cache.set(key, JSON.stringify(value), ttlSeconds + jitter);
        return value;
      } finally {
        this.inFlight.delete(key);
      }
    })();
    this.inFlight.set(key, promise);
    return promise;
  }

  async invalidate(key: string): Promise<void> {
    await this.cache.del(key);
  }
}

With the redis npm package, the KeyValueCache methods map to client.get(key), client.set(key, value, { EX: ttl }) and client.del(key).

Invalidation, TTLs and stampedes

  • On update, delete the cache key (then the next read reloads fresh data). Deleting is safer than writing the new value into the cache, which can race with other writers.
  • Always set a TTL, so even a missed invalidation heals itself.
  • Cache stampede (thundering herd): a popular key expires and 1,000 requests all miss at once and hit the database together. Defences: let only one request load while others wait (the inFlight map above does this within one process; across servers, use a short Redis lock), add random jitter to TTLs so keys do not all expire together, or refresh popular keys before they expire.
  • Keys: include everything the value depends on: tenant:42:product:7:v2. Version prefixes let you invalidate everything after a format change.
  • Do not cache data that must be perfectly fresh (balances during payment) without careful design.

Other caching patterns: write-through (write to the cache and database together), write-behind (write to the cache, save to the database later; fast but risky), read-through (the cache library loads on a miss for you).

Other uses of Redis

  • Sessions (Lesson 200) shared by all app instances.
  • Rate limiting with INCR + EXPIRE or sorted sets (Lesson 238).
  • Distributed locks (SET lock:job NX PX 30000), with care.
  • Queues (BullMQ).
  • Pub/sub messaging between servers (used to scale WebSockets, below).

Real-time: three options

OptionHowDirectionGood for
PollingClient asks every N secondsClient to serverSimple dashboards; low frequency
Long pollingThe server holds the request open until there is newsClient to serverOlder fallback
Server-Sent Events (SSE)One long HTTP response streaming data: linesServer to client onlyNotifications, live feeds, progress, AI token streaming. Auto-reconnects; works over plain HTTP
WebSocketsA persistent, two-way connection after an HTTP upgradeBoth waysChat, multiplayer games, collaborative editing, live trading

Choose the simplest option that works: if updates only flow from the server, SSE is often enough.

WebSockets

A WebSocket starts as an HTTP request with Upgrade: websocket; the server replies 101 Switching Protocols, and the same TCP connection then carries messages in both directions until closed.

TypeScript
import { WebSocketServer, WebSocket } from "ws";
import type { Server } from "node:http";

type ChatMessage = { type: "chat"; room: string; text: string };

export function attachChat(server: Server) {
  const wss = new WebSocketServer({ server, path: "/ws" });
  const rooms = new Map<string, Set<WebSocket>>();

  wss.on("connection", (socket, request) => {
    const room = new URL(request.url ?? "/", "http://localhost").searchParams.get("room") ?? "general";
    const members = rooms.get(room) ?? new Set<WebSocket>();
    members.add(socket);
    rooms.set(room, members);

    socket.on("message", (raw) => {
      let text: string;
      try {
        const parsed = JSON.parse(raw.toString()) as { text?: unknown };
        if (typeof parsed.text !== "string" || parsed.text.length === 0 || parsed.text.length > 1000) return;
        text = parsed.text;
      } catch {
        return;
      }
      const message: ChatMessage = { type: "chat", room, text };
      for (const member of members) {
        if (member.readyState === WebSocket.OPEN) member.send(JSON.stringify(message));
      }
    });

    socket.on("close", () => {
      members.delete(socket);
      if (members.size === 0) rooms.delete(room);
    });
  });

  return wss;
}

Production concerns:

  • Authenticate during the upgrade (check the session cookie or a short-lived token), and authorise each room or channel.
  • Validate every message (it is user input) and limit message size and rate.
  • Heartbeats (ping and pong) detect dead connections; the client reconnects with backoff.
  • Check the Origin header during the upgrade (WebSockets are not covered by CORS).
  • Libraries such as Socket.IO add rooms, reconnection, acknowledgements and fallbacks on top.

Scaling WebSockets

Each connection lives on one server. With three servers behind a load balancer, users in the same chat room may be connected to different servers. A message received by server A must reach users on servers B and C:

  • Use a pub/sub backplane: each server publishes incoming messages to Redis pub/sub (or Redis Streams, NATS, Kafka) and subscribes to deliver messages to its own connected clients. Socket.IO has a Redis adapter for this.
  • The load balancer must support WebSocket upgrades and long-lived connections (idle timeouts).
  • Sticky sessions are needed for some fallbacks (Socket.IO long polling).
  • Managed options: AWS API Gateway WebSockets, Pusher, Ably.

How to say it in an interview

"Redis is an in-memory store I use for caching, sessions, rate limiting, locks and queues. For caching I use cache-aside: read the cache, on a miss load from the database and set the value with a TTL, and on updates delete the key. I always set TTLs with jitter, include tenant and version in keys, and prevent stampedes by letting only one request reload a key. For real-time I pick the simplest option: polling, Server-Sent Events for server-to-client streams, or WebSockets for two-way communication like chat. WebSockets need authentication during the upgrade, message validation, heartbeats and reconnection, and to scale across servers I use Redis pub/sub as a backplane."

Key words

WordMeaning
RedisAn in-memory key-value data store
TTLTime to live: automatic expiry
Cache-asideLoad into the cache on a miss; delete on update
Cache stampedeMany requests reloading the same expired key at once
Server-Sent EventsA one-way stream of events from server to browser
WebSocketA persistent two-way connection
HeartbeatRegular ping messages to detect dead connections
Pub/subPublish and subscribe messaging between processes

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.