Skip to main content

Task 3: Add the /realtime endpoint to server realtime metrics.

Last time, we added the /metrics and /metrics/{kind} endpoints to our server. Now, a natural feature we could implement is a real-time endpoint that sends metric updates at a fixed rate. This will allow clients to subscribe to the endpoint and receive live updates without polling the server.

To do so, we'll implement the /realtime endpoint using Server-Sent Events (SSE). This technology allows servers to push updates to clients over a single, long-lived connection.

What are Server-Sent Events (SSE)?​

Server-Sent Events (SSE) is a standard for sending real-time updates from a server to a client over HTTP. It's a simple and efficient way to stream data from the server to the client without the need for polling.

SSE works by establishing a persistent connection between the client and the server. The server can then send messages to the client at any time, and the client will receive them as they arrive.

In our project, we'll use SSE to stream live metric updates to clients who connect to the /realtime endpoint.

Your Task​

As task, implement the /realtime endpoint to stream live metric updates using Server-Sent Events (SSE). The endpoint should send a message every second with the current system metrics.

To do so, we'll use the tokio-stream crate to create a stream that sends updates at a fixed rate. We'll then use the axum::sse module to send these updates to clients.

Hint​

To generate a new metric every second, we'll use the following code:

use std::time::Duration;
use tokio_stream::{StreamExt, wrappers::IntervalStream};

let stream = IntervalStream::new(tokio::time::interval(Duration::from_secs(1)));