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 type | Example use | Commands |
|---|---|---|
| String | Cached JSON, counters | SET, GET, INCR, EXPIRE |
| Hash | An object with fields | HSET, HGET, HGETALL |
| List | A simple queue, recent items | LPUSH, RPOP, LRANGE |
| Set | Unique members (online users) | SADD, SISMEMBER |
| Sorted set | Leaderboards, time-ordered data, rate limit windows | ZADD, ZRANGE, ZREMRANGEBYSCORE |
| Stream | An append-only event log with consumer groups | XADD, 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"):
- Look in the cache.
- Hit: return it.
- Miss: load from the database, store it in the cache with a TTL, return it.
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
inFlightmap 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+EXPIREor 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
| Option | How | Direction | Good for |
|---|---|---|---|
| Polling | Client asks every N seconds | Client to server | Simple dashboards; low frequency |
| Long polling | The server holds the request open until there is news | Client to server | Older fallback |
| Server-Sent Events (SSE) | One long HTTP response streaming data: lines | Server to client only | Notifications, live feeds, progress, AI token streaming. Auto-reconnects; works over plain HTTP |
| WebSockets | A persistent, two-way connection after an HTTP upgrade | Both ways | Chat, 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.
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
Originheader 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
| Word | Meaning |
|---|---|
| Redis | An in-memory key-value data store |
| TTL | Time to live: automatic expiry |
| Cache-aside | Load into the cache on a miss; delete on update |
| Cache stampede | Many requests reloading the same expired key at once |
| Server-Sent Events | A one-way stream of events from server to browser |
| WebSocket | A persistent two-way connection |
| Heartbeat | Regular ping messages to detect dead connections |
| Pub/sub | Publish and subscribe messaging between processes |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.