# 🔴 Redis Cache Schema **Purpose:** Real-time user presence (WebSocket layer) **Type:** Ephemeral data (TTL-based) **Owner Service:** WSManager Redis is used ONLY for temporary, real-time data. --- # 1️⃣ User Presence Each connected user has one presence key. ## Key Format presence:user:{keycloak_id} ## Example presence:user:user123 ## Value (JSON) { "instanceId": "ws-node-1", "socketId": "abc123", "connectedAt": 1700000000 } ## TTL 60 seconds If TTL expires → user automatically considered OFFLINE. --- # 2️⃣ Instance Reverse Mapping Used to track which users are connected to a specific WebSocket instance. ## Key Format ws:instance:{instanceId} ## Example ws:instance:ws-node-1 ## Type Redis SET ## Value Example user123 user456 user789 This allows: - Cleanup if instance crashes - Targeted message routing - Fast disconnection handling --- # 3️⃣ Presence Lifecycle ## On WebSocket Connect 1. Validate user (JWT) 2. SET presence:user:{id} 3. ADD user to ws:instance:{instanceId} 4. Set TTL = 60s ## On WebSocket Heartbeat - Refresh TTL ## On WebSocket Disconnect 1. DEL presence:user:{id} 2. SREM ws:instance:{instanceId} If crash occurs → TTL expiration handles cleanup. --- # 4️⃣ ONLINE / OFFLINE Logic User is ONLINE if: presence:user:{id} exists User is OFFLINE if: Key does not exist (expired or deleted) --- # 5️⃣ Data Responsibility | Layer | Responsibility | |--------|---------------| | PostgreSQL | Persistent profile data | | MongoDB | Message history | | Redis | Live presence | | Kafka | Event propagation | --- # 6️⃣ Design Rules - Redis never stores business data - Redis never stores message history - Redis only stores ephemeral session data - Presence must always use TTL - No permanent data in Redis