Skip to content
NestRS

Streaming responses

Return a chunked body or a Server-Sent Events stream from a handler — a streamed Body passes straight through.

A handler can return a body that streams instead of one buffered whole in memory, or a live Server-Sent Events feed the browser reads with EventSource. A streamed body is a Body built from a stream, passed through untouched — no wrapper, no schema requirement; an events feed is its own decorator, #[sse].

crates/features/src/audio/http/controller.rs (from the demo, abridged)
#[get("/download")]
// … #[http_code(200)], #[meta(…)], #[api(…)]
async fn download(&self, Query(query): Query<TranscodeDto>) -> Result<Response> {
let file = query.file;
match self.svc.open_result(file).await.opaque()? {
Some(stream) => Ok(Response::builder()
.content_type(HeaderValue::from_static("audio/mpeg"))
.body(Body::from_stream(stream))),
None => Err(HttpError::from_status(StatusCode::NOT_FOUND)),
}
}

Body::from_stream is the whole trick: the object’s bytes flow chunk by chunk, never whole in memory.

Body::from_stream turns any Stream<Item = Result<Bytes, E>> into a response body. Feed it a source that itself streams — the object-storage client’s get_stream hands back the S3 GetObject chunks directly, so a large download proxies through the server without ever sitting whole in process memory.

The stream is polled after the handler returned, and it runs under what the handler ran under: the request’s trace and actor, every ambient value a layer added, and the caller’s ability on a route whose posture names an entity. A service the stream calls reads on the pool, never on the route’s transaction — that one has settled by the time the body is written — so a read in the stream of a POST sees what the route committed.

A route whose posture names no subject withholds the ability, so a scoped read there fails closed rather than answering rows no posture declared. An #[sse] stream gated on a capability reads under the caller’s ability, in its handler and in the stream, and each wire row it emits is judged for that caller where it is built; a posture naming an entity is refused there.

#[sse("/path")] is a GET that answers a long-lived text/event-stream. The handler returns an SseStream of SseEvents and nothing else — the decorator owns the response, the keep-alive and the connection ceiling.

crates/features/src/audio/http/controller.rs (from the demo, abridged)
#[sse("/events")]
// … #[meta(…)], #[api(…)]
async fn events(
&self,
Query(query): Query<TranscodeDto>,
resume: Header<StreamResumeDto>,
) -> SseStream {
let file = query.file;
let seen = resume.into_inner().last_event_id;
let events = self
.svc
.clone()
.transcode_events(file)
// … drop the progress ticks `seen` says the browser already showed
.map(|payload| {
SseEvent::json(&payload)
.event_type("transcode")
.id(payload.attempt.to_string())
});
SseStream::new(events)
}

SseEvent::json writes the payload as the JSON a listener parses. A payload that does not serialize sends no event in its place: the failure is filed at error with its chain, as a JSON answer’s is, and the stream ends there — the browser reads no made-up state, and its EventSource reconnects. SseEvent::message carries text as it is.

Each event carries an id, so a browser that reconnects sends the last one back as Last-Event-ID; Header<StreamResumeDto> reads it, and the stream resumes rather than replays.

nestrs writes each event itself, as the browser reads it (WHATWG HTML §9.2). Every line of the data — split on \r\n, \n or \r, the three breaks an EventSource splits on — goes on a data: line of its own, so no payload can open a field of its own; an id or an event type holds one line, and any line break in it is dropped. .retry(Duration) tells the browser how long to wait before it reconnects, and an event with no data sets its id or retry hint without dispatching anything.

SseEvent and SseStream come from nest_rs::http, which also re-exports futures_util — so a controller that streams declares no transport crate of its own. SseStream::new is what makes the stream 'static: an async fn on &self returning impl Stream captures the &self lifetime, and a response body has to outlive the call.

The OpenAPI document types the route from the decorator — text/event-stream, with no annotation. A hand-built streamed Response states its own with #[api(response_content_type = "audio/mpeg")]; on an #[sse] route that key is a compile error, because it could only describe something the route never sends.

Two <PREFIX>_HTTP__* keys, both defaulting to something usable:

Key Default What it does
SSE_MAX_CONNECTION_SECS 14400 (4 h) ends the stream, so the client’s EventSource reconnects. 0 ⇒ unlimited
SSE_KEEP_ALIVE_SECS 15 comment interval that keeps an idle feed alive through proxies. 0 ⇒ none

A stream runs inside the request that opened it, even though its handler returned long before the first event. current_trace_id() and current_actor_id() answer there, and every event the stream logs carries the request’s trace_id — see Correlation. That is the framework’s doing, not the decorator’s: the same holds for any streaming body a handler returns.

The ceiling is a security control, and the same one <PREFIX>_WS__MAX_MESSAGE_BYTES bounds an inbound frame at the protocol layer — 64 KiB by default, so buffering stops before a giant frame is fully read. <PREFIX>_WS__MAX_CONNECTION_SECS and <PREFIX>_GRAPHQL__MAX_CONNECTION_SECS carry, at the same default. A stream is authenticated once, when the request arrives, then emits with those privileges for as long as it lives — so without a ceiling it outlives an expired token, a logout, or a revoked grant. Reconnecting re-runs the guard chain.

It bounds emission: the deadline is evaluated whenever the response body is polled, so no event is produced past the ceiling at any rate the client reads at. Reconnecting re-runs the guard chain, which is the window that matters.

A peer that stops reading is cut by the transport, not the ceiling: once it has taken nothing for <PREFIX>_HTTP__SEND_TIMEOUT_SECS (60 s by default), its connection is dropped — on HTTP/2 its stream is reset, and the connection serves its other streams on — and the task and buffers the stream held go with it. The deadline runs only while a write waits, so a slow reader that keeps taking bytes is never cut. See Connection deadlines.

At shutdown a stream ends at the signal. A stream never finishes on its own, so holding it open would only spend the whole shutdown window (<PREFIX>_HTTP__SHUTDOWN_TIMEOUT_SECS, 20 s by default) waiting for an end that is not coming. The transport ends it the moment shutdown is asked for — cleanly, its last chunk written, so the client’s EventSource reads an end and reconnects, to a replica still in the load balancer. Its http.request line carries the head’s status, the bytes written, and outcome="cancelled": the transport ended it, not the stream. A peer that stopped reading parks the write, so its stream ends at the send deadline or with the window, whichever comes first. See Shutdown.

#[sse] marks its response as having no end of its own. A handler that streams events some other way marks its own, so it ends at the signal too:

crates/features/src/chat/http/controller.rs
use nest_rs::http::{IntoResponse, OpenEndedBody, Response};
let mut response: Response = events.into_response();
response.extensions_mut().insert(OpenEndedBody);

Gate a stream on a capability: #[authorize(Manage, Transcoding)], on a subject #[subject] declares, runs the class gate and opens the stream’s reads to the caller’s ability. #[authorize] naming an entity on an #[sse] route is a compile error, decided by the subject’s type.

  • A streamed body has no schema in the document, only a media type and OpenAPI’s string / format: binary — there is no Json<T> to derive one from.
  • SSE and streamed bodies are HTTP only; the WebSocket gateway is the push channel for two-way traffic.
  • Compression sits outside the handler, so a streamed body is still encoded if the client accepts it — usually you leave compression off for already-compressed media.