expression
Axum: configure SSE keep-alive comments
An idle SSE connection can receive periodic comments to keep traffic flowing. A comment is not an application event and cannot guarantee that every proxy keeps the connection open. This fixture configures the policy and tests a finite event; it does not assert heartbeat timing. In-memory standalone Cargo example. Expected stdout (not executed): finite event received Common mistake: Assuming a heartbeat substitutes for a shutdown signal or guarantees delivery.
Formal Syntax & Structure
rust syntaxrust
Sse::new(stream).keep_alive(KeepAlive::new().interval(duration).text(message))Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use axum::response::{IntoResponse, sse::{Event, KeepAlive, Sse}}; use futures_util::stream; use std::{convert::Infallible, time::Duration}; let events = stream::iter([Ok::<_, Infallible>(Event::default().data("hello"))]); let response = Sse::new(events).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)).text("ping")).into_response(); let bytes = to_bytes(response.into_body(), 128).await.unwrap(); assert!(std::str::from_utf8(&bytes).unwrap().contains("hello")); println!("finite event received");}