Skip to main content

Streaming

Streaming response bodies

Actix 4.9+ 6 min readAdvanced Topic

# Streaming Responses

When returning large datasets or files, loading the entire payload into memory is inefficient and dangerous. Instead, you can stream the response body.

#Returning a Stream

Actix Web accepts asynchronous streams of Bytes.

code_blocksrust
use actix_web::{get, HttpResponse, Error};
use actix_web::body::SizedStream;
use futures_util::stream;
use bytes::Bytes;

#[get("/stream")]
async fn stream_data() -> HttpResponse {
    let my_stream = stream::iter(vec![
        Ok::<_, Error>(Bytes::from_static(b"Hello ")),
        Ok::<_, Error>(Bytes::from_static(b"World!")),
    ]);
    
    HttpResponse::Ok().streaming(my_stream)
}

#Use Cases

Streaming is crucial for video/audio delivery, large CSV exports, and proxying data from other APIs or databases without buffering.

Was this page helpful?

Reference Implementation

The following code snippet demonstrates the authoritative pattern for this documentation.

src/main.rs
1use actix_web::{get, App, HttpServer, HttpResponse};
2use futures_util::stream;
3use bytes::Bytes;
4use std::convert::Infallible;
5
6#[get("/stream")]
7async fn do_stream() -> HttpResponse {
8 let chunks = vec![
9 Result::<_, Infallible>::Ok(Bytes::from("chunk1 ")),
10 Result::<_, Infallible>::Ok(Bytes::from("chunk2 ")),
11 ];
12 let stream = stream::iter(chunks);
13
14 HttpResponse::Ok().streaming(stream)
15}
16
17#[actix_web::main]
18async fn main() -> std::io::Result<()> {
19 HttpServer::new(|| App::new().service(do_stream))
20 .bind(("127.0.0.1", 8080))?
21 .run()
22 .await
23}
Was this page helpful?