> ## Documentation Index
> Fetch the complete documentation index at: https://docs.learnway.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# WebSockets & Real-time Events

> Socket.IO architecture, authentication handshakes, room partitioning, and real-time state synchronization.

# WebSockets & Real-time Events

LearnWay uses **Socket.IO** with Redis-backed state replication to power synchronous multiplayer experiences and real-time alerts.

***

## Active Gateways

| Gateway                         | Namespace / Path | Functionality                                                                           |
| ------------------------------- | ---------------- | --------------------------------------------------------------------------------------- |
| **`QuizBattleGateway`**         | `/quiz-battle`   | 1v1 matchmaking, question delivery timer, live answer submission, winner determination. |
| **`ContestLeaderboardGateway`** | `/contests`      | Real-time leaderboard score broadcasts during live timed competitions.                  |
| **`NotificationGateway`**       | `/notifications` | Live push notifications to active web and mobile user sessions.                         |

***

## Connection & Authentication Lifecycle

```mermaid theme={null}
sequenceDiagram
    autonumber
    actor Client as Mobile / Web Client
    participant Adapter as Redis IO Adapter
    participant Gateway as WebSocket Gateway
    participant Auth as JWT Auth Guard

    Client->>Gateway: Connect with Authorization Header / Query Token
    Gateway->>Auth: Validate JWT Access Token
    alt Token Valid
        Gateway->>Gateway: Attach user identity to socket
        Gateway->>Gateway: Join private room `user_${userId}`
        Gateway-->>Client: Emitted `connection_success`
    else Token Invalid / Missing
        Gateway-->>Client: Disconnect with 401 Unauthorized
    end
```

***

## Quiz Battle Protocol Flow

1. **`join_queue`**: Client emits matchmaking ticket specifying preferred topic or random matchmaking.
2. **`match_found`**: Server pairs two players (or spins up a bot if matchmaking timeout triggers).
3. **`round_start`**: Server distributes question payload without answer keys and starts countdown.
4. **`submit_answer`**: Both clients submit selected option IDs with timestamp milliseconds.
5. **`round_result`**: Gateway broadcasts score deltas and immediate correctness feedback.
6. **`battle_complete`**: Final scores tallied, gems deducted/awarded, and XP distributed.
