Real-time Messages
Build interactive chat and messaging features with millisecond-level data synchronization
Overview
BaxCloud's real-time messaging API enables you to build chat features, presence indicators, typing status, and data synchronization into your applications. Built on WebSocket technology with automatic reconnection, message queuing, and delivery guarantees, it's perfect for enhancing video calls, live streams, collaborative tools, and social applications.
Unlike traditional polling-based approaches or simple WebSocket implementations, BaxCloud provides enterprise-grade messaging with message persistence, delivery acknowledgments, message history, presence tracking, and typing indicators out of the box. Our infrastructure handles millions of concurrent connections with sub-10ms message delivery latency.
Instant Delivery
Messages delivered in < 10ms via optimized WebSocket connections
Presence Tracking
Real-time online/offline status with last-seen timestamps
Data Sync
Synchronize application state across all connected clients
Data Synchronization Protocol
BaxCloud uses a robust publish-subscribe (pub/sub) model with guaranteed delivery and ordering. Messages are delivered via WebSocket with automatic fallback to long-polling for restrictive networks.
Message Flow
- Client sends message via WebSocket connection
- Server validates, persists, and assigns message ID
- Server broadcasts to all subscribers in the room
- Clients receive message and send acknowledgment
- Server marks message as delivered
Delivery Guarantees
- At-least-once delivery: Messages never get lost, even during network issues
- Message ordering: Messages are delivered in the order they were sent
- Automatic retry: Failed deliveries are retried with exponential backoff
- Message persistence: Messages stored for 30 days for history retrieval
Implementation Guide
Step-by-step guide to implementing real-time messaging
Send and Receive Messages
Connect to a room and start sending/receiving messages. All participants in the room receive messages in real-time.
1import { BaxCloudRoomController } from '@baxcloud/react-sdk';
2import { useState, useEffect } from 'react';
3
4function ChatComponent() {
5 const controller = BaxCloudRoomController.instance;
6 const [messages, setMessages] = useState([]);
7 const [input, setInput] = useState('');
8
9 useEffect(() => {
10 const unsubscribe = controller.onChatMessage((message) => {
11 setMessages((prev) => [...prev, message]);
12 });
13
14 return unsubscribe;
15 }, []);
16
17 const sendMessage = async () => {
18 if (input.trim()) {
19 await controller.sendChatMessage(input);
20 setInput('');
21 }
22 };
23
24 return (
25 <div>
26 <div>
27 {messages.map((msg) => (
28 <div key={msg.messageId}>
29 <strong>{msg.userName}:</strong> {msg.message}
30 </div>
31 ))}
32 </div>
33 <input
34 value={input}
35 onChange={(e) => setInput(e.target.value)}
36 onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
37 />
38 <button onClick={sendMessage}>Send</button>
39 </div>
40 );
41}Typing Indicators
Show when participants are typing to create a more engaging chat experience. Typing indicators automatically clear after 3 seconds of inactivity.
1import { BaxCloudRoomController } from '@baxcloud/react-sdk';
2import { useState, useEffect, useRef } from 'react';
3
4function ChatWithTyping() {
5 const controller = BaxCloudRoomController.instance;
6 const [typingUsers, setTypingUsers] = useState<string[]>([]);
7 const typingTimeoutRef = useRef<NodeJS.Timeout>();
8
9 useEffect(() => {
10 const unsubscribe = controller.onTypingIndicator((indicator) => {
11 setTypingUsers((prev) => {
12 const userIds = Array.from(new Set([...prev, indicator.userId]));
13 return userIds;
14 });
15 });
16
17 return unsubscribe;
18 }, []);
19
20 const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
21 // Start typing indicator (auto-stops after 3 seconds)
22 controller.startTyping();
23
24 // Clear existing timeout
25 if (typingTimeoutRef.current) {
26 clearTimeout(typingTimeoutRef.current);
27 }
28
29 // Auto-stop after 3 seconds
30 typingTimeoutRef.current = setTimeout(() => {
31 controller.stopTyping();
32 }, 3000);
33 };
34
35 const sendMessage = async () => {
36 await controller.sendChatMessage(inputText);
37 controller.stopTyping();
38 setInputText('');
39 };
40
41 return (
42 <div>
43 {typingUsers.length > 0 && (
44 <div className="typing-indicator">
45 {typingUsers.length === 1
46 ? `${typingUsers[0]} is typing...`
47 : `${typingUsers.length} people are typing...`
48 }
49 </div>
50 )}
51 <input onChange={handleInputChange} onKeyPress={(e) => e.key === 'Enter' && sendMessage()} />
52 </div>
53 );
54}startTyping() to indicate typing, and it will auto-stop after 3 seconds.Get Chat History
Retrieve chat message history that was received during the current session.
1import { BaxCloudRoomController } from '@baxcloud/react-sdk';
2
3function ChatHistory() {
4 const controller = BaxCloudRoomController.instance;
5
6 // Get chat history (messages received during current session)
7 const history = controller.getChatHistory();
8
9 return (
10 <div>
11 {history.map((msg) => (
12 <div key={msg.messageId}>
13 <strong>{msg.userName}:</strong> {msg.message}
14 </div>
15 ))}
16 </div>
17 );
18}getChatHistory() returns messages received during the current session. To clear the history, use clearChatHistory().Best Practices
1. Handle Connection States
Always handle connection and disconnection events to provide feedback to users.
1import { BaxCloudRoomController } from '@baxcloud/react-sdk';
2import { useEffect } from 'react';
3
4function ChatComponent() {
5 const controller = BaxCloudRoomController.instance;
6
7 useEffect(() => {
8 const unsubscribeConnected = controller.onConnected(() => {
9 console.log('Connected to messaging server');
10 showStatus('Connected');
11});
12
13 const unsubscribeDisconnected = controller.onDisconnected(() => {
14 console.log('Disconnected from server');
15 showStatus('Disconnected');
16});
17
18 const unsubscribeReconnecting = controller.onReconnecting(() => {
19 console.log('Attempting to reconnect...');
20 showStatus('Reconnecting...');
21});
22
23 const unsubscribeReconnected = controller.onReconnected(() => {
24 console.log('Reconnected successfully');
25 showStatus('Connected');
26 });
27
28 return () => {
29 unsubscribeConnected();
30 unsubscribeDisconnected();
31 unsubscribeReconnecting();
32 unsubscribeReconnected();
33 };
34 }, []);
35}2. Implement Message Rate Limiting
Prevent spam by rate-limiting message sending on the client side.
1import { BaxCloudRoomController } from '@baxcloud/react-sdk';
2
3const MESSAGE_RATE_LIMIT = 5; // messages per second
4const messageTimestamps: number[] = [];
5
6const canSendMessage = (): boolean => {
7 const now = Date.now();
8 const oneSecondAgo = now - 1000;
9 const recentMessages = messageTimestamps.filter((t) => t > oneSecondAgo);
10 return recentMessages.length < MESSAGE_RATE_LIMIT;
11};
12
13const controller = BaxCloudRoomController.instance;
14
15const sendMessage = async (text: string) => {
16 if (!canSendMessage()) {
17 showError('Sending messages too fast. Please slow down.');
18 return;
19 }
20
21 messageTimestamps.push(Date.now());
22 await controller.sendChatMessage(text);
23};3. Clean Up Event Listeners
Remove event listeners when components unmount to prevent memory leaks.
1import { BaxCloudRoomController } from '@baxcloud/react-sdk';
2import { useEffect, useState } from 'react';
3
4function ChatComponent() {
5 const controller = BaxCloudRoomController.instance;
6 const [messages, setMessages] = useState([]);
7
8 useEffect(() => {
9 const unsubscribeMessage = controller.onChatMessage((message) => {
10 setMessages((prev) => [...prev, message]);
11 });
12
13 const unsubscribeTyping = controller.onTypingIndicator((indicator) => {
14 // Handle typing indicator
15 });
16
17 // Cleanup
18 return () => {
19 unsubscribeMessage();
20 unsubscribeTyping();
21 };
22 }, []);
23}Troubleshooting
Messages Not Sending
- Verify client is connected (
client.isConnected) - Check network connectivity
- Ensure message payload is valid JSON
- Check message size (max 64KB per message)
- Verify you have send permissions in the room
Messages Arriving Out of Order
- Use
message.timestampto sort messages client-side - Enable message ordering in client settings
- Check for clock skew on client devices
Duplicate Messages
- Use
message.messageIdto deduplicate - This is expected with at-least-once delivery
- Maintain a Set of seen message IDs
Connection Keeps Dropping
- Check firewall settings (WebSocket port 443)
- Verify network stability
- Enable automatic reconnection
- Check if proxy/VPN is blocking WebSockets
1import { BaxCloudClient } from '@baxcloud/react-sdk';
2
3// Enable console logging for debugging
4const client = new BaxCloudClient({
5 projectId: 'your-project-id',
6 apiKey: 'your-api-key',
7});
8
9// Listen to connection events for debugging
10const controller = BaxCloudRoomController.instance;
11controller.onConnected(() => {
12 console.log('[DEBUG] Connected to room');
13});
14
15controller.onChatMessage((message) => {
16 console.log('[DEBUG] Message received:', message);
17});