Overview
Modelence WebSocket implementation includes:- Real-Time Communication - Instant bidirectional messaging between server and clients
- Channel-Based Architecture - Organize connections into logical channels with access control
- Authentication Integration - Automatic user authentication for WebSocket connections
- Horizontal Scaling - MongoDB adapter enables scaling across multiple server instances
- Type Safety - Full TypeScript support with generic types for message payloads
- Built on Socket.IO - Leverages the robust Socket.IO library with fallback support
How WebSockets Work
Connection Flow
- Client Connection - Client initiates WebSocket connection to the server
- Authentication - Connection is automatically authenticated using the session token
- Channel Registration - Channels are registered in your Module
- Join Channels - Client joins specific channels by category and ID
- Real-Time Messages - Server broadcasts messages to all clients in a channel
- Automatic Reconnection - Socket.IO handles reconnection on network interruptions
Channel Architecture
Channels are organized using acategory:id
pattern:
- Category - Defines the type of channel (e.g., “chat”, “notifications”, “game”)
- ID - Unique identifier for the specific channel instance (e.g., room ID, user ID)
- Access Control - Optional server-side function to control who can join
chat:room123
- Chat room with ID “room123”notifications:user456
- Notifications for user “user456”game:match789
- Game updates for match “match789”
Server-Side Setup
Creating Server Channels
Create a server channel file to define your channel:Registering Channels in Module
Channels are registered in your Module definition:Broadcasting Messages
Use the channel to broadcast messages to all connected clients:Channel with Access Control
Add access control to restrict who can join a channel:Client-Side Setup
Creating Client Channels
Define a client channel to receive messages:Initialize WebSockets
Start WebSocket connection and register channels in your app entry point:Joining and Leaving Channels
Join specific channels to start receiving messages:Complete Example
Here’s a complete example of a real-time chat system:Server
Channel Definition:Client
Channel Definition:Horizontal Scaling
Modelence WebSockets use the Socket.IO MongoDB adapter, which enables horizontal scaling across multiple server instances:How It Works
- Shared MongoDB Collection - All server instances share a MongoDB collection (
_modelenceSocketio
) - Message Distribution - When one server broadcasts a message, it’s stored in MongoDB
- Cross-Instance Delivery - All server instances receive the message and deliver to their connected clients
- Automatic Cleanup - Messages expire after 1 hour (TTL index on
createdAt
field)
Configuration
The MongoDB adapter is automatically configured when you:- Initialize Modelence with MongoDB connection
- Register channels in your Module
- Start your application
Load Balancing
When deploying multiple instances:Security Best Practices
Authentication
- Automatic Auth - WebSocket connections are automatically authenticated using session tokens
- Access Control - Use the second parameter in
ServerChannel
to restrict channel access - Token Validation - Session tokens are validated on every connection
Channel Security
Data Validation
Always validate data before broadcasting:Performance Considerations
Channel Granularity
- Fine-grained - Create specific channels for individual resources (e.g.,
chat:room123
) - User-specific - Use user IDs for personal channels (e.g.,
notifications:user456
) - Avoid Global - Don’t broadcast to all users; use targeted channels
Message Size
Keep message payloads small for optimal performance:TypeScript Support
Full TypeScript support with generic types:API Reference
Server Types
- WebsocketServerProvider - Interface for WebSocket server providers (types.ts:5)
- ServerChannel - Server-side channel class (serverChannel.ts:11)
Client Types
- WebsocketClientProvider - Interface for WebSocket client providers (types.ts:17)
- ClientChannel - Client-side channel class (clientChannel.ts:3)
Functions
- startWebsockets - Initialize WebSocket connection (client.ts:15)
- broadcast - Send message to all clients in a channel (serverChannel.ts:23)
- joinChannel - Join a specific channel (clientChannel.ts:22)
- leaveChannel - Leave a specific channel (clientChannel.ts:29)
Common Use Cases
Real-Time Chat
Live Notifications
Collaborative Editing
Live Dashboard
Gaming
Troubleshooting
Connection Issues
Problem: Client can’t connect to WebSocket server Solutions:- Verify server is started with channels registered in Module
- Check that MongoDB is connected
- Ensure firewall allows WebSocket connections
- Verify CORS settings if connecting from different origin
Messages Not Received
Problem: Client joined channel but not receiving messages Solutions:- Verify channel category matches exactly between client and server
- Check access control function if channel is protected
- Ensure user is authenticated if channel requires auth
- Confirm channels are registered in
startWebsockets()
Scaling Issues
Problem: Messages not reaching all clients across multiple servers Solutions:- Verify MongoDB connection is shared across all instances
- Check that
_modelenceSocketio
collection exists - Ensure TTL index was created successfully
- Review MongoDB logs for adapter errors
Next Steps
- Explore the Authentication docs for securing WebSocket connections
- Check out the Tutorial for complete application examples
- Review Stores documentation for persisting real-time data
- Learn about Modules for organizing your application