When You Need Redis
Memory adapters work perfectly for single-process deployments. Switch to Redis when:
- Running multiple replicas (K8s, Docker Swarm, PM2 cluster)
- A WS message published on replica A must reach clients on replica B
- SSE clients reconnect to a different replica and need event history
- Presence tracking must be consistent across all replicas
The Pub/Sub adapter is the one the server uses itself, once you pass it as pubsub. The Stream and Presence adapters are building blocks: the server does not read or write them on its own, and your stream and channel handlers call them, as the examples below do.
Installation
npm install @noverax/courier-redis ioredisioredis is a peer dependency, version 5.3 or later — you manage the Redis connection yourself.
Pub/Sub Adapter
Routes WebSocket broadcast messages across replicas via Redis Pub/Sub: a channel handler's ctx.broadcast, and broadcast, broadcastToTopic and broadcastToBaseTopic on the handler's connection registry (server.wsConnections), reach the clients of every replica.
import Redis from "ioredis"
import { createRedisPubSub } from "@noverax/courier-redis"
const url = process.env.REDIS_URL ?? "redis://localhost:6379"
const pubsub = createRedisPubSub({
publisher: new Redis(url), // dedicated connection for PUBLISH
subscriber: new Redis(url), // dedicated connection for SUBSCRIBE
prefix: "courier:", // channel key prefix (default: "")
})
await pubsub.connect().catch((error) => console.warn(error.message))Two connections required
Redis enters subscriber mode on SUBSCRIBE, blocking other commands. You must provide separate publisher and subscriber connections.
The adapter works from the moment it is made, whether Redis is there or not:
- Before Redis answers, and while it is away, what is published waits in a queue and goes out, in order, once Redis is back. The queue holds at most 1000 messages, 1 MiB of them, none older than 5 seconds — past those the oldest are dropped, counted in
stats().droppedand logged. Set them withqueue: { maxMessages, maxBytes, maxAgeMs }. A broadcast that waited longer than a few seconds is usually no longer worth sending, so the age is kept short. - While Redis is reached but slow to answer — paused, swapping, or behind on a burst, its connection still up — the adapter stays
readyand sends Redis no more than the queue's bounds unanswered: 1000 messages, 1 MiB, the last one sent taking it past 1 MiB at times, so a larger message still goes in its turn. What is published past them waits in the queue and goes out, in order, as Redis answers. However long Redis takes, a replica holds twice the queue's bounds at most, give or take a message: one that publishes more than that at once — thousands of broadcasts in one loop — givesqueuelarger bounds. - A publish waits for Redis's answer 5 seconds at most —
maxAgeMs— and settles at once when it waits in the queue, so a broadcast, and the registry'sdisconnectandrequireAuth, wait no longer. A message Redis has not answered by then is still counted instats().inFlight, and Redis may deliver it still. - Courier's own commands — the registry's
disconnectandrequireAuth— wait apart from the broadcasts: they go out first, the broadcasts are dropped first, and no broadcast takes a command's place. One that waited longer thanmaxAgeMsis dropped all the same, so revoke the user's credentials as well, as A User's Connections, on Every Replica says. - Leave ioredis's
commandTimeoutoff the publisher. ioredis keeps a command it timed out until Redis answers: the adapter would take it for answered and send Redis more than its bounds, and count as dropped a message Redis may deliver still. - Every subscription is made as soon as Redis answers, made again after each reconnect, and tried again after a pause — growing from a quarter of a second to 30 seconds — when Redis refuses it, an ACL that does not allow the channel yet for instance. A replica that started while Redis was down hears the others once it is up. A channel no handler wants any more is unsubscribed, even one Redis confirmed only after it was let go of, or that ioredis subscribed again after a reconnect. A client is told its subscription is made once Redis has confirmed the replica's — about one round trip when a topic gains its first subscriber on the replica, and two when its last one had just left — so an event another replica publishes after reaches it. While Redis is away the client is told at once, and while Redis is slow to answer after 2 seconds at most: the replica's subscription is made once Redis answers.
connect({ timeoutMs })waits until the adapter isready— 10 seconds by default — and rejects past it, while the adapter goes on connecting: awaiting it at startup is a check, not what makes the adapter work.disconnect({ timeoutMs })lets go of the subscriptions within its deadline — 2 seconds by default — whatever Redis does, and leaves the two ioredis clients open: they are yours toquit().
state says where it stands: connecting until it first reaches Redis; ready once both connections are up and Redis has answered the subscriptions made as they came up — 2 seconds after at the latest — so a subscription that catches up then misses nothing published after; degraded while it lost Redis and is getting it back; stopped after disconnect(). onStateChange(listener) hears each change. stats() gives the channels wanted and those Redis confirmed, what Redis has yet to answer (inFlight), what is queued, and how many messages were published, delivered and dropped. Losing Redis is logged once on one line, and so is getting it back.
Echo Prevention
Each adapter makes an id of its own, a random UUID, and tags what it publishes with it; it skips the messages tagged with its id, so a replica does not hear its own broadcasts twice. The id cannot be set: one the application chose could be shared — by the PM2 or node:cluster workers of one container, by services given one hostname — and adapters sharing it would skip each other's messages without a word. The presence adapter tells its diffs apart the same way.
Topic Log
With log, the adapter keeps a log of each topic's events in Redis, and a WebSocket handler publishes a topic's events through it. One script numbers each event, keeps it and publishes it, so every replica delivers it under the same number, the sender's too, and a client resumes its subscription on whichever replica it reaches next:
const pubsub = createRedisPubSub({
publisher: new Redis(process.env.REDIS_URL ?? "redis://localhost:6379"),
subscriber: new Redis(process.env.REDIS_URL ?? "redis://localhost:6379"),
prefix: "courier:",
log: { maxEvents: 100, ttlMs: 3_600_000 }, // the defaults, which `log: {}` keeps
})Each topic keeps its last maxEvents events, trimmed as Redis trims a stream, a few more at times, for ttlMs after its last event. A replica that missed events while its connection was down reads them from the log and sends them first. A topic whose keys Redis lost begins its sequence anew in another epoch, and its subscribers are told resync. What is appended while Redis is away, or slow to answer, waits in the queue, in order with what is published. Every replica must keep the log, or none: with a log, a replica delivers no event the log did not number.
Stream Adapter
Keeps a stream's events in Redis Streams, so a client that reconnects to any replica can be sent what it missed.
import Redis from "ioredis"
import { createRedisStream } from "@noverax/courier-redis"
const stream = createRedisStream({
redis: new Redis(process.env.REDIS_URL ?? "redis://localhost:6379"),
prefix: "courier:stream:", // stream key prefix (default: "")
maxLen: 1000, // auto-trim MAXLEN per stream (default: 1000, 0 = no trim)
})
await stream.connect()Resuming a Stream
A stream handler resumes from the adapter itself. The code that produces an event appends it, and Redis gives it an id; the handler reads the stream after the last id its client saw — ctx.lastEventId, which the client sends as Last-Event-ID when it reconnects — and yields each event with tracked(id, …), so the id it resumes from next time is the Redis one. Every replica reads the same Redis stream, so it does not matter which one the client comes back to.
import { courier, defineGroup } from "@noverax/courier/define"
import { tracked } from "@noverax/courier/realtime"
import { z } from "zod"
import { history } from "../lib/adapters"
const { stream } = courier()
const Activity = z.object({ user: z.string(), action: z.string() })
/** Wait `ms`, or less when the client leaves. */
function pause(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve) => {
const timer = setTimeout(resolve, ms)
signal.addEventListener("abort", () => {
clearTimeout(timer)
resolve()
}, { once: true })
})
}
export const activity = defineGroup({
prefix: "activity",
endpoints: {
feed: stream
.variables(z.object({ team: z.string() }))
.response(Activity)
.implement(async function* (ctx) {
const topic = `activity:${ctx.variables.team}`
// After the last event this client saw, or from now for a new one
let cursor = ctx.lastEventId ?? `${Date.now()}-0`
while (!ctx.signal.aborted) {
const events = await history.getHistory(topic, cursor)
for (const event of events) {
cursor = event.id
yield tracked(event.id, Activity.parse(event.data))
}
if (events.length === 0) await pause(500, ctx.signal)
}
}),
},
})
/** Called wherever activity happens, on any replica. */
export async function recordActivity(team: string, user: string, action: string): Promise<void> {
await history.append(`activity:${team}`, { data: { user, action }, timestamp: Date.now() })
}getHistory(topic, afterId, limit) runs Redis XRANGE from just after afterId — exclusive, Redis 6.2 or later — and returns at most limit events, 100 by default; the loop above reads on until it has caught up. A client that was away longer than the stream keeps events for resumes from the oldest one left.
Auto-Trim
Streams are trimmed on every append() using Redis approximate MAXLEN ~. This keeps memory bounded while allowing minor overallocation for performance.
Rate Limit Store
Holds each caller of the proxy to one budget across replicas: without it, every replica counts on its own and a caller gets the budget once per replica. Each call is taken in one Lua script, on Redis's own clock, so replicas whose clocks drift still count alike; a caller whose budget is whole again leaves no key behind.
import Redis from "ioredis"
import { createRedisRateLimitStore } from "@noverax/courier-redis"
const store = createRedisRateLimitStore({
redis: new Redis(process.env.REDIS_URL ?? "redis://localhost:6379"),
prefix: "courier:ratelimit:", // key prefix (default: "courier:ratelimit:")
})
courierHandler({ rateLimit: { requests: 300, window: 60_000, store } })One connection serves it, and it may be the one the Pub/Sub adapter publishes on. See Counts across replicas.
Connection Leases
Counts the connections a WebSocket handler's maxConnectionsPerKey limits on every replica: without it, each replica counts its own, and a user gets the limit once per replica. Each decision is one Lua script on one key, made on Redis's own clock, so two connections arriving together on two replicas never both take the last place:
import Redis from "ioredis"
import { createRedisConnectionLeases } from "@noverax/courier-redis"
const ws = createWSHandler({
pubsub,
onConnect: ({ auth }) => ({ userId: auth?.userId }),
maxConnectionsPerKey: { key: (meta) => meta.userId as string | undefined, max: 5 },
connectionLeases: createRedisConnectionLeases({
redis: new Redis(process.env.REDIS_URL ?? "redis://localhost:6379"),
prefix: "courier:leases:", // key prefix (default: "courier:leases:")
ttlMs: 60_000, // how long a lease is kept unless renewed (default: 60 s)
timeoutMs: 2_000, // how long a replica waits on Redis to decide (default: 2 s)
}),
})A replica renews its leases every third of ttlMs, 20 seconds by default, so one that stops without releasing frees them once ttlMs has passed; ttlMs is a whole number of milliseconds, 1000 or more. The key under a limit, a user's id say, reaches Redis hashed, with HMAC under cluster.secret when it is set. If Redis cannot decide within timeoutMs, the replica lets the connection in by its own count of the key's connections and logs why. A lease Redis lacks, one decided that way or lost with its keys, is put back as its replica renews it, as having joined when its connection did, so the limit counts the connection again. See Capping a user's connections.
Presence Adapter
Tracks online users across replicas using Redis ZSET (scores) + HASH (metadata).
import Redis from "ioredis"
import { createRedisPresence } from "@noverax/courier-redis"
const presence = createRedisPresence({
redis: new Redis(process.env.REDIS_URL ?? "redis://localhost:6379"),
prefix: "courier:presence:", // key prefix (default: "presence:")
})
await presence.connect()Presence is used from a channel's handlers: track a connection when it joins, refresh it on each of its heartbeats, untrack it when it leaves, and tell the room. Give the adapter a subscriber connection as well, and onDiff hears the joins and leaves of every replica, not only its own. The adapter works from the moment it is made: what it is asked before Redis answers waits for Redis, as the client's commands do, and connect({ timeoutMs }) resolves once Redis answers both connections.
import { courier, defineGroup } from "@noverax/courier/define"
import { z } from "zod"
import { presence } from "../lib/adapters"
const { channel } = courier()
const Online = z.object({ online: z.array(z.string()) })
async function onlineIn(topic: string): Promise<z.infer<typeof Online>> {
const entries = await presence.list(topic)
return { online: [...new Set(entries.map((entry) => entry.userId))] }
}
export const rooms = defineGroup({
prefix: "rooms",
endpoints: {
room: channel
.variables(z.object({ room: z.string(), user: z.string() }))
.topic((v) => ({ room: v.room }))
.send(z.object({ type: z.literal("heartbeat") }))
.response(Online)
.implement((v) => {
const topic = `room:${v.room}`
return {
async onJoin(ctx) {
await presence.track(topic, { userId: v.user, connectionId: ctx.connectionId, metadata: {} })
const online = await onlineIn(topic)
ctx.send(online)
ctx.broadcast(ctx.topic, online)
},
async onMessage(ctx) {
await presence.heartbeat(topic, ctx.connectionId)
},
async onLeave(ctx) {
await presence.untrack(topic, ctx.connectionId)
ctx.broadcast(ctx.topic, await onlineIn(topic))
},
}
}),
},
})A replica that crashes never untracks its connections; a sweep, below, removes them once their heartbeats stop.
Data Structure
Each topic creates two Redis keys:
| Key | Type | Purpose |
|---|---|---|
{prefix}score:{topic} | ZSET | member = connectionId, score = lastSeenAt (ms) |
{prefix}meta:{topic} | HASH | field = connectionId, value = packed JSON |
Heartbeat & Sweep
heartbeat(topic, connectionId) refreshes a connection's score, as the room's onMessage does above each time the browser sends { type: "heartbeat" } — every 15 seconds, say. A sweep, run on a timer by one process or by each, removes the connections that stopped:
import { presence } from "./lib/adapters"
// Remove entries without a heartbeat in the last 30 seconds (atomic Lua
// script). The second argument is a duration, not a timestamp.
setInterval(async () => {
const stale = await presence.sweep("room:general", 30_000)
// stale = [{ connectionId, userId, metadata, joinedAt, lastSeenAt }]
if (stale.length > 0) console.log(`swept ${stale.length} from room:general`)
}, 10_000)Diff Events
Subscribe to join/leave events per topic:
const unsubscribe = presence.onDiff("room:general", (diff) => {
for (const entry of diff.joins) {
console.log(`${entry.userId} joined`)
}
for (const entry of diff.leaves) {
console.log(`${entry.userId} left`)
}
})Full Setup Example
Create the adapters once, pass the Pub/Sub adapter to the server, and import the other two where your handlers use them — history and presence in the examples above:
import Redis from "ioredis"
import { createRedisPresence, createRedisPubSub, createRedisStream } from "@noverax/courier-redis"
const redisUrl = process.env.REDIS_URL ?? "redis://localhost:6379"
export const pubsub = createRedisPubSub({
publisher: new Redis(redisUrl),
subscriber: new Redis(redisUrl),
prefix: "courier:",
})
export const history = createRedisStream({
redis: new Redis(redisUrl),
prefix: "courier:stream:",
maxLen: 5000,
})
export const presence = createRedisPresence({
redis: new Redis(redisUrl),
subscriber: new Redis(redisUrl),
prefix: "courier:presence:",
})
export async function connectAdapters(): Promise<void> {
await Promise.all([pubsub.connect(), history.connect(), presence.connect()])
}
export async function disconnectAdapters(): Promise<void> {
await Promise.all([pubsub.disconnect(), history.disconnect(), presence.disconnect()])
}import { createCourierServer } from "@noverax/courier-server"
import { activity } from "./api/activity"
import { rooms } from "./api/rooms"
import { connectAdapters, disconnectAdapters, pubsub } from "./lib/adapters"
import { defineApi } from "@noverax/courier/define"
const api = defineApi({ name: "api", baseURL: "https://api.example.com", groups: { activity, rooms } })
await connectAdapters()
// `pubsub` carries ctx.broadcast and the registry's broadcasts to every replica
const server = await createCourierServer({ sources: { api }, pubsub, port: 3001 })
process.on("SIGTERM", async () => {
await server.stop()
await disconnectAdapters()
})Health Monitoring
Each adapter exposes isHealthy(); the Pub/Sub adapter's is state === "ready", and its stats() carries the rest:
import { history, presence, pubsub } from "./lib/adapters"
app.get("/health/redis", (req, res) => {
const healthy = pubsub.isHealthy() && history.isHealthy() && presence.isHealthy()
res.status(healthy ? 200 : 503).json({
pubsub: pubsub.isHealthy(),
history: history.isHealthy(),
presence: presence.isHealthy(),
})
})Health is tracked automatically via Redis connection events (ready, close, end).
import { pubsub } from "./lib/adapters"
const { state, channels, inFlight, queued, dropped } = pubsub.stats()
// state: "ready", channels: { wanted: 42, confirmed: 42 }, inFlight: { messages: 3, bytes: 412 },
// queued: { messages: 0, bytes: 0 }, dropped: 0Error Handling
All adapters expose onError() for observability:
import { history, presence, pubsub } from "./lib/adapters"
const unsubPubSub = pubsub.onError((error) => {
console.error("[PubSub]", error)
})
const unsubHistory = history.onError((error) => {
console.error("[Stream]", error)
})
const unsubPresence = presence.onError((error) => {
console.error("[Presence]", error)
})Failover Behavior
Redis adapters degrade gracefully — they never kill active client connections:
| Scenario | Behavior |
|---|---|
| Redis down at start | The Pub/Sub adapter is connecting: what is published waits in its queue, subscriptions are made once Redis answers. Presence calls wait for Redis, and its diffs are heard once Redis answers. connect() rejects at its deadline; the adapter goes on. |
| Redis temporarily down | PubSub messages wait in the queue, within its bounds, and go out once Redis is back; past the bounds the oldest are dropped and counted. append rejects and getHistory returns no events, and onError hears both. Presence calls wait as the client's commands wait, and once the client gives up they do nothing — list returns no entries — and onError hears why. |
| Redis reconnects | The Pub/Sub adapter makes every subscription again and sends what waited, and presence hears the other replicas' diffs again |
Redis refuses a SUBSCRIBE | Tried again after a growing pause until Redis takes it; onError hears each refusal |
| Redis hangs | The Pub/Sub adapter sends it no more than its queue's bounds unanswered, keeps the rest in the queue, and settles each publish within maxAgeMs. The adapters' disconnect() and a WebSocket handler's destroy() settle within their deadlines all the same |
| Redis fails over and loses its last writes | The topic log gives the lost events' numbers again: a replica that delivered a lost event drops the new one under its number, until the sequence passes it |
isHealthy() returns false | Your load balancer should stop sending new connections |
ioredis reconnection
ioredis reconnects automatically by default with exponential backoff. Configure via retryStrategy in the Redis constructor.
Redis Key Reference
| Adapter | Key Pattern | TTL |
|---|---|---|
| PubSub | {prefix}{topic}, {prefix}{baseTopic}#* (every qualified topic of an endpoint), {prefix}* (every connection) | None (Pub/Sub channels) |
| Stream | {prefix}{topic} | Auto-trim via MAXLEN |
| Presence (score) | {prefix}score:{topic} | Managed by sweep |
| Presence (meta) | {prefix}meta:{topic} | Managed by sweep |
| Connection leases | {prefix}key:{hash}, one hash per key a limit counts | ttlMs, renewed every third of it |
| Topic log | {prefix}courier:log:{sha1} (a topic's number and epoch) and {prefix}courier:log:{sha1}:events (its events), one hash slot by the topic's SHA-1 | ttlMs after the topic's last event |