Body from_stream
Learn how to build an Axum response body from a stream of byte chunks so the client receives pieces as they are ready
Most handlers build the whole response first and then send it. A handler that returns a string waits until the string is complete, and only then does the client see anything. Body::from_stream breaks that pattern. It turns a stream of byte chunks into a response body, so the server can send the first piece while later pieces are still being produced.
A stream is a sequence of values that arrive over time instead of all at once. Each time the server is ready, it hands over the next chunk. The client reads each chunk as it arrives. Nothing waits for the end before the beginning can travel.
Where This Fits
The earlier pages in this chapter start work in the background and answer the client right away. This page is about the opposite shape. The answer itself is the slow part, and it travels to the client in pieces while it is still being made. A background task runs after the response, while a streamed body is the response.
Think of a normal response as a sealed parcel. The sender packs everything, seals the box, and hands it over. A streamed response is a tap left running into a pipe. Water comes out from the first second, and the sender keeps pouring until the tap is turned off.
The Smallest Working Version
Here is a handler that streams three short lines. Each line is one chunk. The handler returns as soon as the stream is built, and the chunks travel to the client one by one.
[package]
name = "stream-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
futures-util = "0.3"
bytes = "1"
use axum::{body::Body, body::Bytes, routing::get, Router};
use futures_util::stream;
use std::convert::Infallible;
async fn stream_handler() -> Body {
let chunks = vec![
Ok::<Bytes, Infallible>(Bytes::from_static(b"one\n")),
Ok(Bytes::from_static(b"two\n")),
Ok(Bytes::from_static(b"three\n")),
];
Body::from_stream(stream::iter(chunks))
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/stream", get(stream_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run the server with cargo run, then ask for the route in a second terminal:
curl http://127.0.0.1:3000/stream
The terminal prints the three lines:
one
two
three
That output looks the same as a plain string response, and that is the point. The client cannot tell from the final text whether the body arrived in one piece or in three. The difference is timing. With a stream, the first line can reach the client before the last line even exists.
Working Setup:
If curl prints all three lines, the stream is wired up correctly. The handler built a body from a stream, Axum sent each chunk, and the client put them back together in order.
What Each Piece Does
The smallest example has four ideas packed into a few lines, and each one is worth naming before the page builds on them.
The vector of results
let chunks = vec![
Ok::<Bytes, Infallible>(Bytes::from_static(b"one\n")),
Ok(Bytes::from_static(b"two\n")),
Ok(Bytes::from_static(b"three\n")),
];
Every item in a body stream is a Result. The Ok side holds one chunk of bytes. The Err side holds an error, for the case where producing a chunk fails halfway through. Bytes is a type from the bytes crate for a chunk of byte data. It is cheap to copy and share because copies point at the same memory instead of duplicating it. Bytes::from_static builds one from bytes baked into the program, which is handy for fixed text.
Infallible is the error type used when failure is impossible. It is a type that has no values at all, so nothing can ever go wrong. Writing Ok::<Bytes, Infallible> tells the compiler that this stream never produces an error. Real streams that read files or call other services use a real error type instead, and that choice is covered later on this page.
Turning a list into a stream
stream::iter(chunks)
futures_util::stream::iter takes a collection and turns it into a stream that hands out one item at a time. It is the simplest way to make a stream, and it is the right tool whenever the pieces already exist in a list. The stream does not copy the list. It walks through it in order, one item per step.
Building the body
Body::from_stream(stream::iter(chunks))
Body is the type Axum uses for request and response bodies. Body::from_stream is an associated function that wraps a stream and returns a Body. From here on, Axum treats the stream as the body. When the server writes the response, it pulls items from the stream and sends each one as it arrives. When the stream runs out of items, the body is finished.
Returning the body from a handler
async fn stream_handler() -> Body {
A handler can return a Body directly. Body implements IntoResponse, which is the trait Axum requires of handler return values. That trait is the contract that says "this value knows how to become an HTTP response". Returning the body on its own produces a 200 OK response with no Content-Type header, because a bare body carries no information about what the bytes mean. Headers are added by pairing the body with them, which the final example on this page shows.
A Stream Is Not a List:
A list holds every item in memory at once. A stream holds only the item it is currently handing over, plus whatever it needs to produce the next one. That is why a stream can describe a body that is still being produced, or a body too large to hold in memory.
What a Stream Is in This Context
A stream is defined by one action: asking for the next item. The code that reads a stream asks, waits, receives either the next item or a signal that there are no more items, and then asks again. In Rust this behaviour comes from the Stream trait in the futures-core crate, and the asking is done through the next method from the StreamExt trait.
The asking is lazy. Nothing is produced until somebody asks. When a handler builds a stream and hands it to Body::from_stream, no chunk has been produced yet. The work starts when the server begins writing the response and asks for the first chunk. Each chunk is produced only when the previous one has been asked for. A stream that reads from a file opens the file when the first chunk is asked for, not when the handler runs.
That laziness shapes how errors behave. If producing the third chunk fails, the first two chunks may already be on their way to the client. The response has already started, so the server cannot go back and change the status code to an error. The client simply sees the connection end early. This is a real trade-off of streaming, and the section on error types below shows how to choose errors with it in mind.
A stream also has no length. The server does not know how many chunks will come, or how many bytes they will hold in total. That is why a streamed response never carries a Content-Length header. The header that appears instead, and how the client knows where the body ends, is the subject of the chunked transfer encoding page in this same cluster.
Why Send a Body in Pieces
A normal response makes the client wait for the slowest part of the answer. If a handler needs ten seconds to compute a result, the client stares at a blank screen for ten seconds. A streamed response lets the handler send what it already has. A progress log can show each step as it happens. A live feed can deliver each event the moment it occurs. A large report can start downloading before the last page is generated.
The second reason is memory. Building a whole body first means holding the whole body in memory at once. A ten-megabyte answer needs ten megabytes of memory per request, and ten requests at the same time need a hundred megabytes. A streamed body holds roughly one chunk at a time. The same ten-megabyte answer needs only a few kilobytes of working memory, no matter how many requests run side by side.
The third reason is that some answers never end. A live feed of events has no final chunk. There is no moment when the whole body exists, so building it first is impossible. Streaming is the only shape that fits.
Streaming Does Not Make Slow Work Fast:
Streaming changes when the client sees the answer, not how long the work takes. A handler that needs ten seconds to produce ten chunks still needs ten seconds. The client sees the first chunk early, but the last chunk still arrives after ten seconds. If the work itself is slow, streaming hides the wait, it does not remove it.
A Stream That Produces Values Over Time
The iterator version above hands out chunks that already exist. The more useful shape is a stream that creates each chunk when its turn comes. stream::unfold builds that kind of stream from a starting state and a small async function that produces the next item and the next state.
This example sends one tick every 50 milliseconds:
use axum::{body::Body, body::Bytes, routing::get, Router};
use futures_util::stream;
use std::{convert::Infallible, time::Duration};
async fn ticks_handler() -> Body {
let ticks = stream::unfold(0, |count| async move {
if count >= 3 {
None
} else {
tokio::time::sleep(Duration::from_millis(50)).await;
let line = format!("tick {}\n", count);
Some((
Ok::<Bytes, Infallible>(Bytes::from(line)),
count + 1,
))
}
});
Body::from_stream(ticks)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/ticks", get(ticks_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The closure receives the current count and returns Some with two things: the next item for the stream, and the state to use on the following call. Returning None ends the stream. The async move on the closure matters because the sleep inside it needs an async context, and move takes ownership of the count so the stream can outlive the handler call.
Run it and watch the timing with curl -N, which tells curl to print each piece as soon as it arrives instead of buffering:
curl -N http://127.0.0.1:3000/ticks
In a live run against this exact code, the three lines arrived about 90 milliseconds apart, one at a time, instead of all at once at the end:
tick 0
tick 1
tick 2
That gap is the visible proof that the body is a stream. A plain string handler would print nothing for 150 milliseconds and then print all three lines together. The streamed version prints the first line after the first sleep, while the handler is still working on the rest.
Bytes::from(line) converts the owned String into bytes. format! builds the text, and the conversion moves it into the chunk without copying the characters a second time.
Sending Text That Is Not Bytes
Chunks do not have to start life as Bytes. Body::from_stream accepts any success type that converts into Bytes, which includes String. This handler streams plain strings:
use axum::{body::Body, routing::get, Router};
use futures_util::stream;
async fn words_handler() -> Body {
let words = stream::iter(vec![
Ok::<String, std::io::Error>("hello ".to_string()),
Ok("world\n".to_string()),
]);
Body::from_stream(words)
}
The two items have the same type, Result<String, std::io::Error>, even though the second one was written without the type annotation. Rust works the type out from the first item. The error type here is std::io::Error, the standard error type for input and output failures. It converts into the boxed error type that Body::from_stream requires, so it compiles without extra work.
This is the right shape for text that is built piece by piece, such as lines of a log or rows of a report. Each piece is an ordinary string, and the conversion to bytes happens inside from_stream.
The Error Type Must Convert Into a Boxed Error:
Body::from_stream requires the stream item to be Result<T, E> where E converts into a boxed error, a Box<dyn std::error::Error + Send + Sync>. Types like std::io::Error satisfy this because they implement the standard Error trait. A plain String does not implement that trait, so Result<Bytes, String> fails to compile. The fix is to map the error into a type that does, which the error section below shows.
Choosing the Error Type
The error type is the part beginners get wrong most often, because the compiler error it produces looks confusing. There are four cases, and each one has a clear answer.
When nothing can fail, use Infallible. A stream built from a fixed list of values, or from arithmetic, never errors. Infallible says so in the type, and the compiler knows the error branch can never happen.
When the work is input or output, use std::io::Error. Reading files, reading from a network socket, and writing to a pipe all report std::io::Error. It converts into a boxed error without any extra code.
When the work has its own failure type, that type must implement the standard Error trait. Here is a small custom error that does:
use axum::{body::Body, body::Bytes, routing::get, Router};
use futures_util::stream;
use std::fmt;
#[derive(Debug)]
struct FetchError(String);
impl fmt::Display for FetchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "fetch failed: {}", self.0)
}
}
impl std::error::Error for FetchError {}
async fn custom_error_handler() -> Body {
let items = vec![
Ok::<Bytes, FetchError>(Bytes::from_static(b"first\n")),
Err(FetchError("the source stopped".to_string())),
];
Body::from_stream(stream::iter(items))
}
Display gives the error a human-readable message, and the empty impl std::error::Error marks it as a proper error type. With both in place, the error converts into a boxed error and from_stream accepts it. Without the Error implementation, the compiler rejects the code even if Display exists.
When the error is a plain string or some other type that is not an error, map it before building the stream. map_err converts each error value through a closure:
use axum::{body::Body, body::Bytes, routing::get, Router};
use futures_util::{stream, TryStreamExt};
async fn mapped_error_handler() -> Body {
let items = vec![
Ok::<Bytes, String>(Bytes::from_static(b"first\n")),
Err("something broke".to_string()),
];
let mapped = stream::iter(items)
.map_err(std::io::Error::other);
Body::from_stream(mapped)
}
std::io::Error::other wraps any message in an input-output error. The stream that reaches from_stream now has error type std::io::Error, which compiles. The .map_err call comes from the TryStreamExt trait, which provides helpers for streams whose items are Result values, so that trait needs to be in scope alongside stream.
Feeding a Stream From a Background Task
A stream does not have to be built by the handler. It can be fed by work running elsewhere, and this is the one place where this page meets the background-task half of the chapter. A spawned task can send chunks through a channel, and the handler streams the receiving end of that channel.
A channel is a pipe between tasks. One side sends values in, the other side receives them out, in order. tokio::sync::mpsc::channel creates a channel with a buffer size, and tokio_stream::wrappers::ReceiverStream turns the receiving end into a stream.
use axum::{body::Body, body::Bytes, routing::get, Router};
async fn channel_handler() -> Body {
let (sender, receiver) = tokio::sync::mpsc::channel::<Result<Bytes, std::io::Error>>(8);
tokio::spawn(async move {
let _ = sender.send(Ok(Bytes::from_static(b"from a task\n"))).await;
});
let stream = tokio_stream::wrappers::ReceiverStream::new(receiver);
Body::from_stream(stream)
}
The handler creates the channel, spawns a task that sends one chunk into it, and returns a body built from the receiving end. The spawned task runs on its own while the response streams. The buffer size of 8 means the sender can put up to 8 chunks into the channel before it has to wait for the receiver to take one. This pattern is worth knowing, and it is also worth keeping small. The channel and the spawned task add moving parts, so use them when the producing work genuinely lives outside the handler, not as a default way to build every stream.
This needs one more dependency:
tokio-stream = "0.1"
The Handler Returns Before the Work Finishes:
In the channel example, the handler returns the body while the spawned task is still running. That is normal for streaming. The response is not finished when the handler returns. It is finished when the stream ends, which happens when the sender is dropped and the channel closes.
What the Client Sees
A client reading a streamed response sees three things that differ from a fixed response. First, the headers arrive before the body is complete. The status line and headers are sent as soon as the handler returns, and the first chunk follows when it is ready. Second, the body arrives in pieces, and the client can act on each piece as it comes. A browser can render the first lines of a page while the rest are still travelling. Third, the body has no declared length. The client knows the body is finished only when the server signals the end of the stream.
That shape has one sharp edge. Headers and the status code are already sent by the time a later chunk fails. If the fifth chunk out of ten fails, the server cannot replace the 200 OK with a 500 error, because the client already received the 200 OK. The client receives the first four chunks and then the connection ends early. A client that checks for a clean end to the body notices the failure. A client that just reads whatever arrives may silently treat a partial answer as a complete one. Handlers that stream therefore need to treat errors as part of the design, not as an afterthought. If a chunk can fail, the stream should be built so the failure is unlikely, or the client should be given a way to detect an incomplete body, such as a final summary chunk that only appears when everything succeeded.
A Plain Text Diagram of the Flow
Handler builds a stream of Result<Bytes, E>
|
v
Body::from_stream wraps the stream as the response body
|
v
Handler returns, headers go out to the client
|
v
Server asks the stream for the next chunk
|
v
Chunk travels to the client as soon as it is ready
|
v
Server asks again, until the stream ends
|
v
Server signals the end of the body, response is complete
The handler is done after the second step. Everything below it happens while the response is already in flight. That is the whole idea in one picture: the handler starts the flow, and the stream finishes it.
Testing a Streamed Response
A streamed response can be tested without a network connection by sending a fake request straight to the router and collecting the body. The oneshot method from tower::ServiceExt sends one request through the router. The collect method from http_body_util::BodyExt pulls every chunk out of the response body and joins them into one buffer.
use axum::{
body::{Body, Bytes},
http::{Request, StatusCode},
routing::get,
Router,
};
use futures_util::stream;
use http_body_util::BodyExt;
use std::convert::Infallible;
use tower::ServiceExt;
async fn stream_handler() -> Body {
Body::from_stream(stream::iter(vec![
Ok::<Bytes, Infallible>(Bytes::from_static(b"one\n")),
Ok(Bytes::from_static(b"two\n")),
]))
}
#[tokio::test]
async fn streamed_body_collects_in_order() {
let app = Router::new().route("/stream", get(stream_handler));
let response = app
.oneshot(Request::builder().uri("/stream").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let bytes = response.into_body().collect().await.unwrap().to_bytes();
assert_eq!(&bytes[..], b"one\ntwo\n");
}
The test needs two development dependencies:
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
http-body-util = "0.1"
The test builds the same router the server uses, sends a request to /stream, and checks two things: the status is 200 OK, and the collected body equals the two chunks joined together. collect waits for every chunk, so the test proves the stream yields the right bytes in the right order. It does not prove the chunks arrive one at a time over the wire. Timing on the wire needs a real server and a client that reads as data arrives, which the curl examples on this page already show.
Run the test with:
cargo test
Common Beginner Mistakes
Passing plain bytes instead of results
// Wrong - will not compile
let items = vec![Bytes::from_static(b"one\n")];
Body::from_stream(stream::iter(items))
from_stream expects each item to be a Result, because a stream that produces data can also fail. Plain Bytes values have no place to put an error, so the compiler rejects them. Wrap each chunk in Ok, and pick the error type from the section above.
Using a String as the error type
// Wrong - will not compile
let items = vec![Err::<Bytes, String>("boom".to_string())];
Body::from_stream(stream::iter(items))
A String is a message, not an error type. It does not implement the standard Error trait, so it cannot convert into a boxed error. Map it with .map_err(std::io::Error::other) or use a proper error type, as shown above.
Collecting the whole answer before streaming it
// Wrong - defeats the purpose of streaming
let mut whole = Vec::new();
while let Some(chunk) = stream.next().await {
whole.extend_from_slice(&chunk.unwrap());
}
Body::from(whole)
This code waits for every chunk, joins them into one big buffer, and then sends the buffer as a fixed body. It works, but it throws away both benefits of streaming: the client waits for the whole answer, and the server holds the whole answer in memory. If the pieces are already in a stream, pass the stream straight to from_stream instead of draining it first.
Streaming borrowed data
// Wrong - will not compile
async fn broken_handler(lines: &[String]) -> Body {
let items = lines
.iter()
.map(|line| Ok::<Bytes, Infallible>(Bytes::copy_from_slice(line.as_bytes())));
Body::from_stream(stream::iter(items))
}
The stream must be 'static, which means it cannot borrow data that belongs to the handler call. The iterator above borrows lines, and lines only lives as long as the handler runs. The handler returns, the borrow ends, and the stream would be left pointing at data that is gone. The compiler reports this as borrowed data escaping the function. The fix is to own the chunks before building the stream: collect the mapped values into a Vec, which owns every Bytes value inside it, and stream the vector instead.
// Fixed - the vector owns every chunk
async fn fixed_handler(lines: &[String]) -> Body {
let items: Vec<Result<Bytes, Infallible>> = lines
.iter()
.map(|line| Ok(Bytes::copy_from_slice(line.as_bytes())))
.collect();
Body::from_stream(stream::iter(items))
}
Expecting a Content-Length header
A streamed body has no Content-Length header, because the total size is unknown when the headers go out. Code that reads the header to learn the size of the answer will find nothing there. That is normal, not a bug. The wire format that replaces the length header is explained on the chunked transfer encoding page in this same cluster.
Final Complete Example
This example puts the page together. A progress endpoint streams one line per step, with a short pause between steps, and labels the body as plain text so the client knows what the bytes mean.
use axum::{
body::{Body, Bytes},
http::header,
routing::get,
Router,
};
use futures_util::stream;
use std::{convert::Infallible, time::Duration};
async fn progress_handler() -> (header::HeaderMap, Body) {
let steps = ["starting", "working", "finishing"];
let ticks = stream::unfold(0, move |count| {
let steps = steps;
async move {
if count >= steps.len() {
None
} else {
tokio::time::sleep(Duration::from_millis(100)).await;
let line = format!("step {} of 3: {}\n", count + 1, steps[count]);
Some((
Ok::<Bytes, Infallible>(Bytes::from(line)),
count + 1,
))
}
}
});
let mut headers = header::HeaderMap::new();
headers.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap());
(headers, Body::from_stream(ticks))
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/progress", get(progress_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Returning a tuple of (HeaderMap, Body) is how a handler attaches headers to a body. Axum implements IntoResponse for tuples that pair headers with a response body. The text/plain content type tells the client the chunks are plain text. Without it, the client would still receive the same bytes, but it would have to guess what they mean.
Run it and watch the lines arrive one at a time:
curl -N http://127.0.0.1:3000/progress
step 1 of 3: starting
step 2 of 3: working
step 3 of 3: finishing
Each line appears about 100 milliseconds after the previous one. The handler never holds more than one line at a time, and the client never waits for the whole report before seeing the first step.
Summary
The choice between a fixed body and a streamed body is a choice about when the answer exists. A fixed body fits when the whole answer is ready before the handler returns: a short message, a small JSON document, a page that is already built. A streamed body fits when the answer arrives over time, when it is too large to hold at once, or when it never ends at all.
The decision framework is short. If the client should see the first piece before the last piece exists, build a stream and hand it to Body::from_stream. If the pieces come from a list, use stream::iter. If they are produced over time, use stream::unfold. If they come from other work, feed them through a channel. Pick the error type by what can actually fail, and remember that a failure after the first chunk cannot change the status code, so a stream that can fail needs a client that can notice a partial body.
The next thing this unlocks is choosing the source of the chunks. A stream can be built from anything that produces bytes over time, and the most common source in a web server is a file on disk. That is a small step from here: open the file, turn its reader into a stream, and hand that stream to the same from_stream call.