Request and Response Streaming
Extractors and Responders introduces the two streaming
tools: the Payload extractor reads a request body as it arrives, and
ResponseBuilder::streaming() sends a response body as it is produced. This
chapter shows how to use them safely:
- Request bodies: limits, records split across chunks, compressed uploads, trailers, and errors.
- Response bodies: streams, producer tasks, framing, and errors.
- Slow clients and timeouts.
- Body streams in filters and middleware.
- Two complete examples, a Server-Sent Events feed and a streaming proxy.
- Testing.
Buffering or Streaming
Most handlers should buffer. A buffered body is a single value that you can validate as a whole. Its size limit is configured once, and a failure becomes an ordinary error response.
Stream when:
- a body is too large to hold in memory;
- the client benefits from early output;
- the data passes through to another service or to storage.
| Buffered | Streamed | |
|---|---|---|
| Request API | Bytes, String, Json<T>, Form<T> | Payload |
| Response API | body(), json(), a responder | streaming(), body(SizedStream), Body::from_message() |
| Memory per request | The whole body | A few chunks plus your own state |
| Request size limit | PayloadConfig, JsonConfig, FormConfig | Your own byte counter |
Request Content-Encoding | Decoded with the compress feature | Raw bytes unless you wrap them in a Decoder |
| Request errors | Rejected before the handler runs | Returned by recv() while the handler runs |
| Response errors | Cannot occur once the body is built | Reach the client after the status was sent |
Streaming Request Bodies
Reading the Payload
The Payload extractor hands the handler the request body as a stream of
Bytes chunks. This handler accepts an upload of up to 16 MiB:
use ntex::web::{self, App, InternalError, types::Payload};
async fn upload(
mut body: Payload,
) -> Result<String, InternalError<&'static str>> {
const LIMIT: usize = 16 * 1024 * 1024;
let mut total = 0;
while let Some(chunk) = body.recv().await {
let chunk = chunk
.map_err(|_| web::error::ErrorBadRequest("Cannot read body"))?;
if chunk.len() > LIMIT - total {
return Err(web::error::ErrorPayloadTooLarge("Body is too large"));
}
total += chunk.len();
// Write `chunk` to storage here.
}
Ok(format!("Received {total} bytes\n"))
}
fn main() {
let app = App::default().route("/upload", web::post().to(upload));
}
recv()returns the next chunk, an error, orNoneat the end of the body.Payloadalso implementsfutures::Stream.- Chunk sizes depend on the network and the protocol, not on how the client wrote the body.
- ntex reads the body only as fast as the handler consumes it, so a handler that awaits storage between chunks needs no buffering of its own. Slow Clients and Timeouts explains how this works for each protocol.
The handler enforces its own size limit: the PayloadConfig limit and
request decompression apply only to the buffered extractors. Count the bytes
you receive, as this handler does. Content-Length is optional and untrusted,
so it is useful only for an early rejection.
A request has one body. Extracting Payload takes it, so a body extractor
that runs afterwards, such as Bytes or Json<T>, gets no data.
Records Across Chunks
Chunk boundaries are not message boundaries. One record can be split across chunks, and one chunk can hold several records.
This handler reads newline-delimited JSON. It keeps the incomplete end of each chunk for the next one and limits both the line length and the whole body:
use ntex::util::{Bytes, BytesMut};
use ntex::web::{self, App, InternalError, types::Payload};
use serde::Deserialize;
#[derive(Deserialize)]
struct Event {
kind: String,
}
/// Reassembles newline-terminated records from arbitrary body chunks.
struct LineReader {
buf: BytesMut,
max_line: usize,
}
impl LineReader {
fn new(max_line: usize) -> Self {
LineReader { buf: BytesMut::new(), max_line }
}
/// Appends `chunk` and returns every line it completes.
fn push(&mut self, chunk: &[u8]) -> Result<Vec<Bytes>, &'static str> {
self.buf.extend_from_slice(chunk);
let mut lines = Vec::new();
while let Some(pos) = self.buf.iter().position(|b| *b == b'\n') {
if pos > self.max_line {
return Err("Line is too long");
}
let mut line = self.buf.split_to(pos + 1);
line.truncate(pos);
lines.push(line);
}
if self.buf.len() > self.max_line {
return Err("Line is too long");
}
Ok(lines)
}
/// Returns the last line when the body does not end with a newline.
fn finish(self) -> Option<Bytes> {
(!self.buf.is_empty()).then(|| self.buf.freeze())
}
}
fn record(line: &[u8]) -> Result<usize, InternalError<&'static str>> {
let line = line.strip_suffix(b"\r").unwrap_or(line);
if line.is_empty() {
return Ok(0);
}
let event: Event = serde_json::from_slice(line)
.map_err(|_| web::error::ErrorBadRequest("Invalid JSON line"))?;
log::info!("event: {}", event.kind);
Ok(1)
}
async fn ingest(
mut body: Payload,
) -> Result<String, InternalError<&'static str>> {
const MAX_BODY: usize = 64 * 1024 * 1024;
let mut lines = LineReader::new(16 * 1024);
let mut total = 0;
let mut events = 0;
while let Some(chunk) = body.recv().await {
let chunk = chunk
.map_err(|_| web::error::ErrorBadRequest("Cannot read body"))?;
if chunk.len() > MAX_BODY - total {
return Err(web::error::ErrorPayloadTooLarge("Body is too large"));
}
total += chunk.len();
for line in lines.push(&chunk).map_err(web::error::ErrorPayloadTooLarge)? {
events += record(&line)?;
}
}
if let Some(line) = lines.finish() {
events += record(&line)?;
}
Ok(format!("Accepted {events} events\n"))
}
fn main() {
let app = App::default().route("/events", web::post().to(ingest));
}
LineReaderalso checks the incomplete line, so a client cannot grow the buffer by never sending a newline.- The last record may end without a newline;
finish()returns it. record()strips a trailing\r, so CRLF line endings work too, and skips empty lines.
The handler processes each record as soon as it is complete. When it rejects
an invalid line with 400, the records before that line have already been
processed. If a batch must be all or nothing, collect the records and commit
them only after the last chunk.
Compressed Uploads
Payload delivers the body as it was sent, still compressed when the request
has a Content-Encoding header. With the compress feature, Decoder
decodes it while streaming:
use futures::StreamExt;
use ntex::http::encoding::Decoder;
use ntex::web::{self, App, HttpRequest, InternalError, types::Payload};
async fn upload(
req: HttpRequest,
body: Payload,
) -> Result<String, InternalError<&'static str>> {
const LIMIT: usize = 16 * 1024 * 1024;
let mut body = Decoder::from_headers(body.into_inner(), req.headers());
let mut total = 0;
while let Some(chunk) = body.next().await {
let chunk = chunk
.map_err(|_| web::error::ErrorBadRequest("Cannot decode upload"))?;
if chunk.len() > LIMIT - total {
return Err(web::error::ErrorPayloadTooLarge(
"Decoded upload exceeds 16 MiB",
));
}
total += chunk.len();
}
Ok(format!("Received {total} decoded bytes"))
}
fn main() {
let app = App::default().route("/upload", web::post().to(upload));
}
Decoder::from_headers()handlesgzip,deflate, andzstd.- A body without
Content-Encoding, or with an encoding the decoder does not recognize, passes through unchanged. Check the header yourself if unknown encodings must be rejected. - Apply the limit to the decoded chunks, as this handler does, because a small compressed body can expand enormously.
- The stream ends after a decoding error.
- Large chunks are decoded on the blocking thread pool, so decoding does not stall the worker.
Trailers
A chunked HTTP/1.1 body or an HTTP/2 body can end with trailer fields. They
carry values that can only be computed over the whole body, such as a
checksum. Read them from the underlying http::Payload after the body has
been read to the end:
use ntex::web::{self, App, InternalError, types::Payload};
async fn upload(
body: Payload,
) -> Result<String, InternalError<&'static str>> {
let mut body = body.into_inner();
let mut total = 0;
while let Some(chunk) = body.recv().await {
let chunk = chunk
.map_err(|_| web::error::ErrorBadRequest("Cannot read upload"))?;
total += chunk.len();
}
let checksum = body
.trailers()
.and_then(|trailers| trailers.get("x-checksum").cloned())
.ok_or(web::error::ErrorBadRequest("Missing x-checksum trailer"))?;
Ok(format!("Received {total} bytes, checksum {checksum:?}\n"))
}
fn main() {
let app = App::default().route("/upload", web::post().to(upload));
}
trailers() returns a copy;
take_trailers() moves them out.
Errors and Cancellation
recv() returns an error when the body cannot be completed, for example
because the client disconnected, sent a malformed body, or missed the
read-rate deadline. PayloadError lists the variants. The
error response often never reaches the client, but returning the error still
ends the handler and releases what it holds.
A closed connection does not always cancel the handler:
- Over HTTP/1, ntex lets the handler run to completion in the background, and reading the rest of the body fails.
- Any handler future can still be dropped at an
.await, for example by a timeout around it or when the worker stops.
So put cleanup of partial work, such as deleting a temporary file, in a Drop
guard rather than after the loop, and make the result visible only after the
last chunk has been read.
Responding Before the Body Ends
A handler can return a response without reading the whole body, for example to reject an upload after checking its first chunk. ntex then disposes of the unread rest:
- Over HTTP/1, it sends the response and closes the connection instead of reading the remaining bytes.
- Over HTTP/2, it resets only that stream with
NO_ERRORand keeps the connection open.
Streaming Response Bodies
Pick the body type by how your data is produced:
| Your data | Use | See |
|---|---|---|
| Comes from a sequence of async calls | streaming() with a Stream | Streaming from Async Calls |
| Is easier to produce in a loop | A task feeding a bstream::channel() | A Producer Task |
| Is a few small messages pushed by other code | An mpsc::channel() | A Producer Task |
| Has a known total size | SizedStream | Known Length |
| Needs full control over polling and size | Your own MessageBody | A Custom Body Type |
Sending a Stream
ResponseBuilder::streaming() sends each chunk as the stream yields it.
This handler sends the numbers 1 to 1000, one per line:
use std::io;
use futures::stream;
use ntex::util::Bytes;
use ntex::web::{self, App, HttpResponse};
async fn numbers() -> HttpResponse {
let lines = (1..=1000).map(|n| Bytes::from(format!("{n}\n")));
HttpResponse::Ok()
.content_type("text/plain")
.streaming(stream::iter(lines.map(Ok::<_, io::Error>)))
}
fn main() {
let app = App::default().route("/numbers", web::get().to(numbers));
}
- The stream must be
Unpin + 'staticand yieldResult<Bytes, E>, whereEimplementsstd::error::Error + 'static. - Over HTTP/1.1, the body is sent with chunked encoding; Framing covers the other cases.
- An
Erritem aborts the response; see Errors After the Headers. - The lines are generated in memory to keep the example short. Send data that
is already in memory with
body()instead, which also setsContent-Length.
Streaming from Async Calls
When each chunk comes from an async call, stream::unfold carries the state
from one call to the next, and Box::pin makes the stream Unpin:
use std::io;
use futures::stream;
use ntex::time::{self, Millis};
use ntex::util::Bytes;
use ntex::web::{self, App, HttpResponse};
/// Returns one page of CSV rows and whether another page follows.
async fn fetch_page(page: u32) -> io::Result<(Bytes, bool)> {
time::sleep(Millis(10)).await;
let rows = format!("{page},row-{page}\n");
Ok((Bytes::from(rows), page < 99))
}
async fn export() -> HttpResponse {
let pages = stream::unfold(Some(0), |next| async move {
let page = next?;
match fetch_page(page).await {
Ok((rows, more)) => Some((Ok(rows), more.then_some(page + 1))),
Err(err) => Some((Err(err), None)),
}
});
HttpResponse::Ok()
.content_type("text/csv; charset=utf-8")
.streaming(Box::pin(pages))
}
fn main() {
let app = App::default().route("/export.csv", web::get().to(export));
}
The server polls the stream only while the connection’s write buffer has
room, so the next page is fetched when the client is ready for it. A slow
client slows the export instead of filling memory. After an Err item, the
stream returns None, so the export stops at the first failure.
A Producer Task
When the producer is easier to write as a loop than as a stream, run it in a
task and feed a bstream::channel():
use std::io;
use ntex::channel::bstream::{self, Status};
use ntex::util::Bytes;
use ntex::web::{self, App, HttpResponse};
/// Stands in for work that produces output in pieces and can fail.
async fn render_part(part: u32) -> io::Result<Bytes> {
Ok(Bytes::from(format!("part {part}\n")))
}
async fn report() -> HttpResponse {
let (tx, rx) = bstream::channel::<io::Error>();
ntex::rt::spawn(async move {
for part in 0..1000 {
if tx.ready().await != Status::Ready {
return; // the response was dropped
}
match render_part(part).await {
Ok(chunk) => tx.feed_data(chunk),
Err(err) => return tx.set_error(err),
}
}
tx.feed_eof();
});
HttpResponse::Ok().content_type("text/plain").streaming(rx)
}
fn main() {
let app = App::default().route("/report", web::get().to(report));
}
Sender::ready()waits until the response has room for more data.ready()returnsStatus::Droppedonce the response stream has been dropped, for example after the client disconnected, so the task stops instead of working for nobody.- Report a failure with
set_error(). If the task only returns, dropping the sender ends the body normally, and the client cannot tell a truncated body from a complete one. - The task is detached; it runs until it finishes or notices
Dropped.
An mpsc::channel() receiver also works as a response stream, as the
Server-Sent Events example shows. It is
unbounded, and send() never waits, so use it for small, infrequent messages
and use bstream when the producer can outrun the client.
Framing
The body type decides how the response is delimited on the wire:
| Body | HTTP/1.1 | HTTP/1.0, or after no_chunking() | HTTP/2 |
|---|---|---|---|
Sized: body(bytes), SizedStream, BodySize::Sized | Content-Length | Content-Length | content-length |
Stream: streaming(), BodySize::Stream | Transfer-Encoding: chunked; a Content-Length header you set is dropped | Your Content-Length header if you set one, otherwise the body ends when the connection closes | DATA frames; content-length is removed |
no_chunking()is for clients that cannot handle chunked encoding.- Responses with status
204,304, or1xxother than101never have a body. - A response to a
HEADrequest is sent as headers only, and its body is never polled. A producer task spawned by the handler still starts, and stops onceready()reportsDropped.
Known Length
When the total size is known in advance, wrap the stream in SizedStream.
The response then carries Content-Length, so the client can show progress,
and HTTP/1.1 needs no chunked encoding:
use std::{error::Error, rc::Rc};
use futures::stream;
use ntex::http::body::SizedStream;
use ntex::util::Bytes;
use ntex::web::{self, App, HttpResponse};
async fn download() -> HttpResponse {
// For example, parts of an object whose total size is in its metadata.
let parts = vec![Bytes::from_static(b"hello, "), Bytes::from_static(b"world\n")];
let size = parts.iter().map(|part| part.len() as u64).sum();
let body = stream::iter(parts.into_iter().map(Ok::<_, Rc<dyn Error>>));
HttpResponse::Ok()
.content_type("application/octet-stream")
.body(SizedStream::new(size, body))
}
fn main() {
let app = App::default().route("/download", web::get().to(download));
}
SizedStreamrequires the error typeRc<dyn Error>.- Its stream must yield exactly the declared number of bytes. If it ends early, the client’s body fails as incomplete; bytes beyond the declared size are not sent.
A Custom Body Type
For full control, implement MessageBody and wrap the value with
Body::from_message(). size() declares the framing, and
poll_next_chunk() produces the chunks:
use std::{error::Error, rc::Rc, task::{Context, Poll}};
use ntex::http::body::{Body, BodySize, MessageBody};
use ntex::util::Bytes;
use ntex::web::{self, App, HttpResponse};
/// Sends `chunk` `count` times.
struct Repeat {
chunk: Bytes,
count: u64,
size: u64,
}
impl Repeat {
fn new(chunk: Bytes, count: u64) -> Self {
let size = chunk.len() as u64 * count;
Repeat { chunk, count, size }
}
}
impl MessageBody for Repeat {
fn size(&self) -> BodySize {
BodySize::Sized(self.size)
}
fn poll_next_chunk(
&mut self,
_: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
if self.count == 0 {
return Poll::Ready(None);
}
self.count -= 1;
Poll::Ready(Some(Ok(self.chunk.clone())))
}
}
async fn filler() -> HttpResponse {
let body = Repeat::new(Bytes::from_static(&[b'x'; 1024]), 1024);
HttpResponse::Ok().body(Body::from_message(body))
}
fn main() {
let app = App::default().route("/filler", web::get().to(filler));
}
This body sends 1 MiB while holding one 1 KiB chunk. poll_next_chunk()
follows the usual poll rules: return Poll::Pending only after arranging a
wake-up through the context.
Errors After the Headers
The status line and headers are sent before the first chunk, so a stream error cannot change the status. What the client sees depends on the protocol:
- Over HTTP/1, ntex closes the connection before the body is complete. A client reading a chunked or sized body sees it end early; only a close-delimited body looks complete.
- Over HTTP/2, the stream is reset with
INTERNAL_ERROR. The client can tell that the body failed, but not why.
Check permissions, validate parameters, and open the data source before returning the response, so the common failures still produce a proper error status.
Compression
With the Compress middleware, streamed responses are compressed too. The
encoder flushes whenever the stream has no chunk ready, so each piece of a slow
stream, such as a Server-Sent Event, reaches the client without waiting for
more data. Keep in mind:
- A response that already has a
Content-Encodingheader is not compressed again, nor is a sized body under 1024 bytes or a204or101response. - A compressed sized body loses its length; HTTP/1.1 sends it chunked.
- Each compressed response keeps its own encoder state, several hundred KiB for gzip or deflate and more for zstd. Many long-lived streams add up.
To send one response uncompressed, call
.encoding(ContentEncoding::Identity) on its builder. The method comes from
the BodyEncoding trait, and ContentEncoding is in ntex::http::header.
Slow Clients and Timeouts
Streaming applies backpressure in both directions: ntex reads a request body only as fast as the handler consumes it, and polls a response stream only as fast as the client reads. A slow client therefore does not fill memory, but it can hold a connection open for a long time. Timeouts limit how long:
| HTTP/1 | HTTP/2 | |
|---|---|---|
| Handler reads slowly | ntex stops reading the socket, and the client’s TCP window fills | The stream’s flow-control window is released as the handler reads, so only that stream slows; see Flow control |
| Client uploads slowly | set_payload_read_rate() limits each request body; disabled by default | IoConfig::set_frame_read_rate() limits each frame; disabled by default |
| Upload misses the deadline | 408 Request Timeout, then the connection closes | GOAWAY; every stream on the connection fails |
| Client stops reading the response | The write timeout, 10 seconds by default, closes the connection | The stream is reset with CANCEL after 5 seconds |
Slow Uploads
A size limit does not stop a client that sends a small body very slowly. Set a
minimum read rate for each protocol in the SharedCfg that you pass to
bind():
use ntex::{SharedCfg, http::HttpServiceConfig, io::IoConfig, time::Seconds};
fn main() {
let config = SharedCfg::new("uploads")
// HTTP/1: the whole request body.
.add(HttpServiceConfig::new().set_payload_read_rate(
Seconds(5), // measurement interval
Seconds(600), // maximum time for one request body
64 * 1024, // bytes required in each interval
))
// HTTP/2 and WebSocket: one frame at a time.
.add(IoConfig::new().set_frame_read_rate(
Seconds(2), // measurement interval
Seconds(10), // maximum time for one frame
1024, // bytes required in each interval
));
}
For HTTP/1, set_payload_read_rate() measures the whole request body. With
these values:
- Each five-second interval must deliver more than 64 KiB.
- The deadline is not extended beyond ten minutes in total.
- A body that misses its deadline fails with a payload error. The default
control service answers
408 Request Timeoutand closes the connection. - The timer pauses while the handler applies backpressure, so a slow handler is not mistaken for a slow client.
For HTTP/2, IoConfig::set_frame_read_rate() takes the same three
parameters but measures single frames:
- The timer runs only while a frame is partly received and resets when the frame completes. With these values, a partly received frame must gain more than 1 KiB every two seconds and complete within ten seconds.
- It catches a client that trickles a single frame, but not one that sends
small complete
DATAframes slowly. To limit the total time of an upload, wrap the read loop inntex::time::timeout(). - A frame carries at most 16 KiB of payload by default, so a
ratenear that size requires each frame to arrive within one interval. - A missed deadline closes the whole connection with
GOAWAY, failing every stream on it. - HTTP/1 ignores this setting. WebSocket connections use it too; see Timeouts.
Connection and protocol configuration describes how configuration reaches the server, and Body limits and separate timeout budgets combines the read rate with per-route limits.
Slow Readers
A client that stops reading eventually fills the connection’s buffers:
- Over HTTP/1, the write timeout closes a connection whose output stays
blocked for too long. It defaults to 10 seconds; change it with
set_write_timeout()on the sameHttpServiceConfig. - Over HTTP/2, a stream that waits too long for flow-control capacity is reset
with
CANCEL, after five seconds by default; see Sending data.
In both cases the response stream is dropped, so a bstream producer sees
Dropped and an mpsc sender gets an error.
Streams in Filters and Middleware
Filters and middleware see the request as a WebRequest, and middleware
sees the response as a WebResponse. Extractors run only when the handler
is called, so this code has no Payload, Bytes, or Json.
It works with the raw body stream instead: PayloadConfig limits do not
apply, and nothing decodes Content-Encoding. To change a body, replace its
stream with a wrapper:
| Request | Response | |
|---|---|---|
| Body type | http::Payload | ResponseBody<Body> |
| Replace | WebRequest::take_payload(), WebRequest::set_payload() | WebResponse::map_body() |
| Wrap a stream | Payload::from_stream() | Body::from_message() |
| Chunk type | Result<Bytes, PayloadError> | Result<Bytes, Rc<dyn Error>> |
Replacing the Request Payload
This filter caps request bodies at 1 MiB for the whole app. It rejects a
larger Content-Length before any handler runs, and wraps the payload so that
a body sent without a length fails once it passes the limit:
use std::{pin::Pin, task::{Context, Poll}};
use futures::Stream;
use ntex::http::{Payload, error::PayloadError, header::CONTENT_LENGTH};
use ntex::util::Bytes;
use ntex::web::{self, App, InternalError, WebRequest, types};
const LIMIT: usize = 1024 * 1024;
/// Fails with `Overflow` once more than `remaining` bytes arrive.
struct Limited {
payload: Payload,
remaining: usize,
}
impl Stream for Limited {
type Item = Result<Bytes, PayloadError>;
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
match this.payload.poll_recv(cx) {
Poll::Ready(Some(Ok(chunk))) if chunk.len() > this.remaining => {
// Drop the rest of the body and end the stream after the error.
this.payload = Payload::None;
Poll::Ready(Some(Err(PayloadError::Overflow)))
}
Poll::Ready(Some(Ok(chunk))) => {
this.remaining -= chunk.len();
Poll::Ready(Some(Ok(chunk)))
}
other => other,
}
}
}
async fn limit_body(
mut req: WebRequest<()>,
) -> Result<WebRequest<()>, InternalError<&'static str>> {
let declared = req
.headers()
.get(CONTENT_LENGTH)
.and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
if declared.is_some_and(|len| len > LIMIT) {
return Err(web::error::ErrorPayloadTooLarge("Body exceeds 1 MiB"));
}
let payload = req.take_payload();
let limited = Limited { payload, remaining: LIMIT };
req.set_payload(Payload::from_stream(limited));
Ok(req)
}
async fn upload(body: types::Payload) -> Result<String, PayloadError> {
let mut body = body.into_inner();
let mut total = 0;
while let Some(chunk) = body.recv().await {
total += chunk?.len();
}
Ok(format!("Received {total} bytes"))
}
fn main() {
let app = App::default()
.filter(limit_body)
.route("/upload", web::post().to(upload));
}
Payload::from_stream()boxes the wrapper, one allocation per request.- Handlers read the wrapped body as usual. Here
uploadgetsOverflowas its next chunk, and?turns it into413 Payload Too Large. - The
BytesandStringextractors answer413the same way.JsonandFormreport a stream error as400 Bad Request, but their own limits, 32 KiB and 16 KiB by default, usually stop the body first. - A wrapped payload has no trailers;
http::Payload::trailers()returnsNonefor it, so leave the body alone on routes that read trailers.
A filter can also decode uploads for every route:
- Wrap the payload with
Decoder::from_headers(payload, req.headers()). - Remove
Content-EncodingandContent-Lengththroughreq.headers_mut(). The buffered extractors decode byContent-Encodingthemselves, so a header left in place makes them decode twice and fail with400, and the old length no longer describes the body. - Register the decoding filter before
limit_body. Filters run in registration order, so the limit then applies to the decoded bytes, as Compressed Uploads recommends.
Wrapping the Response Body
A middleware gets the response when the handler returns, before any of the
body is sent; the body streams after the middleware’s future completes.
WebResponse::map_body() replaces the body and also passes the response
head, so a wrapper that changes the bytes can update the headers.
The Compress middleware works this way (source). It
picks an encoding from Accept-Encoding before calling the inner service,
then maps the body into an Encoder, which sets Content-Encoding and
reports the size as unknown.
This middleware logs how many bytes each response sent and how long that took, measured until the body is finished rather than until the handler returns:
use std::{error::Error, rc::Rc, task::{Context, Poll}, time::Instant};
use ntex::http::body::{Body, BodySize, MessageBody, ResponseBody};
use ntex::util::Bytes;
use ntex::web::{self, App, middleware::from_fn};
/// Passes the body through and logs what was sent when it is dropped.
struct Metered {
body: ResponseBody<Body>,
path: String,
started: Instant,
sent: u64,
}
impl MessageBody for Metered {
fn size(&self) -> BodySize {
self.body.size()
}
fn poll_next_chunk(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
let item = self.body.poll_next_chunk(cx);
if let Poll::Ready(Some(Ok(chunk))) = &item {
self.sent += chunk.len() as u64;
}
item
}
}
impl Drop for Metered {
fn drop(&mut self) {
let elapsed = self.started.elapsed();
log::info!("{} sent {} bytes in {elapsed:?}", self.path, self.sent);
}
}
fn main() {
web::HttpServer::new(async |_| {
App::new()
.middleware(from_fn(async |req, next| {
let path = req.path().to_owned();
let started = Instant::now();
let res = next.call(req).await?;
Ok(res.map_body(move |_head, body| {
let body = Metered { body, path, started, sent: 0 };
ResponseBody::Other(Body::from_message(body))
}))
}))
.route("/report", web::get().to(async || "report"))
});
}
The built-in Logger middleware wraps the body the same way, so its %b,
%T, and %D values cover the whole body.
- The body outlives the middleware call, and
MessageBodyrequires'static. Copy what the wrapper needs, like the path here, instead of borrowing the request. size()passes the inner size through, so a sized response keeps itsContent-Length. A wrapper that changes the bytes must reportBodySize::Streamor the new size, and update headers that describe the old bytes, such asContent-EncodingorETag, through the head.Dropruns when the server is done with the body: after the last chunk, after a stream error, or when the client disconnects. An error from the inner body passes through and behaves as in Errors After the Headers.- Middleware order decides which bytes the wrapper sees. Registered before
Compress, it is the outer layer and counts compressed bytes; registered after, it counts the original ones. - A middleware service written by hand calls
map_body()on the result ofctx.call()in the same way; see Writing a Middleware Service.
Example: Server-Sent Events
Server-Sent Events push text events over an ordinary response, and browsers
read them with EventSource. Each event is a few field: value lines
followed by an empty line; a line that starts with : is a comment.
This server keeps a channel per connected client. GET /events subscribes,
and POST /notify sends a JSON notice to every subscriber:
use std::{cell::RefCell, io, rc::Rc};
use futures::StreamExt;
use ntex::channel::mpsc;
use ntex::time::{self, Seconds};
use ntex::util::Bytes;
use ntex::web::{self, HttpResponse, InternalError, types::Json};
use ntex::{SharedCfg, rt};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
struct Notice {
text: String,
}
type Clients = Rc<RefCell<Vec<mpsc::Sender<Bytes>>>>;
#[derive(Clone)]
struct Worker {
clients: Clients,
_keepalive: Rc<rt::JoinHandle<()>>,
}
type State = web::AppState<Worker>;
/// Queues `message` for every connected client and forgets clients that left.
fn broadcast(clients: &Clients, message: &Bytes) {
clients
.borrow_mut()
.retain(|client| client.send(message.clone()).is_ok());
}
async fn events(state: &State, (): ()) -> HttpResponse {
let (tx, rx) = mpsc::channel();
state.clients.borrow_mut().push(tx);
HttpResponse::Ok()
.content_type("text/event-stream")
.header("cache-control", "no-cache")
.streaming(rx.map(Ok::<_, io::Error>))
}
async fn notify(
state: &State,
(): (),
notice: Json<Notice>,
) -> Result<HttpResponse, InternalError<&'static str>> {
let data = serde_json::to_string(&*notice)
.map_err(|_| web::error::ErrorInternalServerError("Cannot encode notice"))?;
let event = Bytes::from(format!("event: notice\ndata: {data}\n\n"));
broadcast(&state.clients, &event);
Ok(HttpResponse::NoContent().build())
}
fn start_worker() -> State {
let clients = Clients::default();
let keepalive = clients.clone();
let task = rt::spawn(async move {
let ping = Bytes::from_static(b": ping\n\n");
let interval = time::interval(Seconds(15));
loop {
interval.tick().await;
broadcast(&keepalive, &ping);
}
})
.cancel_on_drop();
web::AppState::new(Worker {
clients,
_keepalive: Rc::new(task),
})
}
#[ntex::main]
async fn main() -> io::Result<()> {
web::HttpServer::with_config(
async || Ok(start_worker()),
async |_| {
web::App::new()
.route("/events", web::get().to_with_state(events))
.route("/notify", web::post().to_with_state(notify))
},
)
.workers(1)
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
- A newline inside event data would end the field.
serde_json::to_string()escapes newlines in strings, so each notice is a singledata:line. HttpServer::with_config()creates the state once per worker, as in A periodic task per worker, so each worker has its own client list. A notice posted to one worker reaches only that worker’s clients, which is why the example runs one worker. With several workers, deliver each notice to every worker, for example through a thread-safe broadcast channel that each worker’s task listens on.broadcast()forgets a client whensend()fails, which happens once the server has dropped that client’s response stream after a disconnect or a timeout.- The ping comment every 15 seconds keeps idle proxies from closing the
connection and lets the server notice departed clients when no notices are
sent. The first
tick()completes immediately.cancel_on_drop()stops the task when the worker state is dropped. - The per-client queue is unbounded. A client that stops reading is disconnected by the slow-reader timeouts, but a client that reads more slowly than events arrive builds a backlog. For high event rates, use a bounded queue and disconnect clients that fall behind.
- Behind nginx, add an
x-accel-buffering: noresponse header so that the proxy does not buffer the stream. - The example sends no
id:fields, so a browser that reconnects after a network failure misses the events sent in between. To support resuming, number the events and replay from theLast-Event-IDrequest header.
The server-sent-events example in the examples repository is another runnable version.
Example: Streaming Proxy
This handler forwards an upload to an upstream service and streams the upstream response back, holding only a few chunks of either body in memory:
use ntex::http::header::{self, HeaderName};
use ntex::web::{HttpRequest, HttpResponse, types::Payload};
use ntex::{SharedCfg, client::Client, web};
#[derive(Clone)]
struct Upstream {
client: Client,
url: String,
}
type State = web::AppState<Upstream>;
/// Returns `true` for headers that describe a single connection.
fn hop_by_hop(name: &HeaderName) -> bool {
matches!(
name.as_str(),
"connection"
| "keep-alive"
| "proxy-authenticate"
| "proxy-authorization"
| "te"
| "trailer"
| "transfer-encoding"
| "upgrade"
)
}
async fn upload(
state: &State,
(): (),
req: HttpRequest,
body: Payload,
) -> HttpResponse {
let mut request = state
.client
.request_from(state.url.as_str(), req.head())
.no_decompress();
let headers = request.headers_mut();
let names: Vec<HeaderName> = headers
.keys()
.filter(|name| hop_by_hop(name))
.cloned()
.collect();
for name in names {
headers.remove(name);
}
headers.remove(header::HOST);
headers.remove(header::CONTENT_LENGTH);
let response = match request.send_stream(body).await {
Ok(response) => response,
Err(_) => return HttpResponse::BadGateway().build(),
};
let mut builder = HttpResponse::builder(response.status());
for (name, value) in response.headers() {
if !hop_by_hop(name) && name != header::CONTENT_LENGTH {
builder.header(name.clone(), value.clone());
}
}
builder.streaming(response)
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
let url = std::env::var("UPSTREAM_URL")
.unwrap_or_else(|_| "http://127.0.0.1:9000/upload".to_owned());
web::HttpServer::new(async move |_| {
let state = web::AppState::new(Upstream {
client: Client::new(),
url: url.clone(),
});
web::App::<State>::new()
.route("/upload", web::post().to_with_state(upload))
.build_with(state)
})
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
Client::request_from()copies the method and all headers of the incoming request. The handler removes the headers that describe the client’s own connection,Host, which the client sets from the upstream URL, andContent-Length, because the body is forwarded as a stream. Headers named in aConnectionheader are connection-specific too; a production proxy removes them as well.no_decompress()forwards the upstream body as encoded, matching the copiedContent-Encodingheader.- The upstream
Content-Lengthis dropped becausestreaming()chooses the framing. Upstream trailers are not forwarded. - Each side waits for the other: a slow upstream slows reading of the upload, and a slow client slows reading of the upstream response.
ClientRequest::timeout(), 5 seconds by default, covers only the wait for the upstream response head after the request has been sent. It does not cover connecting, sending the upload, or reading the response body, so a stalled upstream body keeps the client’s response open.- Failures after the response has started follow Errors After the Headers.
Calling another HTTP service shows a buffered call with timeouts, and the http-proxy example is a complete proxy.
Testing Streaming Handlers
TestRequestdelivers a body set withpayload()as a single chunk, so an in-process test does not exercise reassembly across chunks. Test that logic directly; for example, feedLineReadera record split across twopush()calls.test::read_body()collects a response body in-process, andtest::load_stream()collects any stream ofResult<Bytes, E>.- Whether a chunk reaches the client before the stream ends depends on the connection, so test it against a real server.
This test reads the response as a stream and bounds the wait with a timeout:
use std::io;
use futures::{StreamExt, stream};
use ntex::time::{Seconds, timeout};
use ntex::util::Bytes;
use ntex::web::{self, App, HttpResponse, test};
/// Sends one line, then keeps the response open.
async fn feed() -> HttpResponse {
let first = stream::iter([Ok::<_, io::Error>(Bytes::from_static(b"first\n"))]);
HttpResponse::Ok().streaming(first.chain(stream::pending()))
}
#[ntex::test]
async fn first_line_arrives_before_the_stream_ends() {
let server = test::server(async |_| App::new().route("/feed", web::get().to(feed)));
let mut response = server.get("/feed").send().await.unwrap();
let mut received = Vec::new();
timeout(Seconds(2), async {
while !received.ends_with(b"\n") {
let chunk = response.next().await.unwrap().unwrap();
received.extend_from_slice(&chunk);
}
})
.await
.expect("no complete line within two seconds");
assert_eq!(received, b"first\n");
}
Collecting the whole body would hang here, because the stream never ends. Use a real server for connection behavior describes the server helpers.
Checklist
- Buffer unless a body is large, long-lived, or passed through.
- Count request bytes yourself, after decoding if you decode, and limit records and lines inside the body.
- Enable
set_payload_read_rate()for public HTTP/1 upload endpoints. For HTTP/2, set a frame read rate and bound uploads withtimeout(). - Clean up partial work in a guard, and commit only after the last chunk.
- Decide the status before returning a streaming response.
- Stop producers when
ready()reportsDroppedorsend()fails, and report failures withset_error()rather than ending the stream. - Use
SizedStreamwhen the length is known. - In filters and middleware, limit and decode the raw payload yourself, and
keep a wrapped response body’s
size()and headers accurate. - For event streams, check compression and proxy buffering.
- Test reassembly with split chunks and delivery with a real server.