This site counts visits with analytics cookies only if you accept. Read the consent

Skip to content

DeploymentReplication Guide

Replication Guide

Production-ready multi-replica setup for every supported framework — Next.js, Express, Fastify, Hono, NestJS, and Standalone Server.

14 min readUpdated

This guide shows a complete, production-ready realtime setup with Redis adapters for each supported framework.

Prerequisites

All examples assume you have created shared adapters as shown in the Redis Adapters page. The adapters.ts file is reused across all frameworks.

Shared Adapters

Every framework uses the same adapter setup. The server is handed pubsub; history and presence are used by your stream and channel handlers, as the Redis Adapters page shows:

lib/adapters.ts
import Redis from "ioredis"
import { createRedisPubSub, createRedisStream, createRedisPresence } 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()])
}

Awaiting connectAdapters() at startup checks that Redis is there; it is not what makes the Pub/Sub adapter work. The adapter keeps every subscription it was asked for and makes it once Redis answers, and holds what is published until then within its queue's bounds. A replica that started while Redis was down, or lost it on the way, hears the other replicas once Redis is back, and connect() rejecting at its deadline leaves the adapter connecting. See Redis Adapters.

Standalone Server

The simplest setup — one process handles HTTP, SSE, and WebSocket.

server.ts
import { createCourierServer } from "@noverax/courier-server"
import { sources } from "./api/sources"
import { pubsub, connectAdapters, disconnectAdapters } from "./lib/adapters"

await connectAdapters()

const server = await createCourierServer({
  sources,
  port: Number(process.env.PORT) || 3001,
  host: "0.0.0.0",
  allowedOrigins: [process.env.ALLOWED_ORIGIN!],
  pubsub,

  // SSE
  maxSSEConnections: 10_000,
  sseMaxLifetimeMs: 300_000,
  onSSEConnect: ({ connectionId, request, source, group, method }) => {
    return { userId: extractUser(request) }
  },
  onSSEDisconnect: ({ meta, reason, eventCount, duration }) => {
    console.log(`SSE closed: user=${meta.userId} reason=${reason} events=${eventCount}`)
  },

  // WebSocket
  heartbeatIntervalMs: 25_000,
  onConnect: ({ connectionId, request }) => {
    const userId = extractUser(request)
    if (!userId) throw new Error("Unauthorized")
    return { userId }
  },
  onDisconnect: ({ meta, code }) => {
    console.log("WS closed", { meta, code })
  },

  onReady: (url) => console.log(`Courier ready at ${url}`),
})

process.on("SIGTERM", async () => {
  await server.stop()
  await disconnectAdapters()
})

Next.js

Next.js App Router supports SSE natively via sseRoute(). WebSocket requires a separate Courier server process.

SSE Route

app/api/sse/route.ts
import { sseRoute } from "@noverax/courier-next"

export const { GET } = sseRoute({
  maxSSEConnections: 5000,
  sseMaxLifetimeMs: 300_000,
  sseHeaders: {
    "Access-Control-Allow-Origin": process.env.NEXT_PUBLIC_APP_URL!,
  },
  onSSEConnect: ({ connectionId, request }) => {
    return { userId: extractUser(request) }
  },
})

HTTP Proxy Route

app/api/request/route.ts
import { apiRoute } from "@noverax/courier-next"

export const { GET, POST } = apiRoute()

Sources come from the core global registry populated in instrumentation.ts — see the Next.js guide.

Separate WS Server

ws-server.ts
import { createCourierServer } from "@noverax/courier-server"
import { sources } from "./api/sources"
import { pubsub, connectAdapters } from "./lib/adapters"

await connectAdapters()

const server = await createCourierServer({
  sources,
  port: Number(process.env.WS_PORT) || 3001,
  host: "0.0.0.0",
  pubsub,
  allowedOrigins: [process.env.NEXT_PUBLIC_APP_URL!],
  onConnect: ({ request }) => {
    const userId = extractUser(request)
    if (!userId) throw new Error("Unauthorized")
    return { userId }
  },
})

Project Structure

Project structure
├── app/
│   ├── api/
│   │   ├── request/route.ts    ← HTTP proxy
│   │   └── sse/route.ts        ← SSE streaming
│   └── page.tsx
├── ws-server.ts                ← separate WS process
├── lib/
│   └── adapters.ts             ← shared Redis adapters
└── api/
    └── sources.ts

Two processes

Next.js runs SSE via its Edge/Node runtime. WebSocket runs as a separate ws-server.ts process. Deploy them independently — they share state via Redis.

Express

server.ts
import http from "node:http"
import express from "express"
import { registerSources } from "@noverax/courier/server"
import { courierHandler, courierSSEHandler, courierWSAttach } from "@noverax/courier-express"
import { sources } from "./api/sources"
import { pubsub, connectAdapters, disconnectAdapters } from "./lib/adapters"

registerSources(sources)
await connectAdapters()

const app = express()
const server = http.createServer(app)

// HTTP proxy
const proxy = courierHandler()
app.all("/api/request", proxy)

// SSE streaming — do NOT apply compression middleware to this route
const sse = courierSSEHandler({
  pubsub, // sseConnections.disconnect() reaches every replica's streams
  maxSSEConnections: 10_000,
  sseMaxLifetimeMs: 300_000,
  onSSEConnect: ({ connectionId, request }) => {
    return { userId: extractUser(request) }
  },
  onSSEDisconnect: ({ meta, reason, eventCount }) => {
    console.log(`SSE closed: ${meta.userId}, ${reason}, ${eventCount} events`)
  },
})
app.get("/api/sse", sse)

// WebSocket — answers upgrades on `path` only; set the client's proxyPath.ws to match
const cleanupWS = courierWSAttach(server, {
  path: "/api/ws",
  pubsub,
  heartbeatIntervalMs: 25_000,
  allowedOrigins: [process.env.ALLOWED_ORIGIN!],
  maxSubscriptionsPerConnection: 100,
  maxMessageSize: 65_536,
  onConnect: ({ request }) => {
    const userId = extractUser(request)
    if (!userId) throw new Error("Unauthorized")
    return { userId }
  },
  onDisconnect: ({ meta, code }) => {
    console.log("WS closed", { meta, code })
  },
})

// Health checks
app.get("/health", (req, res) => res.json({ status: "ok" }))
app.get("/readyz", (req, res) => {
  res.status(shuttingDown ? 503 : 200).send(shuttingDown ? "draining" : "ready")
})

let shuttingDown = false
server.listen(Number(process.env.PORT) || 3001, "0.0.0.0")

process.on("SIGTERM", async () => {
  shuttingDown = true
  // server.close() waits for open streams and sockets, so drain them first:
  // SSE clients get a `courier:shutdown` notice; cleanupWS() refuses new upgrades,
  // closes each socket with 1001 and settles within 5 seconds, whatever Redis does.
  await Promise.all([proxy.shutdownSSE(), sse.shutdownSSE(), cleanupWS()])
  server.close()
  await disconnectAdapters()
})

SSE and compression

Do not apply compression middleware (like compression()) to the SSE route. Compression buffers the response, breaking the streaming behavior.

Fastify

server.ts
import Fastify from "fastify"
import fastifyWebsocket from "@fastify/websocket"
import { wsFrameLimit } from "@noverax/courier/node"
import { registerSources } from "@noverax/courier/server"
import { courierPlugin, courierSSEHandler, courierWSHandler } from "@noverax/courier-fastify"
import { sources } from "./api/sources"
import { pubsub, connectAdapters, disconnectAdapters } from "./lib/adapters"

registerSources(sources)
await connectAdapters()

const fastify = Fastify({ logger: true })

// WebSocket plugin (must register before WS routes). Its ws server reads
// frames up to maxPayload before Courier sees them — 100 MiB by default —
// so bound it as Courier's own servers do (wsFrameLimit from "@noverax/courier/node")
await fastify.register(fastifyWebsocket, { options: { maxPayload: wsFrameLimit() } })

// HTTP proxy
await fastify.register(courierPlugin, { prefix: "/api/request" })

// SSE streaming — the plugin drains its own streams on close; this route
// drains in preClose, or fastify.close() waits for its streams to end
const sse = courierSSEHandler({
  pubsub, // sseConnections.disconnect() reaches every replica's streams
  maxSSEConnections: 10_000,
  sseMaxLifetimeMs: 300_000,
  onSSEConnect: ({ connectionId, request }) => {
    return { userId: extractUser(request) }
  },
  onSSEDisconnect: ({ meta, reason, eventCount }) => {
    console.log(`SSE closed: ${meta.userId}, ${reason}, ${eventCount} events`)
  },
})
fastify.get("/api/sse", sse)
fastify.addHook("preClose", () => sse.shutdownSSE())

// WebSocket
const ws = courierWSHandler({
  pubsub,
  heartbeatIntervalMs: 25_000,
  allowedOrigins: [process.env.ALLOWED_ORIGIN!],
  maxSubscriptionsPerConnection: 100,
  onConnect: ({ request }) => {
    const userId = extractUser(request)
    if (!userId) throw new Error("Unauthorized")
    return { userId }
  },
  onDisconnect: ({ meta, code }) => {
    console.log("WS closed", { meta, code })
  },
})
fastify.get("/ws", { websocket: true }, ws)
// the same connection over HTTP, for a client whose network lets no WebSocket through
fastify.post("/ws", ws.http)
// closes each socket with 1001 within 5 s, and lets go of its pub/sub subscriptions
fastify.addHook("preClose", () => ws.destroy())

// Health checks
fastify.get("/health", async () => ({ status: "ok" }))
fastify.get("/readyz", async (req, reply) => {
  reply.status(shuttingDown ? 503 : 200).send(shuttingDown ? "draining" : "ready")
})

let shuttingDown = false
await fastify.listen({ port: Number(process.env.PORT) || 3001, host: "0.0.0.0" })

process.on("SIGTERM", async () => {
  shuttingDown = true
  await fastify.close()
  await disconnectAdapters()
})

Hono

Hono is runtime-agnostic — this example uses Node.js with @hono/node-server, which carries its own WebSocket upgrade helper.

server.ts
import { Hono } from "hono"
import { serve, upgradeWebSocket } from "@hono/node-server"
import { WebSocketServer } from "ws"
import { registerSources } from "@noverax/courier/server"
import { courierHandler, courierSSEHandler, courierWSHandler } from "@noverax/courier-hono"
import { sources } from "./api/sources"
import { pubsub, connectAdapters, disconnectAdapters } from "./lib/adapters"

registerSources(sources)
await connectAdapters()

const app = new Hono()
const wss = new WebSocketServer({ noServer: true })

// HTTP proxy
app.all("/api/request", courierHandler())

// SSE streaming
app.get("/api/sse", courierSSEHandler({
  pubsub, // sseConnections.disconnect() reaches every replica's streams
  maxSSEConnections: 10_000,
  sseMaxLifetimeMs: 300_000,
  onSSEConnect: ({ connectionId, request }) => {
    return { userId: extractUser(request) }
  },
}))

// WebSocket
const ws = courierWSHandler({
  pubsub,
  heartbeatIntervalMs: 25_000,
  allowedOrigins: [process.env.ALLOWED_ORIGIN!],
  onConnect: ({ request }) => {
    const userId = extractUser(request)
    if (!userId) throw new Error("Unauthorized")
    return { userId }
  },
  onDisconnect: ({ meta, code }) => {
    console.log("WS closed", { meta, code })
  },
})
// the same connection over HTTP, for a client whose network lets no WebSocket through
app.post("/ws", ws.http)
app.get("/ws", upgradeWebSocket((c) => ws(c)))

// Health checks
app.get("/health", (c) => c.json({ status: "ok" }))

const server = serve({
  fetch: app.fetch,
  port: Number(process.env.PORT) || 3001,
  hostname: "0.0.0.0",
  websocket: { server: wss },
})

process.on("SIGTERM", async () => {
  // each socket closed with 1001 and waited for up to 5 s, before the server closes
  await ws.destroy()
  server.close()
  await disconnectAdapters()
})

Other runtimes

For Bun, Deno, or Cloudflare Workers, replace @hono/node-server with the runtime-specific WebSocket API. See the Cloudflare page for Workers setup.

NestJS

main.ts
import { NestFactory } from "@nestjs/core"
import { registerSources } from "@noverax/courier/server"
import { courierWSAttach } from "@noverax/courier-nestjs"
import { AppModule } from "./app.module"
import { sources } from "./api/sources"
import { pubsub, connectAdapters, disconnectAdapters } from "./lib/adapters"

async function bootstrap(): Promise<void> {
  registerSources(sources)
  await connectAdapters()

  const app = await NestFactory.create(AppModule)

  // WebSocket — answers upgrades on `path` only; set the client's proxyPath.ws to match
  const cleanupWS = courierWSAttach(app.getHttpServer(), {
    path: "/api/ws",
    pubsub,
    heartbeatIntervalMs: 25_000,
    allowedOrigins: [process.env.ALLOWED_ORIGIN!],
    onConnect: ({ request }) => {
      const userId = extractUser(request)
      if (!userId) throw new Error("Unauthorized")
      return { userId }
    },
    onDisconnect: ({ meta, code }) => {
      console.log("WS closed", { meta, code })
    },
  })

  await app.listen(Number(process.env.PORT) || 3001, "0.0.0.0")

  process.on("SIGTERM", async () => {
    // AppModule drains its SSE streams in beforeApplicationShutdown
    await cleanupWS()
    await app.close()
    await disconnectAdapters()
  })
}

bootstrap()
app.module.ts
import {
  type BeforeApplicationShutdown,
  Module,
  type NestModule,
  type MiddlewareConsumer,
} from "@nestjs/common"
import { courierMiddleware, courierSSEMiddleware } from "@noverax/courier-nestjs"

const proxy = courierMiddleware()
const sse = courierSSEMiddleware({
  pubsub, // sseConnections.disconnect() reaches every replica's streams
  maxSSEConnections: 10_000,
  sseMaxLifetimeMs: 300_000,
  onSSEConnect: ({ connectionId, request }) => {
    return { userId: extractUser(request) }
  },
  onSSEDisconnect: ({ meta, reason, eventCount }) => {
    console.log(`SSE closed: ${meta.userId}, ${reason}, ${eventCount} events`)
  },
})

@Module({})
export class AppModule implements NestModule, BeforeApplicationShutdown {
  configure(consumer: MiddlewareConsumer): void {
    consumer.apply(proxy).forRoutes("/api/request")
    consumer.apply(sse).forRoutes("/api/sse")
  }

  // app.close() waits for open streams, so they are drained before it does
  async beforeApplicationShutdown(): Promise<void> {
    await Promise.all([proxy.shutdownSSE(), sse.shutdownSSE()])
  }
}

A User's Connections, on Every Replica

connections.disconnect() and connections.requireAuth() reach the connections a selector names on every replica that shares the pub/sub adapter, so signing a user out, or banning one, closes their connections wherever the load balancer sent them:

sign-out.ts
import type { ConnectionRegistry } from "@noverax/courier/server"

export async function signOutEverywhere(connections: ConnectionRegistry, userId: string) {
  // Each connection whose onConnect returned this userId, on every replica
  await connections.disconnect({ meta: { userId } }, { code: 4001, reason: "Signed out" })
}

export async function askForFreshTokens(connections: ConnectionRegistry, userId: string) {
  // Each of them sends its credentials again within 30 seconds, or is closed with 4401
  await connections.requireAuth({ meta: { userId } }, { timeoutMs: 30_000 })
}

sseConnections.disconnect() takes the same selectors, comparing what onSSEConnect returned, and ends the streams on every replica whose HTTP or SSE handler was given the same pubsub; the standalone server passes its own to both. A stream ended so says nothing of why, and its client reconnects as from a dropped one, so revoke the user's credentials too: onSSEConnect then refuses it. The SSE handlers' commands travel on a channel of their own, signed with the same cluster.secret.

A selector is a connection id, { id } with as many as 1000 of them, or { meta } comparing up to 16 fields of what onConnect returned, each to a string, a number or a boolean. The metadata compared is a copy taken as onConnect returned it, renewed by each onReauth: a change made to ctx.meta after that is not seen, and get() and list() hand out copies of it too. A connection is reached from the moment onConnect returns, while it still waits for its place under maxConnectionsPerKey: disconnect() closes it before it is let in, and requireAuth() asks for its credentials as soon as it is. count, get and list() show the connections let in. Each replica finds the connections a selector names through an index of those fields, without a pass over every connection. One the handler cannot use — no id, a field compared to an object — rejects with a TypeError before anything is closed, and so does a code no socket can send. The call resolves once this replica's connections are closed and the adapter's publish of the command for the others has settled — with Redis, once Redis answered it, at once when it waits in the adapter's queue, and after the queue's maxAgeMs, 5 seconds, at the latest: see the Pub/Sub adapter — and it is not sent at all when every id it names is this replica's. The command goes before the broadcasts waiting with it, and none takes its place; still, a replica Redis cannot reach at that moment misses it, and the adapter drops one that waited longer than maxAgeMs, so revoke the user's credentials as well: a client that reconnects is then refused by onConnect. count, get, list() and send() stay with the replica that holds the connections.

Capping a User's Connections

maxConnectionsPerKey limits the connections that share a key, read from what onConnect returned, and counts them in connectionLeases: this replica's memory unless you give a store every replica shares, as Redis is.

ws.ts
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 }),
})

Over the limit, the oldest connection of the key is closed with 4409 "Replaced by a newer connection", wherever it is held, one still being let in as well, and a Courier client does not reconnect on it. A connection that has ended by the time onConnect returns — a tab closed meanwhile — takes no place and replaces none. With onExceed: "reject", the new connection is closed with 4429 instead, and its onDisconnect runs. The server tells its client to try again in 10 seconds, as a place may free meanwhile, and onConnect and onDisconnect run for each try. A key that is undefined puts the connection under no limit.

Keys reach the store hashed, with HMAC under cluster.secret when it is set, never as they are. If the store cannot decide within its timeoutMs, 2 seconds by default, the replica decides by its own count of the key's connections and logs why: a limit guards against abuse, and an outage of the store must not lock users out. Each replica renews its leases every third of the store's ttlMs, and the store puts back one it lacks, as having joined when its connection did. So once the store answers again, or after it lost its keys, the limit counts every connection still open again, and the next one over the limit evicts the oldest, or is refused.

Give it a list to apply several limits at once. A rule keyed by the address's caller key, as callerKeyOf from @noverax/courier/server gives it, is maxConnectionsPerIP for the whole cluster:

ws.ts
import { callerKeyOf } from "@noverax/courier/server"

const ws = createWSHandler({
  pubsub,
  onConnect: ({ auth }) => ({ userId: auth?.userId }),
  maxConnectionsPerKey: [
    { key: (meta) => meta.userId as string | undefined, max: 5 },
    // at most 50 connections from one caller's address, on every replica together
    { key: (_, { clientIp }) => callerKeyOf(clientIp), max: 50, onExceed: "reject" },
  ],
  connectionLeases: createRedisConnectionLeases({ redis }),
})

The address is the one the handler counts the connection against, after clientIp and the proxies it trusts. maxConnectionsPerIP still holds each replica's own sockets before onConnect admits them; a rule counts every replica's together once it has. The rules that refuse are applied first, so a connection refused has given nothing up. A handler with no rule asks the store nothing.

Signing the commands

Whoever can publish on the adapter's channels can send the replicas a command — on a Redis anything else reaches, close any connection. Give every replica the same secret of 32 bytes or more, and each command is signed with HMAC-SHA-256 for the channel it travels on. One that is not signed, or not with the secret, or signed for the other handlers' channel, is refused, and so is one sent again — to the replica that sent it as well — or more than a minute ago, each on one line of the server's log. A replica carries the commands out in the order they were sent:

adapters.ts
const ws = createWSHandler({
  pubsub,
  cluster: { secret: process.env.COURIER_CLUSTER_SECRET }, // openssl rand -hex 32
})

A shorter secret throws CLUSTER_SECRET_INVALID when the handler is made. Without one, the commands are taken unsigned, and the server's log says so once for each adapter, as the first handler given it is made — unless the adapter is a bus in the process, createMemoryBus() or createMemoryPubSub(), which nothing outside it can publish on. Keep the secret out of the repository, as any credential, and keep publishing on the prefix's channels to your application with Redis ACLs as well. Give each application and each environment a secret of its own: a command is good wherever its secret is, so two that share one on a Redis, under two prefixes, would take a command copied from one to the other.

A replica that gets a command of another version than its own — an older replica's or a newer one's, as while a rolling upgrade runs — skips it, saying so in its log.

Resuming Subscriptions

A client that lost its connection subscribes again with the position it counted, and a handler that keeps history sends it what it missed:

ws.ts
const ws = createWSHandler({
  pubsub,
  history: {}, // 100 events a topic, each kept a minute, 8 MiB of frames in all
})

maxBytes counts the frames kept. A topic held without a subscriber, maxTopics of them at most (10 000 by default), keeps its name besides, as long as the subscription's variables made it: where nothing bounds them, a name runs to maxMessageSize, 64 KiB by default, over half a GiB for all the topics held. Bound the variables in the endpoint's schema, or hold fewer topics.

Each event of a topic carries seq, dense from 1 on the replica that delivers it, and subscribed states the position with the epoch that names its sequence. Frames sent to one connection, such as a snapshot from onJoin, carry no number. A topic its last subscriber left is held for maxAgeMs, its events numbered and kept, so a client back within that time is sent them before onJoin runs — after the middleware and authorize, which is where to check who may hold the topic. onJoin reads ctx.recovered and need not send its snapshot again. Only the replica the client left can resume it; with a log, below, any replica can. A position the history no longer reaches, another epoch or another replica answers recovered: false, and the client starts over from onJoin. Once the pub/sub adapter is ready — its server reached, back from an outage or for the first time after a replica started without it, and the subscriptions made there answered — each subscription is told resync: what other replicas published meanwhile never arrived, and what they publish after does.

Replicas whose pub/sub adapter keeps a log share one sequence a topic instead, and need no history. The log numbers each event as it is published; every replica delivers it, the sender's too, and any replica resumes a subscription from the log, so a client need not come back to the one it left. What arrives live while a subscription resumes is sent after what it missed. A replica that missed events reads them from the log and sends them before the next; where the log no longer keeps them, or began another sequence, its subscribers are told resync. Once its adapter is ready, back from an outage or for the first time, a replica catches each topic up from the log. With Redis, the topic log is createRedisPubSub({ publisher, subscriber, log: {} }); handlers in one process share one through their bus:

ws.ts
const bus = createMemoryBus({ log: {} }) // 1000 events a topic, 10 000 topics
const a = createWSHandler({ pubsub: bus.replica("a") })
const b = createWSHandler({ pubsub: bus.replica("b") })

With a log, no replica delivers an event the log did not number: one sent by pubsub.publish itself is left out, with a warning once an interval.

Framework Comparison

FeatureStandaloneNext.jsExpressFastifyHonoNestJS
HTTP proxyBuilt-inapiRoute()courierHandler()courierPlugincourierHandler()courierMiddleware()
SSEBuilt-insseRoute()courierSSEHandler()courierSSEHandler()courierSSEHandler()courierSSEMiddleware()
WebSocketBuilt-inSeparate servercourierWSAttach()courierWSHandler()courierWSHandler()courierWSAttach()
WS libraryBuilt-inN/Aws (peer)@fastify/websocketws (peer)ws (peer)
Processes12 (Next + WS)1111
PubSub wiringpubsub configOn WS servercourierWSAttach optscourierWSHandler optscourierWSHandler optscourierWSAttach opts
Connections, stop, statsserver.wsConnections, stop(), stats()On WS serverconnections, destroy(), stats() on what courierWSAttach returnson what courierWSHandler returnson what courierWSHandler returnson what courierWSAttach returns

Sticky Sessions

Replicas need none. A WebSocket, or an SSE stream, is one connection to one replica while it lasts. A connection that fell back to HTTP lives on the replica that admitted it, and a request of its that the entry deals to another replica is sent on to that one — see HTTP Fallback. A client that comes back after its connection ended may reach any replica:

  • with a topic log, any replica resumes its subscriptions where they stood;
  • with createRedisStream(), any replica resumes a stream after its Last-Event-ID — see Stream Adapter.

Where a handler keeps history without a log, only the replica a client left resumes its subscriptions, and one that reaches another starts over from onJoin. Affinity there keeps more clients on the replica they left, and it spares the requests of a connection over HTTP their hop to its replica; nothing depends on it:

  • nginx: upstream with ip_hash, or hash on a cookie
  • Traefik: sticky.cookie in the service definition
  • K8s Ingress: nginx.ingress.kubernetes.io/affinity: cookie