From 6e2acd07e487dfc74ed92a3cfd5f062de1a8bc45 Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:28:25 +0100 Subject: [PATCH 01/14] feat(websocket): add Redis Pub/Sub adapter --- .../notification/redisPubSubAdapter.ts | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 backend/services/notification/redisPubSubAdapter.ts diff --git a/backend/services/notification/redisPubSubAdapter.ts b/backend/services/notification/redisPubSubAdapter.ts new file mode 100644 index 00000000..bef3407f --- /dev/null +++ b/backend/services/notification/redisPubSubAdapter.ts @@ -0,0 +1,99 @@ +/** + * Redis Pub/Sub adapter for cross-process WebSocket event delivery. + * + * A dedicated publisher and subscriber connection are required because Redis + * switches a subscribed connection into Pub/Sub mode. The adapter deliberately + * accepts structural client interfaces so callers can reuse their Redis + * connection configuration without coupling this module to a Redis package. + */ + +export interface RedisPubSubClient { + publish(channel: string, message: string): Promise; + subscribe(channel: string): Promise; + unsubscribe(channel: string): Promise; + on(event: 'message', listener: (channel: string, message: string) => void): unknown; + removeListener(event: 'message', listener: (channel: string, message: string) => void): unknown; + quit(): Promise; +} + +export interface RedisPubSubAdapter { + publish(channel: string, message: string): Promise; + subscribe(channel: string, handler: (channel: string, message: string) => void): Promise; + close?(): Promise; +} + +export class IORedisPubSubAdapter implements RedisPubSubAdapter { + private readonly handlers = new Map void>>(); + private readonly subscribedChannels = new Set(); + private readonly pendingSubscriptions = new Map>(); + private closed = false; + + private readonly onMessage = (channel: string, message: string): void => { + for (const handler of this.handlers.get(channel) ?? []) { + try { + handler(channel, message); + } catch { + // One consumer must not prevent delivery to other local consumers. + } + } + }; + + constructor( + private readonly publisher: RedisPubSubClient, + private readonly subscriber: RedisPubSubClient, + ) { + if (publisher === subscriber) { + throw new Error('Redis Pub/Sub requires separate publisher and subscriber connections'); + } + this.subscriber.on('message', this.onMessage); + } + + async publish(channel: string, message: string): Promise { + this.assertOpen(); + await this.publisher.publish(channel, message); + } + + async subscribe( + channel: string, + handler: (channel: string, message: string) => void, + ): Promise { + this.assertOpen(); + const channelHandlers = this.handlers.get(channel) ?? new Set(); + channelHandlers.add(handler); + this.handlers.set(channel, channelHandlers); + + if (this.subscribedChannels.has(channel)) return; + + const pending = this.pendingSubscriptions.get(channel); + if (pending) return pending; + + const subscription = this.subscriber.subscribe(channel).then(() => { + this.subscribedChannels.add(channel); + }).catch((error) => { + this.handlers.delete(channel); + throw error; + }).finally(() => { + this.pendingSubscriptions.delete(channel); + }); + + this.pendingSubscriptions.set(channel, subscription); + return subscription; + } + + async close(): Promise { + if (this.closed) return; + this.closed = true; + this.subscriber.removeListener('message', this.onMessage); + + const channels = [...this.subscribedChannels]; + await Promise.all(channels.map((channel) => this.subscriber.unsubscribe(channel))); + this.handlers.clear(); + this.subscribedChannels.clear(); + + await Promise.all([this.publisher.quit(), this.subscriber.quit()]); + } + + private assertOpen(): void { + if (this.closed) throw new Error('Redis Pub/Sub adapter is closed'); + } +} From 7d614192782782728f1fea6a4e51c971ecb595a4 Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:28:27 +0100 Subject: [PATCH 02/14] test(websocket): cover Redis Pub/Sub adapter --- .../__tests__/redisPubSubAdapter.test.ts | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 backend/services/notification/__tests__/redisPubSubAdapter.test.ts diff --git a/backend/services/notification/__tests__/redisPubSubAdapter.test.ts b/backend/services/notification/__tests__/redisPubSubAdapter.test.ts new file mode 100644 index 00000000..179823cb --- /dev/null +++ b/backend/services/notification/__tests__/redisPubSubAdapter.test.ts @@ -0,0 +1,101 @@ +import { IORedisPubSubAdapter, RedisPubSubClient } from '../redisPubSubAdapter'; + +class FakeRedisClient implements RedisPubSubClient { + readonly listeners = new Set<(channel: string, message: string) => void>(); + readonly published: Array<{ channel: string; message: string }> = []; + readonly subscriptions: string[] = []; + readonly unsubscriptions: string[] = []; + quitCalls = 0; + + async publish(channel: string, message: string): Promise { + this.published.push({ channel, message }); + return 1; + } + async subscribe(channel: string): Promise { + this.subscriptions.push(channel); + return 1; + } + async unsubscribe(channel: string): Promise { + this.unsubscriptions.push(channel); + return 1; + } + on(_event: 'message', listener: (channel: string, message: string) => void): this { + this.listeners.add(listener); + return this; + } + removeListener(_event: 'message', listener: (channel: string, message: string) => void): this { + this.listeners.delete(listener); + return this; + } + async quit(): Promise { + this.quitCalls++; + return 'OK'; + } + emitMessage(channel: string, message: string): void { + for (const listener of this.listeners) listener(channel, message); + } +} + +describe('IORedisPubSubAdapter', () => { + it('publishes through the publisher connection', async () => { + const publisher = new FakeRedisClient(); + const subscriber = new FakeRedisClient(); + const adapter = new IORedisPubSubAdapter(publisher, subscriber); + + await adapter.publish('events', '{"id":1}'); + + expect(publisher.published).toEqual([{ channel: 'events', message: '{"id":1}' }]); + expect(subscriber.published).toHaveLength(0); + await adapter.close(); + }); + + it('subscribes once per channel and dispatches messages to local handlers', async () => { + const publisher = new FakeRedisClient(); + const subscriber = new FakeRedisClient(); + const adapter = new IORedisPubSubAdapter(publisher, subscriber); + const first = jest.fn(); + const second = jest.fn(); + + await adapter.subscribe('events', first); + await adapter.subscribe('events', second); + subscriber.emitMessage('events', 'hello'); + + expect(subscriber.subscriptions).toEqual(['events']); + expect(first).toHaveBeenCalledWith('events', 'hello'); + expect(second).toHaveBeenCalledWith('events', 'hello'); + await adapter.close(); + }); + + it('isolates a throwing handler from other handlers', async () => { + const publisher = new FakeRedisClient(); + const subscriber = new FakeRedisClient(); + const adapter = new IORedisPubSubAdapter(publisher, subscriber); + const next = jest.fn(); + + await adapter.subscribe('events', () => { throw new Error('handler failure'); }); + await adapter.subscribe('events', next); + subscriber.emitMessage('events', 'hello'); + + expect(next).toHaveBeenCalledWith('events', 'hello'); + await adapter.close(); + }); + + it('closes both connections and rejects operations after close', async () => { + const publisher = new FakeRedisClient(); + const subscriber = new FakeRedisClient(); + const adapter = new IORedisPubSubAdapter(publisher, subscriber); + await adapter.subscribe('events', jest.fn()); + + await adapter.close(); + + expect(publisher.quitCalls).toBe(1); + expect(subscriber.quitCalls).toBe(1); + expect(subscriber.unsubscriptions).toEqual(['events']); + await expect(adapter.publish('events', 'message')).rejects.toThrow('closed'); + }); + + it('rejects using the same connection for publishing and subscribing', () => { + const client = new FakeRedisClient(); + expect(() => new IORedisPubSubAdapter(client, client)).toThrow('separate'); + }); +}); From 3cc736606efba8b64c07baee2b0bc0c4ef2befa7 Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:28:53 +0100 Subject: [PATCH 03/14] feat(websocket): add Redis Pub/Sub adapter --- .../notification/redisPubSubAdapter.ts | 42 +++++++++++++++++-- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/backend/services/notification/redisPubSubAdapter.ts b/backend/services/notification/redisPubSubAdapter.ts index bef3407f..5d125934 100644 --- a/backend/services/notification/redisPubSubAdapter.ts +++ b/backend/services/notification/redisPubSubAdapter.ts @@ -1,11 +1,11 @@ /** * Redis Pub/Sub adapter for cross-process WebSocket event delivery. * - * A dedicated publisher and subscriber connection are required because Redis - * switches a subscribed connection into Pub/Sub mode. The adapter deliberately - * accepts structural client interfaces so callers can reuse their Redis - * connection configuration without coupling this module to a Redis package. + * Redis requires dedicated connections for publishing and subscribing. The + * structural client interface keeps this adapter independent of a Redis + * package and makes its lifecycle easy to test. */ +import { loadRedisConfig } from '../../config/redis'; export interface RedisPubSubClient { publish(channel: string, message: string): Promise; @@ -83,6 +83,7 @@ export class IORedisPubSubAdapter implements RedisPubSubAdapter { async close(): Promise { if (this.closed) return; this.closed = true; + await Promise.all([...this.pendingSubscriptions.values()]); this.subscriber.removeListener('message', this.onMessage); const channels = [...this.subscribedChannels]; @@ -97,3 +98,36 @@ export class IORedisPubSubAdapter implements RedisPubSubAdapter { if (this.closed) throw new Error('Redis Pub/Sub adapter is closed'); } } + +/** + * Creates independent publisher/subscriber connections from the shared Redis + * environment configuration. Both connections are owned by the returned adapter. + */ +export async function createRedisPubSubAdapter(): Promise { + const config = loadRedisConfig(); + const ioredisModule = (await import('ioredis')) as { + default: new (options: Record) => RedisPubSubClient; + }; + const Redis = ioredisModule.default; + const options = { + host: config.host, + port: config.port, + password: config.password, + db: config.db, + connectTimeout: config.connectTimeoutMs, + maxRetriesPerRequest: 1, + lazyConnect: true, + }; + + const publisher = new Redis(options); + const subscriber = new Redis(options); + + try { + await Promise.all([publisher.ping?.(), subscriber.ping?.()]); + } catch (error) { + await Promise.allSettled([publisher.quit(), subscriber.quit()]); + throw error; + } + + return new IORedisPubSubAdapter(publisher, subscriber); +} From de7bb4b43328a9faa85c3353b5d333b3b5af4cc9 Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:29:06 +0100 Subject: [PATCH 04/14] fix(websocket): await Pub/Sub readiness and shutdown cleanly --- .../notification/eventDrivenWsServer.ts | 64 +++++++++---------- 1 file changed, 31 insertions(+), 33 deletions(-) diff --git a/backend/services/notification/eventDrivenWsServer.ts b/backend/services/notification/eventDrivenWsServer.ts index 3dd2d9f9..30fec415 100644 --- a/backend/services/notification/eventDrivenWsServer.ts +++ b/backend/services/notification/eventDrivenWsServer.ts @@ -1,24 +1,19 @@ import { EventEmitter } from 'events'; -import { SubscriptionEvent, EventFilter, ClientInfo } from './websocket'; +import { SubscriptionEvent, EventFilter } from './websocket'; import { AuthUser } from '../shared/authStrategies'; +import type { RedisPubSubAdapter } from './redisPubSubAdapter'; export interface StoredEvent extends SubscriptionEvent { sequenceId: number; } -export interface RedisPubSubAdapter { - publish(channel: string, message: string): Promise; - subscribe(channel: string, handler: (channel: string, message: string) => void): Promise; -} - +/** In-memory adapter for unit tests and single-process development. */ export class MockRedisPubSubAdapter implements RedisPubSubAdapter { private handlers: Map void)[]> = new Map(); async publish(channel: string, message: string): Promise { const list = this.handlers.get(channel) || []; - for (const handler of list) { - handler(channel, message); - } + for (const handler of list) handler(channel, message); } async subscribe(channel: string, handler: (channel: string, message: string) => void): Promise { @@ -43,33 +38,33 @@ export class EventDrivenWsServer extends EventEmitter { private eventStore: StoredEvent[] = []; private sequenceCounter = 0; private heartbeatInterval?: NodeJS.Timeout; - private pubSub: RedisPubSubAdapter; + private readonly pubSub: RedisPubSubAdapter; + readonly ready: Promise; constructor(pubSubAdapter?: RedisPubSubAdapter) { super(); this.pubSub = pubSubAdapter || new MockRedisPubSubAdapter(); - this.setupPubSub(); + this.ready = this.setupPubSub(); } - private async setupPubSub() { + private async setupPubSub(): Promise { await this.pubSub.subscribe('subtrackr_ws_events', (_channel, message) => { try { const event: StoredEvent = JSON.parse(message); this.dispatchToLocalConnections(event); - } catch (e) { - // Parse error ignore + } catch (error) { + this.emit('invalidMessage', error); } }); } - startHeartbeat(intervalMs = 30000) { + startHeartbeat(intervalMs = 30000): void { + this.stopHeartbeat(); this.heartbeatInterval = setInterval(() => { - const now = Date.now(); for (const [clientId, conn] of this.connections) { if (!conn.isAlive) { conn.close(4001, 'Heartbeat timeout'); - this.connections.delete(clientId); - this.emit('presence', { type: 'leave', clientId, userId: conn.user.id }); + this.removeConnection(clientId); } else { conn.isAlive = false; } @@ -77,13 +72,14 @@ export class EventDrivenWsServer extends EventEmitter { }, intervalMs); } - stopHeartbeat() { + stopHeartbeat(): void { if (this.heartbeatInterval) { clearInterval(this.heartbeatInterval); + this.heartbeatInterval = undefined; } } - handlePong(clientId: string) { + handlePong(clientId: string): void { const conn = this.connections.get(clientId); if (conn) { conn.isAlive = true; @@ -105,23 +101,22 @@ export class EventDrivenWsServer extends EventEmitter { } async publishEvent(rawEvent: SubscriptionEvent): Promise { + await this.ready; this.sequenceCounter++; const storedEvent: StoredEvent = { ...rawEvent, sequenceId: this.sequenceCounter, }; this.eventStore.push(storedEvent); - if (this.eventStore.length > 10000) { - this.eventStore.shift(); // Keep buffer bounded - } + if (this.eventStore.length > 10000) this.eventStore.shift(); await this.pubSub.publish('subtrackr_ws_events', JSON.stringify(storedEvent)); return storedEvent; } - private dispatchToLocalConnections(event: StoredEvent) { + private dispatchToLocalConnections(event: StoredEvent): void { let delivered = 0; - for (const [_, conn] of this.connections) { + for (const conn of this.connections.values()) { if (this.matchesFilter(event, conn.filter, conn.user.id)) { conn.send(event); delivered++; @@ -135,21 +130,24 @@ export class EventDrivenWsServer extends EventEmitter { if (!conn) return []; const missedEvents = this.eventStore.filter( - (e) => e.sequenceId > lastSequenceId && this.matchesFilter(e, conn.filter, conn.user.id) + (event) => event.sequenceId > lastSequenceId && + this.matchesFilter(event, conn.filter, conn.user.id), ); - - for (const event of missedEvents) { - conn.send(event); - } - + for (const event of missedEvents) conn.send(event); return missedEvents; } + async shutdown(): Promise { + this.stopHeartbeat(); + for (const clientId of [...this.connections.keys()]) this.removeConnection(clientId); + await this.ready; + await this.pubSub.close?.(); + } + private matchesFilter(event: SubscriptionEvent, filter: EventFilter, userId: string): boolean { if (filter.userId && filter.userId !== userId) return false; if (filter.types?.length && !filter.types.includes(event.type)) return false; - if (filter.subscriptionIds?.length && !filter.subscriptionIds.includes(event.subscriptionId)) - return false; + if (filter.subscriptionIds?.length && !filter.subscriptionIds.includes(event.subscriptionId)) return false; return true; } From 9ec2d758ee51c4a019952bff29ec31860ca74d29 Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:29:10 +0100 Subject: [PATCH 05/14] fix(websocket): validate Redis connections before use --- backend/services/notification/redisPubSubAdapter.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/backend/services/notification/redisPubSubAdapter.ts b/backend/services/notification/redisPubSubAdapter.ts index 5d125934..2495281b 100644 --- a/backend/services/notification/redisPubSubAdapter.ts +++ b/backend/services/notification/redisPubSubAdapter.ts @@ -9,6 +9,7 @@ import { loadRedisConfig } from '../../config/redis'; export interface RedisPubSubClient { publish(channel: string, message: string): Promise; + ping(): Promise; subscribe(channel: string): Promise; unsubscribe(channel: string): Promise; on(event: 'message', listener: (channel: string, message: string) => void): unknown; From 2c4bb4a8e14c834b23d4f595b516eed5dbf447f4 Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:29:17 +0100 Subject: [PATCH 06/14] test(websocket): cover Redis connection health checks --- .../services/notification/__tests__/redisPubSubAdapter.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/backend/services/notification/__tests__/redisPubSubAdapter.test.ts b/backend/services/notification/__tests__/redisPubSubAdapter.test.ts index 179823cb..777e5ad4 100644 --- a/backend/services/notification/__tests__/redisPubSubAdapter.test.ts +++ b/backend/services/notification/__tests__/redisPubSubAdapter.test.ts @@ -7,6 +7,7 @@ class FakeRedisClient implements RedisPubSubClient { readonly unsubscriptions: string[] = []; quitCalls = 0; + async ping(): Promise { return 'PONG'; } async publish(channel: string, message: string): Promise { this.published.push({ channel, message }); return 1; From 87c176ba0bb713d3f8f9c536f295277ce764f20d Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:29:26 +0100 Subject: [PATCH 07/14] test(websocket): verify cross-instance Redis event delivery --- .../__tests__/eventDrivenWsServer.test.ts | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 backend/services/notification/__tests__/eventDrivenWsServer.test.ts diff --git a/backend/services/notification/__tests__/eventDrivenWsServer.test.ts b/backend/services/notification/__tests__/eventDrivenWsServer.test.ts new file mode 100644 index 00000000..e3313554 --- /dev/null +++ b/backend/services/notification/__tests__/eventDrivenWsServer.test.ts @@ -0,0 +1,79 @@ +import { EventDrivenWsServer, MockRedisPubSubAdapter, StoredEvent } from '../eventDrivenWsServer'; +import type { RedisPubSubAdapter } from '../redisPubSubAdapter'; +import type { AuthUser } from '../../shared/authStrategies'; + +class SharedPubSub implements RedisPubSubAdapter { + private static handlers = new Map void>>(); + async publish(channel: string, message: string): Promise { + for (const handler of SharedPubSub.handlers.get(channel) ?? []) handler(channel, message); + } + async subscribe(channel: string, handler: (channel: string, message: string) => void): Promise { + const handlers = SharedPubSub.handlers.get(channel) ?? new Set(); + handlers.add(handler); + SharedPubSub.handlers.set(channel, handlers); + } + async close(): Promise { SharedPubSub.handlers.clear(); } +} + +const event = { + type: 'subscription.created' as const, + subscriptionId: 'sub-1', + userId: 'user-1', + payload: { plan: 'pro' }, + timestamp: 1, +}; + +function connection(clientId: string, send: jest.Mock): Parameters[0] { + return { + clientId, + user: { id: 'user-1' } as AuthUser, + lastPing: Date.now(), + isAlive: true, + filter: { userId: 'user-1' }, + send, + close: jest.fn(), + }; +} + +describe('EventDrivenWsServer Redis Pub/Sub integration', () => { + afterEach(() => SharedPubSub['handlers'].clear()); + + it('delivers an event published by one server to connections on another server', async () => { + const publisher = new EventDrivenWsServer(new SharedPubSub()); + const receiver = new EventDrivenWsServer(new SharedPubSub()); + const send = jest.fn(); + await Promise.all([publisher.ready, receiver.ready]); + receiver.registerConnection(connection('client-2', send)); + + const published = await publisher.publishEvent(event); + + expect(send).toHaveBeenCalledWith(expect.objectContaining({ + type: event.type, + subscriptionId: event.subscriptionId, + sequenceId: published.sequenceId, + })); + await Promise.all([publisher.shutdown(), receiver.shutdown()]); + }); + + it('does not deliver events that fail the local connection filter', async () => { + const server = new EventDrivenWsServer(new SharedPubSub()); + const send = jest.fn(); + await server.ready; + server.registerConnection({ + ...connection('client-3', send), + filter: { userId: 'different-user' }, + }); + + await server.publishEvent(event); + + expect(send).not.toHaveBeenCalled(); + await server.shutdown(); + }); + + it('keeps the in-memory adapter available for local development', async () => { + const server = new EventDrivenWsServer(new MockRedisPubSubAdapter()); + await server.ready; + expect(server.activeConnectionsCount).toBe(0); + await server.shutdown(); + }); +}); From e2cb5114576080cc24ede93aa0252923878d4aff Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:29:33 +0100 Subject: [PATCH 08/14] test(websocket): tidy shared Pub/Sub test fixture --- .../notification/__tests__/eventDrivenWsServer.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/services/notification/__tests__/eventDrivenWsServer.test.ts b/backend/services/notification/__tests__/eventDrivenWsServer.test.ts index e3313554..40f74e1f 100644 --- a/backend/services/notification/__tests__/eventDrivenWsServer.test.ts +++ b/backend/services/notification/__tests__/eventDrivenWsServer.test.ts @@ -1,9 +1,10 @@ -import { EventDrivenWsServer, MockRedisPubSubAdapter, StoredEvent } from '../eventDrivenWsServer'; +import { EventDrivenWsServer, MockRedisPubSubAdapter } from '../eventDrivenWsServer'; import type { RedisPubSubAdapter } from '../redisPubSubAdapter'; import type { AuthUser } from '../../shared/authStrategies'; class SharedPubSub implements RedisPubSubAdapter { private static handlers = new Map void>>(); + static reset(): void { SharedPubSub.handlers.clear(); } async publish(channel: string, message: string): Promise { for (const handler of SharedPubSub.handlers.get(channel) ?? []) handler(channel, message); } @@ -36,7 +37,7 @@ function connection(clientId: string, send: jest.Mock): Parameters { - afterEach(() => SharedPubSub['handlers'].clear()); + afterEach(() => SharedPubSub.reset()); it('delivers an event published by one server to connections on another server', async () => { const publisher = new EventDrivenWsServer(new SharedPubSub()); From 935aa4fcbf4372c17dcfc97fcae137a0652d7d73 Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:29:44 +0100 Subject: [PATCH 09/14] docs(websocket): document Redis Pub/Sub deployment --- docs/WEBSOCKET_ARCHITECTURE.md | 70 +++++++++++++++++----------------- 1 file changed, 34 insertions(+), 36 deletions(-) diff --git a/docs/WEBSOCKET_ARCHITECTURE.md b/docs/WEBSOCKET_ARCHITECTURE.md index ea5c6e3e..99387de8 100644 --- a/docs/WEBSOCKET_ARCHITECTURE.md +++ b/docs/WEBSOCKET_ARCHITECTURE.md @@ -1,58 +1,56 @@ # SubTrackr Event-Driven WebSocket Architecture ## Overview -SubTrackr's real-time messaging system uses an event-driven architecture decoupled from HTTP transports via Redis Pub/Sub, connection pooling, and sequence-based event replay. + +The real-time messaging layer separates event production from WebSocket connections. The default event adapter is in-memory for local development and tests. Multi-process deployments can use Redis Pub/Sub to fan events out to every backend instance. ## Core Components 1. **`WebSocketServer` (`backend/services/notification/websocket.ts`)** - Uses an injectable `SubscriptionEventBus` to decouple producers from socket transports. - - Keeps the legacy `broadcast(event)` API by publishing onto the event bus. - - Supports local in-memory delivery by default and can be backed by Redis in production adapters. + - Preserves the `broadcast(event)` API and local in-memory delivery. + - Supports batching, backpressure, heartbeat checks, and delivery metrics. 2. **`EventDrivenWsServer` (`backend/services/notification/eventDrivenWsServer.ts`)** - - Redis Pub/Sub compatible server for sequence-based replay and horizontal fan-out. - - Manages connection presence, client filter matching, and event dispatch. + - Manages local socket connections, filters, presence, event sequencing, and replay. + - Subscribes to the shared `subtrackr_ws_events` channel before accepting published events. + - Exposes `ready` so startup can wait for the Redis subscription to be active. + - `shutdown()` stops heartbeats, removes local connections, and closes its Pub/Sub adapter. + +3. **Redis Pub/Sub adapter (`backend/services/notification/redisPubSubAdapter.ts`)** + - `IORedisPubSubAdapter` uses separate publisher and subscriber connections, as Redis subscriber connections cannot be used for normal commands. + - A single Redis subscription fans messages out to local handlers registered for that channel. + - `createRedisPubSubAdapter()` creates and health-checks both connections using the shared `REDIS_HOST`, `REDIS_PORT`, `REDIS_PASSWORD`, and `REDIS_DB` configuration. + - The adapter owns both connections and closes them during shutdown. -3. **Connection Pooling & Active Heartbeat** - - Server runs a periodic ping/pong audit across connected client pools. - - Stale/unresponsive sockets are automatically disconnected (`Heartbeat timeout`). +## Production setup -4. **Event Replay Store** - - Every published event receives a monotonically increasing `sequenceId`. - - Reconnecting clients supply `lastSequenceId` via `replayEventsSince()`, receiving all missed events in exact chronological sequence. +Create one adapter per backend process and inject it into the event-driven server: -5. **Client SDK Client (`src/services/WebSocketClient.ts`)** - - Manages automatic reconnection with exponential backoff and transparent state recovery. +```ts +import { EventDrivenWsServer } from '../backend/services/notification/eventDrivenWsServer'; +import { createRedisPubSubAdapter } from '../backend/services/notification/redisPubSubAdapter'; -6. **Load Testing Harness (`scripts/load-test-websocket.js`)** - - Benchmark script testing connection scale up to 10,000+ virtual client sockets. +const pubSub = await createRedisPubSubAdapter(); +const wsServer = new EventDrivenWsServer(pubSub); -## Event Bus Usage +// Do not accept socket connections until the shared channel is subscribed. +await wsServer.ready; -```ts -import { - InMemorySubscriptionEventBus, - WebSocketServer, -} from '../backend/services/notification/websocket'; - -const eventBus = new InMemorySubscriptionEventBus(); -const wsServer = new WebSocketServer({ batchIntervalMs: 50 }, eventBus); - -wsServer.connect('client-1', 'user-1', (event) => socket.send(JSON.stringify(event))); -eventBus.publish({ - type: 'subscription.renewed', - subscriptionId: 'sub_1', - userId: 'user-1', - payload: { amount: 10 }, - timestamp: Date.now(), -}); +// During graceful process shutdown: +await wsServer.shutdown(); ``` -The default `batchIntervalMs` is `0` to preserve immediate delivery for -existing callers. Production deployments can set a non-zero interval to batch -bursty events while retaining backpressure limits through `maxQueueSize`. +All backend instances must use the same Redis deployment, database, and channel. Each instance receives published events and dispatches them only to its own matching local connections. Redis Pub/Sub is at-most-once delivery: events published while a subscriber is disconnected are not buffered by Redis. Use the event store/replay mechanism when durable recovery is required. + +For local development and isolated unit tests, omit the adapter or inject `MockRedisPubSubAdapter` to avoid a Redis dependency. + +## Event replay + +Each event published through an `EventDrivenWsServer` receives a monotonically increasing sequence identifier and is retained in a bounded in-process replay buffer. A reconnecting client can pass its last seen sequence to `replayEventsSince()`. This buffer is local to the server process; it is not a durable, cluster-wide event log. ## Tests - `backend/services/notification/__tests__/websocket.test.ts` +- `backend/services/notification/__tests__/redisPubSubAdapter.test.ts` +- `backend/services/notification/__tests__/eventDrivenWsServer.test.ts` From dbbf3168e61c85bdae38144bfb1d833832df206a Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:29:55 +0100 Subject: [PATCH 10/14] fix(websocket): make Redis adapter shutdown resilient --- backend/services/notification/redisPubSubAdapter.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/services/notification/redisPubSubAdapter.ts b/backend/services/notification/redisPubSubAdapter.ts index 2495281b..b08431e7 100644 --- a/backend/services/notification/redisPubSubAdapter.ts +++ b/backend/services/notification/redisPubSubAdapter.ts @@ -84,15 +84,15 @@ export class IORedisPubSubAdapter implements RedisPubSubAdapter { async close(): Promise { if (this.closed) return; this.closed = true; - await Promise.all([...this.pendingSubscriptions.values()]); + await Promise.allSettled([...this.pendingSubscriptions.values()]); this.subscriber.removeListener('message', this.onMessage); const channels = [...this.subscribedChannels]; - await Promise.all(channels.map((channel) => this.subscriber.unsubscribe(channel))); + await Promise.allSettled(channels.map((channel) => this.subscriber.unsubscribe(channel))); this.handlers.clear(); this.subscribedChannels.clear(); - await Promise.all([this.publisher.quit(), this.subscriber.quit()]); + await Promise.allSettled([this.publisher.quit(), this.subscriber.quit()]); } private assertOpen(): void { From af5a49b25825265b2a209fa5fa831a817341567c Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:30:01 +0100 Subject: [PATCH 11/14] fix(websocket): preserve adapter exports and shutdown on startup errors --- .../services/notification/eventDrivenWsServer.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/backend/services/notification/eventDrivenWsServer.ts b/backend/services/notification/eventDrivenWsServer.ts index 30fec415..db2bc748 100644 --- a/backend/services/notification/eventDrivenWsServer.ts +++ b/backend/services/notification/eventDrivenWsServer.ts @@ -1,7 +1,8 @@ import { EventEmitter } from 'events'; import { SubscriptionEvent, EventFilter } from './websocket'; -import { AuthUser } from '../shared/authStrategies'; -import type { RedisPubSubAdapter } from './redisPubSubAdapter'; +import type { AuthUser } from '../shared/authStrategies'; +import type { RedisPubSubAdapter as PubSubAdapter } from './redisPubSubAdapter'; +export type { RedisPubSubAdapter } from './redisPubSubAdapter'; export interface StoredEvent extends SubscriptionEvent { sequenceId: number; @@ -38,10 +39,10 @@ export class EventDrivenWsServer extends EventEmitter { private eventStore: StoredEvent[] = []; private sequenceCounter = 0; private heartbeatInterval?: NodeJS.Timeout; - private readonly pubSub: RedisPubSubAdapter; + private readonly pubSub: PubSubAdapter; readonly ready: Promise; - constructor(pubSubAdapter?: RedisPubSubAdapter) { + constructor(pubSubAdapter?: PubSubAdapter) { super(); this.pubSub = pubSubAdapter || new MockRedisPubSubAdapter(); this.ready = this.setupPubSub(); @@ -140,8 +141,11 @@ export class EventDrivenWsServer extends EventEmitter { async shutdown(): Promise { this.stopHeartbeat(); for (const clientId of [...this.connections.keys()]) this.removeConnection(clientId); - await this.ready; - await this.pubSub.close?.(); + try { + await this.ready; + } finally { + await this.pubSub.close?.(); + } } private matchesFilter(event: SubscriptionEvent, filter: EventFilter, userId: string): boolean { From 466c67d4722801262789771281115123953fee23 Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:30:32 +0100 Subject: [PATCH 12/14] fix(websocket): use shared adapter type in mock implementation --- backend/services/notification/eventDrivenWsServer.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/services/notification/eventDrivenWsServer.ts b/backend/services/notification/eventDrivenWsServer.ts index db2bc748..b355a70e 100644 --- a/backend/services/notification/eventDrivenWsServer.ts +++ b/backend/services/notification/eventDrivenWsServer.ts @@ -9,7 +9,7 @@ export interface StoredEvent extends SubscriptionEvent { } /** In-memory adapter for unit tests and single-process development. */ -export class MockRedisPubSubAdapter implements RedisPubSubAdapter { +export class MockRedisPubSubAdapter implements PubSubAdapter { private handlers: Map void)[]> = new Map(); async publish(channel: string, message: string): Promise { From f30d35a876c66fd524468afef15d0a209e586dfa Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:30:43 +0100 Subject: [PATCH 13/14] chore(websocket): require Redis health checks --- backend/services/notification/redisPubSubAdapter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/services/notification/redisPubSubAdapter.ts b/backend/services/notification/redisPubSubAdapter.ts index b08431e7..472197a1 100644 --- a/backend/services/notification/redisPubSubAdapter.ts +++ b/backend/services/notification/redisPubSubAdapter.ts @@ -124,7 +124,7 @@ export async function createRedisPubSubAdapter(): Promise const subscriber = new Redis(options); try { - await Promise.all([publisher.ping?.(), subscriber.ping?.()]); + await Promise.all([publisher.ping(), subscriber.ping()]); } catch (error) { await Promise.allSettled([publisher.quit(), subscriber.quit()]); throw error; From ea623cb7236658e4d995de3f39d6b2ed77123613 Mon Sep 17 00:00:00 2001 From: Barry Date: Fri, 27 Nov 2026 03:30:47 +0100 Subject: [PATCH 14/14] test(websocket): make auth fixture type-safe --- .../services/notification/__tests__/eventDrivenWsServer.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/services/notification/__tests__/eventDrivenWsServer.test.ts b/backend/services/notification/__tests__/eventDrivenWsServer.test.ts index 40f74e1f..6029cde5 100644 --- a/backend/services/notification/__tests__/eventDrivenWsServer.test.ts +++ b/backend/services/notification/__tests__/eventDrivenWsServer.test.ts @@ -27,7 +27,7 @@ const event = { function connection(clientId: string, send: jest.Mock): Parameters[0] { return { clientId, - user: { id: 'user-1' } as AuthUser, + user: { id: 'user-1' } as unknown as AuthUser, lastPing: Date.now(), isAlive: true, filter: { userId: 'user-1' },