expression
Axum SSE: configure keep-alive comments
Periodic SSE comments can reduce idle disconnections through intermediaries. They are not business events and do not prove that the browser processed an update. This finite fixture verifies the configured response still carries its event; it does not verify timer behavior. Standalone synthetic example. Expected stdout (not executed): event preserved Common mistake: Assuming a keep-alive comment is a delivered business event or a guarantee against proxy buffering.
Formal Syntax & Structure
rust syntaxrust
Sse::new(events).keep_alive(KeepAlive::new().interval(duration))Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}, response::{IntoResponse, sse::{Event, Sse}}, extract::ws::{Message, WebSocketUpgrade, WebSocket}};use std::convert::Infallible;use futures_util::stream;use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use axum::response::sse::KeepAlive; let events = stream::iter([Ok::<_, Infallible>(Event::default().data("ready"))]); let res = Sse::new(events).keep_alive(KeepAlive::new().interval(std::time::Duration::from_secs(15)).text("heartbeat")).into_response(); let bytes = to_bytes(res.into_body(), 1024).await.unwrap(); let text = std::str::from_utf8(&bytes).unwrap(); assert!(text.lines().any(|s| s.strip_prefix("data:").is_some_and(|v| v.trim_start() == "ready"))); println!("event preserved");}