Real-time
Learn how to build real-time applications with Query-2jz's WebSocket and Server-Sent Events support.
What is Real-time?
Query-2jz's real-time features enable instant data synchronization across all connected clients. When data changes, all subscribed clients receive updates immediately.
Real-time Features
Transport Options
Choose between WebSockets and Server-Sent Events based on your needs.
WebSockets
Full-duplex communication
- • Bidirectional communication
- • Lower latency
- • More efficient for frequent updates
- • Supports binary data
- • Better for interactive apps
- • Automatic reconnection
Server-Sent Events
One-way server to client
- • Simpler implementation
- • Works through firewalls
- • Built-in reconnection
- • HTTP/2 compatible
- • Better for notifications
- • Lower server overhead
WebSocket Implementation
Set up WebSocket connections for real-time communication.
WebSocket Server
Configure WebSocket server in Query-2jz
Server Configuration
{
"realtime": {
"enabled": true,
"transport": "websocket",
"port": 3001,
"cors": {
"origin": ["http://localhost:3000", "https://myapp.com"],
"credentials": true
},
"heartbeat": {
"interval": 30000,
"timeout": 60000
},
"compression": true,
"maxPayload": 16 * 1024
}
}Client Connection
const ws = new WebSocket('ws://localhost:3001');
ws.onopen = () => {
console.log('Connected to Query-2jz WebSocket');
// Subscribe to real-time updates
ws.send(JSON.stringify({
type: 'subscribe',
model: 'User',
action: 'all'
}));
};
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
handleRealTimeUpdate(message);
};
ws.onclose = () => {
console.log('WebSocket connection closed');
// Implement reconnection logic
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};Server-Sent Events
Use SSE for simpler one-way real-time communication.
SSE Implementation
Server-Sent Events for real-time updates
Server Configuration
{
"realtime": {
"enabled": true,
"transport": "sse",
"cors": {
"origin": ["http://localhost:3000"],
"credentials": true
},
"retry": 3000,
"keepAlive": {
"interval": 30000
}
}
}Client Connection
const eventSource = new EventSource('/api/query-2jz/subscribe?model=User&action=all');
eventSource.onmessage = (event) => {
const message = JSON.parse(event.data);
handleRealTimeUpdate(message);
};
eventSource.onerror = (error) => {
console.error('SSE error:', error);
// SSE automatically reconnects
};
eventSource.onopen = () => {
console.log('SSE connection opened');
};
// Close connection when done
eventSource.close();Real-time Events
Understand the different types of real-time events Query-2jz sends.
Event Types
Different types of real-time events
Data Change Events
// Create event
{
"type": "create",
"model": "User",
"data": {
"id": "1",
"name": "John Doe",
"email": "john@example.com"
},
"timestamp": "2024-01-01T00:00:00Z"
}
// Update event
{
"type": "update",
"model": "User",
"data": {
"id": "1",
"name": "John Updated",
"email": "john@example.com"
},
"changes": {
"name": "John Updated"
},
"timestamp": "2024-01-01T12:00:00Z"
}
// Delete event
{
"type": "delete",
"model": "User",
"data": {
"id": "1"
},
"timestamp": "2024-01-01T18:00:00Z"
}System Events
// Connection event
{
"type": "connected",
"clientId": "client_123",
"timestamp": "2024-01-01T00:00:00Z"
}
// Heartbeat event
{
"type": "ping",
"timestamp": "2024-01-01T00:00:00Z"
}
// Error event
{
"type": "error",
"message": "Invalid subscription",
"code": "INVALID_SUBSCRIPTION",
"timestamp": "2024-01-01T00:00:00Z"
}Use Cases
Common real-time application patterns with Query-2jz.
Live Chat
Real-time messaging application
Features
- • Instant message delivery
- • Typing indicators
- • Online status
- • Message read receipts
// Subscribe to messages
ws.send(JSON.stringify({
type: 'subscribe',
model: 'Message',
where: { "roomId": "room_123" },
action: 'all'
}));Collaborative Editing
Real-time document collaboration
Features
- • Live cursor positions
- • Real-time text changes
- • User presence
- • Conflict resolution
// Subscribe to document changes
ws.send(JSON.stringify({
type: 'subscribe',
model: 'Document',
id: 'doc_123',
action: 'all'
}));Live Notifications
Real-time notification system
Features
- • Instant notifications
- • User-specific alerts
- • Notification history
- • Read/unread status
// Subscribe to user notifications
ws.send(JSON.stringify({
type: 'subscribe',
model: 'Notification',
where: { "userId": "user_123" },
action: 'all'
}));Live Dashboard
Real-time data visualization
Features
- • Live metrics updates
- • Real-time charts
- • Status indicators
- • Alert systems
// Subscribe to metrics
ws.send(JSON.stringify({
type: 'subscribe',
model: 'Metric',
where: { "type": "system" },
action: 'all'
}));Connection Management
Handle connections, authentication, and scaling for real-time applications.
Advanced Connection Handling
Production-ready connection management
Authentication
// Authenticate WebSocket connection
ws.onopen = () => {
// Send authentication token
ws.send(JSON.stringify({
type: 'auth',
token: 'jwt_token_here'
}));
};
// Handle authentication response
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.type === 'auth_success') {
console.log('Authenticated successfully');
// Start subscribing to data
} else if (message.type === 'auth_error') {
console.error('Authentication failed:', message.message);
}
};Reconnection Strategy
class Query-2jzRealtimeClient {
constructor(url, options = {}) {
this.url = url;
this.options = {
maxReconnectAttempts: 5,
reconnectDelay: 1000,
...options
};
this.reconnectAttempts = 0;
this.subscriptions = new Set();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
this.reconnectAttempts = 0;
this.authenticate();
};
this.ws.onclose = () => {
this.reconnect();
};
}
reconnect() {
if (this.reconnectAttempts < this.options.maxReconnectAttempts) {
this.reconnectAttempts++;
const delay = this.options.reconnectDelay * this.reconnectAttempts;
setTimeout(() => {
console.log(`Reconnecting... (attempt ${this.reconnectAttempts})`);
this.connect();
}, delay);
}
}
}Best Practices
Do
- • Implement proper reconnection logic
- • Use authentication for connections
- • Handle connection errors gracefully
- • Clean up subscriptions on disconnect
- • Use heartbeats for connection health
- • Implement rate limiting
- • Monitor connection metrics
Don't
- • Ignore connection errors
- • Forget to handle reconnection
- • Subscribe to everything without filters
- • Ignore memory leaks
- • Skip authentication
- • Process every update immediately
- • Forget to clean up resources