Architecture: How to implement real-time cross-device chat message sync?

Documentation for Sessions

🏗️ Architecture: How to implement real-time cross-device chat message sync?

Date: 2026-03-03
Time: 19:21:31 UTC
Session: gspace1-166.12
Agent: backend
Confidence: 95%
Status: ✅ Documented


📋 Decision Context

Question:

How to implement real-time cross-device chat message sync?

Task: Session 170: Real-time cross-device chat sync via Socket.IO


🎯 Decision Made

Chosen:

New ChatGateway on /chat Socket.IO namespace in backend-ai-api. Manual emit after appendMessages() saves to MongoDB (not MongoDB Change Streams). Dual rooms: user:{userId} for all devices + chat:{sessionId} for session viewers. Frontend ChatRealtimeService connects and pushes received messages into _backendSessions signal via injectRealtimeMessages() with message ID dedup. ~160 lines total across 2 new files + 5 modified files.

Options Considered:


💭 Reasoning

Socket.IO over SSE because chat is bidirectional and we already have 7 Socket.IO gateways. Manual emit over Change Streams because we call appendMessages() — we know exactly when to emit, no cursor/oplog overhead. Separate /chat namespace (not CommandCenterGateway) because separation of concerns and consistent with existing pattern (/sync, /agent-tasks, /docs-sync). Inject into _backendSessions signal because it's immune to autoFlashState race conditions (Session 129 pattern). Dedup by message ID because HTTP response + Socket.IO may both deliver same message. Redis adapter already exists for horizontal scaling.


📁 Files Involved


🔗 Related


Auto-generated by MCP Smart Consolidation