- Updated: March 18, 2026
- 7 min read
Real‑Time Rating Updates with OpenClaw: A WebSocket Streaming Guide
Real‑time rating updates with OpenClaw can be streamed over WebSockets, giving AI agents instant, low‑latency data without the overhead of polling.
1. Introduction
AI agents thrive on fresh data. Whether they are recommending products, adjusting game difficulty, or moderating content, the moment a rating changes can be the difference between a relevant response and a missed opportunity. Traditional pull‑based APIs force agents to poll for updates, incurring unnecessary latency and resource consumption. By switching to a push‑based model—specifically WebSocket streaming—developers can deliver real‑time rating updates directly to their agents.
Why push‑based consumption matters
- Latency reduction: Data arrives the instant it’s generated.
- Resource efficiency: No repeated HTTP requests, saving bandwidth and CPU.
- Event‑driven architecture: Simplifies orchestration of downstream workflows.
2. Why Push‑Based Consumption Matters for AI‑Agent Workloads
AI agents are often part of larger pipelines that include inference, decision making, and user interaction. In such pipelines, every millisecond counts.
2.1 Latency reduction
When a rating is updated in OpenClaw, a WebSocket push can reach the agent in < 10 ms on a typical cloud network, compared to 200‑500 ms for a poll‑then‑response cycle.
2.2 Resource efficiency
Polling at a 1‑second interval for thousands of agents quickly balloons into millions of HTTP requests per minute. WebSockets maintain a single persistent connection, turning that into a few bytes per update.
2.3 Event‑driven architectures
Modern micro‑service ecosystems rely on events. By emitting rating changes as events, you can trigger downstream processes (e.g., cache invalidation, analytics pipelines) without additional glue code.
3. Overview of OpenClaw Rating Service
OpenClaw is a lightweight, open‑source rating engine designed for high‑throughput environments. Its core features include:
- RESTful CRUD endpoints for creating, reading, updating, and deleting ratings.
- Pluggable storage back‑ends (SQL, NoSQL, in‑memory).
- Built‑in rate limiting and audit logging.
While the REST API is perfect for batch operations, it does not natively support real‑time streaming. That gap is filled by the optional WebSocket module we’ll configure.
4. Configuring OpenClaw for WebSocket Streaming
Enabling WebSocket support involves three main steps: activating the module, defining topics, and securing the connection.
4.1 Enable WebSocket module
OpenClaw ships with a websocket plugin that can be toggled in config.yml:
modules:
websocket:
enabled: true
port: 8081
4.2 Define rating update topics
Topics are logical channels that clients can subscribe to. For rating updates we recommend a hierarchical naming scheme:
topics:
rating:
- "rating.global"
- "rating.game.{game_id}"
- "rating.user.{user_id}"
4.3 Authentication setup
OpenClaw uses JWT tokens for WebSocket authentication. Add the following to auth.yml:
jwt:
secret: "YOUR_SUPER_SECRET"
algorithm: HS256
expiry_seconds: 3600
Clients must send the token as a query parameter ?token=... when opening the socket.
5. Step‑by‑Step Guide
Below is a concise, MECE‑structured checklist that takes you from a fresh OpenClaw clone to a fully streaming rating service.
5.1 Install dependencies
- Clone the repository:
git clone https://github.com/openclaw/openclaw.git - Enter the directory:
cd openclaw - Install Node.js dependencies:
npm install - Install optional WebSocket library:
npm install ws
5.2 Update configuration files
Open config.yml and enable the WebSocket module as shown in section 4.1. Then, add the topics and JWT settings.
5.3 Deploy changes
For a quick local test, run:
npm run startIn production, you’ll likely use Docker. A minimal Dockerfile example:
FROM node:18-alpine
WORKDIR /app
COPY . .
RUN npm ci --only=production
EXPOSE 8080 8081
CMD ["npm", "run", "start"]
5.4 Verify WebSocket endpoint
Use WebSocket.org’s test client (external link, rel=”noopener”) to connect:
wss://your-domain.com:8081?token=YOUR_JWTIf you receive a connection_success message, the server is ready.
6. Complete Code Example
Below is a minimal, production‑ready snippet that demonstrates both the server‑side broadcast and a client‑side consumer.
6.1 Server‑side (OpenClaw) snippet
// server.js (Node.js + ws)
const WebSocket = require('ws');
const jwt = require('jsonwebtoken');
const config = require('./config.yml');
const wss = new WebSocket.Server({ port: config.modules.websocket.port });
function authenticate(info, cb) {
const params = new URLSearchParams(info.req.url.split('?')[1]);
const token = params.get('token');
try {
const payload = jwt.verify(token, config.jwt.secret);
cb(true, payload);
} catch (e) {
cb(false, null);
}
}
wss.on('connection', (ws, req) => {
authenticate(req, (ok, user) => {
if (!ok) {
ws.close(4001, 'Invalid token');
return;
}
ws.user = user;
ws.send(JSON.stringify({ type: 'connection_success' }));
});
ws.on('message', (msg) => {
// Optional: handle subscription messages
const data = JSON.parse(msg);
if (data.action === 'subscribe' && data.topic) {
ws.subscribedTopic = data.topic;
}
});
});
// Broadcast function called whenever a rating changes
function broadcastRatingUpdate(rating) {
const payload = {
type: 'rating_update',
topic: `rating.game.${rating.gameId}`,
data: rating,
};
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN &&
client.subscribedTopic === payload.topic) {
client.send(JSON.stringify(payload));
}
});
}
// Example: simulate rating change every 5 seconds
setInterval(() => {
const fakeRating = {
gameId: 42,
userId: 7,
score: Math.floor(Math.random() * 5) + 1,
timestamp: new Date().toISOString(),
};
broadcastRatingUpdate(fakeRating);
}, 5000);
6.2 Client‑side (WebSocket consumer) snippet
// client.js (browser)
const token = localStorage.getItem('jwt'); // Assume JWT is stored after login
const socket = new WebSocket(`wss://api.yourdomain.com:8081?token=${token}`);
socket.addEventListener('open', () => {
// Subscribe to a specific game’s rating updates
socket.send(JSON.stringify({
action: 'subscribe',
topic: 'rating.game.42',
}));
});
socket.addEventListener('message', (event) => {
const msg = JSON.parse(event.data);
if (msg.type === 'rating_update') {
console.log('New rating received:', msg.data);
// Feed the rating directly into your AI agent’s inference pipeline
updateAgentState(msg.data);
}
});
socket.addEventListener('close', (e) => {
console.warn('WebSocket closed:', e.reason);
});
7. Scaling Considerations
WebSocket connections are stateful, so scaling requires careful planning.
7.1 Horizontal scaling of WebSocket servers
- Run multiple instances behind a TCP load balancer that supports sticky sessions (e.g., HAProxy, NGINX with
ip_hash). - Use a shared session store (Redis) to keep authentication state consistent across nodes.
7.2 Load balancing strategies
For large fleets, consider a layer‑7 reverse proxy that can route based on the Sec-WebSocket-Protocol header, allowing you to separate rating streams from other real‑time channels.
7.3 Message broker integration
Offload broadcast logic to a broker like Redis Pub/Sub or Apache Kafka. The server publishes rating events to a topic; each WebSocket instance subscribes and forwards to its connected clients. This decouples the rating engine from the real‑time layer and improves fault tolerance.
8. Security Considerations
Real‑time streams expose a persistent surface, so security must be baked in from day one.
8.1 TLS encryption
Always serve WebSockets over wss://. Obtain a certificate from Let’s Encrypt or your cloud provider and configure the server:
const https = require('https');
const fs = require('fs');
const server = https.createServer({
cert: fs.readFileSync('/etc/ssl/certs/fullchain.pem'),
key: fs.readFileSync('/etc/ssl/private/privkey.pem')
});
const wss = new WebSocket.Server({ server });
server.listen(8443);
8.2 Token‑based authentication
JWTs should be short‑lived (≤ 15 minutes) and signed with a strong secret. Rotate secrets regularly and revoke compromised tokens via a blacklist stored in Redis.
8.3 Rate limiting and DoS protection
- Limit new connections per IP (e.g., 10 connections per second).
- Implement per‑client message throttling to prevent flood attacks.
- Use a CDN edge firewall (Cloudflare, Fastly) to block malformed WebSocket upgrade requests.
9. Embedding the Internal Link
For developers who prefer a managed hosting solution, UBOS offers a one‑click deployment of OpenClaw. Learn how to spin up the service on the OpenClaw hosting page and focus on building your AI agents instead of infrastructure.
10. Additional UBOS Resources
While you’re exploring real‑time streams, you might also benefit from other UBOS capabilities:
- UBOS platform overview – a unified environment for AI‑driven micro‑services.
- AI marketing agents – pre‑built agents that can consume rating data for personalized campaigns.
- Workflow automation studio – visually orchestrate rating‑triggered actions.
- Web app editor on UBOS – quickly prototype a dashboard that visualizes rating streams.
- UBOS pricing plans – transparent pricing for scaling from startups to enterprises.
11. Conclusion
Streaming real‑time rating updates with OpenClaw via WebSockets transforms AI agents from reactive pollers into proactive, event‑driven participants. By enabling the WebSocket module, defining clear topics, securing connections with JWT and TLS, and planning for horizontal scaling, you gain:
- Sub‑second latency for critical decision‑making.
- Reduced bandwidth and CPU overhead.
- Seamless integration with UBOS’s broader AI ecosystem.
Start by following the step‑by‑step guide above, test with the provided code snippets, and then explore UBOS’s hosted OpenClaw offering to accelerate production rollout. Your AI agents will thank you for the instant, reliable data stream.