Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(events): fan WebSocket events out across replicas via a Redis adapter

Yudhi Armyndharis523e32f0004f
diff --git a/.env.example b/.env.example
index d1dfe11bb..f36dbc9d2 100644
--- a/.env.example
+++ b/.env.example
@@ -271,7 +271,10 @@ DATABASE_CONNECTION_TIMEOUT_MS=10000 # Fails fast if a new connection can't be a
# =============================================================================
# REDIS / QUEUE (Phase 2)
# =============================================================================
-# REDIS_ENABLED=false # Enable Redis for queue and caching
+# REDIS_ENABLED=false # Enable Redis for queue, caching, AND cross-replica WebSocket
+ # event fan-out (Socket.IO Redis adapter). Multi-replica
+ # deployments need this so a WS client on one replica receives
+ # events raised on another; single-node can leave it off.
REDIS_BUILTIN=false # Use built-in Redis container?
# Process webhooks/ingress through the BullMQ queue (needs a reachable Redis via REDIS_HOST/REDIS_PORT).
# Off by default (inline dispatch). In the bundled Docker Compose this is dashboard-managed
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 364a6839d..ca7febb6e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **WebSocket events now fan out across replicas when Redis is enabled.** The realtime gateway
+ broadcasts to Socket.IO rooms, but the default in-memory adapter only reached sockets on the same
+ process — so a client connected to one replica never saw an event raised on another. A Socket.IO
+ Redis adapter (`@socket.io/redis-adapter`, pub/sub over the existing `REDIS_*` connection) is now
+ attached when `REDIS_ENABLED=true` — the same flag the throttler and cache already use — so a
+ broadcast reaches clients on every replica. The scope is fan-out only: mid-connection API-key
+ eviction, per-key WS rate-limit state, and the engine registry remain process-local (see
+ docs/13). Without `REDIS_ENABLED` the adapter is inert and delivery is single-node exactly as
+ before; a Redis outage falls back to local delivery rather than failing the boot.
+
- **Session requests are now routed to the owning node (opt-in via `NODE_URL`).** In a multi-node
deployment a load balancer knows nothing about session placement; a request landing on a
non-owner previously could not be served. When every node announces its own reachable URL
diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.md
index 551fa16aa..386b1afc3 100644
--- a/docs/13-horizontal-scaling.md
+++ b/docs/13-horizontal-scaling.md
@@ -46,13 +46,21 @@
> which is exactly how a takeover begins. Without `NODE_URL` the whole path is inert and
> single-node deployments pay nothing.
>
-> **What does not exist yet, and is why one replica is still the answer.** There is **no**
-> Socket.IO Redis adapter, so a WebSocket client connected to one replica does not receive
-> events raised on another. Not every lifecycle path is fenced: the liveness watchdog and
-> reconnect timers still act on whatever is in the local registry. `BulkMessageService`
-> keeps its live batch state in process, so a takeover cannot resume a batch — only fail
-> it. MCP/agent tool invocations execute on the node that received them rather than being
-> forwarded.
+> **WebSocket events now fan out across replicas** when Redis is enabled (`REDIS_ENABLED=true`,
+> the same flag the throttler and cache already use). The gateway broadcasts to rooms; a Redis
+> pub/sub adapter attached to Socket.IO relays those broadcasts to every replica, so a client
+> connected to node A receives an event raised on node B. Scope honestly: this distributes event
+> **fan-out only**. Mid-connection key eviction (`socketsByKeyId`) is still process-local — a key
+> revoked on node A tears down only A's sockets — as are the per-key WS rate-limit buckets (counted
+> per replica) and the engine registry. Without `REDIS_ENABLED` the adapter is inert and delivery
+> is single-node, exactly as before.
+>
+> **What does not exist yet, and is why one replica is still the answer.** The cross-replica gaps
+> just named (key eviction, WS rate-limit state) remain process-local. Not every lifecycle path is
+> fenced: the liveness watchdog and reconnect timers still act on whatever is in the local
+> registry. `BulkMessageService` keeps its live batch state in process, so a takeover cannot resume
+> a batch — only fail it. MCP/agent tool invocations execute on the node that received them rather
+> than being forwarded.
>
> Everything below (node affinity, `replicas: 3`) remains a **design sketch** until those
> land.
diff --git a/package-lock.json b/package-lock.json
index b8ba874a1..d5bdd62d8 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -26,6 +26,7 @@
"@nestjs/throttler": "^6.5.0",
"@nestjs/typeorm": "^11.0.3",
"@nestjs/websockets": "^11.1.28",
+ "@socket.io/redis-adapter": "^8.3.0",
"@whiskeysockets/baileys": "7.0.0-rc13",
"adm-zip": "^0.6.0",
"archiver": "^8.0.0",
@@ -4138,6 +4139,40 @@
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
"license": "MIT"
},
+ "node_modules/@socket.io/redis-adapter": {
+ "version": "8.3.0",
+ "resolved": "https://registry.npmjs.org/@socket.io/redis-adapter/-/redis-adapter-8.3.0.tgz",
+ "integrity": "sha512-ly0cra+48hDmChxmIpnESKrc94LjRL80TEmZVscuQ/WWkRP81nNj8W8cCGMqbI4L6NCuAaPRSzZF1a9GlAxxnA==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "~4.3.1",
+ "notepack.io": "~3.0.1",
+ "uid2": "1.0.0"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "socket.io-adapter": "^2.5.4"
+ }
+ },
+ "node_modules/@socket.io/redis-adapter/node_modules/debug": {
+ "version": "4.3.7",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
+ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@sqltools/formatter": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/@sqltools/formatter/-/formatter-1.2.5.tgz",
@@ -11175,6 +11210,12 @@
"node": ">=0.10.0"
}
},
+ "node_modules/notepack.io": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/notepack.io/-/notepack.io-3.0.1.tgz",
+ "integrity": "sha512-TKC/8zH5pXIAMVQio2TvVDTtPRX+DJPHDqjRbxogtFiByHyzKmy96RA0JtCQJ+WouyyL4A10xomQzgbUT+1jCg==",
+ "license": "MIT"
+ },
"node_modules/npm-run-path": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz",
@@ -13048,6 +13089,7 @@
"resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.8.tgz",
"integrity": "sha512-6Oy52pbg+kvdCVvjcN+FnY7BvxZ7cIHNScbvztT/It5d0vbwoJoVZmF2gjJmnV0/4WlXRfG15zc45ySk9Ah8bw==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"debug": "~4.4.1",
"ws": "~8.21.0"
@@ -14432,6 +14474,15 @@
"node": ">=8"
}
},
+ "node_modules/uid2": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/uid2/-/uid2-1.0.0.tgz",
+ "integrity": "sha512-+I6aJUv63YAcY9n4mQreLUt0d4lvwkkopDNmpomkAUz0fAkEMV9pRWxN0EjhW1YfRhcuyHg2v3mwddCDW1+LFQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 4.0.0"
+ }
+ },
"node_modules/uint8array-extras": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.5.0.tgz",
diff --git a/package.json b/package.json
index d36c479b3..1e00ebc9b 100644
--- a/package.json
+++ b/package.json
@@ -75,6 +75,7 @@
"@nestjs/throttler": "^6.5.0",
"@nestjs/typeorm": "^11.0.3",
"@nestjs/websockets": "^11.1.28",
+ "@socket.io/redis-adapter": "^8.3.0",
"@whiskeysockets/baileys": "7.0.0-rc13",
"adm-zip": "^0.6.0",
"archiver": "^8.0.0",
diff --git a/src/main.ts b/src/main.ts
index 00e3aa0d0..7fa2ab2c4 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -35,6 +35,7 @@ import { Request, Response, NextFunction, json, urlencoded } from 'express';
import { randomBytes } from 'crypto';
import { readFileSync } from 'fs';
import { extname, join } from 'path';
+import { RedisIoAdapter } from './modules/events/redis-io.adapter';
// The created app, exposed at module scope so the fatal handler below can run a best-effort teardown
// (engine sessions, Redis/pg) when bootstrap fails AFTER NestFactory.create succeeded — notably a
@@ -99,6 +100,11 @@ async function bootstrap() {
const app = await NestFactory.create(AppModule, { bodyParser: false });
appInstance = app;
+ // Cross-replica WebSocket fan-out: when Redis is enabled, broadcasts reach clients on every
+ // replica, not just this process. Set before the gateway's namespace is created so it inherits
+ // the adapter. Inert (plain in-memory adapter) without REDIS_ENABLED, so single-node pays nothing.
+ app.useWebSocketAdapter(new RedisIoAdapter(app));
+
// Aggregate in-flight body budget (DoS hardening): once too many body bytes are being buffered
// across ALL connections, new requests get 503 + Retry-After without their body being read.
// This is a deliberate PRE-GUARD: the throttler/auth guards run at the Nest routing layer —
diff --git a/src/modules/events/redis-io.adapter.spec.ts b/src/modules/events/redis-io.adapter.spec.ts
new file mode 100644
index 000000000..11bbd09c8
--- /dev/null
+++ b/src/modules/events/redis-io.adapter.spec.ts
@@ -0,0 +1,177 @@
+/**
+ * The adapter is the whole opt-in surface for cross-replica fan-out, so what has to hold is narrow
+ * and load-bearing: it attaches the Redis adapter ONLY when Redis is enabled, never opens a
+ * connection otherwise (a single-node deployment must pay nothing), survives a client-construction
+ * failure by falling back rather than crashing the boot, and closes both connections on shutdown.
+ */
+
+const redisInstances: FakeRedis[] = [];
+
+class FakeRedis {
+ readonly handlers: Record<string, (err: Error) => void> = {};
+ quit = jest.fn().mockResolvedValue('OK');
+ constructor(public readonly opts?: unknown) {
+ redisInstances.push(this);
+ }
+ duplicate(): FakeRedis {
+ return new FakeRedis(this.opts);
+ }
+ on(event: string, handler: (err: Error) => void): this {
+ this.handlers[event] = handler;
+ return this;
+ }
+}
+
+jest.mock('ioredis', () => ({ __esModule: true, default: FakeRedis }));
+
+// The mock's return references its args, so createAdapter(pub, sub) yields an identifiable value
+// carrying both clients — proving both that it was called with the pair and that its result is
+// what gets handed to server.adapter().
+const createAdapterMock = jest.fn((pub: unknown, sub: unknown) => ({ tag: 'redis-adapter-fn', pub, sub }));
+jest.mock('@socket.io/redis-adapter', () => ({
+ createAdapter: (pub: unknown, sub: unknown) => createAdapterMock(pub, sub),
+}));
+
+import { RedisIoAdapter, isWsRedisEnabled, wsRedisOptions } from './redis-io.adapter';
+import { IoAdapter } from '@nestjs/platform-socket.io';
+import type { Server } from 'socket.io';
+
+describe('RedisIoAdapter', () => {
+ const prevEnv = { ...process.env };
+
+ beforeEach(() => {
+ redisInstances.length = 0;
+ createAdapterMock.mockClear();
+ });
+
+ afterEach(() => {
+ process.env = { ...prevEnv };
+ });
+
+ const fakeServer = (): { server: Server; adapterFn: jest.Mock } => {
+ const adapterFn = jest.fn();
+ return { server: { adapter: adapterFn } as unknown as Server, adapterFn };
+ };
+
+ /** Stub the base createIOServer so no real socket.io server is spun up. */
+ const withBaseServer = (server: Server): jest.SpyInstance => {
+ return jest.spyOn(IoAdapter.prototype, 'createIOServer').mockReturnValue(server);
+ };
+
+ describe('isWsRedisEnabled', () => {
+ it('is true only for the exact string "true"', () => {
+ process.env.REDIS_ENABLED = 'true';
+ expect(isWsRedisEnabled()).toBe(true);
+ for (const v of ['false', 'True', '1', '']) {
+ process.env.REDIS_ENABLED = v;
+ expect(isWsRedisEnabled()).toBe(false);
+ }
+ delete process.env.REDIS_ENABLED;
+ expect(isWsRedisEnabled()).toBe(false);
+ });
+ });
+
+ describe('wsRedisOptions', () => {
+ it('maps the same REDIS_* env the cache/throttler read', () => {
+ process.env.REDIS_HOST = 'redis.internal';
+ process.env.REDIS_PORT = '6380';
+ process.env.REDIS_PASSWORD = 'secret';
+ const opts = wsRedisOptions();
+ expect(opts.host).toBe('redis.internal');
+ expect(opts.port).toBe(6380);
+ expect(opts.password).toBe('secret');
+ // Reconnect-forever so a blip never strands the SUBSCRIBE connection.
+ expect(typeof opts.retryStrategy).toBe('function');
+ expect((opts.retryStrategy as (n: number) => number)(100)).toBe(5000);
+ });
+ });
+
+ describe('createIOServer', () => {
+ it('opens no Redis connection and does not touch the adapter when Redis is disabled', () => {
+ delete process.env.REDIS_ENABLED;
+ const { server, adapterFn } = fakeServer();
+ const spy = withBaseServer(server);
+ try {
+ const adapter = new RedisIoAdapter({} as never);
+ expect(adapter.createIOServer(2785)).toBe(server);
+ expect(redisInstances).toHaveLength(0);
+ expect(adapterFn).not.toHaveBeenCalled();
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('attaches the Redis adapter with a pub/sub pair when Redis is enabled', () => {
+ process.env.REDIS_ENABLED = 'true';
+ const { server, adapterFn } = fakeServer();
+ const spy = withBaseServer(server);
+ try {
+ const adapter = new RedisIoAdapter({} as never);
+ adapter.createIOServer(2785);
+ // pub + its duplicate = two clients, both given an error handler.
+ expect(redisInstances).toHaveLength(2);
+ expect(redisInstances[0].handlers.error).toBeDefined();
+ expect(redisInstances[1].handlers.error).toBeDefined();
+ expect(createAdapterMock).toHaveBeenCalledWith(redisInstances[0], redisInstances[1]);
+ expect(adapterFn).toHaveBeenCalledWith(
+ expect.objectContaining({ tag: 'redis-adapter-fn', pub: redisInstances[0], sub: redisInstances[1] }),
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('falls back to the base server (no crash) if wiring the adapter throws', () => {
+ process.env.REDIS_ENABLED = 'true';
+ const { server, adapterFn } = fakeServer();
+ adapterFn.mockImplementation(() => {
+ throw new Error('adapter boom');
+ });
+ const spy = withBaseServer(server);
+ try {
+ const adapter = new RedisIoAdapter({} as never);
+ expect(() => adapter.createIOServer(2785)).not.toThrow();
+ } finally {
+ spy.mockRestore();
+ }
+ });
+ });
+
+ describe('close', () => {
+ it('quits both pub and sub clients', async () => {
+ process.env.REDIS_ENABLED = 'true';
+ const { server } = fakeServer();
+ const createSpy = withBaseServer(server);
+ const closeSpy = jest.spyOn(IoAdapter.prototype, 'close').mockResolvedValue(undefined);
+ try {
+ const adapter = new RedisIoAdapter({} as never);
+ adapter.createIOServer(2785);
+ const [pub, sub] = redisInstances;
+
+ await adapter.close(server);
+
+ expect(pub.quit).toHaveBeenCalledTimes(1);
+ expect(sub.quit).toHaveBeenCalledTimes(1);
+ expect(closeSpy).toHaveBeenCalledWith(server);
+ } finally {
+ createSpy.mockRestore();
+ closeSpy.mockRestore();
+ }
+ });
+
+ it('is safe to close when Redis was never enabled (no clients to quit)', async () => {
+ delete process.env.REDIS_ENABLED;
+ const { server } = fakeServer();
+ const createSpy = withBaseServer(server);
+ const closeSpy = jest.spyOn(IoAdapter.prototype, 'close').mockResolvedValue(undefined);
+ try {
+ const adapter = new RedisIoAdapter({} as never);
+ adapter.createIOServer(2785);
+ await expect(adapter.close(server)).resolves.toBeUndefined();
+ } finally {
+ createSpy.mockRestore();
+ closeSpy.mockRestore();
+ }
+ });
+ });
+});
diff --git a/src/modules/events/redis-io.adapter.ts b/src/modules/events/redis-io.adapter.ts
new file mode 100644
index 000000000..81b5c1736
--- /dev/null
+++ b/src/modules/events/redis-io.adapter.ts
@@ -0,0 +1,95 @@
+import { INestApplicationContext } from '@nestjs/common';
+import { IoAdapter } from '@nestjs/platform-socket.io';
+import { createAdapter } from '@socket.io/redis-adapter';
+import Redis, { type RedisOptions } from 'ioredis';
+import type { Server, ServerOptions } from 'socket.io';
+import { createLogger } from '../../common/services/logger.service';
+
+const logger = createLogger('RedisIoAdapter');
+
+/**
+ * Whether cross-replica WebSocket fan-out is switched on. Same `REDIS_ENABLED === 'true'` gate the
+ * throttler and cache read at boot, so a deployment already using Redis for those gets event
+ * fan-out with no extra flag, and a single-node deployment (the default) never opens a connection.
+ */
+export function isWsRedisEnabled(): boolean {
+ return process.env.REDIS_ENABLED === 'true';
+}
+
+/** ioredis options for the pub/sub pair, mirroring the throttler/cache connection env exactly. */
+export function wsRedisOptions(): RedisOptions {
+ return {
+ host: process.env.REDIS_HOST || 'localhost',
+ port: parseInt(process.env.REDIS_PORT || '6379', 10),
+ username: process.env.REDIS_USERNAME,
+ password: process.env.REDIS_PASSWORD,
+ connectTimeout: parseInt(process.env.REDIS_CONNECT_TIMEOUT_MS || '5000', 10),
+ // The adapter's SUBSCRIBE connection cannot issue ordinary commands, so a bounded retry that
+ // gives up (returning null) would strand fan-out permanently after one blip. Reconnect forever
+ // with capped backoff, matching the cache client.
+ retryStrategy: times => Math.min(times * 500, 5000),
+ };
+}
+
+/**
+ * A Socket.IO server whose broadcasts reach clients connected to OTHER replicas, via the Redis
+ * pub/sub adapter.
+ *
+ * The gateway already broadcasts to rooms (`server.to(room).emit(...)`); the default in-memory
+ * adapter only reaches sockets on THIS process, so a client connected to replica A never sees an
+ * event raised on replica B. Attaching the Redis adapter on the root `io` — before any namespace
+ * is used — makes every namespace, including `/events`, fan its room broadcasts out through Redis.
+ * No emit site changes.
+ *
+ * SCOPE (honest): this distributes event FAN-OUT only. Key eviction (`socketsByKeyId`), the WS
+ * rate-limit buckets, and the engine registry remain process-local — a key revoked on replica A
+ * still tears down only A's sockets, and per-key WS limits are counted per replica. See
+ * docs/13-horizontal-scaling.md.
+ *
+ * Failure posture: if the pub/sub clients cannot be created the server falls back to the in-memory
+ * adapter — the local node keeps working, only cross-node fan-out is lost — rather than refusing to
+ * boot. A Redis outage after boot is ioredis's problem to retry; the adapter recovers on reconnect.
+ */
+export class RedisIoAdapter extends IoAdapter {
+ private pubClient?: Redis;
+ private subClient?: Redis;
+
+ constructor(app: INestApplicationContext) {
+ super(app);
+ }
+
+ createIOServer(port: number, options?: ServerOptions): Server {
+ const server = super.createIOServer(port, options) as Server;
+ if (!isWsRedisEnabled()) return server;
+
+ try {
+ const pubClient = new Redis(wsRedisOptions());
+ const subClient = pubClient.duplicate();
+ for (const [name, client] of [
+ ['pub', pubClient],
+ ['sub', subClient],
+ ] as const) {
+ client.on('error', err => logger.warn(`Redis ${name} client error: ${err.message}`));
+ }
+ this.pubClient = pubClient;
+ this.subClient = subClient;
+ server.adapter(createAdapter(pubClient, subClient));
+ logger.log('WebSocket events fan out across replicas via the Redis adapter');
+ } catch (error) {
+ logger.error(
+ 'Could not attach the Redis WebSocket adapter; falling back to single-node event delivery. ' +
+ 'Events raised on other replicas will not reach clients connected here.',
+ error instanceof Error ? error.stack : String(error),
+ );
+ }
+ return server;
+ }
+
+ /** Close the pub/sub connections so a shutdown does not leak them. Called by Nest on app close. */
+ async close(server: Server): Promise<void> {
+ await Promise.allSettled([this.pubClient?.quit(), this.subClient?.quit()]);
+ this.pubClient = undefined;
+ this.subClient = undefined;
+ await super.close(server);
+ }
+}