Build a Scalable WebSocket Server with Room Management

Build a WebSocket server with authentication, room management, structured messaging, and horizontal scaling support.

๐Ÿ“ The Prompt

Build a production-ready WebSocket server in [PROGRAMMING_LANGUAGE] using the [WEBSOCKET_LIBRARY] library. The server will power a [APPLICATION_TYPE] application (e.g., real-time chat, live dashboard, collaborative editor) and must handle up to [EXPECTED_CONCURRENT_USERS] concurrent connections. Please implement the following features with clean, well-documented code: 1. **Server Setup & Configuration**: Initialize the WebSocket server on port [PORT] with configurable options for heartbeat/ping-pong intervals (default 30 seconds), maximum payload size, and CORS settings for allowed origins [ALLOWED_ORIGINS]. 2. **Connection Lifecycle Management**: - Handle new connections with an authentication step that validates a [AUTH_METHOD] (e.g., JWT token, API key) passed during the handshake. - Assign each connection a unique client ID and store metadata (user ID, connected timestamp, rooms). - Implement graceful disconnection handling with cleanup of all subscriptions and rooms. - Add automatic reconnection detection using client fingerprinting. 3. **Room/Channel System**: - Allow clients to join and leave named rooms with optional capacity limits. - Support broadcasting messages to all clients in a specific room. - Implement room-level permissions (read-only, read-write, admin). - Provide a mechanism to list active rooms and their member counts. 4. **Message Protocol**: Define a structured JSON message protocol with the following message types: `join_room`, `leave_room`, `broadcast`, `direct_message`, `presence_update`, and `error`. Each message should include a type field, a unique message ID, a timestamp, and a payload object. 5. **Error Handling & Resilience**: Implement structured error codes and messages, handle malformed messages gracefully, add connection timeout handling, and include try-catch blocks with logging for all critical paths. 6. **Monitoring & Logging**: Add an endpoint or admin command to retrieve server stats (active connections, rooms, messages per second), and integrate structured logging with [LOGGING_PREFERENCE]. Include a sample client-side connection snippet and a brief explanation of how to horizontally scale this server using [SCALING_STRATEGY] (e.g., Redis pub/sub, sticky sessions).

๐Ÿ’ก Tips for Better Results

Specify your authentication method clearly โ€” JWT-based auth requires different handling than session-based or API key auth Define your expected message frequency and payload sizes so the AI can suggest appropriate buffer and throttling configurations If you plan to scale horizontally, mention your infrastructure (Redis, RabbitMQ, etc.) for tailored pub/sub integration code

๐ŸŽฏ Use Cases

Backend developers building real-time features like chat systems, live notifications, collaborative tools, or multiplayer game servers who need a robust WebSocket foundation.

๐Ÿ”— Related Prompts

๐Ÿ’ป Coding beginner

Explain Code Like Im a Beginner

Get any code explained in plain English with line-by-line breakdowns, analogies, and learning suggestions.

๐Ÿ’ป Coding beginner

Debug My Code and Explain the Fix

Get your code debugged with clear explanations of what went wrong and why, plus the corrected version.

๐Ÿ’ป Coding intermediate

Write Unit Tests for My Code

Generate thorough unit tests covering edge cases, error handling, and both positive and negative scenarios.

๐Ÿ’ป Coding intermediate

Convert Code Between Languages

Convert code between any programming languages while maintaining idiomatic patterns and best practices.

๐Ÿ’ป Coding intermediate

Write a REST API Endpoint

Generate production-ready REST API endpoints with validation, error handling, and documentation.

๐Ÿ’ป Coding advanced

Create a GitHub Actions CI/CD Workflow for Automated Testing and Deployment

Generate a complete GitHub Actions CI/CD workflow with build, test, deploy, and notification jobs for your project.