Real-time Dashboard
Dashboard yang update live: analytics, monitoring, trading, IoT. SSE atau WebSocket push updates, client render charts/metrics.
SSE-based Dashboard
// Server: stream metrics
app.get("/api/dashboard/stream", (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
const interval = setInterval(async () => {
const metrics = await collectMetrics();
res.write(`data: ${JSON.stringify(metrics)}\n\n`);
}, 1000); // update setiap detik
req.on("close", () => clearInterval(interval));
});
async function collectMetrics() {
return {
activeUsers: await redis.scard("online_users"),
requestsPerSecond: await getRequestRate(),
errorRate: await getErrorRate(),
avgLatency: await getAvgLatency(),
timestamp: Date.now(),
};
}
Client: React + Chart
function useDashboardStream() {
const [metrics, setMetrics] = useState([]);
useEffect(() => {
const source = new EventSource("/api/dashboard/stream");
source.onmessage = (event) => {
const data = JSON.parse(event.data);
setMetrics(prev => {
const updated = [...prev, data];
return updated.slice(-60); // Keep last 60 data points
});
};
return () => source.close();
}, []);
return metrics;
}
function Dashboard() {
const metrics = useDashboardStream();
const latest = metrics[metrics.length - 1];
return (
<div className="grid grid-cols-4 gap-4">
<MetricCard label="Active Users" value={latest?.activeUsers} />
<MetricCard label="Req/s" value={latest?.requestsPerSecond} />
<MetricCard label="Error Rate" value={`${latest?.errorRate}%`} />
<MetricCard label="Latency" value={`${latest?.avgLatency}ms`} />
<LineChart data={metrics} dataKey="requestsPerSecond" />
</div>
);
}
Throttling
- Server-side: aggregate metrics, send at fixed interval (not per-event)
- Client-side: requestAnimationFrame untuk render, skip if tab not visible
- Adaptive: send more often saat dashboard visible, less saat background