ntex framework guide
ntex is a Rust framework for building asynchronous network services. You can use it for an HTTP API, a web application, or a server that speaks your own protocol. Its web framework handles routing, request extraction, middleware, and responses, while the lower-level crates let you work directly with connections and messages. You can start with the web APIs without learning all of those layers first.
This guide is for Rust developers who want to build something with ntex and
understand how its pieces fit together. It assumes you know Rust’s basic
types, traits, and async/await; it does not assume experience with ntex.
Examples show the public APIs, and the linked API reference gives the full
type signatures and options when you need them.
The common building block is a service: a component that accepts a request and produces a response or an error asynchronously. A request might be an HTTP request, a decoded protocol message, or a connection. Pipelines give services a shared context for state, readiness, calls, and shutdown. That makes the same composition model useful for a small handler and for a stack of protocol services. You will meet services gradually, rather than needing to implement one before your first web route.
ntex also separates protocol code from the runtime that drives it. You can choose Tokio, Compio, or ntex’s native runtime without rewriting your web handlers. The I/O layer provides buffered connections and filters, so concerns such as TLS can sit below your protocol implementation. These layers matter most when you need a custom protocol or control over connection behavior; ordinary web applications usually let the HTTP server assemble them.
Servers run applications on workers. Each worker can initialize its own state, such as a client handle or cache, and that state can use single-threaded shared types. When data must be shared across workers, you choose a thread-safe shared handle instead. The distinction helps you decide where initialization belongs and what a state clone should share, rather than treating every application value as process-wide.
Start with Getting Started to run a server, add a few routes, and write a test. If you are building a web application, continue with chapter 8, beginning with Routing and Handlers. You can return to the service and server chapters when you need more control over startup, state, or middleware.
If you are writing a protocol, begin with Service Model, Service Pipelines, and the I/O Abstraction Layer. The chapters are also useful independently: follow the links for the layer you are working on, or use the cookbook for a focused example. The API reference, LLM documentation, and migration guide are listed below the chapters.
- Getting Started
- Service Model
- Service Pipelines
- Service State
- Runtime
- Server
- Worker and Request State
- I/O Abstraction Layer
- Web Application Framework
- Testing
- Integrations
- Securing Connections with TLS
- Byte Buffers
- Timers and Time Utilities
- Cookbook
API reference
LLM documentation
- llms.txt: rules and templates for generated code
- llms-full.txt: this guide as a single text file
Migration
Getting Started
Start with a small HTTP server, then add a route, a JSON endpoint, and shared state. You need a Rust toolchain compatible with ntex 4; the current release in this repository requires Rust 1.97 or later.
Create a project
Create a binary crate:
cargo new hello-ntex
cd hello-ntex
Add ntex to the generated Cargo.toml:
[dependencies]
ntex = { version = "4", features = ["tokio"] }
Use tokio as a starting choice, especially if your application will use
Tokio-based libraries. You still start the application with #[ntex::main],
not #[tokio::main], because ntex sets up its own runtime context too.
An explicit runtime feature is not required. Without one, ntex uses its
native runtime: Linux tries io-uring and falls back to polling, other Unix
systems use polling, and Windows uses IOCP. To choose another backend,
replace tokio with compio, neon-polling (native polling on Unix), or
neon-uring (native io-uring on Linux, without the polling fallback).
Choose one rather than combining runtime features. See
Runtime for the runtime model.
The only default feature is ws, which enables WebSocket support. TLS
(openssl or rustls), compression (compress), and cookies (cookie) are
opt-in. You do not need them for this example. Enabling a feature makes its
APIs available; configuring HTTPS or installing compression middleware is a
separate step.
Run your first server
Replace src/main.rs with this application:
use ntex::{SharedCfg, web};
async fn hello() -> &'static str {
"Hello, ntex!"
}
fn config(cfg: &mut web::ServiceConfig) {
cfg.route("/", web::get().to(hello));
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
web::HttpServer::new(async |_| web::App::new().configure(config))
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
HttpServer owns the listener and workers. Its asynchronous factory creates
an App, which maps GET / to the hello handler. Returning a string makes
it the response body. SharedCfg configures the listener’s I/O and protocol
services; it is not application state.
Keep route registration in config from the start. Both the server and your
tests can call App::new().configure(config), so tests exercise the same
routes you actually serve.
Run the application:
cargo run
In another terminal, try it:
curl http://127.0.0.1:8080/
The response body is Hello, ntex! (without a trailing newline). Stop the
server with Ctrl-C. If port 8080 is already in use, change the bind address
and the curl URL together. For listener and worker options, see
Server.
Write your first test
Append this module to the same src/main.rs:
#[cfg(test)]
mod tests {
use super::*;
use ntex::{http::StatusCode, web::test};
#[ntex::test]
async fn hello_returns_a_greeting() {
let app = test::init_service(web::App::new().configure(config)).await;
let req = test::TestRequest::with_uri("/").to_request();
let res = test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(test::read_body(res).await.as_ref(), b"Hello, ntex!");
}
}
Run it with cargo test. This test builds the application in process; it
opens no socket. Checking both the status and the body catches an unexpected
error response as well as an incorrect greeting. See Testing
for JSON requests, stateful applications, and real-server tests.
Add a path parameter
Add a handler and replace config with this version:
async fn greet(name: web::types::Path<String>) -> String {
format!("Hello, {}!", name.into_inner())
}
fn config(cfg: &mut web::ServiceConfig) {
cfg.route("/", web::get().to(hello))
.route("/hello/{name}", web::get().to(greet));
}
GET /hello/Ada now returns Hello, Ada!. The Path extractor turns a
captured route segment into a typed handler argument. For route patterns and
scopes, continue with Routing and Handlers. The
Extractors and Responders chapter covers typed inputs and
response values.
Accept and return JSON
Add serde alongside ntex in Cargo.toml:
serde = { version = "1", features = ["derive"] }
Add these types and handler, then replace config again:
#[derive(serde::Deserialize)]
struct GreetingRequest {
name: String,
}
#[derive(serde::Serialize)]
struct GreetingResponse {
message: String,
}
async fn create_greeting(
body: web::types::Json<GreetingRequest>,
) -> web::HttpResponse {
web::HttpResponse::Ok().json(&GreetingResponse {
message: format!("Hello, {}!", body.name),
})
}
fn config(cfg: &mut web::ServiceConfig) {
cfg.route("/", web::get().to(hello))
.route("/hello/{name}", web::get().to(greet))
.route("/greetings", web::post().to(create_greeting));
}
Restart the server, then send a JSON body:
curl -X POST http://127.0.0.1:8080/greetings \
-H 'Content-Type: application/json' \
-d '{"name":"Ada"}'
The response body is {"message":"Hello, Ada!"}. Json<T> deserializes the
request with serde; .json(&value) serializes the response. See
Extractors and Responders for limits and extractor
configuration, and Error Handling for returning
application errors.
Share application state
A counter needs to outlive one request. Wrap it in AppState so ntex can use
it as web application state, and use an Arc so every worker shares the same
atomic counter. Add the imports, type, and handler below, then replace
config and main. Keep the earlier handlers and JSON types.
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
type Counter = web::AppState<Arc<AtomicUsize>>;
async fn visits(state: &Counter, (): ()) -> String {
let count = state.fetch_add(1, Ordering::Relaxed) + 1;
count.to_string()
}
fn config(cfg: &mut web::ServiceConfig<Counter>) {
cfg.route("/", web::get().to(hello))
.route("/hello/{name}", web::get().to(greet))
.route("/greetings", web::post().to(create_greeting))
.route("/visits", web::get().to_with_state(visits));
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
let state = Counter::new(Arc::new(AtomicUsize::new(0)));
web::HttpServer::new(async move |_| {
web::App::<Counter>::new()
.configure(config)
.build_with(state.clone())
})
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
GET /visits returns the next count. to_with_state passes application
state first, then request-local state (() here), then any extractors.
build_with supplies fixed application state rather than inheriting the
outer server’s state. Cloning the Arc shares the counter instead of copying
its current value.
Update the test’s application construction to supply a fresh counter, while
keeping the same config function and assertions:
let state = Counter::new(Arc::new(AtomicUsize::new(0)));
let app = test::init_service(
web::App::<Counter>::new()
.configure(config)
.build_with(state),
)
.await;
For worker-local state, construct Rc-backed values inside worker
initialization instead. Application State explains both
state access styles, and Worker and Request State shows
where to initialize worker-local and process-wide resources.
See request logs
ntex does not install access logging automatically. Add
env_logger = "0.11" to your dependencies, initialize it once in main
before creating the server, and add Logger before registering routes. For
the stateful application above, replace main with:
#[ntex::main]
async fn main() -> std::io::Result<()> {
env_logger::init();
let state = Counter::new(Arc::new(AtomicUsize::new(0)));
web::HttpServer::new(async move |_| {
web::App::<Counter>::new()
.middleware(web::middleware::Logger::default())
.configure(config)
.build_with(state.clone())
})
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
Run RUST_LOG=ntex=info cargo run, then make a request with curl. Logger
emits request and response information through the log crate at info
level; env_logger displays it according to RUST_LOG. The default format
includes the request line, status, response size, and elapsed time. The log
entry is written when the response body is dropped, normally after it has
been sent. See Filters and Middleware for adding your own
request-processing layers.
How ntex fits together
The web APIs sit on a common Service Model. A service asynchronously turns an input into a response or an error. Inputs can be connections, protocol messages, or HTTP requests; the same model connects these layers. A Pipeline supplies state and coordinates a service’s readiness, calls, and shutdown.
The Runtime drives asynchronous work and network events.
The Server accepts connections and runs services on workers.
The web framework builds routing, extractors, and middleware on that
foundation, so you can begin with HttpServer and learn the lower layers
when you need them.
Below HTTP, the I/O Abstraction Layer provides buffered connections independent of the runtime’s socket type. Filters can transform the bytes, for example to implement TLS, without changing your protocol handler. This becomes useful when you build a custom protocol or integrate a transport rather than just add a web route.
Where to go next
- Routing and Handlers
- Application State
- Filters and Middleware
- Extractors and Responders
- Error Handling
- Testing
- Cookbook
Component and Service Model
ntex is built from small pieces called services. A service takes a request, does some work, and eventually returns either a response or an error. The request is whatever input the service expects: an HTTP request, a TCP connection, a decoded MQTT packet, or a value from your own domain. Almost everything in ntex, from accepting connections to routing web requests, is a service or is built from services.
This chapter explains the idea and the reasoning behind it. The exact API comes in the next chapters.
Start with a Function
Imagine a component that receives an operation, performs some work, and returns a result. Its implementation might be complex, but callers should not need to know about any of that. From the outside, it should have a small, predictable interface.
In Rust, the most natural way to express this is an async function:
async fn execute(op: Operation) -> Result<OperationResult, Error> {
// Execute the operation.
// ...
}
That is all the caller needs to see. Give the function an Operation, and it
either returns an OperationResult or reports an Error. How it produces that
result is an implementation detail. One input, one output, and a clear
contract: the function is easy to understand, easy to test, and easy to
combine with others.
Building an HTTP Endpoint
Suppose we want to expose execute through an HTTP endpoint. We need a thin
layer for the HTTP details: read an operation from the request, run it, and
turn the result into a response. That layer can be another function:
async fn endpoint(req: HttpRequest) -> Result<HttpResponse, Error> {
// Extract an operation from the request.
let operation = load_operation(req).await?;
// Execute the operation.
let result = execute(operation).await?;
// Convert the result into an HTTP response.
into_response(result).await
}
The endpoint is only glue. The execution code knows nothing about HTTP, and the HTTP layer does not know how operations are executed. Neither depends on the other directly; each step turns one type into another.
Composing Services
To connect two steps, the output of one only has to match the input of the next. That makes it easy to add steps, such as authentication and authorization, without changing the overall shape:
async fn endpoint(req: HttpRequest) -> Result<HttpResponse, Error> {
// Authenticate the request.
let req = authenticate(req).await?;
// Extract the operation from the request.
let operation = load_operation(req).await?;
// Check whether the operation is allowed.
let operation = authorize(operation).await?;
// Execute the operation.
let result = execute(operation).await?;
// Convert the result into an HTTP response.
into_response(result).await
}
The processing flow now looks like this:
HttpRequest
-> authenticate
-> load operation
-> authorize
-> execute
-> build response
-> HttpResponse
From the outside, it is still one transformation from HttpRequest to
HttpResponse. Everything in between is an implementation detail, and each
step can be written, tested, and replaced on its own.
Services in Networking
The same pattern shows up all over networking code, especially in the generic, reusable parts.
A TCP connection handler receives a TcpStream and either handles the
connection or fails with an I/O error:
TcpStream -> ()
Once connection handling looks like this, a generic server can run any compatible connection service. That is the basic idea behind ntex-server.
A TCP connector receives a socket address and returns an established connection:
SocketAddr -> TcpStream
A TLS handshake receives a plain stream and returns an encrypted one:
T -> TlsStream<T>
The TLS service does not need to know whether the stream came from a server, a client, or an in-memory transport. It only needs a stream it can work with.
The types differ, but the shape stays the same: input, service, output. A connector creates a stream, a TLS service transforms it, and a connection handler consumes it. Because they share one model, these pieces can be wrapped, reused, and combined without knowing how the others work.
More Than a Function
Treating all of these the same way pays off quickly. An async function or a closure can be a service. So can a struct that carries configuration, a connection pool, or a counter. A chain of services joined end to end is itself a service, so it can be wrapped, chained again, or handed to a server. Any tool written for “a service” works with every one of them.
A service can also hold another service and add behavior around it; that is all middleware is. The wrapper does not call its inner service directly. It goes through a small context that ntex passes to every call, which keeps the whole chain working as one unit.
A plain function is a good mental model, but network code needs a bit more. The ntex service model adds a few ideas on top of “input in, output out”. None of them changes the basic shape. Each one answers a practical question that comes up as soon as real traffic arrives.
One Service, Many Requests
A service handles requests through a shared reference. While one request waits on a database or a socket, the same service can start working on the next one. A connection handler, for example, serves every connection its worker accepts, all at the same time.
ntex runs each worker on its own thread, and each worker gets its own instance
of the service. A service never moves between threads, so it can keep mutable
state in a Cell or RefCell instead of behind a lock. The reasons for this
design are covered below.
Ready Before the Call
A function cannot say “not now”. A service can. Before a request is handed over, the caller waits until the service reports that it is ready. A service at its connection limit, or one whose database pool is used up, stays not ready until capacity frees up. The request waits with the caller instead of piling up in a hidden queue inside the service.
This is how ntex handles backpressure. You rarely check readiness by hand: when services are chained, the chain only accepts a request once every service in it is ready, so a slow step at the end holds back new work at the front. Readiness can also fail, which tells the caller that the service cannot accept requests at all.
The readiness example shows both cases with console output: a concurrency limit that holds back new work and a gate whose readiness fails while it is closed.
Services Come from Factories
Services often need some setup before the first request. They may need to read configuration, open a connection, or warm a cache. That work can be asynchronous, and it can fail. ntex keeps it out of request handling by using a service factory, an object whose only job is to build a service.
A server keeps the factory and asks it for a new service on every worker. If setup fails, the factory reports an initialization error, separate from the errors a service returns while handling requests. You will often pass a factory where you might expect a service; an async function works as either one.
Shutting Down
Services also take part in an orderly shutdown. When a worker stops, it asks its service to shut down and waits, up to a timeout, for it to finish. A service can use that time to flush buffers, close connections, or let work in progress complete. A wrapper shuts down the services it holds as well.
What It Looks Like in Code
Here is the model in real code. The first example turns two async closures into services and joins them. The first service parses a number from a string, and the second doubles it:
use ntex::service::{Pipeline, fn_service, service};
#[ntex::main]
async fn main() -> Result<(), String> {
let parse = fn_service(async |line: String| {
line.trim().parse::<u32>().map_err(|e| e.to_string())
});
let double = fn_service(async |n: u32| Ok::<_, String>(n * 2));
// The chain is itself a service. A `Pipeline` is how you call it.
let pipeline = Pipeline::new((), service(parse).and_then(double));
assert_eq!(pipeline.call(" 21 ".to_string()).await?, 42);
assert!(pipeline.call("abc".to_string()).await.is_err());
Ok(())
}
The chain takes a String and returns a u32. If parsing fails, double
never runs and the error goes straight back to the caller. The () passed to
Pipeline::new is the pipeline’s state. This example does not need any.
The second example uses a factory. It reads a limit from the configuration once, when the service is built, and the service then checks every request against it:
use std::convert::Infallible;
use ntex::service::{factory, fn_factory, fn_service};
struct Limits {
max: u32,
}
#[ntex::main]
async fn main() -> Result<(), String> {
let check = fn_factory(async |limits: &Limits| {
let max = limits.max;
Ok::<_, Infallible>(fn_service(async move |n: u32| {
if n <= max { Ok(n) } else { Err(format!("{n} is over {max}")) }
}))
});
let pipeline = factory(check).pipeline(Limits { max: 100 }).await.unwrap();
assert_eq!(pipeline.call(42).await?, 42);
assert!(pipeline.call(500).await.is_err());
Ok(())
}
Setup can’t fail here, so the factory’s error type is Infallible. A factory
that opens a database connection would return a real error, reported when the
service is built, before it handles any request.
Closures are enough for small steps. Larger services are usually structs that
implement the Service trait directly, which is shown in the next chapter.
Why One Thread per Worker
Many async runtimes move tasks between threads to keep every CPU busy. That
works well, but it has a cost: anything a task holds must be safe to send to
another thread. Shared data ends up behind Arc, Mutex, or atomics, and the
hot path pays for synchronization even when there is no real contention.
ntex takes a different approach. A server starts several workers, usually one per CPU core. Each worker is a thread with its own single-threaded runtime and its own instance of every service. A separate accept thread spreads new connections across the workers, and a connection stays on the worker that accepted it for its whole life.
Because nothing moves between threads, services and their futures do not need
to be Send. That has practical benefits:
- State can use
Rc,Cell, andRefCell. Updating a counter or a small cache is a plain memory write, not a lock or an atomic operation. - A worker’s data stays local to that thread, and to its CPU’s cache when workers are pinned to cores.
- Code is easier to reason about. Requests on one worker interleave only at
.awaitpoints, never in the middle of a statement.
The model has trade-offs too:
- Work cannot move to an idle worker. If one connection does a lot of
CPU-heavy work, other connections on that worker wait. Run blocking or
long computations on the blocking thread pool with
spawn_blocking(). - Data shared by all workers must be shared explicitly, with
Arcand thread-safe types. Often it is simpler for each worker to build its own copy in the service factory. This is why the factory itself must beSend, while the services it creates need not be. - Requests interleave at
.awaitpoints, so don’t hold aRefCellborrow across an.await. Another request on the same worker may try to borrow it.
For network servers, where most time is spent waiting on sockets and many small requests run at once, this usually gives better throughput and more predictable latency. The Server chapter covers worker counts, CPU placement, and load balancing.
From an Idea to a Framework
The ntex-service crate turns this model into code, and the rest of ntex is built on it.
The next two chapters make the ideas above concrete.
Service Pipelines shows how services are combined, how
readiness moves through a chain, and what the full Service trait looks like.
Service State covers the state a pipeline shares with its
services. After that, you can go to the Server or the web
framework, starting with Routing and Handlers, and you will
find the same model underneath.
Glossary
These terms come up throughout the guide.
- Service: something that takes a request and, asynchronously, returns a
response or an error. An async function or closure, or a struct that
implements the
Servicetrait. - Request and response: a service’s input and output. They can be any Rust type: an HTTP request, a TCP stream, a number.
- Service factory: an object that builds a service. Building can be async and can fail.
- Initialization error: the error a factory returns when it can’t build a service. It is separate from the errors a service returns while handling requests.
- Chain: services joined end to end, so the output of one becomes the input of the next. A chain is itself a service.
- Middleware: a service that wraps another service and adds behavior around its calls, such as logging, timeouts, or extra headers.
- Pipeline: a service together with its state, ready to be called. It also keeps readiness consistent across the services inside it.
- State: data a pipeline shares with all of its services, such as a database pool or application settings. See Service State.
- Context: a small value ntex passes to every call. A service uses it to reach the pipeline state and to call its inner services.
- Readiness: a service’s signal that it can accept another request. A service that is not ready makes callers wait.
- Backpressure: slowing down the producers of work when the consumers can’t keep up. In ntex, readiness provides it.
- Worker: a thread with its own runtime and its own instances of the application’s services.
- Shutdown: the step where a service finishes outstanding work and releases resources before its worker stops.
Service Pipelines
In the previous section, we introduced the idea of a service. Consider the HTTP endpoint from our earlier example:
async fn endpoint(req: HttpRequest) -> Result<HttpResponse, Error> {
// Extract an operation from the request.
let operation = load_operation(req).await?;
// Execute the operation.
let result = execute(operation).await?;
// Convert the result into an HTTP response.
into_response(result).await
}
This function is a sequence of fallible, asynchronous transformations. Each step takes the output of the previous step and either produces the next value or returns an error.
That structure maps naturally to a service pipeline. We can compose the same
steps with an and_then combinator, similar to Result::and_then():
let pipeline = service(authenticate)
.and_then(load_operation)
.and_then(authorize)
.and_then(execute)
.and_then(into_response);
Each service runs only if the previous one succeeds. If any stage returns an error, the remaining stages are skipped and the pipeline returns that error.
The completed pipeline is itself a service:
Service<HttpRequest, Res = HttpResponse>
From the outside, it behaves just like the original endpoint function. It
accepts an HttpRequest and produces an HttpResponse. Everything that happens
between those two types remains an implementation detail.
The benefit of this approach is that each stage remains independent. We can replace, remove, or insert a service without rewriting the rest of the pipeline.
For example, adding request throttling is a local change:
let pipeline = service(authenticate)
.and_then(throttle) // <- throttling service
.and_then(load_operation)
.and_then(authorize)
.and_then(execute)
.and_then(into_response);
The external interface has not changed. The pipeline still represents the same overall transformation:
HttpRequest -> HttpResponse
The only requirement is that the types line up: the output of one service must match the input expected by the next.
A throttling service can be designed specifically for HTTP requests:
Service<HttpRequest, Res = HttpRequest>
Such a service inspects a request and returns it unchanged when the request is allowed to continue.
The service can also be generic over its input:
Service<R, Res = R>
A generic throttling service can act as a reusable concurrency or rate-limiting boundary anywhere in a pipeline. It does not need to know anything about HTTP or the application’s domain types.
This is what makes service pipelines useful: they let us build larger behavior from small, focused transformations while preserving a simple interface for the result.
Implementing and_then
Given the Service trait, we can describe and_then as a generic operation. It
accepts two services and connects them so that the output of the first becomes
the input of the second:
fn and_then<Req, A, B>(first: A, second: B) -> impl Service<Req, Res = B::Res, Error = A::Error>
where
A: Service<Req>,
B: Service<A::Res, Error = A::Error>,
{
AndThen { first, second }
}
The type constraints describe the rules of composition:
firstaccepts the original request.secondaccepts the response produced byfirst.- Both services use the same error type.
- The combined service returns the response produced by
second.
The implementation is equally straightforward:
struct AndThen<A, B> {
first: A,
second: B,
}
impl<Req, A, B> Service<Req> for AndThen<A, B>
where
A: Service<Req>,
B: Service<A::Res, Error = A::Error>,
{
type Res = B::Res;
type Error = A::Error;
async fn call(&self, req: Req) -> Result<Self::Res, Self::Error> {
let intermediate = self.first.call(req).await?;
self.second.call(intermediate).await
}
}
The first service processes the request and produces an intermediate value. If
it succeeds, that value is passed to the second service. If it fails, the ?
operator returns the error immediately and the second service is never called.
This is ordinary sequential composition with short-circuiting on error. Other
familiar combinators, such as then, map, and map_err, follow the same
general pattern.
In practice, this machinery is already available in the
ntex-service crate.
Its
ServiceChain
type provides a fluent, strongly typed API for composing services:
let chain = service(authenticate)
.and_then(load_operation)
.and_then(authorize)
.and_then(execute)
.and_then(into_response);
Each call wraps the existing chain in another service combinator. The resulting
ServiceChain is itself a service, so it can be extended further, wrapped in
middleware, or placed in a Pipeline.
The entire chain remains strongly typed. If one service produces a value that the next service cannot accept, the code fails to compile. Invalid pipelines are therefore caught while the application is being built rather than after it starts running.
Readiness and Backpressure
So far, Service::call() describes what a service does, but it says nothing
about when the service is able to accept more work.
Real services are not always ready. A service may have reached its limit for in-flight requests, filled an internal queue, or be waiting for an external resource such as a database connection.
If callers can invoke call() at any time, the service must either buffer an
unlimited amount of work or implement backpressure through a separate,
non-composable mechanism.
We can make backpressure part of the service contract by adding a readiness check:
trait Service<Req> {
type Res;
type Error;
async fn ready(&self) -> Result<(), Self::Error>;
async fn call(&self, req: Req) -> Result<Self::Res, Self::Error>;
}
Conceptually, ready() acts as a gate. It waits until the service can accept
more work without exceeding its internal limits. If the service cannot become
ready—for example, because an underlying resource has failed—it returns an
error.
A caller would follow this pattern:
service.ready().await?;
let response = service.call(request).await?;
For a composed service such as AndThen<A, B>, readiness is no longer local to
one component. A request may pass through both services, so the combined service
is ready only when both components are ready.
A simplified implementation looks like this:
impl<Req, A, B> Service<Req> for AndThen<A, B>
where
A: Service<Req>,
B: Service<A::Res, Error = A::Error>,
{
type Res = B::Res;
type Error = A::Error;
async fn ready(&self) -> Result<(), Self::Error> {
self.first.ready().await?;
self.second.ready().await?;
Ok(())
}
async fn call(&self, req: Req) -> Result<Self::Res, Self::Error> {
let intermediate = self.first.call(req).await?;
self.second.call(intermediate).await
}
}
This captures the basic rule: the composed service should not accept a request unless every stage needed to process it is ready.
A production implementation can check the services concurrently rather than waiting for them one at a time. More importantly, it must coordinate readiness across all concurrent calls to the same service graph.
That coordination is the responsibility of the Pipeline.
Pipeline Readiness
A Pipeline turns a service chain into a runnable service graph. It owns the
graph’s state and coordinates readiness, calls, and shutdown.
This matters because several requests may be in flight at the same time. Whether the pipeline can accept more work may depend on active calls, queue capacity, connection limits, or external resources used by any of its inner services.
Readiness is therefore a cross-cutting concern. It cannot be managed reliably by looking at each call or service in isolation.
Before dispatching a request, the pipeline waits until the required services are ready. If one of them reaches capacity, processing pauses until that service can accept more work.
This gives us a useful distinction:
ServiceChaindescribes how services are connected.Pipelineowns the runnable service graph and coordinates its lifecycle.
Shared Readiness
Concurrent calls use the same underlying pipeline and therefore share its readiness state. Each active call receives its own pipeline binding, which identifies the call while readiness is being coordinated.
A normal call creates this binding internally:
let response = pipeline.call(request).await?;
Sometimes a call must be stored, moved into another task, or allowed to outlive
the borrow of pipeline. In that case, Pipeline::call_static() returns an
owned future that keeps its binding alive:
let call = pipeline.call_static(request);
let response = call.await?;
Both methods use the same service graph and shared readiness state. The difference is how the lifetime of the call is managed.
This coordination prevents multiple callers from independently driving the same readiness check. It also avoids hiding excess work in unbounded internal queues: when the pipeline is not ready, callers wait.
The pipeline owns a readiness scope. A successful readiness check, such as
Pipeline::poll_ready(), is cached by that scope until a service notifies it
that its readiness has changed. Every binding and every call of the pipeline
reuses the cached result, and calls do not consume it. A dispatcher that waits
for readiness before each call therefore re-checks the services only after
something has changed.
The Service Tree
A composed pipeline is a directed tree of services. The pipeline is the root, combinators are inner nodes, and the services that do the actual work are the leaves:
let pipeline = service(authenticate)
.and_then(ready(throttle))
.and_then(execute)
.pipeline(());
Pipeline <- scope
└── AndThen
├── AndThen
│ ├── authenticate
│ └── ready(throttle) <- scope
└── execute
Requests flow down the tree, from the root to the leaves. Readiness flows in
the opposite direction: every node depends on the readiness of the nodes below
it, so readiness links point backward from the leaves to the root. The pipeline
is ready only when authenticate, throttle, and execute are all ready.
A service shared through Rc can be bound under several parents. Its readiness
then feeds every one of them, which turns the tree into a directed acyclic
graph.
Building Dependencies in Service::bind()
Readiness links are not discovered at runtime. Each service declares them once
in Service::bind(). The pipeline calls bind() when it is constructed, and
Ctx::create() calls it for services created later. In both cases, bind()
runs synchronously before any ready(), call(), or shutdown().
The BindCtx
passed to bind() registers dependencies in the current readiness scope:
ctx.subscribe(¬ifier)registers aReadyNotifierthat the service uses to report changes in its own readiness.ctx.bind(&child)binds a child service. It must be called for every child the service uses, including children that are only called and never checked for readiness. A raw child shares the current scope. AReadyBindingorready()child links its own scope below the current one.ctx.on_notify(&callback)optionally registers aReadyCallbackthat runs when a notification reaches the current scope.- A child pipeline is bound with
pipeline.bind_to(&ctx).
struct Limited<S> {
inner: S,
changed: ReadyNotifier,
}
impl<S: Service<(), u8>> Service<(), u8> for Limited<S> {
type Res = S::Res;
type Error = S::Error;
fn bind(&self, ctx: BindCtx<'_>) {
ctx.subscribe(&self.changed); // changes of our own readiness
ctx.bind(&self.inner); // readiness of the child
}
// ready() and call() ...
}
When a child implements Service for several request types, pass the types
explicitly, for example ctx.bind::<_, St, Req>(&self.first). Services that
wrap child services can use forward!(St, field, ...), which forwards
bind(), ready(), and shutdown() to every listed field. Use
map_err = f as the last argument to convert readiness errors. Register
Pipeline fields with pipeline.bind_to(&ctx). The default bind() does nothing, which is correct
for leaf services that have no notification sources.
A few rules follow from this design:
- All dependencies must be known at bind time.
ready()andcall()cannot register new ones. - Using a
ReadyBindingthat its parent did not bind panics, so a missingbind()forward is detected instead of silently losing notifications. The panic message names the fix: callctx.bind(&child)in the parent’sbind, or useforward!. - Shared services can be bound more than once. Repeated subscriptions are idempotent.
- Children created lazily at runtime must use
ctx.create(&factory).await, which binds the new service in the current scope and invalidates it.
Readiness Scopes
A readiness scope caches a successful readiness check of its subtree until it is notified that readiness has changed. Not every node of the tree has its own scope. Scopes exist only at:
- the pipeline root,
- each
ReadyBinding, - each service wrapped with
ready()or created byready_factory().
Plain services and combinators such as and_then, then, and apply store
their children raw, so those children share the nearest scope above them.
A scope’s cached readiness remains valid only while every service below it is still ready:
- When a service calls
ReadyNotifier::notify(), the scope it is subscribed to and every scope above it are invalidated before any waiting task is woken. Scopes in unrelated branches stay valid. In the example above, a notification fromthrottleinvalidates both scopes, while one fromexecuteinvalidates only the pipeline scope. - A notification never marks a service ready. It only forces the next
ready()orcall()to check again.
A service whose readiness can change must therefore notify on every change, such as taking the last free slot, releasing a slot, a timer firing, or an external failure, before another caller can reuse the stale result. Waking a task is not the same as invalidating a scope: a wake only re-polls a pending check.
fn acquire(&self) {
self.in_flight.set(self.in_flight.get() + 1);
self.changed.notify(); // may have become not ready
}
fn release(&self) {
self.in_flight.set(self.in_flight.get() - 1);
self.changed.notify(); // may have become ready
}
The readiness example
builds a concurrency limit and a gate on top of ReadyNotifier, and prints
each readiness change so you can follow the scope being invalidated and
re-checked.
Observing Readiness Notifications
Use a reusable
ReadyCallback
to observe explicit readiness notifications. A service registers its handle
during Service::bind:
fn bind(&self, ctx: BindCtx<'_>) {
ctx.subscribe(&self.changed);
ctx.on_notify(&self.on_notify);
ctx.bind(&self.inner);
}
Pipelines also expose pipeline.on_notify(&callback), as do PipelineBinding,
PipelineState, and PipelineStateBinding. For example:
use ntex::service::ReadyCallback;
let callback = ReadyCallback::new(|| println!("readiness notified"));
let pipeline = ntex::Pipeline::new((), async |_: ()| Ok::<_, ()>(()));
pipeline.on_notify(&callback);
pipeline.bind().on_notify(&callback); // Same scope and identity: one registration.
The callback runs synchronously when ReadyNotifier::notify() reaches its
scope, including notifications propagated from child scopes and repeated
notifications while the scope is already invalid. It does not run for
successful readiness checks, cached calls, ordinary task wakeups, or internal
resets such as lazy service creation and shutdown. All affected scopes are
invalidated before callbacks run, outside internal borrows and locks.
Nested notifications still invalidate every affected scope, but skip callback delivery on scopes already executing callbacks. Registrations made during that delivery are retained for later notifications. Delivery reuses each scope’s registered callback storage without allocating a snapshot or cloning handles.
Callbacks are registered on the nearest scope: raw services share their
enclosing one, while ready(svc) gives the service its own. Registering one
handle on two affected scopes invokes it once for each scope. Cloning a handle
preserves its identity. Registrations persist until the scope is dropped,
independently of readiness checks and runtime binding handles. Callbacks must
own their captures; avoid strong reference cycles through a pipeline that
retains the callback.
Readiness Between Services
Readiness must also be respected while a request moves through the service chain. A service should not invoke the next service directly, because doing so would bypass that service’s readiness check.
Instead, services call one another through an execution context:
let result = ctx.call(&next_service, request).await?;
In ntex-service, this execution context is represented by Ctx. It carries the
pipeline-level information needed to coordinate otherwise independent service
instances, including the nearest readiness scope above the current service.
Ctx uses that scope to decide whether a readiness check is needed:
| Operation | Behavior |
|---|---|
ctx.call(&svc, req), scope valid | Dispatches immediately, without a check. |
ctx.call(&svc, req), scope invalid | Waits for svc.ready() only. The scope above is not marked ready. |
ctx.call(&binding, req) | Checks the binding’s own scope, independent of the scope above. |
ctx.ready(&svc) | Checks the raw service every time and does not update any scope. |
ctx.ready(&binding) | Reuses the binding’s scope, re-checking only after a notification. |
The same rules apply to services wrapped with ready(), which use a
ReadyBinding internally. This allows backpressure to propagate through the
chain, even if readiness changes while a request is being processed.
Use ready() when a child needs its own readiness, independent of its siblings.
A typical case is a second stage called after an .await: its readiness may
change in the meantime, and with its own scope it is re-checked only when it
notifies, not every time a sibling changes.
A useful mental model is:
Servicedefines what happens at each step.ServiceChaindescribes how the steps are connected.Pipelineowns the runnable graph and its root readiness scope.ReadyBindingandready()add independent readiness scopes inside the graph.Ctxcontrols how execution moves safely between services.
The Complete Service Trait
Once we include state, readiness, and shutdown, a simplified version of the ntex
Service trait looks like this:
trait Service<St, Req> {
type Res;
type Error;
fn bind(&self, ctx: BindCtx<'_>) {}
async fn ready(&self, ctx: Ctx<'_, Self, St>) -> Result<(), Self::Error>;
async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<Self::Res, Self::Error>;
async fn shutdown(&self, ctx: Ctx<'_, Self, St>);
}
The context serves several related purposes:
- It provides access to the pipeline state.
- It connects services to the pipeline that owns them.
- It coordinates readiness between services through the nearest readiness scope.
- It allows one service to call another without bypassing backpressure.
- It participates in orderly shutdown.
The important point is that readiness is not merely a method that callers are expected to use correctly. It is built into the way requests move through a pipeline. This makes backpressure explicit, composable, and enforceable without relying on hidden queues or coordination outside the service model.
The St parameter represents the service state made available through the
context. We will explore service and pipeline state in the next section.
Shutdown
The shutdown() method represents the final stage of the service lifecycle:
async fn shutdown(&self, ctx: Ctx<'_, Self, St>);
It is called by the service’s owner—typically a Pipeline—when the service is
being taken out of operation.
A service can use shutdown() to:
- stop background tasks gracefully;
- release external resources;
- flush buffered data; and
- allow in-flight work to finish cleanly.
Simple services may not need to do anything during shutdown. Services that own resources or run background tasks, however, should use this method to clean up properly rather than stopping abruptly.
Composite services should also propagate shutdown to their inner services so that the entire pipeline stops cleanly.
Service State
Services often need information beyond the request they are handling. This might be connection metadata, a database pool, application configuration, or a channel to another subsystem.
Putting these dependencies into every request would mix long-lived resources with the data for one operation. Storing a copy in every service can work, but then each wrapper has to carry dependencies it does not itself use. Pipeline state gives the service graph one place to obtain this shared context.
The St type parameter on Service represents this information:
trait Service<St, Req> {
type Res;
type Error;
async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<Self::Res, Self::Error>;
async fn ready(&self, ctx: Ctx<'_, Self, St>) -> Result<(), Self::Error>;
async fn shutdown(&self, ctx: Ctx<'_, Self, St>);
}
A service borrows pipeline state through Ctx. It can still own fields,
such as configuration or inner services. You can access pipeline state during
calls, readiness checks, and shutdown:
async fn call(&self, req: Req, ctx: Ctx<'_, Self, AppState>) -> Result<Self::Res, Self::Error> {
let state: &AppState = ctx.st();
// ...
}
Rust checks that the pipeline supplies a compatible state type because that
type is part of Service<St, Req>. You cannot place a service that requires
AppState directly in a pipeline with an unrelated state type.
Keep the three kinds of data separate. The request is the input consumed by
one call. A service’s fields belong to that service instance: its configuration,
children, or a cache used only by that component. St is the context supplied
to the service graph, so several components can borrow the same database pool
or connection metadata without embedding it in each request.
For example, Service<AppState, String> processes a String using AppState;
Service<(), String> has no additional state. The order matters: St comes
first. It is an ordinary Rust type, not a string-keyed container, so dependency
requirements appear in trait bounds and the compiler checks them. Low-level
service state does not require the web framework’s web::State trait.
State-aware functions
You can turn an asynchronous function into a state-aware service by making
&St its first argument:
use std::convert::Infallible;
use ntex::Pipeline;
struct AppState {
prefix: &'static str,
}
async fn format_value(state: &AppState, value: usize) -> Result<String, Infallible> {
Ok(format!("{}-{value}", state.prefix))
}
#[ntex::main]
async fn main() {
let service = Pipeline::new(AppState { prefix: "item" }, format_value);
assert_eq!(service.call(10).await.unwrap(), "item-10");
}
The function receives &AppState on each call. The IntoService
implementation converts it into a service automatically.
Use fn_service_st explicitly if you need to name the service value or pass
it through an API before creating the pipeline. Use fn_service instead when
the function only takes a request; it does not receive pipeline state.
The state is borrowed, not cloned for every call. Pipeline::new owns both the
state and service, and requires them to be 'static. An owned String or Rc
can meet that bound; 'static does not mean you must leak memory or use a global
variable. A reference to a local stack value generally cannot be stored there.
The state type itself need not implement Clone for Pipeline::new.
Testing state-aware function services
You can test a state-aware function service without starting a server. Create
the service with fn_service_st. Put it and the test state in a pipeline
using Pipeline::new, then call it with the request value.
This exercises the same state access and readiness handling used in production.
If the state contains external dependencies, you can use a mocking library to check how the service uses them. These examples show two approaches:
tests/mockalldefines the state behavior as a trait. Mockall creates a mock state and checks calls to its accessor and operation methods.tests/shimforgekeeps the concrete state type. Shimforge replaces methods during the test, including a method on an object nested in the state. It checks the receiver’s attributes and call arguments.
Both examples configure call counts and ordering. Each invokes the service through a pipeline and asserts its response.
Pipeline-owned state
Use Pipeline::new to keep one service and one state value together. Every
call, readiness check, and shutdown operation uses that same state instance.
The state belongs to the pipeline, rather than the process. Each new pipeline
owns the state value you give it. Whether the underlying data is independent
or shared depends on that value: two separately constructed counters are
independent, but two Rc clones point to the same counter. Similarly, several
worker-local states can each hold a clone of the same Arc<Pool>.
Pipeline bindings share the original pipeline and its state. Cloning a
PipelineBinding does not clone the state value. Bindings also participate
in the pipeline’s coordinated readiness and shutdown handling.
Sharing Mutable State
A borrowed state value can still contain mutable data. For worker-local
counters, Cell inside an Rc is enough. Here a separate handle lets the
caller observe how many requests the service processed:
use std::{cell::Cell, convert::Infallible, rc::Rc};
use ntex::{Pipeline, service::fn_service_st};
struct Counters {
calls: Rc<Cell<usize>>,
}
async fn record_call(state: &Counters, value: usize) -> Result<usize, Infallible> {
state.calls.set(state.calls.get() + 1);
Ok(value)
}
#[ntex::main]
async fn main() {
let calls = Rc::new(Cell::new(0));
let pipeline = Pipeline::new(
Counters { calls: calls.clone() },
fn_service_st(record_call),
);
let handle = pipeline.bind();
assert_eq!(pipeline.call(10).await.unwrap(), 10);
assert_eq!(handle.call(20).await.unwrap(), 20);
assert_eq!(calls.get(), 2);
}
Both calls reach the same service and counter. Creating a binding does not
construct another Counters value. You also do not need to make Counters
implement Clone just to share this pipeline.
Pipelines and their bindings are thread-local. Use Rc, Cell, and RefCell
for data confined to that thread; use Arc with suitable synchronization for
resources deliberately shared across workers. An Arc alone does not make
mutable data thread-safe. When using RefCell, end a mutable borrow before an
.await that could let another request borrow the same value.
Calling nested services
When your service wraps another service, call the child through Ctx. The
context provides ctx.st() and connects the call to the pipeline’s readiness
and shutdown handling:
async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<Self::Res, Self::Error> {
ctx.call(&self.inner, req).await
}
Ctx::call reuses valid readiness from the nearest upstream scope. On a
cache miss, it checks only the target service. A child wrapped with ready(svc)
also checks its own independent cache.
Calls do not consume cached success. When the cache is valid, the call adds no
readiness allocations. Use ctx.call(&self.inner, req).await even after an
explicit readiness check. It keeps this fast path while observing any
invalidation between the check and the call.
Ctx also provides ready() and shutdown() operations. Wrappers must forward
the lifecycle methods to their children:
Service::bindService::readyService::shutdown
You can use forward! to forward these methods. A service whose readiness
changes must subscribe to a ReadyNotifier in bind and notify on every
relevant change.
A raw Ctx::ready call does not populate an upstream cache. Use ready(svc)
when a child needs independent, persistent readiness.
Readiness checks and their wake sources must run on the pipeline’s thread.
A child receives the same &St as its parent unless you explicitly substitute
state. A generic wrapper that does not read it can implement Service<St, Req>
for any compatible St; it should not hard-code () and accidentally exclude
stateful children. The ResponseHeaderService middleware in
Writing a Middleware Service
shows the complete pattern with forward!.
If constructing a child needs state, its factory receives &St too. A factory
can use that reference to configure a new service, but a service stored in an
owned pipeline cannot retain a short-lived borrow of the factory argument.
Clone an owned resource handle into the service when it needs to keep one, or
borrow the state through Ctx on each call. For a lazily created child, use
ctx.create(&factory).await so creation also registers its dependencies.
Substituting state
Use map_state when one service in a chain needs a different state type. It
wraps that service with a fixed state value. The outer pipeline can keep using
its own state type:
use std::convert::Infallible;
use ntex::{Pipeline, service::map_state};
struct Metrics {
prefix: &'static str,
}
async fn record(metrics: &Metrics, value: usize) -> Result<String, Infallible> {
Ok(format!("{}-{value}", metrics.prefix))
}
#[ntex::main]
async fn main() {
let service = map_state(Metrics { prefix: "metric" }, record);
// The wrapped service uses Metrics even though the outer pipeline uses ().
let pipeline = Pipeline::new((), service);
assert_eq!(pipeline.call(10).await.unwrap(), "metric-10");
}
The adapter owns Metrics and supplies it to the inner service’s readiness,
call, and shutdown methods. It does not convert the outer state or look up a
field in it. Use this for a component with fixed private context, not as a way
to select a different tenant or user on each request. The surrounding readiness
scope is preserved; replacing state does not create an independent capacity
gate.
State supplied per operation
Use PipelineState when callers need to select the state for each
operation. It stores a service without owning its state. The caller supplies a
state reference for each readiness check, call, or shutdown operation:
use std::convert::Infallible;
use ntex::service::pipeline::PipelineState;
struct RequestContext {
prefix: &'static str,
}
async fn format_value(state: &RequestContext, value: usize) -> Result<String, Infallible> {
Ok(format!("{}-{value}", state.prefix))
}
#[ntex::main]
async fn main() {
let service = PipelineState::new(format_value);
let first = RequestContext { prefix: "first" };
let second = RequestContext { prefix: "second" };
assert_eq!(service.call(1, &first).await.unwrap(), "first-1");
assert_eq!(service.call(2, &second).await.unwrap(), "second-2");
}
Use Pipeline when one state value should stay attached to the service.
PipelineState keeps the same service and readiness machinery while letting
each caller choose the state.
To attach an owned state value, call PipelineState::bind_state(). It produces
a normal PipelineBinding and requires the state type to implement Clone.
All of these handles share one readiness cache and pending checker, even when they supply different state values. Passing a different state does not invalidate cached success.
Service::ready may inspect the state, but its result must describe the shared
pipeline-wide gate. Use separate pipelines or service bindings if you need
independent, state-specific gates. For example, changing a tenant identifier
between two calls is not enough to re-check a tenant-specific quota. A shared
cache could still contain the first tenant’s success. Keep such admission
checks in request processing or give independently limited services their own
gates.
Carrying state with a request
At some protocol boundaries, the input contains both a request and the state
for a nested pipeline. The RequestState trait represents this input.
This packaging does not itself change any pipeline’s state: the receiving
service unpacks it and supplies the state to the nested pipeline.
State<St, Req> implements the trait by splitting the input into a state and
a request. The tuple (St, Req) implements it too:
use ntex::service::{RequestState, State};
let input = State {
state: "connection-1",
req: "request",
};
let (connection, request) = input.unpack();
assert_eq!(connection, "connection-1");
assert_eq!(request, "request");
For example, ntex HTTP services use RequestState to extract an accepted
connection’s state. They provide that state to the HTTP request and
control-service pipelines. Connection setup state stays separate from the HTTP
request value and keeps its concrete type.
A plain Io also implements RequestState, using () as its state. An
ordinary server can therefore pass accepted connections to HttpService
without wrapping them. See
Passing Connection State to the HTTP Service
for an example that wraps an accepted Io in State.
Choosing State at Application Boundaries
Start with Pipeline when the service and its context should have the same
lifetime. Use PipelineState when one service must work with a caller-selected
context. Use map_state for a fixed inner context, and State or a tuple to
carry context across a protocol boundary. These choices control who supplies
the value; none automatically creates a process-wide shared resource.
The server state chapter applies the same distinction to workers and connections. Server configuration creates worker state; connection setup can add metadata before passing an accepted stream to HTTP. Expensive pools and caches usually belong to worker or process setup, not to an application service constructed for each connection.
For web handlers, Web Application State builds on this model
with the web::State trait and handler APIs. Its application state is distinct
from request-local state carried through web filters. Keeping those lifetimes
separate avoids two common surprises: expecting a plain cloned value to share
mutations across connections, and putting one request’s identity into a
long-lived worker-wide value.
Runtime
Each ntex runtime thread runs its own single-threaded event loop. Tasks stay
on the thread where they started. Your services and futures can use Rc,
Cell, RefCell, and other types that are not Send or Sync.
Your application can still use several CPU cores. A server normally starts
several worker threads, each with its own single-threaded runtime. State shared
between workers needs thread-safe types such as Arc, atomics, or locks.
For most applications, use #[ntex::main] as the entry point and
#[ntex::test] for async tests. Start tasks with ntex::rt::spawn. Use
System and Arbiter when you need explicit control over startup, shutdown,
or cross-thread coordination.
Choosing a runtime backend
Choose a backend through Cargo features. DefaultRuntime selects both the
async runtime and its matching ntex network reactor:
tokiouses Tokio. If a Tokio runtime handle is already entered on the current thread, ntex uses it. Otherwise, ntex creates a current-thread Tokio runtime. ntex tasks run inside a TokioLocalSet.compiocreates a Compio runtime on each runtime thread. Compio chooses the I/O driver for the platform and configuration.- With neither feature, ntex uses its native runtime. On Linux it tries io_uring and falls back to polling; other Unix platforms use polling, and Windows uses IOCP.
Tokio takes precedence if you enable both tokio and compio. With the native
backend, neon-polling forces polling on Unix. The neon-uring feature
requires io_uring on Linux. Do not enable both native features.
For example:
[dependencies]
ntex = { version = "4", features = ["tokio"] }
Tokio and Compio are useful when your application uses libraries from those ecosystems. The native backend uses the platform reactor directly, without running a second general-purpose runtime.
With io_uring, each runtime thread registers its sockets in the ring’s fixed
file table, so reads and writes skip the kernel’s per-operation descriptor
lookup. The table has 16384 slots by default, capped by the open file limit
(RLIMIT_NOFILE). Each slot takes 8 to 16 bytes of kernel memory. Connections
beyond the table size, and all connections on kernels older than 5.19, use
plain descriptors. To change the size, set the NTEX_URING_FIXED_FILES
environment variable before the first runtime starts; 0 disables the table.
Let #[ntex::main] own the process entry point unless you need another setup.
SystemRunner::block_on blocks the current thread. Do not call it inside an
async Tokio task to nest one runtime inside another.
Spawning tasks
ntex::rt::spawn starts a future on the current runtime thread:
#[ntex::main]
async fn main() {
let task = ntex::rt::spawn(async {
// `Rc`, `RefCell`, and other `!Send` values may be used here.
10usize
});
assert_eq!(task.await.unwrap(), 10);
}
Neither the future nor its result needs to be Send. The future must be
'static, so use async move when it captures owned values. Calling spawn()
outside a running ntex runtime panics.
Await the returned JoinHandle when you need the task’s output. If you no
longer need the work, call cancel(). Use is_finished() to check whether it
has finished without awaiting it.
The handle is neither Send nor Sync, even when the result is Send.
Keep it on the thread that created it. If the task panics or is cancelled,
awaiting the handle returns a JoinError instead of the task’s output.
By default, dropping a JoinHandle detaches the task: it continues without
anyone waiting for its result. Call cancel_on_drop() on the handle to request
cancellation instead when it is dropped. The older detach() method also
detaches a task, but is deprecated. A detached task is not guaranteed to finish
before its arbiter or the whole system shuts down.
Spawning on another thread
To run work on another runtime thread, get that arbiter’s Handle and call
spawn() on it. Both the future and its output must be Send + 'static.
Handle::spawn() returns a RemoteJoinHandle<T> rather
than a JoinHandle<T>. Like the local handle, it is neither Send nor Sync.
Keep it on the thread that called spawn().
async fn example(handle: ntex_rt::Handle) {
let task = handle.spawn(async { 42 });
assert_eq!(task.await.unwrap(), 42);
}
The runtime thread owns the submitted work. On that thread, Handle::spawn()
spawns a local task. From another thread, it puts the future in a single
allocation and hands it to the runtime thread to poll and drop. The allocation
later holds the output too. All three backends behave this way.
Dropping a RemoteJoinHandle detaches the task. Call
RemoteJoinHandle::cancel() to cancel it on the runtime thread. The handle
returns JoinError if the runtime shuts down or the task is cancelled before
producing a result.
If the runtime rejects a submission, however, it never polls the future and may drop it on the submitting thread instead.
The two handle types reflect these different needs. Keeping them separate
makes the common local case small: a native JoinHandle is a single pointer.
RemoteJoinHandle supports both paths, while same-thread submissions still
avoid the shared allocation.
Use Handle::spawn_detached() when you do not need a result. It returns ()
and discards the output on the runtime thread. The output does not need to be
Send.
A submitted future can start non-Send work with ntex::rt::spawn. The
submitted future must stay Send, so it cannot hold that local JoinHandle
across an .await. Await the local result inside a local task instead.
Timers and timeouts
Use ntex::time rather than a backend-specific timer, so the code works with
all three backends:
use ntex::time::{Millis, sleep, timeout};
#[ntex::main]
async fn main() {
sleep(Millis(10)).await;
let result = timeout(Millis(100), async { "done" }).await;
assert_eq!(result.unwrap(), "done");
}
ntex timers are for scheduling and timeouts, rather than precise measurement.
Their resolution is about 16 milliseconds. Even a zero-duration sleep or
timeout waits for at least one timer tick. Use timeout_checked if a zero
timeout should mean “no timeout”.
See Timers and Time Utilities for the timer design and full API.
System lifecycle
Use System to manage the runtime as a whole. It holds shared runtime
configuration and keeps track of arbiters. It also delivers signals and
provides the blocking thread pool.
#[ntex::main] builds a system for you. Build one yourself when you need
explicit control; this gives you a SystemRunner:
fn main() {
let result = ntex::rt::System::build()
.name("worker")
.build(ntex::rt::DefaultRuntime)
.block_on(async { 10usize });
assert_eq!(result, 10);
}
The lifetime of the root future determines when block_on(future) returns.
It starts the system, runs that future, and returns its output when the future
completes, as in the example above.
For a process that should keep running until explicitly stopped, use
run(callback) instead. It calls a synchronous startup callback inside the
running system, then keeps the event loop going until System::stop() or
System::stop_with_code() is called:
use std::io;
use ntex::rt::{self, DefaultRuntime, System};
use ntex::time::{Millis, sleep};
fn main() -> io::Result<()> {
System::build()
.name("my-app")
.build(DefaultRuntime)
.run(|| {
rt::spawn(async {
sleep(Millis(10)).await;
System::current().stop();
});
Ok(())
})
}
Use run_until_stop() to run without a startup callback. It otherwise behaves
like run(). Each of these methods consumes the runner. You cannot call
block_on() and then run_until_stop() on the same runner.
A non-zero stop code is returned as an I/O error.
Signal and panic handling are off by default. Enable signal handling to make
process signals available through ntex::rt::signals. Your application still
decides how to shut down. ntex servers listen for signals while they run and
handle their own shutdown.
Fatal signal handling is off by default as well. On Unix,
Builder::fatal_signals(true) installs process-wide SIGSEGV and SIGABRT
handlers that report these signals as Signal::Panic while signal handling is
enabled. The process still terminates.
Arbiters and runtime threads
Use an Arbiter when you need another runtime thread with its own event
loop. Every system already has a primary arbiter. Call Arbiter::new() or
Arbiter::with_name() to start another OS thread with the same runtime
configuration. ntex server workers are arbiter threads too.
Arbiter::current() returns the arbiter for the current thread. It panics
outside an arbiter. For an arbiter created with new() or with_name(), call
stop() to request shutdown. Call join() to wait for its thread to exit.
The primary arbiter runs on the thread that started the system. It has no
thread handle, and its join() returns immediately. You cannot stop it on its
own; stop the System to end it.
Choose the shutdown scope deliberately. Arbiter::stop() stops one separately
created runtime thread; System::stop() stops every registered arbiter and
ends the system.
The same distinction applies to typed storage. Use System::get_value() for
a thread-safe value shared by the whole system. Use Arbiter::get_value() for
a cloneable value local to one runtime thread, such as a per-worker client or
cache that should not be shared.
Blocking work
Blocking an arbiter thread stalls connection handling, timers, and every other
task on that thread. Move CPU-heavy work and blocking system calls to a
thread pool with spawn_blocking():
#[ntex::main]
async fn main() {
let total = ntex::rt::spawn_blocking(|| (0..1_000u64).sum::<u64>())
.await
.unwrap();
assert_eq!(total, 499_500);
}
The closure and its result must be Send. Inside a system, the work runs on a
blocking pool that grows and shrinks as needed. Each arbiter has its own pool,
so work submitted from a server worker runs on that worker’s pool. On Linux and
Android, pool threads are not pinned to the worker’s CPU, they use the CPU
affinity the worker thread had before it was pinned.
By default, each pool allows up to 64 threads. An idle thread exits after 60
seconds. Set the limit with thread_pool_limit() and the idle timeout with
thread_pool_recv_timeout():
use std::time::Duration;
fn main() {
ntex::rt::System::build()
.thread_pool_limit(32)
.thread_pool_recv_timeout(Duration::from_secs(30))
.build(ntex::rt::DefaultRuntime)
.block_on(async {});
}
Outside a running system, spawn_blocking() runs the closure immediately on
the calling thread. It does not start a background thread. The returned
future is already complete. This fallback does not start background work
before the runtime is up.
Dropping the returned future stops queued work from starting. It cannot
interrupt a closure that is already running. Call detach() if the work should
go ahead even when nobody needs the result. Cancellation and panics in the
closure are reported as BlockingError.
Runtime diagnostics
If requests slow down, runtime diagnostics help you check whether arbiters
are responding and tasks are getting time to run. The system pings each
spawned arbiter every two seconds. System::list_arbiter_pings() returns the
ten most recent round-trip times. Set ping_interval(0) to turn pings off.
For a closer view of scheduling delays, each arbiter measures its latency
every latency_interval(), 100 milliseconds by default. Arbiter::latency()
returns a histogram of how late those measurements woke up.
A watchdog thread marks an arbiter as stalled if no measurement arrives within
the interval plus ping_threshold(). The threshold defaults to one second.
Arbiter::latency() also counts these stalls. Set latency_interval(0) to turn
off both measurement and stall detection.
To help locate a stall on the native (neon) runtime,
Handle::current_task() returns the spawn location of the task being polled.
The stall log includes this location. A stall with no running task happened
in the driver; tasks that ntex spawns itself report a location inside ntex.
On Tokio and Compio, current_task() returns None.
A busy task may also keep making itself runnable without waiting for input.
The native runtime counts these self-wakes in Handle::self_wake_count().
A self-wake is a wake a task triggers while it is being polled.
If a task wakes itself 10,000 times in a row over at least one second without
waiting, the runtime logs a possible busy loop. It logs the warning once, with
the task’s spawn location. Adjust the limits with
RuntimeBuilder::self_wake_threshold(). A count of zero turns the warning off.
On Linux and Windows, use System::set_latency_callback() to receive a
backtrace of a stalled arbiter. The callback also gets the task’s spawn
location if the same task is still running after the capture. Without a
callback, the backtrace is logged.
On Linux, capturing a backtrace requires ntex signal handling and uses
SIGUSR2. If you embed ntex, do not use that signal for anything else. On
Windows, the watchdog briefly suspends the stalled thread and walks its stack.
This is supported on x86_64 and aarch64 only.
Custom runners
Use a custom runner when your application provides both an executor and a
compatible network reactor. Otherwise, use DefaultRuntime.
System::build().build(...) accepts any implementation of ntex_rt::Runner.
ntex networking expects a compatible reactor on every runtime thread. Your
runner must set up everything the chosen backend relies on; replacing the
executor alone is not enough.
Runtime attributes
#[ntex::main] turns an async function into a synchronous entry point. It
builds a System and drives the function’s future:
#[ntex::main]
async fn main() {
// Start the application.
}
It accepts these options:
name = "..."sets the system name;signals = trueorfalse;fatal_signals = trueorfalse;panic_handling = trueorfalse;ping_interval = Nin milliseconds, where zero turns off arbiter pings;thread_pool = Nsets the blocking thread pool limit;rt = Typeselects a custom runtime runner.
For example:
#[ntex::main(
name = "my-service",
signals = true,
panic_handling = true,
ping_interval = 250,
)]
async fn main() {
// Start the application.
}
The async function can return a value such as Result<(), E>, and the
generated synchronous function returns it.
Use #[ntex::test] to run an async test in a fresh system named after the test.
The attribute marks it as a test system and turns off signal, fatal signal, and
panic handling.
It also sets up ntex test logging:
#[ntex::test]
async fn runtime_test() {
let value = ntex::rt::spawn(async { 10usize }).await.unwrap();
assert_eq!(value, 10);
}
The no-test-logging feature skips the logging setup.
Native runtime
The native runtime, called neon, pairs a task runner with a platform-specific
I/O reactor. Its design takes advantage of the same thread locality that lets
your services use Rc: waking a task on its own thread needs no
synchronization. The following sections explain that design; you do not need
these details to use ntex.
Rust’s standard Waker must be Send + Sync. Any thread can hold a clone and
call wake(). Tokio and async-task meet that requirement by synchronizing
every waker operation. Their reference counts and task state are atomics, so
each clone, wake, and drop pays for synchronization, even on the task’s own
thread.
The native runtime separates local and remote access. A waker first detects
which thread is using it. On the task’s owner thread, state and reference
counts are plain values wrapped in Cell. Cloning, waking, and dropping a
waker need no atomic operations, and a woken task goes straight onto the local
ready queue.
From another thread, the waker never touches the task directly. It pushes a command onto a Crossbeam queue for the owner thread to apply on its next turn. This makes remote wakes slower than in Tokio or async-task, but local wakes cheaper. Most wakes in an ntex application are local because a connection’s I/O, timers, and services live on one thread.
Owner-thread wake handles
A timer or I/O waiter often needs to keep a wake handle for later. For these
local wakes, ntex_rt::LocalWaker gives ntex code an owned handle that stays
on its owner thread. Timers, I/O waiters, and notification slots store these
handles internally. Despite the similar name, ntex::task::LocalWaker is a
different type: it is a notification slot, not the handle stored in one.
Creating a LocalWaker from a borrowed standard waker checks its kind, owner
thread, and runtime. It then takes a local reference to the task. After that,
cloning, waking, and dropping the handle need no further thread checks.
Keep the handle to benefit from these local operations. Acquiring a new one
and converting it back every time has a cost. into_waker() consumes the
handle and returns a thread-safe standard waker. For native tasks, it takes
the standard-waker reference before releasing the local one. The local handle
itself cannot cross threads.
On 64-bit targets, the handle, Option<LocalWaker>, and the notification slot
are each 16 bytes. Neither native nor fallback handles allocate a wrapper.
A native task uses a single allocation for routing metadata, its pinned
execution core, and storage for the future and result.
There is no separate wake-token allocation or per-task lookup table. The remote command queue does allocate segments. Arbitrary waker callbacks, timers, and I/O storage may allocate as they grow.
These changes speed up a hot path without guaranteeing faster scheduling or request handling. Registering the same waker again still requires a kind check. Tokio, Compio, and wrapped or custom wakers keep their original callbacks and may pay a small extra dispatch cost.
Remote wakes
Remote wakes must keep task storage alive without changing its local state. They do this by sending commands to the owner thread through a Crossbeam FIFO, a first-in, first-out queue. Only the owner changes a task’s reference count, even after completion. A standard native waker used on another thread publishes reference and wake commands without touching the count.
On 64-bit targets, each command is one pointer-sized word. Task alignment leaves three low bits free to store the operation. The encoding preserves pointer provenance, and the tag is removed before the task is accessed. Other targets store the pointer and operation separately, without increasing task alignment.
To avoid queue work for tasks that stay local, each task has an atomic flag that records whether a remote waker command has ever been published for it. The flag is set just before the first such command and never cleared. Tasks without the flag release their references directly, including the last one, without looking at the FIFO.
Submitting a task from another thread does not set the flag. Its initial reference passes to the owner before the task can hand out a waker.
Once the flag is set, the owner’s final release waits behind acquisitions already queued. While commands are pending, the owner’s other releases go through the queue too. Otherwise, a release could overtake an earlier queued release and invalidate a later wake or acquisition.
When a remotely cloned waker returns to the owner, the flag store is synchronized. Until then, the waker it was cloned from keeps the allocation alive. Processing a queued command also synchronizes with the flag store. The flag is shared metadata only; remote threads never update the reference count.
Task completion
A finished task and a freed task allocation are not the same thing. Completing a task drops its future, but wake and join handles may keep its storage allocated. That leftover storage is not a running future.
The storage remains while any native standard waker, local handle, or join handle points to it. A join handle also owns the result until it is taken. Dropping the join handle frees the result, whether or not wake handles remain.
The list of unfinished tasks does not own them, so it never keeps an orphaned future alive.
Routing remote commands
A standard waker uses a global registry to find where to send commands. The registry maps runtime IDs to runtimes, and IDs are never reused.
Looking up every remote wake in the registry would add synchronization. Instead, each remote thread caches owned references to runtime endpoints it has used. A cache hit skips the registry lookup and per-operation reference counting on the queue. Caching a new endpoint also removes closed ones; accessing a closed cached endpoint removes it too.
Remote waker commands and unpolled submissions reserve admission before they publish. Shutdown therefore waits for accepted work, even when the publisher bypassed the registry. A closed cached endpoint rejects new work.
Cleanup must not call back into the runtime while these shared structures are in use. Notifications therefore run only after admission, registry locks, and cache borrows are released. Removed endpoints are also dropped outside locks or borrows, before the new operation is admitted, so driver destructors can safely re-enter. Wakers used while thread-locals are being destroyed fall back to the registry.
The owner thread caches the last runtime ID it checked and whether that endpoint is open. A hit also proves that the current thread owns the runtime, saving a separate thread-ID lookup. A miss checks ownership before consulting the registry.
Shutdown records the closed state in this cache before running callbacks. Because IDs are never reused, that entry stays correct. This cache holds no queue reference. Switching between runtimes on one thread goes back to the registry.
Cross-thread task submissions use this routing too. Unpolled Send
submissions travel through the same FIFO as remote wakes. Once a task runs,
its state, references, join results, and awaiters are all local to the owner.
Local wakes use an intrusive ready queue, whose links live in the task rather
than separate queue entries. Native join awaiters hold LocalWakers that can
still be released after they unregister.
Each task stores a raw pointer to its queue, rather than a strong or weak reference. Only the owner thread uses it. Unfinished tasks use it while their runtime or runner keeps the queue alive. Completed tasks need a live endpoint before borrowing it.
Deferred releases on a busy owner publish without taking a temporary strong queue reference. Releases that may send a notification or run shutdown cleanup still take one. Cleanup that can run callbacks resolves the runtime ID to a strong queue reference outside the registry lock.
Limits and memory layout
Keeping routing information in each task makes its size important. The native runtime uses 16-bit runtime IDs and owner-thread indexes to keep the task core at 80 bytes on 64-bit targets.
A process can create at most 65,535 native runtimes. At most 65,535 threads can
own one. Neither IDs nor indexes are reused, and the process aborts if either
runs out. Threads that only wake tasks or spawn through a Handle do not use
an index.
Fields used by wakes, runs, and releases sit in the core’s first 64 bytes. Task-list links come last; they are used only on spawn, completion, and shutdown. Task allocations are not cache-line aligned. This layout makes single-cache-line access more likely without guaranteeing it.
After running local tasks, the scheduler checks whether the remote FIFO is empty before trying to pop from it. This avoids the full memory fence that an empty pop costs. The scheduler rechecks readiness afterward. A command published in the meantime either keeps the runtime polling or wakes the driver.
A non-empty FIFO is drained in order, within the scheduler’s per-turn budget.
Shutdown
Shutdown has to account for commands already on their way to the owner. It stops new work and drops live futures on their owner thread, first closing admission and disabling the runtime’s wake endpoint, then draining accepted commands.
The closed registry entry remains available for owner cleanup, including panic cleanup, until draining finishes. Removing it only afterward prevents owner releases from overtaking pending commands. After removal, standard-waker operations are ignored. Cloning such a waker produces an inert one.
Standard wakers still alive at shutdown permanently keep their task allocations, even after they are dropped. The memory remains, but execution does not continue. Task allocations do not keep the driver or the queue’s backing memory alive.
Separately, a remote thread’s endpoint cache can keep closed queues and their drivers alive. A closed entry is released when the thread next accesses it, caches a new endpoint, or exits. Owner-local handles can still be released after shutdown without touching the possibly dangling queue pointer.
If you need to reclaim task memory, drop standard wakers and let the owner process their queued releases before shutdown.
Server
An ntex server spreads connections across single-threaded workers to use multiple CPU cores. A dedicated accept thread owns the listening sockets and sends each connection to an available worker:
listeners -> accept thread -> worker-local service
On Linux and Android, LoadBalancing::Reuseport removes the accept thread:
each worker accepts connections on its own listener. See
Per-worker listeners.
The server manages sockets and workers without knowing the connection’s
protocol. Each worker’s service decides how to handle the resulting Io,
whether it carries HTTP, MQTT, or a custom protocol.
For encrypted connections, put a TLS acceptor before the protocol service. Neither the listener nor the protocol implementation needs backend-specific TLS logic. See Securing Connections with TLS for backend configuration, HTTPS helpers, and connection-level client-certificate authentication.
Starting a server
To start a server, create it inside an active ntex System. Register at least
one listener, then call run():
use ntex::http::{HttpService, Response};
#[ntex::main]
async fn main() -> std::io::Result<()> {
ntex::server::build()
.bind(
"http",
"127.0.0.1:8080",
ntex::SharedCfg::default(),
async |_| {
HttpService::new(async |_| {
Ok::<_, std::io::Error>(
Response::Ok().body("Hello world!"),
)
})
},
)?
.run()
.await
}
server::build() needs a current System. In this example, #[ntex::main]
creates one.
bind() takes four arguments:
- A service name, used in logs and to associate listeners with services.
- An address that implements
ToSocketAddrs. - A
SharedCfgattached to accepted connections. - An asynchronous factory that builds the connection service for each worker.
run() returns a cloneable Server controller. Await it to wait for the
server to stop. The future always resolves to Ok(()). It reports completion,
not the health of every connection or worker.
run() panics if you have not registered a listener.
Binding and existing listeners
Use bind() to let the server create and own a listening socket. Use
listen() when you already own a TcpListener, for example with socket
activation or custom socket options.
If an address resolves to several socket addresses, ntex tries all of them.
It registers every listener that binds successfully. The call succeeds when
at least one address binds. Use a concrete SocketAddr when you need exactly
one listener.
The builder’s backlog() setting applies only to listeners created by later
bind() and configure() calls. It cannot change an existing listener’s
backlog.
On Unix, bind_uds() creates a Unix domain socket, while listen_uds() uses
an existing listener. Before binding, bind_uds() removes any existing file
at the socket path. It removes the socket file again when the server stops.
You can register several listeners and protocols on one server. Keep service
names clear and unique when using modular configure() callbacks. Those
callbacks attach worker services to listeners by name.
Workers and service factories
By default, the server starts one worker for each available logical CPU. Set a
different number with workers():
let builder = ntex::server::build()
.workers(4);
The worker count must be at least one. workers(0) panics because a server
without workers could never become ready or dispatch connections.
Each worker runs on its own arbiter thread and owns its own service instance.
The factory you pass to bind() runs for every worker. Its setup must be safe
to repeat. It may run again after a worker restarts or a readiness failure
causes a service to be recreated.
The factory must be Send, Clone, and 'static. The service it creates
stays on one worker, so it does not need to implement Send or Sync. You can
use worker-local types such as Rc, Cell, or RefCell in that service.
Share data across workers explicitly, using thread-safe types such as Arc,
atomics, or locks. For richer process-wide and worker-local state, use
build_with_config() with ServerAppConfig. Worker and request
state explains that model in detail.
Only workers that report ready receive connections. A worker stops receiving new connections if it reaches its connection limit or any registered service is not ready. If no worker is available, the accept loop pauses until one becomes ready again.
The default limit is 25,600 concurrent connections per worker for this server:
let builder = ntex::server::build()
.workers(4)
.max_connections(10_000);
Other servers in the process keep their own connection limits.
Server configuration
Most servers only need to choose their capacity and shutdown policy. Set
these on ServerBuilder before calling run(). Alongside workers() and
max_connections(), use backlog() to allow more connection attempts to
wait at listeners created afterward. Give the server a name() to identify
its accept and worker threads in logs; otherwise it uses the current system
name.
For shutdown, graceful_shutdown_timeout() sets how long workers may take to
finish; the default is 30 seconds. A failed worker normally restarts.
stop_on_panic() stops the server instead, and graceful_shutdown() makes
those failures, SIGQUIT, fatal signals, and application panics stop it
gracefully rather than immediately. Use disable_signals() if your
application will handle signals itself. The
shutdown section explains how these policies interact.
For example, this builder gives each worker a connection limit and allows 15 seconds for a graceful stop:
use ntex::time::Seconds;
let builder = ntex::server::build()
.name("api")
.workers(4)
.backlog(1024)
.max_connections(20_000)
.graceful_shutdown_timeout(Seconds(15))
.stop_on_panic();
Call stop_runtime() to stop the complete ntex System after this server
stops. It is disabled by default; enable it when one server owns the process
lifecycle. Leave it disabled if other work or independent servers must keep
using the same System.
The remaining placement settings, affinity() and load_balancing(), control
where workers run and which connections they receive. The next section
explains their defaults and when to change them.
Read Server::status() to check whether the server can accept connections.
Use Server::status_changed() to wait for the next change, for example in a
supervisor or health check. The states are:
Startinguntil a worker becomes available, thenReady.Unavailablewhile no worker is available.PausedafterServer::pause(), until you callServer::resume().Stopping, followed byStopped, when the server stops.
Listeners accept connections only while the server is Ready. This status
describes acceptance, not the health of every worker. Changes in quick
succession may produce a single notification with the latest status.
Worker placement and load balancing
Worker placement and load balancing keep connection processing close to the CPU receiving its packets. With the defaults, that CPU, or at least its physical core, also handles the connection.
These are two separate decisions: affinity() places each worker thread
on a CPU, while load_balancing() chooses the worker for each new
connection. Keeping them close keeps packet data, socket state, and worker
data in the same CPU caches and on the same NUMA node. The network stack
also avoids waking a thread on another CPU for every received packet.
use ntex::server::{Affinity, LoadBalancing};
let builder = ntex::server::build()
.workers(8)
.affinity(Affinity::Core)
.load_balancing(LoadBalancing::IncomingCpu);
Worker placement
Worker placement spreads workers across physical cores before sharing them. At startup, ntex reads the CPU topology and orders the logical CPUs the process may use:
- On hybrid CPUs, faster cores come first. Performance cores precede efficiency cores.
- Within each class, ntex takes one logical CPU from every physical core. It interleaves them across the L3 caches of a NUMA node, then across NUMA nodes. With four workers on a two-socket machine, each socket gets two workers. They use different L3 caches if the socket has several.
- The remaining SMT siblings (hyper-threads) follow in the same order.
Worker i takes entry i from this list. The list starts over when there are
more workers than CPUs. Workers never share a physical core until every core
has a worker. A restarted worker keeps its predecessor’s placement.
The placement is applied with one of the Affinity modes:
| Mode | Windows | Linux and Android |
|---|---|---|
Disabled | not placed | not placed |
Cpu | pinned to one logical CPU (SetThreadGroupAffinity) | pinned to one logical CPU (sched_setaffinity) |
Core | pinned to the logical CPUs of one physical core | pinned to the logical CPUs of one physical core |
Soft | preferred CPU only, the ideal processor (SetThreadIdealProcessorEx) | same as Core |
The default is Soft on Windows and Core on Linux and Android. With Core,
the scheduler can move a worker between its core’s SMT siblings, which share
L1 and L2 caches. Other platforms have no topology support and ignore
affinity.
ntex applies placement on the worker thread before creating its runtime.
The runtime, its timers, and the worker’s buffer page cache are then allocated
on the NUMA node of the worker’s CPU. ntex logs each placement at info level:
Set affinity to Soft cpu 2 (core 2 3) for worker "api:worker:1"
When you start workers directly, pass a logical CPU index to Worker::start().
On Windows, numbering continues from processor group 0 into group 1.
Windows
On a large Windows machine, the worker count should not be limited to the CPUs in a single processor group. Windows divides machines with more than 64 logical CPUs into groups, and a thread runs in one group at a time. ntex spreads workers across those groups while respecting explicit process CPU limits.
ntex reads topology through GetLogicalProcessorInformationEx. This includes
physical cores and their efficiency classes, L3 caches, and NUMA nodes across
all processor groups. Only Windows 10 APIs are used.
std::thread::available_parallelism() counts only the current group. ntex
counts all groups for the default worker count and spreads workers across
them. A Soft worker’s ideal processor must belong to its thread’s group.
If that processor is in another group, ntex also gives the worker affinity to
that whole group.
The allowed CPUs come from:
- An explicit process affinity mask, such as
start /affinityor job object affinity limits. This also keeps workers in the process’s processor group. - The group affinity of a job object the process runs in.
- The process’s default CPU sets, set through
SetProcessDefaultCpuSetsor container CPU limits.
The groups where the process happens to run do not restrict placement. Without explicit limits, ntex uses all groups.
Soft is a hint. The scheduler uses the ideal processor when it is free and
another CPU in the group otherwise. A worker can then avoid a busy thread or
interrupt-heavy CPU. On dedicated machines, use Core or Cpu when strict
isolation matters more.
Linux and Android
On Linux and Android, placement follows the process’s allowed CPUs. Linux
has no preferred-CPU hint, so Soft works like Core.
ntex reads topology from sysfs under /sys/devices/system/cpu/cpuN/:
topology/core_cpus_list, orthread_siblings_list, identifies the physical core.cache/index3/shared_cpu_listidentifies the L3 cache. If there is none, ntex uses the package.- The
nodeNlink identifies the NUMA node. cpu_capacityidentifies big.LITTLE cores.
The allowed CPUs come from sched_getaffinity(). ntex therefore respects
taskset, cgroup cpusets (docker run --cpuset-cpus), and systemd’s
CPUAffinity=.
The default worker count follows std::thread::available_parallelism(), which
also honors a cgroup CPU quota (docker run --cpus). A quota does not restrict
which CPUs run the process. Workers still spread across all allowed CPUs.
Connection load balancing
Load balancing chooses which ready worker receives each new connection.
The accept thread makes that choice and queues the connection to the worker.
With LoadBalancing::Reuseport, the kernel chooses instead, see
Per-worker listeners. The worker turns the socket
into an ntex Io and registers it with its own runtime. All later I/O for
that connection runs on the same worker.
Items submitted with Server::process() follow the same dispatch rules on
the submitting thread. While no worker is available, items wait in the
server’s command loop until a worker is ready. That loop runs on the thread
that started the server.
Only ready workers receive connections. See
Workers and service factories for readiness
rules. Among those workers, LoadBalancing decides:
-
RoundRobinsends connections to workers in turn. It skips workers whose runtimes are blocked while another worker is available. -
LeastLoadedpicks two random workers and chooses the one with lower runtime utilization. Utilization is the share of time the runtime was busy, averaged over about 250 ms and sampled at most every 10 ms. If the two differ by less than 10%, the one with fewer open and queued connections wins.Blocked workers are skipped while another worker is available. See Stall detection. On tokio, busy time is available only for current-thread runtimes. Otherwise, the connection count decides.
-
IncomingCpu, the default, prefers a worker on the CPU that receives the connection’s packets. Otherwise, it works likeLeastLoaded. -
Reuseportlets each worker accept TCP connections on its ownSO_REUSEPORTsocket, without an accept thread. Linux and Android only, see Per-worker listeners. Other connections and items work likeIncomingCpu.
For each connection, IncomingCpu follows these steps:
- Ask the operating system which CPU receives the connection’s packets. This happens once, when the connection is accepted.
- Find workers placed on that CPU. If there are none, find workers whose
physical core contains it. This includes SMT siblings the process may not
use, for example with
taskset. The network stack may still process packets on those CPUs. - Choose an unblocked worker with the lowest utilization, then the fewest connections.
- Compare it with the
LeastLoadedchoice. Use the local worker unless its utilization is more than 20% higher or its load exceeds the other worker’s load by more than half plus 16 connections.
These limits prevent the preference from overloading workers. An adapter may deliver traffic to only a few CPUs, or its hash may spread connections unevenly. Some connections may also cost much more to process than others. Under normal load, nearly every connection stays local.
Connections without an incoming CPU use the LeastLoaded choice. This
applies to:
- Loopback connections on Windows.
- Platforms other than Windows, Linux, and Android.
Affinity::Disabled.- Custom
ServerConfigurationimplementations that do not overrideincoming_cpu().
A worker whose placement could not be applied is never preferred as local. Connections that arrive while no worker is available wait in the server. They follow the same balancing rules once a worker becomes available.
The incoming CPU is read only once. The connection stays on its worker even if the operating system later moves its traffic to another CPU. This can happen when RSS is rebalanced or irqbalance moves an interrupt.
The counters ServerMetrics::incoming_cpu_hits and incoming_cpu_misses
show how often connections stay local. See Incoming CPU.
Rescheduling
The server can move a queued connection if its worker cannot handle it. A connection stays in the queue until the worker takes it. The server moves it to another worker when the original worker:
- Fails, for example because its service panics. If no other worker is available, queued connections wait in the server for the restarted worker.
- Is not ready, for example while its service is recreated.
- Is blocked by a task. With two or more workers, the server checks for blocked workers every 50 ms. It moves their queued connections while another worker is not blocked. See Stall detection.
Only queued connections move. Once a worker takes a connection, it registers that connection with its runtime and keeps it there. A blocked worker handles it after becoming unblocked. A failed worker drops it.
Moved connections are balanced again without their incoming CPU. They are
not counted again in incoming_cpu_hits or incoming_cpu_misses.
ServerMetrics::rescheduled counts them instead. See
Rescheduled connections.
Windows: receive-side scaling
Receive-side scaling (RSS) directs each connection’s packets to a CPU.
The adapter hashes the connection’s addresses and ports into an indirection
table that selects a receive queue. One CPU serves each queue and runs the
NDIS receive processing. ntex reads that CPU’s processor group and number
with WSAIoctl(SIO_QUERY_RSS_PROCESSOR_INFO).
With Affinity::Soft, the chosen worker’s ideal processor is the RSS CPU.
The receive processing that completes its I/O usually runs on the same CPU
as the worker thread it wakes.
By default, RSS uses one logical CPU per physical core, starting at the adapter’s base processor. Worker placement also takes one logical CPU from each core first. With one worker per core, the RSS CPUs have their own workers.
Loopback connections (127.0.0.1, ::1) do not pass through an adapter and
have no RSS CPU. Connections to the machine’s own adapter addresses do have
one, including connections from WSL. You can use those addresses to test RSS
on a single machine. Adapters without RSS, or with RSS disabled, report none.
Use Get-NetAdapterRss to inspect the adapter’s RSS settings. It shows
BaseProcessorNumber, MaxProcessors, and the processors used by the
indirection table. If many connections miss, align the RSS processors with
the worker CPUs, for example:
Set-NetAdapterRss -Name "Ethernet" -BaseProcessorNumber 0 -MaxProcessors 8
Linux and Android: SO_INCOMING_CPU
On Linux 3.19 or later, getsockopt(SOL_SOCKET, SO_INCOMING_CPU) identifies
the CPU that processed the socket’s last received packet. ntex reads this
value when accepting a connection. At that point, it identifies the CPU that
processed the last packet of the TCP handshake.
The adapter’s receive-queue interrupt affinity sets that CPU through
/proc/irq/N/smp_affinity_list. Two mechanisms can change it:
- Receive Packet Steering moves packet processing to other CPUs. Its setting
is
/sys/class/net/<dev>/queues/rx-N/rps_cpus. - Receive Flow Steering moves processing to the CPU where the consuming thread last ran.
Loopback packets are processed on the sending CPU, so loopback connections report the client’s CPU. Test servers on loopback therefore count hits and misses too.
Use ethtool -l <dev> to check the number of receive queues. Change it with
ethtool -L <dev> combined N. Check /proc/interrupts to see which CPUs
handle the queues.
For the best locality, use one queue per worker and pin the queue interrupts to the worker CPUs. irqbalance may move them again unless you stop it or tell it to leave those interrupts alone.
Per-worker listeners
LoadBalancing::Reuseport removes the accept thread for TCP listeners on
Linux and Android. ntex replicates every bound TCP socket with
SO_REUSEPORT, one socket per worker, each with the backlog() length.
Each worker accepts on its own sockets on its own thread, so connections
never pass between threads.
use ntex::server::LoadBalancing;
let builder = ntex::server::build()
.load_balancing(LoadBalancing::Reuseport);
The kernel chooses the socket for each new connection. ntex sets
SO_INCOMING_CPU on the sockets of each worker placed on a CPU. On Linux 6.1
or later, the kernel then sends the connection to the worker on the CPU that
processed its packets. Connections processed on a CPU without a worker are
spread by a hash of their addresses and ports, as are all connections with
Affinity::Disabled. Spread the receive queues, or RPS, over the worker CPUs
as described in the previous section.
A worker accepts only while it is ready, for example below
max_connections(). Otherwise, new connections wait in its socket’s listen
backlog. The kernel has already chosen the socket, so ntex cannot move them:
- Utilization and blocked workers are not considered, and Rescheduling does not apply. A blocked worker delays the connections queued on its socket until it unblocks.
- A failed worker’s sockets stay open. Its replacement accepts the connections waiting there.
Server::pause()stops every worker from accepting.- When the server stops, workers close their sockets first. Connections still in a listen backlog are reset. Accepted connections finish within the graceful shutdown timeout as usual.
The accept thread still handles:
- Every listener on the tokio and compio runtimes. Reuseport requires the
neon-pollingorneon-uringruntime. ntex logs a warning and falls back to the accept thread. - Every listener on platforms other than Linux and Android.
- Unix domain sockets.
- A TCP listener that cannot be replicated, for example when binding a copy
fails. ntex logs
Cannot replicate <addr>, using an accept thread.
Those connections, and items from Server::process(), are balanced like
IncomingCpu.
Choosing the settings
Start with the defaults, then compare the workers’ active_connections
and utilization. If connections stay uneven under IncomingCpu, try
LoadBalancing::LeastLoaded. An adapter with fewer queues than workers may
concentrate connections on only a few CPUs. Without a known incoming CPU,
IncomingCpu already falls back to LeastLoaded.
On machines shared with other busy processes, prefer Affinity::Soft on
Windows, or use Affinity::Disabled. The scheduler can then move workers
away from busy CPUs. If you have more workers than CPUs, several workers
share a CPU; IncomingCpu chooses the least loaded of those workers.
Use LoadBalancing::RoundRobin when you want connections assigned in turn,
with blocked workers skipped as described in
Connection load balancing.
Consider LoadBalancing::Reuseport on Linux when the accept thread limits
the connection rate, for example with many short-lived connections. It
scales accepting with the workers and avoids a thread hop per connection.
It suits workers with similar connection costs that rarely block, because
the kernel never moves connections away from a busy worker. Check the
workers’ active_connections, not_ready_duration, and latency.stalls
for imbalance. With uneven connections or frequent stalls, stay with
IncomingCpu.
Controlling a running server
Clone the controller when another task needs to pause, resume, or stop the server:
use ntex::server::Server;
async fn manage(server: Server) -> std::io::Result<()> {
let control = server.clone();
ntex::rt::spawn(async move {
control.pause().await;
// Perform maintenance or wait for an external readiness condition.
control.resume().await;
control.stop(true).await;
});
server.await
}
Call pause() to stop accepting new connections without closing existing
ones. New connection attempts normally wait in the operating system’s listen
backlog. Call resume() to enable the listeners again. At startup, the server
is paused until its first worker becomes ready, then resumes automatically.
Use stop(true) for a graceful stop. The accept loop closes its listeners.
The server then asks workers currently available for dispatch to finish
active work. It waits up to the configured graceful-shutdown timeout.
Use stop(false) when the controller should not wait for workers to finish
active work. Available worker services still receive a shutdown request and
a default three-second local timeout. That cleanup may continue after the
server controller reports completion. An immediate stop does not guarantee
that every in-flight operation has finished.
A graceful stop does not wait for workers still initializing or recreating their services. Give long-lived factory setup its own cancellation or ownership boundary.
Repeated stop requests join the stop already in progress. Await stop(...)
or the original Server if later work must wait until the server reaches
its stopped state.
Server metrics
When clients wait longer to connect or requests slow down, server metrics
help you find where work is waiting. Start with the accept loop to see
whether new connections can get in, then compare workers and their I/O.
Server::metrics() returns a ServerMetrics snapshot. The call is
synchronous and cheap enough to run periodically.
Counters and durations are totals since the server started. Take two snapshots
and use their differences to get rates. Gauges describe the moment of the
snapshot. These include active_connections, accept_backlog, the *_active
and *_buffered values, and cached pages.
use ntex::server::Server;
use ntex::time::{Seconds, sleep};
async fn report(server: Server) {
let mut prev = server.metrics();
loop {
sleep(Seconds(10)).await;
let cur = server.metrics();
let paused = cur.accept_paused_duration - prev.accept_paused_duration;
println!("accept paused {paused:?}, backlog {}", cur.accept_backlog);
for (w, p) in cur.workers.iter().zip(&prev.workers) {
println!(
"worker {:?}: {} new, {} active, not ready {:?}",
w.id,
w.items - p.items,
w.active_connections,
w.not_ready_duration - p.not_ready_duration,
);
}
prev = cur;
}
}
The worker list has one entry per worker slot. Its order stays the same across snapshots. A restarted worker keeps its predecessor’s metrics.
Accept loop
Accept-loop metrics show when the server stops accepting connections and how
many accepted connections are waiting. These fields are on ServerMetrics.
| Metric | Kind | Meaning |
|---|---|---|
accept_pauses | counter | Number of times the accept loop stopped accepting, because no worker was ready or the server was paused. |
accept_paused_duration | duration | Total time the accept loop was not accepting, including the current pause. |
accept_backlog | gauge | Accepted connections waiting for a ready worker. |
ntex does not reject connections at the limit. While the accept loop is
paused, new connection attempts wait in the operating system’s listen
backlog. This is different from accept_backlog, which counts connections
the server has already accepted.
If accept_paused_duration grows steadily outside a deliberate pause,
check why workers are not ready. When all workers are at capacity, add
workers with workers() or scale out. You can also raise
max_connections() if workers have spare CPU and memory.
A non-zero accept_backlog, or short frequent pauses, indicates that
connections are waiting for workers. Clients then see higher connect
latency. For bursts of load, a larger backlog() keeps the operating system
from dropping connection attempts. Pauses caused by Server::pause() count
too, so account for maintenance windows when interpreting these numbers.
With LoadBalancing::Reuseport, connections accepted by workers never wait
in accept_backlog, and a worker that is not ready does not pause the
other workers. Only Server::pause() counts in accept_pauses and
accept_paused_duration. Use the workers’ not_ready_duration to find
workers whose sockets hold waiting connections.
Incoming CPU
These counters show how often LoadBalancing::IncomingCpu keeps a connection
on the CPU receiving its packets. Both fields are on ServerMetrics.
| Metric | Kind | Meaning |
|---|---|---|
incoming_cpu_hits | counter | Connections sent to the worker on the CPU that receives their packets. |
incoming_cpu_misses | counter | Connections with a known incoming CPU sent to another worker, because no worker is placed on that CPU or its worker was busier. |
Neither counter includes connections without a known incoming CPU. These
include Windows loopback connections and servers on platforms other than
Windows, Linux, and Android. Connections accepted by workers with
LoadBalancing::Reuseport are not counted either, because the kernel
chooses their worker.
Many misses mean packets reach CPUs without workers, or workers on the receiving CPUs are busier than the others. The adapter might use CPUs outside the process affinity or have fewer queues than the server has workers.
Compare the adapter’s RSS settings with worker placement. Use
Get-NetAdapterRss on Windows. On Linux, use ethtool -l and
/proc/interrupts.
Rescheduled connections
The rescheduled counter shows how often queued connections move to another
worker. This field is on ServerMetrics. See
Connection load balancing for the dispatch rules.
| Metric | Kind | Meaning |
|---|---|---|
rescheduled | counter | Connections taken from the queue of a failed, not ready or blocked worker and sent to another worker. |
An occasional increase follows a worker restart or stall. A steady increase
means workers are blocked often. Check latency.stalls for stalls and
current_task for the blocking code in Runtime. Connections
accepted by workers with LoadBalancing::Reuseport are never rescheduled.
Listeners
Listener metrics show where connections arrive and why accepts fail.
ServerMetrics::listeners has one ListenerMetrics entry per bound socket.
| Metric | Kind | Meaning |
|---|---|---|
name, addr | label | Service name and address passed to bind(). |
accepted | counter | Connections accepted on the listener. |
connection_errors | counter | Per-connection accept errors, for example a connection reset before it was accepted. |
resource_errors | counter | Accept failures caused by resource exhaustion, for example running out of file descriptors. After each one the listener pauses briefly. |
Compare the rate of accepted across listeners to see where load comes from.
It gives the connection rate per service.
A few connection_errors are normal on the internet. A rising rate suggests
clients that give up early or a network problem. Treat any resource_errors
as a capacity problem. Raise the file descriptor limit with ulimit -n or
lower max_connections().
Workers
Compare worker metrics to check load balancing and find workers at capacity.
ServerMetrics::workers has one WorkerMetrics entry per worker slot.
| Metric | Kind | Meaning |
|---|---|---|
id | label | Worker id. |
items | counter | Connections (or other items) the worker received. |
active_connections | gauge | Open connections on the worker. Network servers only. |
not_ready | counter | Number of times the worker’s services stopped being ready, for example on reaching max_connections(). |
not_ready_duration | duration | Total time the worker was not ready, including the current period. |
restarts | counter | Number of times the worker was restarted after a failure. |
io, io_other | I/O statistics, see below. | |
page_cache | Buffer page cache statistics of the worker thread, see below. | |
runtime | Runtime statistics of the worker thread, see below. |
Start by comparing active_connections and the rate of items across
workers. They should be close with the default
LoadBalancing::IncomingCpu or with LoadBalancing::LeastLoaded. With
LoadBalancing::Reuseport, they follow the kernel’s choice and depend on
how the receive queues are spread over the worker CPUs. A worker
with much higher not_ready_duration than the others points to long-lived
or expensive connections pinned to it. If that duration grows on all
workers, together with accept_paused_duration when an accept thread is
used, the server is at capacity.
The connection limit can also stop workers that have CPU to spare. If
active_connections reaches max_connections() while CPU is idle, raise
the limit to suit the workload. Many idle keep-alive or WebSocket
connections can cause this.
Treat restarts separately from load: it should stay at zero. Any increase
means a worker failed. Alert on it and check the logs.
Runtime
Runtime metrics help you find overloaded workers and tasks that delay other
work. WorkerMetrics::runtime contains a RuntimeMetrics for the worker
thread’s runtime. A field is None when the runtime does not provide it.
Totals survive worker restarts. The current_turn and current_task fields
describe the current worker thread. So do the latency gauges: last,
last_sample, and stalled.
| Metric | Kind | Runtimes | Meaning |
|---|---|---|---|
busy_duration | duration | all | Time the runtime spent running tasks and handling I/O events. |
polls | counter | neon, compio | Runtime turns that ran scheduled tasks. |
polls_again | counter | neon, compio | Runtime turns that left scheduled tasks for the next turn. |
self_wakes | counter | neon | Polls in which a task woke itself, for example by yielding. |
poll_histogram | histogram | neon, compio | Duration of runtime turns. |
current_turn | duration | neon, compio | How long the current runtime turn has been running, None while the runtime is idle. |
current_task | location | neon | Spawn location of the task being polled now. |
latency | all | Scheduling latency and stalls, see below. None if sampling is disabled. |
The latency field contains a LatencyMetrics. A task on each worker sleeps
for interval and records how late it wakes up:
| Metric | Kind | Meaning |
|---|---|---|
interval | setting | Sampling interval. |
last | gauge | Lateness of the most recent sample. |
histogram | histogram | Lateness of all samples. |
last_sample | gauge | Time of the most recent sample. |
stalls | counter | Times the worker recorded no sample for longer than interval plus the stall threshold. |
stall_duration | duration | Total duration of finished stalls. |
stalled | gauge | Whether the worker is stalled now. |
Utilization tells you the share of time the worker was busy; the next section shows how to calculate it and explains runtime differences. A worker close to 100% needs more CPU capacity, so consider adding workers or cores. Uneven utilization points to expensive connections pinned to a few workers.
Scheduling latency tells you how long ready work waits to run, adding to
request processing time. Watch high percentiles of the histogram
difference. Values of several milliseconds mean the worker is overloaded
or a task runs too long between .await points. Long turns in
poll_histogram help identify the latter: they delay every task woken
during the turn. Move such work to spawn_blocking() or split it.
If the ratio of polls_again to polls is close to 1, tasks are scheduled
faster than the worker runs them, leaving a backlog. A high self_wakes
rate instead points to tasks that busy-loop by yielding.
stalls should stay at zero. A stall means blocking code, such as a
synchronous call or a lock, held the worker. Alert on it.
Worker stalls and busy loops explains how
to find the task and set the sampling interval and stall threshold on the
system builder.
Worker utilization
To measure worker utilization, take two snapshots of busy_duration.
Divide its growth by the time between the snapshots. This running total
survives worker restarts:
use std::time::Instant;
use ntex::server::Server;
use ntex::time::{Seconds, sleep};
async fn utilization(server: Server) {
let mut prev = server.metrics();
let mut prev_time = Instant::now();
loop {
sleep(Seconds(10)).await;
let cur = server.metrics();
let now = Instant::now();
let elapsed = (now - prev_time).as_secs_f64();
for (w, p) in cur.workers.iter().zip(&prev.workers) {
let (Some(busy), Some(prev_busy)) =
(w.runtime.busy_duration, p.runtime.busy_duration)
else {
continue; // not reported by this runtime
};
let stalled = w.runtime.latency.as_ref().is_some_and(|l| l.stalled);
let pct = if stalled {
100.0
} else {
100.0 * busy.saturating_sub(prev_busy).as_secs_f64() / elapsed
};
println!("worker {:?}: {pct:.1}% busy", w.id);
}
prev = cur;
prev_time = now;
}
}
Use the same measurement window for all workers. A window of 5 to 10 seconds smooths out short spikes. Shorter windows show bursts.
The runtimes report busy time differently:
-
On neon and compio,
busy_durationincludes the turn running now. A worker held by a long task shows up as 100% busy right away. -
On tokio,
busy_durationis reported only for current-thread runtimes. It excludes handling I/O events, so values are lower than on neon or compio for the same load.Tokio adds busy time only after a batch of tasks finishes. A stalled worker can therefore show low utilization. Treat a worker with
latency.stalledset as fully busy, as the example does.
Compare utilization with the rate of items and with active_connections.
High utilization with few connections points to expensive requests. High
utilization on only one worker points to an imbalance, as described above.
I/O metrics
I/O metrics show traffic, buffer use, and backpressure for each service and worker. To get a service’s totals across the server, add its entries from all workers.
Each worker collects metrics per I/O configuration: an IoConfig in a
SharedCfg. ntex registers every listener configuration automatically.
WorkerMetrics::io has one IoConfigMetrics entry per listener
configuration. The SharedCfg fields id, tag, and service identify it.
Other configurations can have their own entries too, such as an HTTP client’s
configuration. Enable them with IoConfig::set_metrics(true). Connections
whose configuration has no separate metrics entry count together in
io_other.
I/O metrics are always collected. The default, set_metrics(false), only
removes a configuration’s separate entry. It does not affect registered
listener entries.
Each entry is an IoMetricsSnapshot:
| Metric | Kind | Meaning |
|---|---|---|
bytes_read | counter | Bytes read from the transport. |
bytes_written | counter | Bytes written to the transport. |
read_buffered | gauge | Bytes held in read buffers, not yet consumed by the application. |
read_buffers_held | gauge | Connections that keep a read buffer allocated for unconsumed input, such as the start of a frame that has not fully arrived. |
read_buffer_capacity | gauge | Bytes allocated by those read buffers, a whole page for a pooled buffer. |
write_buffered | gauge | Bytes in write buffers, or held by the transport and not yet written. |
read_backpressure | counter | Number of times read backpressure was enabled: the read buffer reached set_read_backpressure() and reading stopped. |
read_backpressure_active | gauge | Connections with read backpressure enabled now. |
read_backpressure_time | duration | Total connection-time spent under read backpressure. |
write_backpressure | counter | Number of times write backpressure was enabled: the write buffer reached set_write_backpressure(). |
write_backpressure_active | gauge | Connections with write backpressure enabled now. |
write_backpressure_time | duration | Total connection-time spent under write backpressure. |
eager_writes | counter | Writes started in place, as soon as buffered output reached set_write_buf_threshold(). |
eager_writes_partial | counter | Eager writes that could not write all output and left the rest to the write task. |
scheduled_writes | counter | Writes left to the write task. With io-uring all writes use the write task. |
closed | Closed connections by reason, see below. |
Backpressure time adds up across connections. Ten connections under backpressure for one second add ten seconds. Divide its rate by the number of active connections to get the share of time a connection spends blocked.
Traffic and buffer memory
Rates of bytes_read and bytes_written give bandwidth per service and
worker. Divide them by the items rate to get average traffic per
connection. For memory pressure, look at read_buffer_capacity and
write_buffered together. Lowering set_read_backpressure() and
set_write_backpressure(), or reducing max_connections(), can reduce
memory held in connection buffers.
A read buffer is released once its input is consumed, so busy connections
appear in read_buffers_held only briefly. A snapshot mostly shows idle
connections waiting for the rest of a frame. Each may keep a whole page
for a few bytes. If read_buffer_capacity far exceeds read_buffered,
these small leftovers are holding memory.
Many such connections point to slow or stalled clients. Use
set_frame_read_rate() to bound how long they can hold a buffer. A smaller
minimum page in set_read_size() lowers the cost of each. These metrics
exclude buffers held by pending io-uring reads and frames split off buffers
that keep their pages alive; Io buffer attribution
counts them.
Read and write pressure
The direction of backpressure tells you which side cannot keep up. Growing
write_backpressure_time means clients read slower than the application
writes. A few slow clients are normal, but a persistently high
write_backpressure_active holds memory and connection slots. HTTP/1
connections that stay backpressured for ten seconds are closed by default;
tune that with set_write_timeout() and watch closed.write_timeout.
Growing read_backpressure_time means the application processes input
slower than it arrives. Check the service’s processing time or worker CPU.
A larger set_read_backpressure() only helps with short bursts.
On the write path, most writes should be eager on fast networks. A high
share of eager_writes_partial means the socket send buffer fills, which
is normal for large responses and slow clients. If scheduled_writes
dominate, output may be arriving in many small pieces. Raising
set_write_buf_threshold() batches more output per system call; lowering
it reduces latency. With io-uring, all writes are scheduled, so do not
interpret that counter as a sign of small writes.
Close reasons
Close reasons help you distinguish timeouts and protocol errors from normal
connection closes. IoMetricsSnapshot::closed contains a CloseStats.
Each closed connection counts once in total and once under its first
reported reason:
| Metric | Meaning |
|---|---|
total | Closed connections. |
keepalive | The connection was idle for longer than the keep-alive timeout. |
read_timeout | Input did not arrive within the read timeout, for example set_frame_read_rate(). |
write_timeout | Write backpressure stayed enabled for longer than set_write_timeout(). |
peer_gone | The peer closed the connection. |
io | The transport failed with an I/O error. |
decoder | Incoming data could not be decoded, for example a malformed request. |
encoder | Outgoing data could not be encoded. |
service | The service failed or closed the connection. |
shutdown | The server was shutting down. |
custom | Application-defined reasons Custom1 to Custom8, counted in custom[0] to custom[7]. |
other | No reason was reported, for example the application closed the connection or the response had no keep-alive. |
A high share of keepalive closes means connections sit idle. Shorten
set_keepalive_timeout() to free connection slots sooner, or lengthen it
if clients reconnect often. Compare with the accepted rate to see the
tradeoff. Rising read_timeout closes point to slow or idle clients, or
slow-read attacks; rising write_timeout closes point to clients that
stopped reading. Check the timeouts against legitimate slow clients before
tightening them.
Protocol and transport failures need a different investigation. A sudden
increase in decoder closes usually means a broken client release, a
scanner, or abuse. The io and peer_gone reasons reflect network quality
and client behavior. An io spike together with connection_errors points
to a network problem.
For service closes, compare the rate with application error logs.
shutdown closes are expected during deploys and worker restarts, but at
other times they point to unexpected stops.
You can track application-specific reasons by setting a reason before closing the connection or failing the service. Examples include authentication failures, rate-limited clients, and upgrades:
use ntex::io::CloseReason;
// in a service that owns the connection's `Io`
io.set_close_reason(CloseReason::Custom1); // for example "auth failed"
io.close();
The first reported reason is kept. A later dispatcher reason, such as
Service, does not replace one your application already set.
Page cache
The page cache reuses released I/O buffer pages to avoid repeated
allocations. Pages have fixed sizes, and each worker thread keeps its own
cache. Its statistics are in WorkerMetrics::page_cache.
Use page_cache.get(size) to read statistics for one page size. Use
page_cache.iter() for all sizes, or page_cache.total() for the sum.
Each entry is a PageCacheStats:
| Metric | Kind | Meaning |
|---|---|---|
size | label | Page size, BytePageSize::Unset for totals. |
hits | counter | Pages taken from this class’s cache, including those used for requests for the next larger class. |
misses | counter | Requests that found no cached page of the requested class. |
fallbacks | counter | Misses served by a cached page one class smaller; also counted as a hit for that smaller class. |
cached | counter | Released pages returned to the cache. |
freed | counter | Released pages freed because the cache was full. |
pages | gauge | Pages in the cache now. |
bytes | gauge | Memory held by the cached pages. |
Subtract fallbacks from misses to count fresh page allocations. If that
rate and freed are both high for the same class, pages are being freed,
then allocated again. The cache is too small for the workload. Raise its
limit for that page size with ntex_bytes::set_page_cache_size() on each
worker thread, for example in its service factory.
If bytes stays high while traffic is low and misses are rare, the cache
is larger than needed. Lower its limit to free excess cached pages.
Byte Buffers explains these limits and
how they differ from memory held by live buffers.
Statistics may be slightly off after a worker restart. The old and new worker threads can update them at the same time.
Io buffer attribution
Use buffer attribution to measure input memory even after it leaves a connection. You can measure how much memory a listener’s request bodies hold or find the connection holding the most input.
The I/O metrics count only read buffers a connection holds. A Bytes frame
split off a read buffer can keep the whole allocation alive in your
application. Buffers held by pending io-uring reads also keep allocations
alive. These do not appear in the read-buffer metrics.
Attribution charges each read buffer allocation to a BytesTracker for the
allocation’s lifetime, wherever its data ends up. It requires the tracker
feature, which adds a pointer to every heap buffer’s header:
ntex = { version = "4", features = ["tracker"] }
Configure attribution per IoConfig with set_buf_tracker():
BufTracker | Behavior |
|---|---|
Disabled | Read buffers are not attributed. This is the default. |
PerConnection | Each connection charges its read buffers to its own tracker, created when first used. |
Shared(tracker) | All connections of the configuration, on all workers, charge their read buffers to tracker. |
Use a shared tracker to get a total per listener or service. Create it before the server starts and keep a clone so you can read it:
use ntex::io::{IoConfig, BufTracker};
use ntex::time::{Seconds, sleep};
use ntex::util::BytesTracker;
use ntex::SharedCfg;
let api_input = BytesTracker::new();
let cfg = SharedCfg::new("API").add(
IoConfig::new().set_buf_tracker(BufTracker::Shared(api_input.clone())),
);
let server = ntex::server::build()
.bind("api", "0.0.0.0:8080", cfg, async |_| { /* service */ })?
.run();
ntex::rt::spawn(async move {
loop {
sleep(Seconds(10)).await;
let snap = api_input.snapshot();
println!(
"api input: {} bytes in {} buffers",
snap.live_bytes, snap.live_allocations
);
}
});
With PerConnection, use IoRef::buf_tracker() to get the connection’s
tracker. In a handler, you can reach it through HttpRequest::io(). Filters
can use IoContext::buf_tracker(). These methods return None when
attribution is disabled.
Do not use the returned reference after calling Io::set_config(). Clone the
tracker if you need to keep it longer. A clone keeps reporting buffers that
outlive the connection without keeping the connection itself alive.
if let Some(tracker) = req.io().and_then(|io| io.buf_tracker()) {
if tracker.snapshot().live_bytes > 64 * 1024 * 1024 {
// the connection holds too much input, reject or close it
}
}
You can also charge application buffers to the tracker. For example, you might assemble a body from many frames, decompress a payload, or receive a buffer from another source for the connection. That memory then appears alongside the connection’s read buffers.
With either PerConnection or Shared, pass the tracker to
BytesMut::with_page_size_in(size, tracker) when creating a buffer from the
page cache. For an existing buffer, call BytesMut::set_tracker(tracker).
That moves any previous charge to the new tracker, including while Bytes
frames split off the allocation are still alive. Use BytesMut::tracker()
to find which tracker currently owns the charge.
use ntex::util::{BytePageSize, BytesMut};
let mut body = match req.io().and_then(|io| io.buf_tracker()) {
Some(tracker) => BytesMut::with_page_size_in(BytePageSize::Size16, tracker),
None => BytesMut::with_page_size(BytePageSize::Size16),
};
while let Some(chunk) = payload.next().await {
body.extend_from_slice(&chunk?);
}
Application buffers follow the same rules as read buffers. The charge lasts until the last handle is dropped. A growing buffer stays charged, while copies are not charged.
Read BytesTracker::snapshot() to get a BytesTrackerSnapshot:
| Metric | Kind | Meaning |
|---|---|---|
live_bytes | gauge | Memory held by the attributed allocations, including the allocation header. |
live_allocations | gauge | Number of attributed allocations. |
Tracker values are separate from ServerMetrics and IoMetricsSnapshot.
Read the trackers you created and export their values alongside those metrics.
The two fields are read one after the other. A snapshot taken during buffer
allocation or release is therefore only approximately consistent.
Use BytesTracker::ptr_eq() to check whether two handles refer to the same
tracker.
What is charged
A tracker follows allocations, not just bytes waiting in a connection. Attribution covers:
- Every read buffer the connection allocates or takes from the page cache. The charge covers the full allocation size, regardless of how much data it holds. A buffer that grows into a new allocation keeps the same tracker.
- Buffers of a pending read, including io-uring provided-buffer pages once they receive data. A buffer returned empty by a read goes back to the page cache, ending its charge.
- Plaintext read buffers of filters such as TLS.
- Frames split off a read buffer. The charge lasts until the last
BytesorBytesMutreferring to the allocation is dropped. It ends on whichever thread drops that handle, even after the connection closes.
Attribution does not charge:
- Pages in the page cache. A cached page is charged again only to its next user.
- Write buffers.
- Copies of data. This includes small frames stored inline in a
Byteshandle, up to 23 bytes on 64-bit targets, and copies made byBytes::trimdown(). Data copied into application types is also uncharged unless you charge it explicitly as described above.
A shared view keeps the original allocation charged. Copies do not inherit
that charge: cloning a BytesMut copies its data, while splitting or
freezing a small result can copy it inline.
Configuration changes and cost
A configuration change through Io::set_config() can change attribution,
for example after a protocol upgrade:
- With
PerConnectionin both configurations, the connection keeps its tracker. - Switching to
Shared(tracker)moves the buffers the connection holds totracker. Frames that already left the connection stay charged to the old tracker. - Switching from
SharedorDisabledtoPerConnectioncreates a new tracker. - Switching to
Disabledstops charging new buffers. Existing buffers stay charged until they are released.
Without the tracker feature, attribution has no cost. Enabling it grows
every heap buffer’s header from 16 to 32 bytes on 64-bit targets, or to
20 bytes on 32-bit targets, whether attributed or not. Allocating or growing
a buffer and releasing its last handle check for a tracker and update its
atomic counters when present. Sharing views needs no counter update, though
freezing the last mutable handle into inline storage releases its allocation
and ends its charge.
A Shared tracker also has a cache line updated by every worker thread,
which becomes contended under load. Prefer one tracker per listener or
service over one per server. Use PerConnection when you only need
per-connection limits.
Interpreting tracker values
Compare a shared tracker’s live_bytes with the sum of
read_buffer_capacity for the same service. A much higher value points to
input outside the connection’s current read buffer: request bodies queued
for later processing, cached frames, or pending io-uring reads. A small
part of a large buffer can hold the whole allocation; copy that part, for
example with Bytes::trimdown(), to release the buffer. If
live_allocations keeps growing while active connections stay stable,
check whether frames are ever dropped.
To estimate cost, divide live_bytes by live_allocations for the average
allocation size, or by active_connections for average input memory per
connection. A high average with little traffic points to the partial-input
case in I/O metrics.
With PerConnection, you can check a client’s tracker before accepting
more input and close connections that exceed a limit. Unlike
set_read_backpressure(), this also counts input the connection already
handed to the application.
Worker stalls and busy loops
Blocking a worker delays every connection it handles because they all share
one thread. A synchronous call, a long-held lock, or a long computation
between .await points can block that thread. The runtime detects blocked
workers and tasks that never wait. It logs them and reports them in worker
metrics.
Stall detection
Stall detection identifies workers that stop making progress. Each worker runs a task that sleeps for the latency sampling interval and records how late it wakes up. A watchdog thread checks workers every interval.
A worker is stalled if it records no sample for longer than the interval plus the stall threshold. The defaults are 100 ms for the interval and 1 s for the threshold. A worker is therefore stalled after about 1.1 s without progress.
When a stall starts, the watchdog logs an error:
Arbiter my-server:worker:0(Id(3)) is stalled, no progress for 1.1s, running task spawned at src/main.rs:42:9
On neon, the message names the running task’s spawn location. Tasks spawned by ntex itself, such as connection dispatchers, report a location inside ntex. A stall without a running task happens in the I/O driver.
When the worker makes progress again, a warning reports the stall duration:
Arbiter my-server:worker:0(Id(3)) recovered after 2.4s stall
You can monitor the same information in WorkerMetrics::runtime.
latency.stalls and latency.stall_duration count finished stalls; alert
on any increase. During a stall, latency.stalled is set and
current_turn shows how long the worker has been blocked. On neon,
current_task identifies the blocking task’s spawn location. Shorter
blocking that stays under the threshold instead appears as high values in
the latency.histogram and poll_histogram differences.
While another worker is available, new connections skip a worker if:
- Its runtime turn has lasted 100 ms or more.
- It has recorded no latency sample for 100 ms past its interval.
- It is stalled.
Queued connections move to other workers. See Rescheduling. Connections the worker has already taken still wait for it.
Set the interval and threshold in milliseconds on the system builder.
#[ntex::main] has no options for them, so build the system directly:
use ntex::rt::{DefaultRuntime, System};
fn main() -> std::io::Result<()> {
System::build()
.name("my-server")
.signals(true) // backtraces on Linux need signal handling
.latency_interval(50) // sample every 50 ms
.ping_threshold(500) // stalled after 550 ms without a sample
.build(DefaultRuntime)
.block_on(async {
// build and run the server
Ok(())
})
}
A shorter interval detects stalls sooner and gives a finer latency histogram. It also causes more timer wakeups on idle workers. Keep the threshold above the longest blocking you accept to avoid logging expected work.
Set latency_interval(0) to disable sampling and stall detection.
WorkerMetrics::runtime.latency is then None.
Busy loop detection
A task can waste CPU and delay other tasks without stalling the worker.
A loop around yield_now() or wake_by_ref(), for example, wakes itself on
every poll instead of waiting for an event. The worker stays busy but is
not blocked.
The neon runtime counts these self-wakes. If a task wakes itself 10 000 times in a row over at least one second, the runtime logs one warning for that streak:
Task spawned at src/main.rs:42:9 woke itself 10000 times in 1.2s without waiting, possible busy loop
WorkerMetrics::runtime.self_wakes holds the total count. A steadily rising
rate, high utilization (busy_duration), and a low connection rate point to
a busy loop. Replace it with code that waits for an event or timer.
The tokio and compio runtimes do not count self-wakes. To change the limits,
use RuntimeBuilder::self_wake_threshold() when building the runtime
directly. You cannot change them otherwise. See the runtime chapter.
Backtrace capture
A stall backtrace helps you locate blocking code on the worker thread. On Linux and Windows, the watchdog captures one backtrace when a stall starts:
- On Linux, it sends
SIGUSR2to the worker thread. The signal handler records the stack. Enable ntex signal handling withsignals = truein#[ntex::main], or callSystem::build().signals(true). Your application must not useSIGUSR2for anything else. - On Windows, the watchdog briefly suspends the worker thread and walks its stack. This works on x86_64 and aarch64.
- Other platforms only log the stall.
By default, the watchdog resolves the backtrace and logs it as an error with
the task location. Use System::set_latency_callback() to replace that
logging, for example to send the backtrace to an error tracker.
The callback receives the unresolved backtrace and the blocking task’s spawn
location. Keep it short because it is process-wide and runs on the watchdog
thread. The location is None if the task changed during capture. In that
case, the backtrace may belong to a different task.
use ntex::rt::System;
fn install() {
System::set_latency_callback(|bt, task| {
let bt = bt.resolve();
log::error!("worker stalled, task spawned at {task:?}\n{bt}");
});
}
Backtraces need symbols. Release builds without debug information may show
wrong or missing function names. Add debug = "line-tables-only" to the
release profile for readable backtraces with file and line numbers.
Signals and shutdown
The server handles shutdown signals by default. You can use its built-in policy or disable it and stop the server yourself:
| Event | Default behavior |
|---|---|
SIGTERM | graceful stop |
SIGINT / Ctrl-C | immediate stop |
SIGQUIT | immediate stop, or graceful with graceful_shutdown() |
SIGHUP | ignored by the server |
| fatal signal or application panic | immediate stop, or graceful with graceful_shutdown() |
Signal delivery belongs to the ntex System, not an isolated server.
If several servers share a system, call disable_signals() consistently and
stop the appropriate server controllers yourself. Do the same if your
application installs its own signal policy.
Fatal-signal notifications require runtime fatal signal handling
(Builder::fatal_signals(true) or #[ntex::main(fatal_signals = true)]), and
application-panic notifications require runtime panic handling. Both are off
by default.
Fatal-signal shutdown is best effort. The operating system may terminate the process before graceful cleanup finishes. On Windows, Ctrl-C arrives as the interrupt event.
The graceful server timeout bounds a worker as a whole. Each connection has
its own IoConfig::set_shutdown_timeout() for flushing and closing. Leave
enough server-level time for those connection shutdowns to complete.
Connection and protocol configuration
Use SharedCfg to give each connection the configuration its I/O layer and
protocol services need. Pass it to bind() or listen(). ntex clones it onto
each accepted Io, and each layer retrieves the types it understands from
that container:
use ntex::http::{HttpService, HttpServiceConfig, Response};
use ntex::io::IoConfig;
use ntex::time::Seconds;
use ntex::SharedCfg;
#[ntex::main]
async fn main() -> std::io::Result<()> {
let cfg = SharedCfg::new("HTTP")
.add(
IoConfig::new()
.set_shutdown_timeout(Seconds(2)),
)
.add(
HttpServiceConfig::new()
.set_keepalive_timeout(Seconds(30)),
);
ntex::server::build()
.bind("http", "127.0.0.1:8080", cfg, async |_| {
HttpService::new(async |_| {
Ok::<_, std::io::Error>(
Response::Ok().body("Hello world!"),
)
})
})?
.run()
.await
}
IoConfig controls connection-level behavior, including shutdown, memory,
and read-rate limits. HttpServiceConfig controls HTTP behavior, including
keep-alive, request-head limits, and protocol timeouts. TLS and other protocols
add their own configuration types to the same SharedCfg.
If you omit a configuration type, lookups fall back to its Default value.
Each worker thread creates and caches its own default. A lookup does not
report whether the value was added or defaulted. The framework’s
configuration types get their defaults this way.
If your application requires a configuration value, add it explicitly.
Validate it when you build the SharedCfg rather than relying on a default.
The I/O chapter explains buffer limits, read rates, write backpressure, keep-alive, and shutdown timing in detail.
Test servers
Use test_server() to run a service on an available local port in a test.
It starts one worker on a separate thread and disables signal handling.
Its service factory receives &(), just like the factories passed to
http::test::server and web::test::server:
use ntex::http::{HttpService, Response};
use ntex::{client::Client, server};
#[ntex::test]
async fn test_server_response() {
let server = server::test_server(async |_| {
HttpService::new(async |_| {
Ok::<_, std::io::Error>(
Response::Ok().body("Hello world!"),
)
})
});
let url = format!("http://{}/", server.addr());
let response = Client::new()
.get(url.as_str())
.send()
.await
.unwrap();
assert!(response.status().is_success());
}
Use addr() to get the address for an HTTP client. Use connect() to open
a client Io with the test server’s client configuration. The server()
method returns the underlying server controller.
With TestServerBuilder, you can set separate server and client SharedCfg
values. If service construction needs application state, use
TestServerBuilder::with(cfg, async |state| service). The service factory
receives &Cfg::State. The state-initialization closure remains
async || Ok(state).
For custom listeners, build_test_server() exposes the full ServerBuilder.
Set the address on the returned TestServer before calling connect().
Dropping the last TestServer clone stops its server and runtime. It briefly
blocks the current thread while the test thread shuts down. Drop it outside
timing-sensitive assertions.
Worker and request state
A database client is usually worth reusing across requests. The current user’s identity usually belongs to the request instead. Choose where to keep state based on which requests or connections need to share it. A worker can reuse long-lived resources while each request carries its own information.
Each ntex worker runs its own single-threaded runtime and application instance. To use multiple CPU cores, the server starts several workers and distributes incoming connections among them.
Application startup usually has two stages. First, you load configuration for the whole process, normally on the main thread. You might read environment variables, parse command-line arguments, load configuration files, or fetch settings from an external service.
Next, ntex uses that configuration to initialize each worker. You provide an
object that implements ServerAppConfig. The server calls its create()
method inside each worker whenever that worker starts. If a worker fails and
restarts, create() runs again to give it fresh state.
The configuration object must implement Send + Sync because the server
shares it across worker threads. The state returned by create() belongs to
one worker and stays on its thread. You can use single-threaded types such as
Rc and RefCell in that state.
Worker state must also implement Clone: the server clones it when building
listener services. Servers such as web::server_with_config() clone it again
for every connection. To make those clones share a worker’s data, put that
data behind a shared handle, such as Rc<RefCell<T>> or Rc<Cache>. Each
handle then refers to the same value. Cloning a plain field does not by itself
share later changes with other clones.
The asynchronous create() method can prepare resources the worker needs.
You can open database connections, create clients, or initialize caches there.
If initialization fails, return an error rather than start the worker with
invalid state.
struct AppBuilder {
// Configuration shared across the process
}
#[derive(Clone)]
struct AppState {
// Resources owned by one worker, usually behind `Rc`
}
impl ServerAppConfig for AppBuilder {
type State = AppState;
// Called each time a worker starts.
async fn create(&self) -> io::Result<Self::State> {
Ok(AppState {
// Initialize this worker's resources.
})
}
}
You do not always need a separate configuration type. ServerAppConfig also
supports async closures that return io::Result<State>:
let server = ntex::server::build_with_config(async || {
Ok(AppState {
// ...
})
});
For servers that need no state, NoConfig provides unit state.
Creating the Worker Application
Once a worker has its resources, it can build the application that uses them.
The server calls each registered application factory in each worker, after
ServerAppConfig::create() finishes, and passes a reference to the worker’s
state.
#[ntex::main]
async fn main() -> std::io::Result<()> {
// Load the process-wide configuration.
let builder = AppBuilder {
// ...
};
web::server_with_config(builder, async |_state: &AppState| {
web::App::new().service(
web::resource("/").to(async || {
web::HttpResponse::Ok()
}),
)
})
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
Here, AppBuilder implements ServerAppConfig, so its create() method
produces a fresh AppState for each worker. The application factory receives
that state and builds the worker’s web::App factory.
There are two kinds of factory at work here. The application factory runs
during worker setup; the resulting App creates a service for each connection,
with its own clone of the worker state. You can therefore use state both when
setting up the application and its services, and throughout the lifecycle of
the worker’s connection-handler pipelines.
Worker-Local and Process-Wide State
An Rc shares data within one worker, not across the whole server. For a
value that every worker must see, make process-wide sharing explicit: wrap
the value in an Arc and clone it into each worker’s state. Mutable values
also need suitable synchronization, such as an atomic type, Mutex, or
RwLock.
Complete process/worker configuration example
Service and Pipeline State
A service may need state before it accepts a request or after it finishes one.
The state parameter on Service makes state available while the service
checks readiness, handles requests, and shuts down.
A simplified version of the trait looks like this:
trait Service<St, Req> {
type Res;
type Error;
async fn call(
&self,
req: Req,
ctx: Ctx<'_, Self, St>,
) -> Result<Self::Res, Self::Error>;
async fn ready(
&self,
ctx: Ctx<'_, Self, St>,
) -> Result<(), Self::Error>;
async fn shutdown(&self, ctx: Ctx<'_, Self, St>);
}
St names the state type the service expects. Because it is part of the
Service definition, Rust checks that you use the service with the right
kind of state.
The same state is available throughout the lifecycle: ready() uses it while
checking whether the service can accept more work, call() while handling a
request, and shutdown() while stopping. It is not limited to request
handling.
For the request-handling part, a stateful service works like an asynchronous function that receives both the state and the request:
async fn my_service(
state: &St,
req: Req,
) -> Result<Res, Error> {
// ...
}
The Service trait provides state through Ctx, rather than a separate
argument. The context also connects the service to its pipeline. That
pipeline manages readiness, request processing, and shutdown.
Constructing a Pipeline
To call a service, place it in a Pipeline with its state. A pipeline can
hold one service or a chain of services that use the same state.
use std::io;
struct AppState {
prefix: &'static str,
}
async fn my_service(
state: &AppState,
req: usize,
) -> Result<String, io::Error> {
Ok(format!("{} {req}", state.prefix))
}
#[ntex::main]
async fn main() -> io::Result<()> {
// Create a pipeline containing one state instance and one service.
let state = AppState { prefix: "request" };
let svc = ntex::Pipeline::new(state, my_service);
// Both calls use the same AppState instance.
let first = svc.call(1).await?;
let second = svc.call(2).await?;
println!("{first}:{second}");
Ok(())
}
This example creates AppState when it builds the pipeline. Both calls reuse
that instance; svc.call() does not create new state.
In a chain, each compatible service can access the same state. You can share resources across the chain without storing a copy in every service.
Worker state
The server builds the same service-and-state pairing for incoming connections. When a worker starts, it passes a reference to that worker’s state to the application factory. The factory builds a connection-handler service, which the server places in a pipeline with the state. Each worker has its own instance, so this is a worker-local pipeline rather than a process-wide one.
/// Handles an I/O connection using worker-local state.
async fn handle_io(
state: &AppState,
io: ntex::io::Io,
) -> Result<(), io::Error> {
// Process the connection using the worker state.
Ok(())
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
// Load the process-wide configuration.
let builder = AppBuilder {
// ...
};
ntex::server::build_with_config(builder)
.bind(
"handler",
"127.0.0.1:8080",
SharedCfg::new("S"),
async |_state: &AppState| {
// Build the connection-handler service.
ntex::service(handle_io)
},
)?
.run()
.await
}
State Accumulation
A request or connection may need to collect information as it moves through a service chain. Each service can inspect the information so far, add to it, and pass the updated state to the next service.
Unlike worker and pipeline state, accumulated state travels with the item being processed. Worker state lasts for the worker’s lifetime, and pipeline state for the pipeline’s lifetime; both are created once and reused across many calls. Accumulated state belongs to one request, or to one connection when the chain processes connections.
For example, the first service handling an incoming connection might record
its ID and peer address. The next could read the TLS ClientHello and extract
the Server Name Indication (SNI). Later services could load configuration for
that server name, validate the client, calculate resource usage, and apply
throttling. Finally, a service performs the TLS handshake before passing the
connection to an HTTP server.
The pipeline might look like this:
accept connection
→ collect connection information
→ read SNI
→ load client information
→ validate and throttle
→ negotiate TLS
→ handle HTTP
The ntex-service crate provides the RequestState trait for passing a
message and its accumulated state through a service chain. State<St, Req>
is the most common implementation: it keeps the state and message together
as they move from one service to the next.
You can also use a (St, Req) tuple, which is convenient for small services.
Io and IoBoxed implement RequestState with () state. A plain connection
can therefore go to any service that expects a RequestState.
The ntex protocol servers support RequestState, including ntex::http,
ntex-h2, ntex-mqtt, and ntex-amqp.
Collecting Connection Information
Start by wrapping the raw I/O connection with the information you want later services to use. This service records a connection ID, creation time, and peer address:
use std::{io, net::SocketAddr, time::Instant};
use ntex::{io::Io, service::State};
use uuid::Uuid;
struct Connection {
id: Uuid,
created: Instant,
peer_addr: SocketAddr,
}
async fn connect(_: &AppState, io: Io) -> io::Result<State<Connection, Io>> {
let peer_addr = load_peer_addr(&io)?;
Ok(State {
req: io,
state: Connection {
id: Uuid::new_v4(),
created: Instant::now(),
peer_addr,
},
})
}
The next service unpacks those values, performs the TLS handshake, and adds the server name:
use ntex::service::{RequestState, State};
struct ConnectionWithTls {
id: Uuid,
created: Instant,
peer_addr: SocketAddr,
server_name: String,
}
async fn tls(_: &AppState, msg: State<Connection, Io>) -> io::Result<State<ConnectionWithTls, TlsIo>> {
let (connection, io) = msg.unpack();
let server_name = load_server_name(&io).await?;
let io = accept_tls(io, &server_name).await?;
Ok(State {
req: io,
state: ConnectionWithTls {
id: connection.id,
created: connection.created,
peer_addr: connection.peer_addr,
server_name,
},
})
}
The TLS service changes both parts of the input. It replaces the raw Io
connection with a TLS-enabled TlsIo and extends the state with the server
name extracted during TLS negotiation. The connection ID, creation time, and
peer address carry forward too, so the HTTP server receives everything the
earlier services collected.
Passing Connection State to the HTTP Service
Connect the services in a chain to pass the collected state to the HTTP handler. In this example, the handler uses the server name added by the TLS service:
use ntex::{server, service, SharedCfg};
use ntex::http::{self, Request, Response};
/// Handles an HTTP request using information about its connection.
async fn handle_request(st: &ConnectionWithTls, _req: Request) -> io::Result<Response> {
Ok(Response::Ok()
.body(format!("server name: {}", st.server_name)),
)
}
#[ntex::main]
async fn main() -> io::Result<()> {
let builder = AppBuilder {
// ...
};
server::build_with_config(builder)
.bind(
"HTTP",
"127.0.0.1:8080",
SharedCfg::new("S"),
async |_: &AppState| {
// Collect the initial connection information.
service(connect)
// Perform the TLS handshake.
.and_then(tls)
// Pass the established connection to the HTTP service.
.and_then(http::HttpService::new(handle_request))
},
)?
.run()
.await
}
Complete state accumulation example
Implementation Details
The connection chain above collects information once, but a connection may carry many requests. Keep that distinction in mind when choosing where to store state. Each ntex protocol exposes connection and per-request state a little differently.
ntex::http
HttpService passes connection state to the request handler while it runs
the HTTP protocol on the I/O stream. It separates its input into those two
parts using RequestState.
ntex::web
A web application can use both long-lived state and state collected for one
request. When a web::App serves as the handler for HttpService, the state
extracted by HttpService becomes the application’s state.
A web service looks roughly like this:
async fn handler(state: &St, req: web::WebRequest) -> Result<web::WebResponse, Err> {
// ...
}
The state argument holds the long-lived application or connection state.
The generic parameter of WebRequest holds state for one request:
web::WebRequest<RequestState>
That means St comes from the service pipeline and remains available across
requests, while RequestState belongs to one request and moves through its
processing chain. A filter or middleware can inspect a WebRequest, do some
work, and return a new WebRequest with a different state type. This lets you
collect request-specific information without putting it in long-lived state.
For example, a request-processing chain might look like this:
validate request
→ load and authenticate the user
→ apply throttling
→ call the handler
The request starts without additional state:
web::WebRequest<()>
After loading and verifying the user, the authentication service can return:
web::WebRequest<AuthenticatedUser>
The next service can require WebRequest<AuthenticatedUser>. It cannot be
called until authentication has completed and the request contains an
authenticated user.
I/O Abstraction Layer
You can write protocol and service code without tying it to a runtime or reactor such as Tokio, Compio, or Neon. The ntex I/O layer gives that code a common interface to the connection. It also handles buffered reads and writes, backpressure, timeouts, and graceful shutdown.
Socket abstractions
Protocol code works with Io rather than a concrete socket type. A runtime
adapter moves bytes between its socket and buffers owned by Io. The I/O
subsystem does not call Tokio, Compio, or Neon socket APIs directly.
Each direction has an in-memory buffer owned by Io. The read half carries
bytes from the transport to the application, and the write half carries them
back. Owning the buffers lets Io apply backpressure and run filters as
bytes pass through.
You normally pass an Io to a protocol service such as
ntex::http::HttpService or ntex_mqtt::Server. The service decodes input
into protocol messages and encodes responses into the write buffer. It does
not depend on the concrete socket type. The ntex-net crate provides the
runtime-specific implementations for Tokio, Compio, and Neon.
You only need to work below this interface when integrating a transport. If you use an existing backend, you can move on to configuration and timeouts.
To integrate a socket type, implement IoStream. Its start() method
receives an IoContext and starts the transport-specific tasks. It returns
a Handle for controlling or querying the transport.
The work on an active connection falls into these roles:
- A protocol or dispatcher task consumes decoded input and queues encoded
output through
IoorIoRef. It typically runs the protocol service and, indirectly, application code. - A transport read task waits for read readiness, reads bytes from the socket, and submits them to the I/O subsystem.
- A transport write task takes queued bytes from the I/O subsystem and writes them to the socket.
The runtime adapter decides how to schedule this work. Built-in adapters
usually use cooperating read and write tasks. That scheduling is an
implementation detail, not a requirement of IoStream.
The read task first waits for IoContext::poll_read_ready to permit more
input. This keeps socket reads in step with ntex backpressure.
Use IoContext::take_read_buf to obtain the buffer for a read. After the
read, pass the buffer and result to IoContext::release_read_buf. ntex then
processes filters, wakes the dispatcher, and pauses further reads when the
configured high-water mark is reached.
For synchronous reads that do not hold the buffer across an await, use
IoContext::with_read_buf instead. It combines taking and releasing the
buffer into one call. It borrows the buffer in place, without detaching it and
appending it back.
The write task waits for IoContext::poll_write_ready before working on
output. Use IoContext::with_write_dst to access the queued data. Then
report how many bytes reached the peer through
IoContext::update_write_status. ntex uses that report to manage write
backpressure, resume waiting services, and coordinate graceful shutdown.
A transport can also report bytes it has taken before it writes them. Completion-based backends take ownership of whole pages until an operation completes. Those bytes have left the write buffer, but they still count as outstanding output. They remain outstanding until the transport reports them as written or returns them to the buffer. Flush completion, write backpressure, and the shutdown drain all include those bytes.
Readiness and transport teardown
An adapter must distinguish queued work from a socket that is ready to do it.
The buffer-release and write-status methods return an IoTaskStatus. Its
Io status means work remains, not that the transport is ready. Re-arm
transport readiness before the next operation.
On writes, the status is Io whenever output remains buffered, even if the
last attempt made no progress. Output already owned by the transport does not
keep the task running. Its completion wakes the task again.
The two IoContext readiness methods instead return a Readiness value.
Readiness::Ready lets the task perform its next operation; the other values
tell it how to tear down the connection.
Readiness::Close tells the task to close both directions and release the
socket, cancelling any operations still in flight. It covers graceful
shutdown, I/O or filter failure, and an expired shutdown deadline. On the
graceful path, ntex reports it only after draining buffered output, so nothing
remains to flush.
For a socket, closing means shutdown(SHUT_RDWR) followed by close().
Discard any data left in the receive queue first. Closing with unread input
aborts the connection with an RST and loses the output that was just drained.
Readiness::Terminate occurs only after an explicit force close through
IoRef::terminate. It deliberately discards buffered data. The task must
abort the connection rather than close gracefully, without draining the
receive queue or calling shutdown(SHUT_RDWR).
For a socket, set SO_LINGER to zero before close(). The peer then sees an
RST and cannot mistake a truncated stream for a complete one.
If a transport fails or decides to abort, call IoContext::stop with the
error. This terminates the connection without draining pending work.
Once transport teardown finishes, call IoContext::stopped, regardless of
which side initiated it. That report completes Io::shutdown. Finishing
filter shutdown and flushing alone does not complete it; the backend must
report that the connection has stopped.
The following example sketches a Tokio-style adapter. Real adapters use their
runtime’s native readiness and buffer APIs. Only the adapter accesses the
socket; application and protocol code use Io and IoRef. Buffer limits and
read/write backpressure apply consistently across supported runtimes.
impl IoStream for TcpStream {
fn start(self, ctx: IoContext) -> Box<dyn Handle> {
let socket = Rc::new(self);
tokio::task::spawn_local(read_task(socket.clone(), ctx.clone()));
tokio::task::spawn_local(write_task(socket.clone(), ctx));
Box::new(SocketHandle(socket))
}
}
async fn read_task(socket: Rc<TcpStream>, ctx: IoContext) {
loop {
// resolves `IoContext::poll_read_ready`
match wait_for_read_readiness(&ctx).await {
Readiness::Ready => {}
Readiness::Close | Readiness::Terminate => break,
}
let mut buf = ctx.take_read_buf();
let result = read_from_socket(&socket, &mut buf);
match ctx.release_read_buf(buf, result) {
IoTaskStatus::Io => {}
IoTaskStatus::Pause => wait_for_read_resume(&ctx).await,
IoTaskStatus::Stop => break,
}
}
}
async fn write_task(socket: Rc<TcpStream>, ctx: IoContext) {
let terminate = loop {
// resolves `IoContext::poll_write_ready`
match wait_for_write_readiness(&ctx).await {
Readiness::Ready => {}
Readiness::Close => break false,
Readiness::Terminate => break true,
}
let result = ctx.with_write_dst(|buf| {
write_to_socket(&socket, buf)
});
// `result` carries the number of bytes that reached the peer
match ctx.update_write_status(result) {
IoTaskStatus::Io => {}
IoTaskStatus::Pause => wait_for_queued_output(&ctx).await,
IoTaskStatus::Stop => break false,
}
};
if terminate {
// force close, abort so that the peer sees an RST
abort_socket(&socket);
} else {
// close both directions
shutdown_socket(&socket).await;
}
// report teardown as complete
ctx.stopped(None);
}
Transport handles and metadata
You may need transport information even though Io hides the socket. The
Handle returned by IoStream::start() exposes metadata through typed
queries. It can also resume transport writes on request.
Each backend chooses which query types to support. The built-in network
backends expose the remote socket address as PeerAddr. Use
IoRef::query to request it; you can also call this method on Io through
dereferencing. The returned QueryItem provides the value through get():
use ntex::io::{Io, types::PeerAddr};
fn log_peer_addr(io: &Io) {
if let Some(addr) = io.query::<PeerAddr>().get() {
println!("Peer address {:?}", addr.into_inner());
}
}
A query passes through the filter stack before it reaches the transport handle. Filters can expose their own typed metadata along the way.
Configuration and timeouts
Start with the default buffering and timeouts, then use IoConfig when a
workload needs different limits. You normally add it to a SharedCfg. When
you create a connection, Io::new() reads the IoConfig from that shared
configuration, or uses defaults if it is absent.
This example combines the settings in one place; you rarely need to change all of them:
use ntex::{
SharedCfg,
io::IoConfig,
time::{Millis, Seconds},
util::BytePageSize,
};
let cfg = SharedCfg::new("my-protocol")
.add(
IoConfig::new()
.set_connect_timeout(Millis(5_000))
.set_keepalive_timeout(Seconds(30))
.set_shutdown_timeout(Seconds(2))
.set_frame_read_rate(Seconds(2), Seconds(10), 1_024)
.set_write_timeout(Seconds(10))
.set_read_size(BytePageSize::Size4, BytePageSize::Size32)
.set_read_backpressure(32 * 1024)
.set_write_backpressure(32 * 1024)
.set_write_buf_threshold(8 * 1024),
)
.build();
Timeouts
Timeouts protect different stages of a connection. The ntex-net crate uses
the connection timeout while resolving and opening an outgoing connection.
Once connected, protocol dispatchers handle the keep-alive timeout and frame
read-rate limits. A read-rate limit protects a decoder from peers that send
an incomplete frame too slowly. It also covers the first frame, so a peer
that connects and stays silent is closed when the limit expires.
An I/O dispatcher can change these two limits for one connection without
touching its configuration. Dispatcher::keepalive_timeout replaces the
keep-alive timeout, and Seconds::ZERO disables it.
Dispatcher::skip_first_frame_timeout lets the peer stay silent after
connection setup; the read-rate limit applies once data arrives. Use them for
protocols where the server speaks first or the peer may stay idle, as
web::ws does for WebSocket connections.
A peer can also stop reading your output. The write timeout bounds how long write backpressure can remain enabled before the dispatcher stops with a write timeout. Its timer runs from the moment backpressure is enabled until it is disabled; keep-alive and read-rate timers do not run during that time. After backpressure is disabled, only keep-alive bounds any remaining output in the dispatcher. Set a write timeout especially for untrusted peers: without one, a peer that stops reading can keep a backpressured connection and its output alive indefinitely.
When you use Io directly, the write timeout also bounds each wait in
send(), flush(), and write_ready(). If it expires, the wait fails and
leaves the connection open for you to close.
The HTTP/1 dispatcher has its own keep-alive, read-rate, and write timeout
settings. Configure those through HttpServiceConfig, including its own
set_write_timeout(), rather than the corresponding IoConfig settings.
Unlike IoConfig, HttpServiceConfig enables a ten-second write timeout
by default.
Finally, the graceful-shutdown timeout covers filter shutdown and the transport drain of pending output together. You cannot disable it: a zero value is rejected. It defaults to one second. Connection, keep-alive, and write timeouts and frame read-rate limits are all disabled by default.
Buffer limits
Buffering has two separate controls: page sizes govern allocation, while high-water marks tell producers or transports when to pause. A watermark is not a hard memory limit, because one socket read or encoded item can cross it. The default read and write high-water marks are about 32 KiB and 16 KiB, respectively.
Write backpressure ends when outstanding output falls to half its high-water mark. This count includes both buffered output and bytes owned by the transport but not yet written to the peer.
The minimum and maximum read page sizes bound the adaptive size of new read
buffers. They control allocation and read-call frequency, not how much unread
data a connection can queue. Increase the maximum for sustained large frames
or bodies; keep the minimum small for many mostly idle connections. Before
another socket read, a buffer grows when less than BytePageSize::low of
its page remains free.
On the write side, the page size controls newly allocated BytePages, which
hold output; write backpressure takes only a high-water mark. The write
threshold tells supported transports when to attempt an early direct write.
It is a latency hint for starting transport work earlier, not a flush or a
replacement for write backpressure.
Reconfiguring a connection
A protocol upgrade may change a connection’s timeout or buffer requirements.
If only the keep-alive timeout or the first-frame read limit must change,
set them on the dispatcher instead, as described in Timeouts.
Otherwise use Io::set_config to switch an established connection to
another shared configuration.
The method is unsafe. Replacing the configuration may release the
allocation behind references returned by IoRef::cfg. No such reference
may remain live across the call or be used afterwards.
Filter subsystem
A protocol service may need a transformed byte stream rather than raw socket bytes. TLS decrypts incoming records and encrypts outgoing data. A protocol can also run inside another framing layer, as MQTT does over WebSocket.
Use FilterLayer for these transformations. Filters work on in-memory
buffers and do not perform socket I/O. You can use the same filter with any
supported runtime backend.
FilterLayer::process_read_buf transforms bytes received from the next
inner layer. FilterLayer::process_write_buf transforms application output
before passing it toward the transport.
You can compose filters with Io::add_filter. It adds a layer and allocates
the intermediate read and write buffers between adjacent layers. For
example, an MQTT service can use either of these stacks:
socket <-> TLS <-> MQTT
socket <-> TLS <-> WebSocket <-> MQTT
Read bytes move from the socket through the inner filters toward the application. Write bytes move in the opposite direction. In the second stack, the WebSocket filter removes and creates WebSocket framing. The TLS filter decrypts and encrypts the resulting stream.
The MQTT service still reads and writes MQTT bytes. It does not need to know which filters sit below it. The TLS chapter shows this model in HTTP clients, WebSocket clients, and servers. It also covers backend configuration and peer certificate authentication.
Filters can keep protocol state and expose typed metadata through query().
A TLS filter, for example, can expose the negotiated protocol or peer
certificate. Filters also participate in graceful shutdown; a WebSocket
filter can generate a close frame then.
A filter can emit output while processing input. ntex pushes that output toward the transport as soon as read processing finishes, without waiting for the application to write.
Most byte transformations need only FilterLayer. To observe or control the
whole chain, wrap it with a lower-level Filter through
Io::map_filter.
Filter handles buffer processing, queries, and shutdown. It also takes part
in read and write readiness decisions. A wrapper can delay readiness to
throttle traffic, then wake the I/O tasks when work can resume. It can also
observe buffer processing for metrics or accounting without changing bytes.
A custom Filter normally stores the filter it wraps. Delegate each operation
you do not intend to override. ntex provides forwarding macros for readiness,
queries, and shutdown to make this less error-prone.
Typed versus erased filter stacks
Keep a concrete filter stack type while building a connection. At a service boundary, you may need one I/O type for connections with different stacks. Type erasure gives you that common type without changing connection behavior.
Io stores the stack in its type parameter. A new connection starts as
Io<Base>, with the Base filter. Calling add_filter(layer) consumes the
value and returns Io<Layer<U, F>>. The Layer marker pairs the new outer
layer U with the previous stack F.
The concrete type provides static dispatch. Io::filter can also return
the concrete outer filter:
let io: Io<Base> = create_io();
let io: Io<Layer<MyFilter, Base>> = io.add_filter(MyFilter::new());
Use Io::seal to erase the stack type and get Io<Sealed>, using the
Sealed marker. Io::boxed returns the IoBoxed convenience wrapper.
Both consume the original Io and keep the same connection state and filter
behavior behind a dynamically dispatched Filter.
let io: IoBoxed = io.boxed();
start_protocol(io);
You can add typed layers to a sealed stream and erase the result again. Normally, erase the type where a protocol or service needs uniform I/O, rather than while you are building the stack.
Read/write streams
Choose read and write APIs based on how your protocol handles messages. Incoming and outgoing bytes follow separate buffer paths. Queuing bytes and waiting for transport progress are separate operations.
Reading
A codec or protocol service reads from the application-facing buffer. The
transport adapter fills a BytesMut with socket input, then the bytes pass
through the filter chain into that buffer.
Choose the highest-level read API that fits your protocol:
- Use
recv(codec)for framed messages. It decodes buffered input and waits when the codec reports an incomplete frame. - Use
read_exact()for a fixed-size header or field. - For a custom parser, inspect or consume the buffer through
IoRef. CallIo::read_moreonly when you have decided that you need more bytes. It actively resumes transport reads and releases read backpressure, even if the buffer is still large. UseIoRef::read_dst_sizefor a passive size check.
Read backpressure depends on the size of the application-facing buffer. When it reaches the configured high-water mark, ntex pauses the transport read task. Consuming input through these methods wakes the task once the buffer falls to half that mark:
Io::recv and Io::read_exact wait for more input. They release
backpressure regardless of how much input remains buffered.
BytesMut is contiguous and growable. A decoder can split immutable Bytes
values from it without copying larger payloads. Short values are copied into
the Bytes handle itself. A decoded message can therefore retain part of the
input while the decoder continues with later data.
The remaining read-buffer details matter when tuning allocation. Read
buffers use ntex-bytes pages, with each connection choosing new buffers’
page size between the minimum and maximum set by IoConfig::set_read_size.
The defaults are Size4 and Size64. A connection starts at the minimum, so
idle and light connections pin small pages.
Consecutive reads that fill their buffer form a batch, together with the read that ends the sequence. If a batch is larger than the page, the page size grows to fit it, up to the maximum.
Once traffic becomes lighter, the page size shrinks by one step after four
consecutive batches fit in half of the next smaller page. It never shrinks
below the minimum. Io::set_config restarts it at the minimum. If you want
a fixed page size instead, set equal minimum and maximum sizes.
Page size does not affect read backpressure. The default read high-water mark
is the Size32 capacity, 32,752 bytes. Use
IoConfig::set_read_backpressure to change it.
An empty buffer returns to the per-thread page cache for its size. Write
pages and other pooled BytesMut buffers share that cache; configure it with
set_page_cache_size. A frame split from the read buffer keeps the page
alive. The page returns to the cache when the last frame is dropped.
Before another socket read, the adapter obtains a buffer from IoContext.
ntex calls BytesMut::reserve_more when less than BytePageSize::low of
the page remains free. It compacts data within the page if the data still fits.
If larger input must be buffered, the buffer moves to bigger page sizes. Beyond the largest page size, it uses a plain allocation. That allocation is freed rather than cached.
Writing
Queue output first, then decide how long to wait for it. Encoding methods make bytes available to the transport write task; they do not wait for every byte to reach the socket.
Use IoRef::encode to queue codec-encoded output. IoRef::encode_slice
and IoRef::encode_bytes also queue output. Queueing schedules the
transport write task when it needs to resume.
On transports that support direct writes, the write threshold can trigger a write while your application is still producing output. This can reduce latency for large responses.
Use Io::flush to choose the write wait policy:
flush(false)waits for backpressure to ease, rather than draining all output. It returns immediately below the high-water mark. Once that mark is reached, it waits until outstanding output falls to half the mark.flush(true)waits until all queued data reaches the peer. This includes bytes owned by the transport but not yet written.
Io::send combines codec encoding with a full flush.
Write backpressure is advisory. The encode methods keep accepting output
after the high-water mark is reached. Refusing half of a protocol message
would be difficult to recover from.
If a dispatcher does not manage your producer, await IoRef::write_ready
before queueing each next chunk. You can also use flush(false) between
batches:
use ntex::{
io::Io,
util::Bytes,
};
async fn queue_chunk(io: &Io, chunk: Bytes) -> std::io::Result<()> {
io.write_ready().await?;
io.encode_bytes(chunk)
}
This keeps normal streaming output around the configured watermark. It does not split a large chunk or make the watermark a strict per-connection memory cap.
These APIs all queue output in BytePages, a growable collection of byte
pages. Newly allocated pages use the size configured by IoConfig. Owned
buffers passed to IoRef::encode_bytes can become pages directly when their
storage can be retained, avoiding a copy.
Write filters consume the pages in order. They transform the contents and place the result in the next buffer toward the transport.
Connection lifecycle and shutdown
A protocol service needs to notice connection changes even while it waits on a dependency or a slow response. It also needs to give pending output a chance to reach the peer when closing. A connection stays usable until the application closes it, the peer disconnects, or the transport reports an error.
Use Io::poll_status_update while waiting on work other than input. It
reports an IoStatusUpdate value:
Timeoutmeans the dispatcher timer expired, such as the keep-alive timer.WriteBackpressuremeans outstanding output reached the write high-water mark. Stop producing output and flush.PeerGonemeans the connection closed, whether the peer disconnected, the transport failed, or shutdown started locally. It carries the transport error if one occurred, orNoneafter a clean close.
Use Io::poll_read_pause if you also want to stop accepting transport input
while waiting. The pause is cooperative. Decoding, accessing the application
read buffer, or explicitly requesting more input resumes reads. Use it while
a dispatcher waits on readiness, not to disable the read half permanently.
A codec-driven service receives the same conditions as RecvError from
Io::poll_recv. It also receives decoder failures. Unlike the status
update, RecvError::PeerGone reports a stream truncated mid-frame. If clean
peer EOF leaves undecodable bytes, it carries an
io::ErrorKind::UnexpectedEof error rather than None.
If you only need to wake when the connection goes away, await the Waiter
returned by IoRef::on_disconnect. To check whether closing has started,
use IoRef::is_active, which becomes false at that point.
IoRef::is_closed becomes true only after the backend releases the
transport and finishes teardown.
Clean peer EOF ends the read direction but leaves the write half open. Your service can finish encoding and flushing its response before closing.
When you have finished the response, call IoRef::close to request
graceful shutdown and return immediately, or await Io::shutdown to drive
it to completion. Graceful shutdown gives both filters and the transport time
to finish, in two phases.
During the first phase, both directions stay open. Each filter can emit
closing data through FilterLayer::shutdown, such as TLS close_notify or
a WebSocket close frame. Reads continue normally, so the peer’s closing data
still reaches the filters. A read failure does not abort shutdown, but it
means the filter handshake cannot finish.
During the second phase, the transport drains remaining output into the connection, then closes both directions. The read side pauses because the filters have finished and cannot use more input. The transport discards any data left in the receive queue just before closing. The application receives no more input in this phase.
One deadline covers both phases. If the filters finish early, the transport gets the remaining time to drain output.
If the deadline expires while filters are pending, ntex ends the filter phase
and starts transport shutdown with the already-expired deadline. When the
transport observes it, it discards undrained output. Io::shutdown reports
the timeout error after transport teardown.
IoRef::terminate skips graceful shutdown and drops the connection without
flushing pending output.
Dropping the owning Io does not replace awaiting shutdown. If no output
would be lost, dropping it starts a normal close. If dropping the filter stack
prevents buffered output from being delivered, ntex aborts the transport.
The peer then cannot mistake a truncated stream for a complete one. Call
shutdown().await when delivery and a clean close matter.
Testing
Use IoTest to test a codec, filter, or protocol service without opening
sockets. It creates two connected in-memory transports. Each endpoint
implements IoStream, so you can wrap it in Io.
Writing to one endpoint supplies input to the other. The read() method
collects bytes written back by the peer:
use ntex::codec::BytesCodec;
use ntex::io::{Io, testing::IoTest};
use ntex::util::Bytes;
#[ntex::test]
async fn protocol_io() {
let (client, server) = IoTest::create();
// Allow the server transport to write to the client.
client.remote_buffer_cap(1024);
let io = Io::from(server);
client.write(b"request");
let request = io.recv(&BytesCodec).await.unwrap().unwrap();
assert_eq!(request, Bytes::from_static(b"request"));
io.send(Bytes::from_static(b"response"), &BytesCodec)
.await
.unwrap();
assert_eq!(client.read().await.unwrap(), b"response"[..]);
}
You can also force pending reads or inject read and write errors. Close either
side, or constrain write capacity to exercise backpressure. For
transport-query tests, attach a PeerAddr value.
Routing and Handlers
Build an HTTP application with ntex::web. The module provides routing,
request extractors, and responses, along with middleware and testing tools.
Use web::App to assemble the application. You register routes and group
them into resources and scopes. You can also add middleware, filters, and
fallback services. ntex builds these into the service that handles requests.
The server evaluates your application factory independently in each worker:
use ntex::web::{self, HttpResponse};
#[ntex::main]
async fn main() -> std::io::Result<()> {
web::server(async |_| {
web::App::new()
.route(
"/",
web::get().to(async || HttpResponse::Ok().body("Hello")),
)
})
.bind("127.0.0.1:8080", ntex::SharedCfg::default())?
.run()
.await
}
The factory returns an application factory, not a running service.
HttpService uses it to create an application service for each connection.
Application services are never shared between workers.
A worker can invoke the outer factory again when its service needs to be recreated. Keep setup repeatable; do not rely on it running exactly once.
For workers, server configuration, and application state, see Server and Worker and request state.
A Small Notes API
Start with a read-only API for a notebook. It needs a list endpoint, a detail endpoint, and a health check. Keeping those routes together gives us a useful application to grow without hiding routing behind a database dependency:
use ntex::web::{self, HttpResponse};
mod notes {
use ntex::web::{self, HttpResponse, types::{Json, Path}};
use serde::Serialize;
#[derive(Serialize)]
struct Note {
id: u32,
title: &'static str,
}
fn saved_notes() -> Vec<Note> {
vec![
Note { id: 1, title: "Learn routing" },
Note { id: 2, title: "Add application state" },
]
}
async fn list() -> Json<Vec<Note>> {
Json(saved_notes())
}
async fn show(id: Path<u32>) -> Option<Json<Note>> {
let id = id.into_inner();
saved_notes().into_iter().find(|note| note.id == id).map(Json)
}
pub fn configure(cfg: &mut web::ServiceConfig) {
cfg.service(web::resource("/notes").route(web::get().to(list)));
cfg.service(
web::resource("/notes/status")
.route(web::get().to(async || "ready")),
);
cfg.service(
web::resource("/notes/{id}").route(web::get().to(show)),
);
}
pub async fn missing() -> HttpResponse {
HttpResponse::NotFound().json(&serde_json::json!({
"error": "unknown API path"
}))
}
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
web::server(async |_| {
web::App::new()
.service(
web::scope("/api").service(
web::scope("/v1")
.configure(notes::configure)
.default_service(web::to(notes::missing)),
),
)
.default_service(web::to(async || {
HttpResponse::NotFound()
.content_type("text/plain; charset=utf-8")
.body("Unknown path")
}))
})
.bind("127.0.0.1:8080", ntex::SharedCfg::default())?
.run()
.await
}
This example uses serde with its derive feature and serde_json, alongside
ntex with a runtime feature such as tokio. The notes are fixed data, not a
persistent store. That keeps the first version easy to run; replacing
saved_notes() with a database query comes after
Application State.
The full path is the outer scope prefix, the inner scope prefix, and the resource path joined together:
| Request | Result |
|---|---|
GET /api/v1/notes | A JSON array of notes |
GET /api/v1/notes/1 | The first note as JSON |
GET /api/v1/notes/99 | 404, because the handler returns None |
GET /api/v1/notes/status | Plain-text ready |
GET /api/v1/missing | The versioned scope’s JSON 404 |
GET /elsewhere | The application’s plain-text 404 |
Register /notes/status before /notes/{id}. The router does not favor a
literal path over a parameter automatically. If the parameter route comes
first, it captures status; the Path<u32> extractor then fails instead of
trying another resource. Matching a resource and extracting its arguments
are separate steps.
There are also two different kinds of missing note here. An unknown path
reaches a fallback service. A known detail path with an unknown ID reaches
show, which returns None. The response happens to be 404 in both cases,
but the scope fallback does not run for the second one. If every API error
must have the same JSON shape, return an explicit JSON error response from
show too; a routing fallback cannot rewrite handler responses.
The notes module owns its route handlers and exposes a registration
function and a fallback. The application owns the public prefix and version,
so the module does not bake /api/v1 into every path. You can later mount the
same configuration below a different scope without rewriting its handlers.
Handlers
Use App::route() to connect a path and HTTP method to a handler:
use ntex::web::{self, HttpResponse};
let app = web::App::<()>::new()
.route("/users", web::get().to(async || HttpResponse::Ok()))
.route(
"/users",
web::post().to(async || HttpResponse::Created()),
);
A handler receives request extractors. Each extractor implements
FromRequest. The handler returns a value that implements Responder.
See Extractors and
Responders for the built-in types and for
writing your own. The basics example shows handlers that combine path and
session extractors with several responders, and the extractors examples
cover JSON, form, and multipart bodies.
Each call to App::route() creates a separate Resource containing one
Route. The route’s method and custom guards become resource guards. You
can therefore register the same path several times with different guards.
When several routes share a path, group them in a web::resource() and
register it with App::service(). A resource can have its own name and
fallback service. It can also have middleware and filters:
use ntex::web::{self, HttpResponse};
let app = web::App::<()>::new().service(
web::resource("/users/{id}")
.name("user")
.route(web::get().to(async || HttpResponse::Ok()))
.route(web::delete().to(async || HttpResponse::NoContent())),
);
Resource::to() adds a route without a method guard, so it accepts every HTTP
method:
use ntex::web::{self, HttpResponse};
let app = web::App::<()>::new().service(
web::resource("/health").to(async || HttpResponse::Ok()),
);
You can also use attribute macros for common routes. Pass the generated
service directly to App::service():
use ntex::web::{self, HttpResponse};
#[web::get("/health")]
async fn health() -> HttpResponse {
HttpResponse::Ok().into()
}
let app = web::App::<()>::new().service(health);
Method-specific route helpers include get, post, put, delete, patch,
head, and query. For other methods, use web::method(), as in
web::method(Method::OPTIONS).
Method matching is exact. A GET route does not also register HEAD, and
ntex does not add an OPTIONS route for you. Register those methods explicitly
when clients need them.
Choosing a Handler Return Type
Choose the smallest return type that expresses the endpoint’s contract. A
String or &'static str produces a plain-text 200 OK, which suits a
health check. Json<T> serializes a value implementing serde::Serialize
and sets the JSON content type. The notes list uses this form because its
successful result needs no special status or headers.
Return HttpResponse when the endpoint must choose a status, add headers, or
build a body explicitly. For example, a future create endpoint can use
HttpResponse::Created().json(¬e), while a delete endpoint can return
HttpResponse::NoContent().build().
Option<T> is convenient for a lookup: Some(value) uses the value’s
responder, and None becomes 404 Not Found. Result<T, E> separates a
successful responder from an error that implements WebResponseError for
your application’s error domain. Neither wrapper changes how routes match.
For extraction, custom response types, and error handling, continue with
Extractors and Responders and
Web Application Errors.
Choosing a Registration Style
Use App::route() for a small endpoint. Choose an explicit Resource when
one path has several methods or needs a name. A resource also lets you attach
middleware, filters, or a fallback to that path.
Use a Scope when several resources share a path prefix or policy.
web::service() is a lower-level option for code that already implements an
ntex service over WebRequest. Most handler-based applications do not need it.
Builder Order
Configure application-wide settings before registering services. The App
builder has two phases:
- In the settings phase, use
middleware()andfilter()to add layers. Set routing behavior withcase_insensitive_routing(), attach configuration withwith_config(), and register external URLs withexternal_resource(). - The first call to
route(),service(),configure(), ordefault_service()starts service registration. After that, onlyroute(),service(), anddefault_service()are available.
use ntex::web::{self, HttpResponse};
let app = web::App::<()>::new()
// Application-wide settings
.case_insensitive_routing()
.external_resource("docs", "https://docs.example.com/{page}")
// Service registration
.route("/", web::get().to(async || HttpResponse::Ok()))
.default_service(web::to(async || HttpResponse::NotFound()));
Calling a setting such as external_resource() after route() does not
compile. The same ordering rule applies to Scope settings. Add guards with
guard() before registering services. Add layers with middleware() and
filter(), and set case_insensitive_routing() in that phase too.
How Routing Works
Routing chooses a resource by its path and guards, then chooses a route within that resource. Request-target settings control which form of the path reaches the router.
Request-target validation and normalization
You can validate request targets before they reach your application and normalize them before routing. Validation and normalization are both disabled by default for HTTP/1 and HTTP/2.
With these defaults, routing sees the original path structure.
/a/../users does not automatically match /users. The router still decodes
individual segments for matching and parameters, so /%75sers can match
/users. The request URI keeps its original percent-encoding and query
spelling.
Malformed targets can reach application code in this mode. HTTP message
framing, mandatory HTTP/2 pseudo-header checks, UTF-8 and representation limits
remain enforced. HTTP/1 also rejects raw non-ASCII bytes in the request target
with 400 Bad Request; clients must percent-encode them.
HTTP/1 Host-header validation is separate and also disabled by default. Enable
it with HttpServiceConfig::set_host_validation(true). Requests with more than
one Host header and HTTP/1.1 requests without one are always rejected with
400 Bad Request.
Enable validation and normalization together in the HTTP service configuration
passed to the listener. For example, pass this configuration to
web::server(...).bind(...):
use ntex::{SharedCfg, http::HttpServiceConfig};
let config = SharedCfg::new("HTTP")
.add(HttpServiceConfig::new().set_request_target_normalization(true));
With normalization enabled, ntex first validates target syntax and method-specific forms during HTTP/1 and HTTP/2 decoding. It then normalizes percent-encoding, dot segments, scheme, host and port. All application layers see the normalized target, including middleware, filters, guards, nested scopes, handlers and the application fallback.
If ntex cannot validate or normalize the target within the URL length limit,
it returns 400 Bad Request. This happens before application middleware or
filters run.
The same setting applies to lower-level HttpService handlers without an App.
Normalization does not redirect clients or merge duplicate slashes. Application rewrites are not automatically validated or normalized again before routing. Test request builders bypass transport decoding and preserve raw targets.
For explicit processing, use the public urly::Url::validate_target() and
urly::Url::normalize() APIs. Callers must also enforce method-specific forms.
Enable validation alone to reject malformed targets while keeping valid ones byte-for-byte. This is useful in proxies or when verifying signatures over the raw target:
use ntex::{SharedCfg, http::HttpServiceConfig};
let config = SharedCfg::new("HTTP")
.add(HttpServiceConfig::new().set_request_target_validation(true));
Validation-only mode performs the same syntax and method-form checks. Failures
return the same 400 Bad Request. A valid target such as /%41/../b reaches
the application unchanged.
Normalization always validates first. The validation setting therefore has no effect while normalization is enabled.
Routing stages
A request moves through the application in several stages:
- Application middleware wraps the application service.
- Application filters process the incoming
WebRequest. - The application router finds a
Resourcewhose path and resource guards match. - Resource middleware wraps the selected resource’s filter and routes.
- The resource filter processes the request.
- The resource checks its routes in registration order. A route matches only if all its method and custom guards pass.
- The first matching route calls its handler.
Middleware can return a response without calling the service it wraps. When that happens, ntex skips every later stage.
Where routing stops determines which fallback runs:
- If no resource path-and-guard combination matches, the application default
service runs. The built-in application default returns
404 Not Found. - If a resource path matches but none of its routes match, the resource
default service runs. The built-in resource default returns
405 Method Not Allowed. - Resource fallbacks are independent of application and scope fallbacks.
use ntex::web::{self, HttpResponse};
let app = web::App::<()>::new()
.service(
web::resource("/reports")
.route(web::get().to(async || HttpResponse::Ok()))
.default_service(
web::to(async || HttpResponse::MethodNotAllowed()),
),
)
.default_service(
web::to(async || HttpResponse::NotFound().body("Unknown path")),
);
Guards restrict which requests a resource or route accepts. Resource guards help the application router choose a resource. Route guards run after that choice. They can check methods, headers, or custom conditions:
use ntex::http::Method;
use ntex::web::{self, guard, HttpResponse};
let app = web::App::<()>::new().service(
web::resource("/events").route(
web::route()
.method(Method::POST)
.guard(guard::Header("content-type", "application/json"))
.to(async || HttpResponse::Accepted()),
),
);
Guards receive only the request head, so they can check methods, headers, and other request metadata. They cannot inspect the body or values produced by extractors. Use a filter, extractor, or handler for those checks.
The guard’s location determines what happens when the method does not match:
App::route("/reports", web::get().to(handler))uses the application fallback for a non-GETrequest. The method guard belongs to the generated resource.Scope::route()behaves the same way.web::resource("/reports").route(web::get().to(handler))first selects the resource by path. If its method guard fails, it uses the resource’s default405 Method Not Allowedresponse.
Use guards for routing decisions, not as the only authentication check. A
header guard answers “does this resource match?”; it does not produce an
explanation or automatically return 401 Unauthorized. A failed guard can
let the router choose another resource or a fallback. For the notes API,
keep public and private resource selection separate from checking a user’s
credentials. An authentication filter or middleware can reject a request
with an intentional status; see
Filters and Middleware.
You can combine conditions with guard::Any(first).or(second),
guard::All(first).and(second), and guard::Not(condition). For a condition
not covered by the built-ins, guard::fn_guard() accepts a closure over the
request head. Keep that closure quick and synchronous: body parsing and
asynchronous database checks belong later in the pipeline.
Order Matters
Put specific patterns before broad dynamic or remainder patterns. ntex checks resources and scopes in registration order. The first matching path whose guards pass wins. Routes inside a resource follow the same rule:
use ntex::web::{self, App};
let app = App::default()
.service(web::resource("/files/status").to(async || "ready"))
.service(web::resource("/files/{path}*").to(async || "file"));
If you reverse these registrations, the remainder resource handles
/files/status. Add an unguarded route with Resource::to() after guarded
routes for the same reason. Once it matches, later routes cannot be reached.
Use App::middleware() to wrap the whole application. Use App::filter() to
transform every incoming WebRequest before routing. Resources and scopes
offer the same methods when the behavior should apply to only part of the
application. See
Web Application Filters and Middleware for details.
Route Path Format
Use route patterns to match fixed paths or capture parts of a path. Patterns
contain static and dynamic segments separated by /. ntex adds a leading
/ to resource and scope paths when needed. Include it yourself to make the
full route easier to read.
Static Paths
A static pattern matches the same path:
/users
/users/profile
Trailing slashes matter: /users and /users/ are different paths. Query
strings are not included in path matching.
Routing is case-sensitive by default. Use App::case_insensitive_routing()
to make static path segments ASCII case-insensitive. This does not change how
dynamic segments match. Scopes can enable the same behavior for their nested
routes.
Dynamic Segments
Write a dynamic segment as {name}. It matches one non-empty path segment:
/users/{id}
/teams/{team}/users/{user}
You can combine variables with static text or use several variables in one segment:
/releases/v{major}.{minor}
/files/{name}.{extension}
Add a regular expression as {name:regex} to restrict what a variable
accepts:
/users/{id:[0-9]+}
/releases/{version:v[0-9]+\.[0-9]+}
The regular expression must match the whole segment. Invalid route patterns and regular expressions panic while the application is built. Define routes as trusted application configuration; do not build them from user input.
Remainder Matches
Add * after a dynamic variable to capture the rest of the path, including
/ separators:
/files/{path}*
This matches both /files/readme.txt and /files/images/logo.svg. The path
value is readme.txt in the first case and images/logo.svg in the second.
The default expression is .*, so the captured value may be empty. Remainder
matches cannot use a custom regular expression.
A remainder value keeps its percent-encoding. A request for
/files/my%20file.txt captures my%20file.txt. Decode it yourself if the
handler needs the decoded path. Validate the value before using it as a file
system path.
Static tail patterns such as /files/* also work, but a named remainder is
usually clearer and works naturally with typed path extraction.
Multiple Patterns
A resource or scope can use an array or vector to accept several patterns:
use ntex::web::{self, HttpResponse};
let app = web::App::<()>::new()
.service(
web::resource(["/health", "/status"])
.to(async || HttpResponse::Ok()),
);
Every pattern points to the same service.
When a multi-pattern resource is named, URL generation uses its first pattern. Put the canonical path first and treat the remaining patterns as aliases.
Accessing Path Variables
Use the typed Path extractor to read variables captured by a route:
use ntex::web::{self, HttpResponse};
async fn user(path: web::types::Path<(u32,)>) -> HttpResponse {
let user_id = path.0;
HttpResponse::Ok().body(format!("user {user_id}"))
}
let app = web::App::<()>::new().route(
"/users/{id:[0-9]+}",
web::get().to(user),
);
Tuples deserialize variables in path order. To access variables by name, use a
struct that derives serde::Deserialize:
use ntex::web::{self, HttpResponse};
#[derive(serde::Deserialize)]
struct UserPath {
organization: String,
user_id: u32,
}
async fn user(path: web::types::Path<UserPath>) -> HttpResponse {
HttpResponse::Ok().body(format!(
"organization: {}, user: {}",
path.organization,
path.user_id,
))
}
let app = web::App::<()>::new().route(
"/organizations/{organization}/users/{user_id:[0-9]+}",
web::get().to(user),
);
The struct fields must have the same names as the route variables. This
example requires the derive feature from serde.
For a notebook URL such as /notebooks/{notebook}/notes/{id}, a single
Path<(String, u32)> reads both captures. A struct with notebook: String
and id: u32 makes the relationship clearer as the route grows. Do not split
this into separate Path arguments expecting each to consume a capture:
each extractor reads the request’s full set of path variables.
A pattern restriction and a Rust type check solve different problems. The
pattern /notes/{id:[0-9]+} rejects letters during routing, but a long string
of digits can still overflow u32 during extraction. With DefaultError, a
failed Path extraction produces 404 Not Found, and the handler is not
called. Use a domain check in the handler for valid numbers that have no
meaning in your application, such as a notebook ID the user cannot access.
You can also read variables directly from HttpRequest::match_info():
use ntex::web::{self, HttpRequest};
async fn file(req: HttpRequest) -> String {
req.match_info()
.get("path")
.unwrap_or_default()
.to_owned()
}
let app = web::App::<()>::new().route(
"/files/{path}*",
web::get().to(file),
);
ntex splits the path into segments before percent-decoding normal dynamic
variables. It stores those decoded values in the request’s match information.
An encoded slash such as %2F can therefore appear inside a decoded variable.
Escapes that are not valid UTF-8 remain percent-encoded. Remainder values stay
as they appear in the request path.
Path values are untrusted input. A variable that looked like one URL segment
can decode to ../ or contain /. Validate it before using it as a file name,
database key, or other identifier with stricter rules.
Scopes
A Scope groups related services under a shared path prefix:
use ntex::web::{self, HttpResponse};
let app = web::App::<()>::new().service(
web::scope("/api")
.service(
web::resource("/users")
.route(web::get().to(async || HttpResponse::Ok())),
)
.service(
web::resource("/users/{id}")
.route(web::get().to(async || HttpResponse::Ok())),
),
);
These resources match /api/users and /api/users/{id}. You can nest scopes
and use variables in their prefixes. Nested handlers can access those
variables:
use ntex::web::{self, HttpResponse};
let app = web::App::<()>::new().service(
web::scope("/organizations/{org}")
.route(
"/users/{user}",
web::get().to(
async |path: web::types::Path<(String, String)>| {
HttpResponse::Ok()
.body(format!("{}:{}", path.0, path.1))
},
),
),
);
A scope prefix matches complete path segments. scope("/api") can contain
routes below /api/; it never matches /apix. The scope alone does not
provide a handler for the bare /api path. Inside it, an empty resource
pattern ("") matches /api, while "/" matches /api/:
use ntex::web::{self, HttpResponse};
let app = web::App::<()>::new().service(
web::scope("/api")
.route("", web::get().to(async || HttpResponse::Ok().body("/api")))
.route("/", web::get().to(async || HttpResponse::Ok().body("/api/"))),
);
A scope can have its own guards, middleware, and filters. It can also have its own case-sensitivity setting and fallback service.
Once a scope matches, unmatched paths inside it use the scope fallback.
Without a custom scope fallback, ntex returns its built-in 404 Not Found.
It does not use the application fallback.
Named and External Resources
Give a resource a name when handlers need to link to it without hard-coding its path:
use ntex::web::{self, HttpRequest, HttpResponse, error::UrlGenerationError};
async fn index(req: HttpRequest) -> Result<HttpResponse, UrlGenerationError> {
let url = req.url_for("user", ["42"])?;
Ok(HttpResponse::Ok().body(url.to_string()))
}
let app = web::App::<()>::new()
.service(
web::resource("/users/{id}")
.name("user")
.route(web::get().to(async || HttpResponse::Ok())),
)
.route("/", web::get().to(index));
Here, the index handler generates an absolute URL such as
http://some-host-name/users/42.
HttpRequest::url_for() returns a ntex::url::Url. Values fill dynamic
segments in pattern order. For a resource inside a scope, supply values for
dynamic scope segments before values for the resource itself.
Use HttpRequest::url_for_static() when the pattern has no dynamic segments.
Each value is percent-encoded as one literal segment. URL delimiters in a
value cannot change the generated URL’s structure.
Keep resource names unique across the application, including across scopes. Names are application-wide lookup keys. With duplicate names, generated links depend on which definition is found.
Generation can fail if the name is unknown, too few values are supplied, or
the completed URL is invalid. Return UrlGenerationError from your handler,
as above, to avoid panicking on those errors.
For an application resource, the request’s ConnectionInfo supplies the
scheme and host. The resource and its containing scopes supply the path.
ConnectionInfo uses forwarding headers only when your configured
ForwardedPolicy allows them; the default policy ignores them. If you enable
trust for a front-end proxy, have that proxy replace or correctly append to
client-supplied forwarding headers before exposing generated URLs to clients.
Without trusted forwarding information, the request target, Host, and
server configuration supply connection information.
Use App::external_resource() to name a URL outside the application. Register
it before the first route or service. You can also register it inside
App::configure() through ServiceConfig::external_resource():
use ntex::web::{self, HttpRequest, HttpResponse, error::UrlGenerationError};
async fn docs(req: HttpRequest) -> Result<HttpResponse, UrlGenerationError> {
let url = req.url_for("documentation", ["page1.html"])?;
Ok(HttpResponse::Ok().body(url.to_string()))
}
let app = web::App::<()>::new()
.external_resource(
"documentation",
"https://docs.example.com/{page}",
)
.route("/docs", web::get().to(docs));
The docs handler generates https://docs.example.com/page1.html. The
external pattern supplies its own scheme and host, so generation does not use
the request’s connection information. External resources are URL templates
only. They do not participate in request routing.
Modular Configuration
Split route registration into functions when one builder chain becomes hard
to read. App::configure() passes a ServiceConfig to a function so it can
register part of the application:
use ntex::web::{self, HttpResponse};
fn configure_api(cfg: &mut web::ServiceConfig) {
cfg.route(
"/health",
web::get().to(async || HttpResponse::Ok()),
);
cfg.service(
web::resource("/version")
.to(async || HttpResponse::Ok().body("4")),
);
}
let app = web::App::default()
.configure(configure_api)
.route("/", web::get().to(async || HttpResponse::Ok()));
ServiceConfig can register routes, services, and external resources. These
items join the application at the point where you call configure(). The
callback does not create another routing boundary.
Both applications and scopes support modular configuration.
In the notes application, notes::configure is mounted on the versioned
scope rather than on App. That makes /api/v1 a real routing boundary with
its own fallback, while the callback itself remains only a registration
helper. A sibling accounts::configure could register another group inside
that scope. Because calling configure() starts service registration, attach
shared middleware and filters to the scope before calling it.
The callback’s type must match the application state. The default
ServiceConfig means ServiceConfig<(), ()>. When you introduce a named
state type, change it to ServiceConfig<ApplicationState>. If a module does
not depend on a particular application state, give the callback a generic
St: web::State and accept &mut web::ServiceConfig<St>. A callback behind a
state-changing filter must also name the resulting request-state type as
its second type argument. These types connect the module to its surrounding
pipeline; they do not create or clone state.
Testing Routes
Test routes without opening a network socket. Use web::test to initialize
an App, send requests to it, and inspect the responses:
use ntex::http::StatusCode;
use ntex::web::{self, HttpResponse};
use ntex::web::test::{TestRequest, call_service, init_service};
#[ntex::test]
async fn user_route() {
let service = init_service(
web::App::new().route(
"/users/{id}",
web::get().to(async || HttpResponse::Ok()),
),
)
.await;
let request = TestRequest::get()
.uri("/users/42")
.to_request();
let response = call_service(&service, request).await;
assert_eq!(response.status(), StatusCode::OK);
}
Test method mismatches and trailing slashes as well as successful requests. Cover dynamic-variable constraints, scope boundaries, and fallback services. Each exercises a different part of route selection.
A Routing Regression Test
A small table-driven test can capture the routing contract before you add
more handlers. Here, status must reach the static route, an unsupported
method must use the resource’s 405, and the scope must keep its own 404:
use ntex::http::{Method, StatusCode};
use ntex::web::{self, test, types::Path};
#[ntex::test]
async fn notes_routing_contract() {
let app = test::init_service(
web::App::new().service(
web::scope("/api/v1")
.service(
web::resource("/notes/status")
.route(web::get().to(async || "ready")),
)
.service(
web::resource("/notes/{id}").route(web::get().to(
async |id: Path<u32>| format!("note {}", id.into_inner()),
)),
),
),
)
.await;
for (method, path, expected) in [
(Method::GET, "/api/v1/notes/status", StatusCode::OK),
(Method::GET, "/api/v1/notes/12", StatusCode::OK),
(Method::GET, "/api/v1/notes/not-a-number", StatusCode::NOT_FOUND),
(Method::POST, "/api/v1/notes/12", StatusCode::METHOD_NOT_ALLOWED),
(Method::GET, "/api/v1/missing", StatusCode::NOT_FOUND),
] {
let request = test::TestRequest::with_uri(path)
.method(method)
.to_request();
let response = test::call_service(&app, request).await;
assert_eq!(response.status(), expected, "{path}");
}
}
This test exercises the application service, not an actual HTTP connection.
It deliberately includes an extraction failure as well as a routing failure:
both return 404, but take different paths through the application. For
requests with bodies and JSON assertions, see Testing.
Lower-Level HTTP Service
Use the lower-level server builder when you need connection-level services
before HttpService. These services can inspect or transform the Io
object. They can also map the state passed to the HTTP and application
services.
For most applications, start a server with web::server(factory). It is
equivalent to web::HttpServer::new(factory).
After you register routes and services, the application builder can become a
service factory. This factory converts http::Request values into
http::Response values. HttpService uses it to handle HTTP/1.1 and HTTP/2
connections.
Here is the same server built at the lower level:
use ntex::{http, server, web, SharedCfg};
use ntex::web::HttpResponse;
#[ntex::main]
async fn main() -> std::io::Result<()> {
server::build()
.bind("http", "127.0.0.1:8080", SharedCfg::new("S"), async |_| {
http::HttpService::new(
web::App::new()
.route("/", web::get().to(async || {
HttpResponse::Ok().body("Hello")
}))
.build(),
)
})?
.run()
.await
}
To give the web application its own state instead of the surrounding service pipeline’s state, see Web Application State.
Web Application State
Application state makes your services and configuration available throughout
a web application. A web::App has an application state type and usually
inherits its value from the surrounding server or service pipeline. Handlers,
extractors, filters, middleware, and error responses can all use that value.
ntex distinguishes two kinds of state:
- Application state is the state supplied by the service pipeline. A
worker’s value is cloned for each connection, and handlers borrow that
connection’s clone. Data that must be shared between connections belongs
behind a shared handle such as
Rc. - Request-local state belongs to one request. It is owned by
WebRequest, can change type as the request moves through filters and middleware, and can be moved into a state-aware handler.
For worker initialization and process-wide versus worker-local data, see Worker and request state. For the underlying service-state model, see Service state.
The web::State Trait
Implement web::State to use your type as application state and choose its
error domain:
pub trait State: 'static {
type Error;
}
The trait has no methods. Its associated Error type defines the application’s
error domain. Handlers, filters, middleware, and fallback services use this
error type through WebError and WebResponseError.
Most applications can use DefaultError:
use ntex::web;
#[derive(Clone)]
struct ApplicationState {
greeting: String,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
web::State itself does not require Clone. State used with the built-in
HTTP server must implement it, though. ServerAppConfig::State requires
Clone, as does state passed to build_with().
HttpService clones the connection state when creating each connection’s
application service. You can use a non-Clone state type directly with an
application factory. You cannot pass it through these server paths.
Inheriting Worker State
Use web::server_with_config() to initialize state for each worker. It
creates one value per worker and passes it to that worker’s application
factory. The returned App uses the same state type:
use std::io;
use ntex::{SharedCfg, web};
/// State created independently for each worker.
#[derive(Clone)]
struct ApplicationState {
greeting: String,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
/// Process-wide factory used to create worker state.
struct ApplicationConfig;
impl ntex::server::ServerAppConfig for ApplicationConfig {
type State = ApplicationState;
async fn create(&self) -> io::Result<Self::State> {
Ok(ApplicationState {
greeting: "Hello".to_owned(),
})
}
}
async fn index(state: &ApplicationState, _request_state: ()) -> String {
state.greeting.clone()
}
#[ntex::main]
async fn main() -> io::Result<()> {
web::server_with_config(ApplicationConfig, async |_| {
web::App::new().route("/", web::get().to_with_state(index))
})
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
Every request handled by a worker can access its state through the service
context. Each connection receives its own clone of the worker state. Put
values that all connections on a worker should share, such as caches or
counters, behind Rc. See
Worker-Local and Process-Wide
State
for details.
Design State for Cheap Cloning
Keep application state cheap to clone because each connection gets a clone. A small collection of handles avoids copying large data structures:
use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::Arc};
use ntex::web;
#[derive(Clone)]
struct ApplicationState {
worker_cache: Rc<RefCell<HashMap<String, String>>>,
shared_settings: Arc<Settings>,
}
struct Settings {
service_name: String,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
Connections on the same worker share worker_cache. All workers can also
share the thread-safe shared_settings value. To share it, the configuration
factory must give each worker a clone of the same Arc.
Handlers receive &ApplicationState. To change data, you normally use a
client handle or an interior-mutable value. That value might use Cell,
RefCell, a lock, or an atomic.
Keep RefCell borrows short. Do not hold them across an .await: unrelated
work could try to borrow the same value and panic.
One Counter per Worker, One Counter for the Process
Suppose the notes API needs a request count for each worker and a total for
this server process. Use Rc<Cell<usize>> for the worker count and an
Arc<AtomicUsize> for the total. Create the Rc inside create(), but put
the Arc in the process-wide configuration so every worker clones the same
handle:
use std::{
cell::Cell,
io,
rc::Rc,
sync::{Arc, atomic::{AtomicUsize, Ordering}},
};
use ntex::{SharedCfg, web};
#[derive(Clone)]
struct Counters {
worker_hits: Rc<Cell<usize>>,
total_hits: Arc<AtomicUsize>,
}
impl web::State for Counters {
type Error = web::DefaultError;
}
struct CounterConfig {
total_hits: Arc<AtomicUsize>,
}
impl ntex::server::ServerAppConfig for CounterConfig {
type State = Counters;
async fn create(&self) -> io::Result<Counters> {
Ok(Counters {
worker_hits: Rc::new(Cell::new(0)),
total_hits: self.total_hits.clone(),
})
}
}
async fn count(state: &Counters, (): ()) -> web::HttpResponse {
let worker = state.worker_hits.get() + 1;
state.worker_hits.set(worker);
let total = state.total_hits.fetch_add(1, Ordering::Relaxed) + 1;
web::HttpResponse::Ok().json(&serde_json::json!({
"worker_hits": worker,
"total_hits": total,
}))
}
#[ntex::main]
async fn main() -> io::Result<()> {
let config = CounterConfig {
total_hits: Arc::new(AtomicUsize::new(0)),
};
web::server_with_config(config, async |_| {
web::App::new().route("/count", web::get().to_with_state(count))
})
.workers(2)
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
Each connection clones Counters, but cloning the two handles does not
reset their contents. Connections assigned to one worker share its local
count. Connections assigned to another worker use a different local count,
while both update the same total. Here the counter measures calls to
/count, not all traffic; move the increment into an application filter
when every request should count.
Ordering::Relaxed is enough for an independent statistic: the atomic
increment needs no relationship to other shared data. It does not turn the
two JSON fields into an atomic snapshot. Other workers can update the total
while this handler builds its response. A process-wide count also is not a
fleet-wide count; another server process has its own memory.
An Rc cannot cross worker threads. Capturing one in the outer server
factory will fail the factory’s Send requirement, and putting it in the
configuration will fail ServerAppConfig’s Send + Sync bounds. Creating it
inside create() is the intended way to get worker-local sharing. Conversely,
creating a new Arc inside each create() call gives separate counters,
not one global counter. Sharing depends on where you allocate the value,
not merely on which pointer type you choose.
For shared structured data, an Arc<Mutex<Cache>> can protect a cache used
across workers. Keep the critical section short and release its guard before
an .await; a standard mutex blocks the worker thread while waiting. A
worker-local Rc<RefCell<Cache>> avoids cross-thread locking, but each worker
has an independent cache and still needs short borrow scopes.
Database Pools and Other Client Handles
Treat a database pool as a long-lived application dependency, not something
to create for each request. Place the driver’s pool handle in your state and
borrow it from a to_with_state() handler. The handler can then await a query
through the pool without rebuilding the connection configuration.
Choose its placement from the driver’s actual guarantees. A thread-safe,
cheaply cloned pool can be created once and supplied to each worker through
the configuration. A thread-local client belongs in the worker’s create()
method. If each worker creates its own pool, budget the database connection
limit across all those pools rather than treating a per-pool limit as a
process limit. The framework does not select a database driver or create a
pool for you.
Do asynchronous connection checks or other fallible startup work in
ServerAppConfig::create(), which returns io::Result. Connection-level
state cloning should copy a handle, not open a new pool. A plain Vec<Note>
or HashMap field is cloned by value, so putting one directly in a Clone
state type does not create shared storage. Wrap mutable in-memory storage in
the appropriate shared handle before passing it to the server.
Accessing Application State in Handlers
Use Route::to_with_state() when a handler needs direct access to state.
For a resource route without a method guard, use Resource::to_with_state().
The handler receives its arguments in this order:
- A shared reference to the application state.
- The request-local state.
- Any request extractors.
use ntex::web;
#[derive(Clone)]
struct ApplicationState {
service_name: &'static str,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
async fn user(
state: &ApplicationState,
_request_state: (),
user_id: web::types::Path<u32>,
) -> String {
format!("{} user {}", state.service_name, user_id.into_inner())
}
fn main() {
let app = web::App::<ApplicationState>::new().route(
"/users/{user_id}",
web::get().to_with_state(user),
);
}
Filters, middleware, and lower-level services access application state through
their service Ctx.
Handlers registered with Route::to() receive only request extractors. Use
to() when the handler does not need application or request-local state.
Extractors receive a shared reference to application state through
FromRequest. Your custom extractors can use it to access application
services or configuration.
Extractors do not receive request-local state. Only to_with_state() supplies
that value, as a separate handler argument.
Sharing State with Filters and Middleware
The handler does not need to own every cross-cutting operation. A resource
filter can update a request counter, while application middleware labels the
response. In a from_fn() closure, next.st() is the application’s state;
req.st() would be the request-local value instead.
This test shows all three access paths together:
use std::{cell::Cell, convert::Infallible, rc::Rc};
use ntex::http::header::{HeaderName, HeaderValue};
use ntex::web::{self, middleware::{Next, from_fn}, test, WebRequest};
#[derive(Clone)]
struct ApplicationState {
name: &'static str,
hits: Rc<Cell<usize>>,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
async fn count_request(
state: &ApplicationState,
req: WebRequest<()>,
) -> Result<WebRequest<()>, Infallible> {
state.hits.set(state.hits.get() + 1);
Ok(req)
}
async fn index(state: &ApplicationState, (): ()) -> String {
format!("{} requests: {}", state.name, state.hits.get())
}
#[ntex::test]
async fn layers_use_the_same_state() {
let state = ApplicationState {
name: "notes",
hits: Rc::new(Cell::new(0)),
};
let app = test::init_service_st(
state.clone(),
web::App::new()
.middleware(from_fn(async |req, next: Next<'_, _, ApplicationState>| {
let name = next.st().name;
let mut response = next.call(req).await?;
response.headers_mut().insert(
HeaderName::from_static("x-application"),
HeaderValue::from_static(name),
);
Ok(response)
}))
.service(
web::resource("/")
.filter(count_request)
.route(web::get().to_with_state(index)),
),
)
.await;
let response = test::call_service(
&app, test::TestRequest::get().uri("/").to_request(),
).await;
assert_eq!(response.headers().get("x-application").unwrap(), "notes");
assert_eq!(test::read_body(response).await, "notes requests: 1");
assert_eq!(state.hits.get(), 1);
}
The Next annotation gives Rust the state type it needs for field access.
For a full middleware service, use ctx.st() instead. You are borrowing the
same application state in each case, not retrieving values from
HttpRequest extensions. See
Filters and Middleware for deciding which layer should own
the operation.
Request-Local State
Use request-local state for data produced while processing a request, such as authentication details. It belongs to one request. Application state is long-lived and shared across requests.
WebRequest carries request-local state. The type parameter in
WebRequest<RequestState> is the state type. An ordinary web request starts
with ().
A filter or middleware can keep the value or mutate it through
WebRequest::st_mut(). To replace it with another type, use
WebRequest::map_state(). A handler registered with to_with_state()
receives the result as its second argument:
use std::convert::Infallible;
use ntex::web::{self, WebRequest};
#[derive(Clone)]
struct ApplicationState {
service_name: &'static str,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
async fn index(state: &ApplicationState, user_id: usize) -> String {
format!("{} user {user_id}", state.service_name)
}
fn main() {
let app = web::App::<ApplicationState>::new()
.filter(async |req: WebRequest<()>| {
// Authentication could produce this request-local value.
Ok::<_, Infallible>(req.map_state(|()| 42usize))
})
.route("/", web::get().to_with_state(index));
}
Request-local state moves through the filter and middleware chain. Changing
the state also changes the WebRequest type expected by the next service.
Rust checks this pipeline at compile time. For example, a handler expecting
AuthInfo can only follow a filter or middleware that produces
WebRequest<AuthInfo>.
Inside filters and middleware, WebRequest::st() returns request-local
state. Use WebRequest::st_mut() for mutable access. Application state comes
from the service context.
map_state() consumes the previous value. If later stages need some of the
old information, include it in the new state:
struct Authenticated {
user_id: usize,
}
struct Validated {
user: Authenticated,
request_id: String,
}
Application filters affect every route. A scope or resource filter can create state needed only by that part of the application. Unrelated handlers then have no dependency on that state.
Request-local state is not stored in HttpRequest extensions. Request
extractors cannot read it. Use to_with_state() when the final handler needs
the value. A handler registered with to() ignores and drops it.
Complete web application state example
Typed Web Configuration Is Separate
Use WebAppConfig for HTTP-facing configuration, especially extractor
limits and settings read from a request. Populate its typed value store with
set_value().
These values are separate from application service state. Service state such
as AppState<T> is not part of the store. Keep services and resources that
participate in the service lifecycle in application state. Store typed web
configuration in WebAppConfig.
- Read configuration values through
HttpRequest::app_value()orWebRequest::app_value(). to_with_state()does not pass them as its first argument.- Values must be
Send + Sync. Worker-local state may containRcandRefCellinstead. - The store holds one value for each concrete type.
Here, the handler reads a configured limit from the request:
use ntex::web::{self, App, HttpRequest, WebAppConfig};
struct Limits {
max_items: usize,
}
async fn limits(req: HttpRequest) -> String {
let max_items = req
.app_value::<Limits>()
.map_or(100, |limits| limits.max_items);
format!("maximum items: {max_items}")
}
let config = WebAppConfig::new().set_value(Limits { max_items: 50 });
let app = App::default()
.with_config(config)
.route("/limits", web::get().to(limits));
Supplying Fixed State with .build_with()
Use AppServices::build_with() when your web application needs its own
state and the surrounding HTTP or server pipeline uses different state or
none.
The application builder becomes AppServices after the first call to
route(), service(), configure(), or default_service(). See
Builder Order. Finish building it with either
build() or build_with().
build() uses state from the surrounding service pipeline.
build_with(state) gives the application its own fixed state. The outer
pipeline can then use a different state type:
use ntex::web::{self, HttpResponse};
#[derive(Clone)]
struct ApplicationState {
greeting: &'static str,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
async fn index(state: &ApplicationState, _request_state: ()) -> HttpResponse {
HttpResponse::Ok().body(state.greeting)
}
fn main() {
let app = web::App::<ApplicationState>::new()
.route("/", web::get().to_with_state(index))
.build_with::<()>(ApplicationState {
greeting: "Hello",
});
}
In this standalone example, () is the outer pipeline’s state type. It is
normally inferred when you pass the application factory to HttpService.
Application state must implement Clone. build_with() clones it when
creating application service instances.
build_with() replaces the application’s state without adding another state
layer. Code outside the application keeps using the outer state. Web handlers
and application middleware receive the fixed state.
Use server_with_config() for asynchronous per-worker initialization or state
that should be recreated with a worker. Use build_with() to embed a ready
value in an application factory, especially when the surrounding HTTP pipeline
uses another state type.
The AppState<T> Wrapper
Use AppState<T> to wrap application state when you use DefaultError.
You do not need to write a web::State implementation.
The wrapper accepts any 'static T and dereferences to the wrapped value.
It implements Clone and Default whenever T does:
use ntex::web;
#[derive(Clone)]
struct Settings {
service_name: &'static str,
}
fn main() {
let state = web::AppState::new(Settings {
service_name: "users",
});
assert_eq!(state.service_name, "users");
assert_eq!(state.st().service_name, "users");
}
Use a dedicated state type and implement web::State directly when you need a
custom error type or other state-specific behavior.
AppState<T> does not change how values are cloned or shared. If T::clone()
copies a plain field, connections receive separate copies. If it clones an
Rc or Arc, they share the value behind that handle.
Testing Stateful Routes
Use test::init_service_st() to test an application with an explicit state
value. Keep a clone of a shared handle if your test needs to inspect what the
handler changed:
use std::{cell::Cell, rc::Rc};
use ntex::web::{self, test};
#[derive(Clone)]
struct ApplicationState {
hits: Rc<Cell<usize>>,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
async fn index(state: &ApplicationState, (): ()) -> &'static str {
state.hits.set(state.hits.get() + 1);
"ok"
}
#[ntex::test]
async fn state_is_used() {
let state = ApplicationState {
hits: Rc::new(Cell::new(0)),
};
let service = test::init_service_st(
state.clone(),
web::App::<ApplicationState>::new()
.route("/", web::get().to_with_state(index)),
)
.await;
let request = test::TestRequest::get().uri("/").to_request();
let _response = test::call_service(&service, request).await;
assert_eq!(state.hits.get(), 1);
}
Web Application Filters and Middleware
Use filters and middleware to add behavior around your handlers. A web
application is a service that accepts an HTTP request, passes it through the
configured pipeline, and returns a WebResponse. Like the rest of ntex,
this pipeline uses Service and Middleware.
Filters and middleware work at different points in that pipeline:
- A filter transforms an incoming
WebRequestbefore processing continues. - Middleware wraps a service, so it can run code both before and after that service.
Both can use application state. Middleware services receive it through
Ctx. A filter function can take it as its first argument. For the
distinction between application state and request-local state, see
Web Application State.
Choosing Between Them
For the notes API, keep path matching in routes and shared request policies
in layers. A filter is a good place to turn credentials into a typed user
value that handlers need. Middleware is a better fit for timing a complete
operation, adding response headers, or serving a cached response.
from_fn() is not a third kind of layer: it is a convenient way to write
middleware without defining a wrapper struct.
Start with a closure for a small policy. Move to a named middleware type when configuration or service lifecycle behavior becomes substantial. You can attach either form to just the API scope, leaving a health check or public page outside that policy.
Filters
Use a filter to transform an incoming request before processing continues.
Register application filters with App::filter(). For scopes and resources,
use Scope::filter() and Resource::filter().
Each call appends a service to the inbound pipeline. A filter accepts
WebRequest<In> and must return WebRequest<Out>:
WebRequest<In> -> filter -> WebRequest<Out>
Filters run in registration order. Each receives the previous filter’s
output. If a filter returns an error, ntex skips the remaining filters,
router, and handler. It renders the error through WebResponseError.
Request state is part of the WebRequest type, so filters can enforce
requirements at compile time. An authentication filter can turn
WebRequest<()> into WebRequest<AuthenticatedUser>. A handler expecting
AuthenticatedUser can only be registered after a filter that provides it:
use std::convert::Infallible;
use ntex::web::{self, WebRequest};
struct AuthenticatedUser {
id: u64,
}
async fn authenticate(
req: WebRequest<()>,
) -> Result<WebRequest<AuthenticatedUser>, Infallible> {
Ok(req.map_state(|()| AuthenticatedUser { id: 42 }))
}
async fn profile(_app: &(), user: AuthenticatedUser) -> String {
format!("User {}", user.id)
}
web::App::default()
.filter(authenticate)
.route("/profile", web::get().to_with_state(profile));
Here, application state is (). The first argument to profile is &().
Its second argument is the AuthenticatedUser produced by the filter.
WebRequest::map_state() consumes the request, transforms its request-local
state, and preserves the HTTP request and payload.
Extractors run only in the handler, so a filter sees the request body as a raw payload stream. It can replace that stream, for example to limit or decode every upload; see Streams in Filters and Middleware.
A filter can take application state as its first argument. It can return any
error that implements WebResponseError. The error stops processing and
becomes the response:
use ntex::web::{self, WebRequest, error};
fn main() {
let app = web::App::default()
.filter(async |_state: &(), req: WebRequest<()>| {
if req.headers().contains_key("x-api-key") {
Ok(req)
} else {
Err(error::ErrorForbidden("missing API key"))
}
})
.route("/", web::get().to(async || "Hello"));
}
Filters run only on the way in. They cannot inspect or modify the handler’s response. Use middleware to wrap the complete request-response operation.
A filter’s successful output must be another WebRequest; it cannot return a
successful response directly. Return an error to reject a request. Use
middleware to return a response without running the inner service, such as
for a cache hit, maintenance page, or authorization decision.
Middleware
Use middleware when you need to work with both requests and responses, or return a response without calling the inner service. A middleware component receives a service and wraps it with another service.
The wrapper can inspect or modify the request before calling the inner
service through Ctx. It can then inspect or modify the response.
Middleware can also change the request-state type before the call. A filter
is usually simpler if you only need to process the request.
Middleware also sees bodies as streams. The request body has not been read by an extractor yet, and the response body is sent after the middleware returns. Streams in Filters and Middleware shows how to wrap either one.
To skip the inner service, return a WebResponse directly. Use
WebRequest::into_response() to keep the original request attached to that
response.
Register middleware on the application with App::middleware(). The
corresponding methods on scopes and resources are Scope::middleware() and
Resource::middleware(). You can install built-in middleware directly:
use ntex::web::{self, App, middleware};
App::default()
.middleware(
middleware::DefaultHeaders::new()
.header("x-application", "example"),
)
.middleware(middleware::Logger::default())
.route("/", web::get().to(async || "Hello"));
Middleware runs in registration order on the way in. Here, DefaultHeaders
receives the request before Logger. The response travels in reverse order.
Logger processes it before DefaultHeaders.
DefaultHeaders inserts a header only if the response does not already have
one. Your handler can therefore override the default. Logger writes through
the log facade. Install and configure a logger to see its output.
For custom middleware, start with an async closure passed to
middleware::from_fn(). The closure receives the request and a Next
handle. Call next.call(req) to run the inner service, or return a response
without calling it to stop there.
Binding, readiness, and shutdown are forwarded automatically:
use ntex::http::header::{HeaderName, HeaderValue};
use ntex::web::{self, App, HttpResponse, middleware::from_fn};
web::HttpServer::new(async |_| {
App::new()
.middleware(from_fn(async |req, next| {
if !req.headers().contains_key("authorization") {
return Ok(req.into_response(HttpResponse::Unauthorized().build()));
}
let mut res = next.call(req).await?;
res.headers_mut().insert(
HeaderName::from_static("x-application"),
HeaderValue::from_static("example"),
);
Ok(res)
}))
.route("/", web::get().to(async || "Hello"))
});
Rust infers the closure types once you pass the application to HttpServer
or a test helper. To reject a request with any WebResponseError, return
Err(web::WebError::from_err(err)).
To read application state, annotate the state type of next. For example,
use next: Next<'_, _, AppState<Config>>, then call next.st().
fn_layer() from ntex::service is the protocol-independent equivalent.
It works for any service. Web closures used with it need explicit request,
response, and error types.
Checking an API Key and Returning 401
A missing credential should produce an intentional response, not merely fail
a route guard. This example compares the key’s value and returns 401 before
the handler runs. An outer DefaultHeaders layer labels both successful
responses and these early rejections:
use std::{cell::Cell, rc::Rc};
use ntex::http::StatusCode;
use ntex::web::{self, HttpResponse, middleware::{self, from_fn}, test};
#[ntex::test]
async fn api_key_is_required() {
let calls = Rc::new(Cell::new(0));
let handler_calls = calls.clone();
let app = test::init_service(
web::App::new()
.middleware(
middleware::DefaultHeaders::new()
.header("x-application", "notes"),
)
.middleware(from_fn(async |req, next| {
let valid = req.headers().get("x-api-key")
.and_then(|value| value.to_str().ok())
== Some("development-only");
if !valid {
return Ok(req.into_response(
HttpResponse::Unauthorized().body("API key required"),
));
}
next.call(req).await
}))
.route("/notes", web::get().to(async move || {
handler_calls.set(handler_calls.get() + 1);
"notes"
})),
)
.await;
for key in [None, Some("wrong"), Some("development-only")] {
let mut request = test::TestRequest::get().uri("/notes");
if let Some(key) = key {
request = request.header("x-api-key", key);
}
let response = test::call_service(&app, request.to_request()).await;
let expected = if key == Some("development-only") {
StatusCode::OK
} else {
StatusCode::UNAUTHORIZED
};
assert_eq!(response.status(), expected);
assert_eq!(response.headers().get("x-application").unwrap(), "notes");
}
assert_eq!(calls.get(), 1);
}
The hard-coded key is only a local demonstration. Load real credentials from application configuration or a secret store, do not log them, and protect them with HTTPS. A header’s presence alone is not authentication. If the handler needs the authenticated identity, use a filter that produces typed request-local state rather than repeating the credential check in each handler.
Returning Ok(req.into_response(...)) matters here: the rejection is already
a response as it travels through outer middleware. Returning an error is
also valid, but that error is normally rendered outside the application’s
response middleware, as described in
Errors and the Response Path.
Timing a Request
Measure around next.call() to observe how long the inner pipeline takes to
produce its response. Copy the metadata you need before moving the request
into that call. Here the middleware logs elapsed time and adds it to a header:
use std::time::Instant;
use ntex::http::header::{HeaderName, HeaderValue};
use ntex::web::{self, middleware::from_fn, test};
#[ntex::test]
async fn timing_adds_a_response_header() {
let app = test::init_service(
web::App::new()
.middleware(from_fn(async |req, next| {
let path = req.path().to_owned();
let started = Instant::now();
let result = next.call(req).await;
let elapsed = started.elapsed().as_micros();
log::info!("{path} completed in {elapsed} us");
let mut response = result?;
response.headers_mut().insert(
HeaderName::from_static("x-response-time-us"),
HeaderValue::try_from(elapsed.to_string()).unwrap(),
);
Ok(response)
}))
.route("/notes", web::get().to(async || "notes")),
)
.await;
let response = test::call_service(
&app, test::TestRequest::get().uri("/notes").to_request(),
).await;
assert_eq!(response.status(), ntex::http::StatusCode::OK);
let value = response.headers().get("x-response-time-us").unwrap();
assert!(value.to_str().unwrap().parse::<u128>().is_ok());
}
The log runs for either an inner response or an inner service error; the
header is added only when a response is available. Configure a log backend,
such as env_logger, in the executable to see the message. Avoid logging
sensitive query strings or credentials in a real access log.
This measures response creation, not the time needed to stream the response
body to the client. A large download can continue after next.call()
returns. To measure until the last byte, wrap the body as in
Wrapping the Response Body.
The built-in Logger already does this; use it when its access-log format
fits your needs instead of maintaining a custom timing layer.
Built-In Response Layers
DefaultHeaders is useful for service labels and other fallback headers. It
does not overwrite a header explicitly set by a handler, and it does not
turn a 401 into a successful response. If your policy requires replacing a
header unconditionally, use headers_mut().insert() after the inner call,
as in the timing example.
With the compress feature enabled, middleware::Compress::default()
negotiates response compression from Accept-Encoding. Register it before
routes like the other middleware. It operates on the response body; request
body decompression is a different concern.
Streams in Filters and Middleware
explains how Compress wraps the body and how a filter can decode uploads.
For API responses, add compression only where it is useful rather than
assuming it replaces sensible payload sizes or pagination.
A default Access-Control-Allow-Origin header alone is not a complete CORS
policy. Browsers can send preflight OPTIONS requests, and authenticated
cross-origin traffic needs a deliberate origin and credentials policy. ntex
does not add OPTIONS routes automatically. Do not copy a wildcard header
into an authentication example and assume that browser access is handled.
Writing a Middleware Service
Write a middleware struct and wrapper service if you need your own
configuration type, your own readiness source, or a named service type.
Middleware can control how the wrapped service reports readiness and
shutdown. A filter implemented as a full Service also participates in both.
A custom middleware struct follows the normal ntex service model:
use ntex::http::header::{HeaderName, HeaderValue};
use ntex::web::{self, WebRequest, WebResponse};
use ntex::{Ctx, Middleware, Service};
struct ResponseHeader;
struct ResponseHeaderService<S> {
service: S,
}
impl<S, St> Middleware<S, St> for ResponseHeader {
type Service = ResponseHeaderService<S>;
fn create(&self, _state: &St, service: S) -> Self::Service {
ResponseHeaderService { service }
}
}
impl<S, St, ReqSt> Service<St, WebRequest<ReqSt>>
for ResponseHeaderService<S>
where
S: Service<St, WebRequest<ReqSt>, Res = WebResponse>,
{
type Res = WebResponse;
type Error = S::Error;
ntex::forward!(St, service);
async fn call(
&self,
req: WebRequest<ReqSt>,
ctx: Ctx<'_, Self, St>,
) -> Result<Self::Res, Self::Error> {
let mut res = ctx.call(&self.service, req).await?;
res.headers_mut().insert(
HeaderName::from_static("x-application"),
HeaderValue::from_static("example"),
);
Ok(res)
}
}
web::App::default()
.middleware(ResponseHeader)
.route("/", web::get().to(async || "Hello"));
Middleware::create() runs when the application service is constructed.
It receives application state and the service to wrap, then returns a wrapper
for that service. The wrapper’s call() method receives a Ctx for each
request.
If the wrapper needs to keep something from application state, clone an owned
handle during create(). Do not try to retain the borrowed &St.
Always call the inner service through Ctx::call() to preserve call-time
readiness checks. You must also forward bind(), ready(), and shutdown()
to the wrapped service. Use forward! for standard forwarding. Implement
these methods explicitly when you need custom behavior.
Without forwarding, the default implementations:
- Report the middleware as always ready.
- Do not register the inner service’s readiness notifications.
- Never shut down the inner service.
The forward! macro takes the state type and one or more named or tuple
fields. Add an optional trailing map_err = f to convert readiness errors.
See Service pipelines for more on readiness and shutdown.
Configure Layers Before Routes
Add filters and middleware before registering services at each level. The
first route, service, configuration callback, or default service moves the
builder to its service-registration stage. You can no longer call filter()
or middleware() after that:
use ntex::web::{self, middleware, App, WebRequest};
App::default()
.middleware(middleware::Logger::default())
.filter(async |req: WebRequest<()>| {
Ok::<_, std::convert::Infallible>(req)
})
.route("/", web::get().to(async || "Hello"));
The same rule applies to Scope and Resource. See
Builder Order.
Middleware and filters form separate stacks, even when you interleave their builder calls. All middleware at a level wraps that level’s complete filter-and-router service. It runs before every filter on the inbound path.
Checking Layer Order in a Test
Ordering affects more than log output. Put a response-header layer outside authentication if rejected requests need its headers too. Put timing outside both when you want to measure all of their work. The first middleware you register is the outermost one, unlike frameworks that reverse registration order.
This test records both sides of two middleware calls, so the inbound and outbound order are visible in one assertion:
use std::{cell::RefCell, rc::Rc};
use ntex::web::{self, middleware::from_fn, test};
#[ntex::test]
async fn middleware_runs_in_registration_order() {
let events = Rc::new(RefCell::new(Vec::new()));
let outer = events.clone();
let inner = events.clone();
let handler = events.clone();
let app = test::init_service(
web::App::new()
.middleware(from_fn(async move |req, next| {
outer.borrow_mut().push("outer in");
let response = next.call(req).await?;
outer.borrow_mut().push("outer out");
Ok(response)
}))
.middleware(from_fn(async move |req, next| {
inner.borrow_mut().push("inner in");
let response = next.call(req).await?;
inner.borrow_mut().push("inner out");
Ok(response)
}))
.route("/", web::get().to(async move || {
handler.borrow_mut().push("handler");
"ok"
})),
)
.await;
let response = test::call_service(
&app, test::TestRequest::get().uri("/").to_request(),
).await;
assert_eq!(response.status(), ntex::http::StatusCode::OK);
assert_eq!(&*events.borrow(), &[
"outer in", "inner in", "handler", "inner out", "outer out",
]);
}
Keep the RefCell borrows confined to each push. None remains active over
next.call().await, so overlapping requests cannot collide with a borrow
held by a suspended middleware call. The event vector is a testing aid, not
an access-log implementation.
Where Filters and Middleware Run
Choose where to install a layer based on which requests need it. You can add filters and middleware to an application, scope, or resource:
| Level | Runs for |
|---|---|
App | Every request entering the application |
Scope | Requests whose scope prefix and scope guards match |
Resource | Requests whose resource path and resource guards match |
For example, a request handled by a resource inside a scope follows this path:
application middleware
-> application filters
-> application routing and scope guards
-> scope middleware
-> scope filters
-> scope routing and resource guards
-> resource middleware
-> resource filters
-> route guards
-> route handler
The response travels back through the middleware layers in reverse. At each level, middleware runs in registration order for the request and reverse registration order for the response. Filters are not part of the response path.
The router checks a scope or resource’s own guards before entering its middleware and filters. Application filters run before the application router chooses a scope or resource. Scope filters run before the scope router chooses a nested resource.
Route guards run later. The resource filter runs first. The resource then checks routes and their guards in registration order.
Fallback services run inside the layers of their level:
- If no resource matches, the application default service runs after application middleware and filters.
- If a scope matches but none of its services do, the scope default service runs after scope middleware and filters.
- If a resource matches but no route does, its default service runs after
resource middleware and filters. Without a custom default, it returns
405 Method Not Allowed.
See Web Applications and Routing for guard and fallback behavior.
Errors and the Response Path
Whether middleware can inspect an error response depends on where the error
becomes a response. The route handler converts extractor failures and errors
returned by handler Result values into WebResponse values. Response
middleware can inspect or modify these responses normally.
Errors returned directly by filters, middleware services, or other web
services stay as service errors while passing back through middleware.
ntex renders them through WebResponseError outside the application
middleware stack.
Middleware that propagates an inner error with ? does not see the final
rendered response. To process that case, catch the error and convert it into a
WebResponse within the middleware. See
Web Application Errors for the error model.
Complete example with state-aware middleware and filters
Web Application Extractors and Responders
Extractors and responders handle request parsing and response building, so your handlers can focus on application logic. Extractors provide a handler’s arguments. Responders turn its return value into an HTTP response.
Extractors
Extractors turn request data into typed handler arguments. Each argument type
must implement FromRequest. A handler can take up to 16 extractor arguments.
Before calling a handler registered with Route::to(), ntex creates its
arguments from the request. It extracts each argument in the order it appears
in the function signature.
The built-in extractors cover common request data. The rejection statuses below assume the default error domain; an application can choose different responses in Error Handling.
| Extractor | Reads | Rejection with the default domain |
|---|---|---|
HttpRequest | A cheap clone of the request handle | Extraction cannot fail |
Path<T> | Dynamic path segments | 404 if deserialization fails |
Query<T> | URL query parameters | 400 if deserialization fails |
Json<T> | A JSON request body | 400 for content-type or parsing errors; 413 for size limit |
Form<T> | A URL-encoded request body | 400 for invalid input; 413 for overflow; 411 for malformed length |
Payload | The streaming request body | Extraction cannot fail; reading the stream can |
Bytes | The complete request body as bytes | 413 for overflow; 400 for other payload errors |
String | The complete request body as decoded text | As for Bytes, plus 400 for invalid charset or text |
Option<T> | Some(value), or None if T fails | Does not reject the request |
Result<T, T::Error> | The value, or the error produced by T | Leaves rejection to the handler |
(A, B, ...) | Several extractors combined into one argument | Uses the failing extractor’s response |
For example, this handler reads a user ID from the path and an optional flag from the query string:
use ntex::web::{self, App};
#[derive(serde::Deserialize)]
struct Options {
details: Option<bool>,
}
async fn user(
user_id: web::types::Path<u32>,
options: web::types::Query<Options>,
) -> String {
format!(
"User {}, details: {}",
user_id.into_inner(),
options.details.unwrap_or(false),
)
}
App::default().route(
"/users/{user_id}",
web::get().to(user),
);
If any extractor fails, ntex skips the handler and turns the error into a
response through WebResponseError.
Path<T> uses serde to deserialize captured path segments. Query<T> also
uses serde, but query strings have a different shape:
- A path tuple reads captured segments by position.
- A path struct reads them by route variable name.
- A query string contains
key=valuepairs. Use a struct or map rather than a tuple.
ntex percent-decodes path values after splitting the URL into segments. An
encoded slash such as %2F can therefore appear inside one extracted value.
Do not treat path values as safe file-system paths; they are request input.
Choosing Handler Arguments
Keep the public shape of the endpoint visible in its signature. A route such
as /users/{user_id} usually takes a Path<u32>; pagination or filtering
belongs in a Query<SearchOptions>. A JSON document belongs in Json<T>.
You can combine these with HttpRequest when you also need a header, the
request method, or other metadata. Reading the request handle does not consume
the body.
Deserialization checks representation, not your business rules. A u32 path
rejects a name such as alice, but it accepts 0 even if your database never
uses zero as an ID. A Json<NewUser> checks the document’s shape, not whether
the username is available. Perform those checks in the handler or a reusable
validation function and return an application error when they fail.
Use Option on fields to make individual fields optional. For example,
details: Option<bool> allows the query to omit details, but still rejects
details=perhaps. This differs from wrapping the entire extractor in
Option<Query<Options>>, which also ignores malformed input.
Application state is not another entry in the extractor list: this version
has no web::types::State<T> extractor. Register a state-aware handler with
to_with_state() instead. Its first argument borrows application state; its
second receives request-local state, which is () without a state-changing
filter. Extractor arguments follow those two. See
Application State for a complete setup and sharing patterns.
Request Bodies
Choose a body extractor for the format your handler expects. All extractors share a request’s single body stream, so a handler should normally have only one body extractor.
The following extractors consume the stream and buffer it in memory. Each has a default size limit:
| Extractor | Default limit |
|---|---|
Json<T> | 32 KiB |
Form<T> | 16 KiB |
Bytes and String | 256 KiB |
Json<T> deserializes values with serde and accepts JSON media types,
including those with a +json suffix. Form<T> also uses serde and requires
application/x-www-form-urlencoded. The query extractor, Query<T>, uses
serde too.
String decodes the body according to the request charset. Bytes returns
bytes without text decoding. Both can decode compressed content, as described
under incremental uploads.
Each body format has its own configuration:
JsonConfigchanges the JSON size limit.JsonConfig::content_type()replaces the default*/jsonand*/*+jsoncheck with your predicate. Include JSON types in that predicate if you want to keep accepting them.FormConfigchanges only the form size limit.PayloadConfigchanges the limit forBytesandString. It can also require a content type. Without that setting, both extractors accept any content type.
Store extractor configuration in WebAppConfig with set_value(). Install
that configuration with App::with_config():
use ntex::web::{self, App, WebAppConfig};
fn main() {
let config = WebAppConfig::new()
.set_value(web::types::JsonConfig::default().limit(4096))
.set_value(web::types::FormConfig::default().limit(8192))
.set_value(web::types::PayloadConfig::new(64 * 1024));
let app = App::default()
.with_config(config)
.route("/", web::post().to(async |body: String| body));
}
Values stored with set_value() must be Send + Sync. Extractors read their
configuration only from WebAppConfig. They ignore a JsonConfig placed in
application state, such as AppState<JsonConfig>.
Without a call to with_config(), the application uses the WebAppConfig
from the connection’s shared configuration. Extractors use their defaults
when that store has no configuration of the right type.
Use Payload to process the body incrementally without buffering it all in
memory. It takes ownership of the remaining body stream and does not apply
PayloadConfig. Your handler decides how much data to read and how to handle
it.
Reading an Upload Incrementally
For an upload you only need to count, forward, or process in chunks, buffering the entire body is unnecessary. This handler counts bytes while enforcing its own one-MiB limit:
use ntex::web::{self, App, InternalError, types::Payload};
async fn upload(
mut body: Payload,
) -> Result<String, InternalError<&'static str>> {
const LIMIT: usize = 1024 * 1024;
let mut total = 0;
while let Some(chunk) = body.recv().await {
let chunk = chunk
.map_err(|_| web::error::ErrorBadRequest("Cannot read upload"))?;
if chunk.len() > LIMIT - total {
return Err(web::error::ErrorPayloadTooLarge(
"Upload exceeds one MiB",
));
}
total += chunk.len();
}
Ok(format!("Received {total} bytes"))
}
fn main() {
let app = App::default().route("/upload", web::post().to(upload));
}
A successful extraction only hands over the stream. The handler can still
fail while reading it, which is why this example returns Result. Do not
trust Content-Length as the only size check: count the actual chunks too.
A real upload handler can write each chunk to storage rather than keeping it.
It should also clean up partial work if reading fails or the request is
cancelled.
With the compress feature, Bytes, String, Json<T>, and Form<T> decode
Content-Encoding before processing the body. Payload exposes the encoded
bytes instead. For compressed uploads, wrap the raw stream with
ntex::http::encoding::Decoder::from_headers() if you need decoded data, and
apply your limit to the decoded chunks. The example above counts the bytes
it actually receives, not a decompressed size.
Request and Response Streaming covers backpressure, slow clients, records split across chunks, compressed uploads, and trailers.
Optional Extractors
Wrap an extractor in Option<T> when your handler should run even if that
input is invalid. Successful extraction produces Some(value). A failure
produces None and is also logged:
use ntex::web::{self, App};
#[derive(serde::Deserialize)]
struct Search {
query: String,
}
async fn search(params: Option<web::types::Query<Search>>) -> String {
match params {
Some(params) => format!("Searching for {}", params.query),
None => "No search query".to_owned(),
}
}
App::default().route("/search", web::get().to(search));
If the handler needs the actual error, use Result<T, T::Error> instead. Both
forms allow the handler to run when extraction fails.
None covers every extraction error, including input that is present but
invalid. It does not mean the input was missing. Use Option<T> only for input
you are willing to ignore when it is invalid.
With Option<Json<T>>, malformed JSON reaches the handler as None, rather
than producing the 400 response from Json<T>. A body over the JsonConfig
limit also becomes None, rather than a 413 response.
To make input optional while rejecting invalid input, extract
Result<T, T::Error> and decide which errors mean “missing”. For Json<T>,
JsonPayloadError::ContentType means the request has no JSON content type,
which is usually the case when it sends no body. Return every other error to
keep the response that Json<T> would produce:
use ntex::web::{self, App, error::JsonPayloadError, types::Json};
#[derive(serde::Deserialize)]
struct Settings {
theme: String,
}
async fn update(
body: Result<Json<Settings>, JsonPayloadError>,
) -> Result<String, JsonPayloadError> {
let settings = match body {
Ok(Json(settings)) => Some(settings),
Err(JsonPayloadError::ContentType) => None,
Err(e) => return Err(e), // malformed: 400, too large: 413
};
Ok(match settings {
Some(s) => format!("Theme set to {}", s.theme),
None => "Settings unchanged".to_owned(),
})
}
App::default().route("/settings", web::post().to(update));
These wrappers do not rewind the request body. How much of the stream a
failed extractor consumes depends on where it fails. For example, Json<T>
rejects an unsupported content type before reading anything. If deserialization
fails, it has already read the body.
A later extractor may see the whole body, part of it, or nothing.
(Option<Json<T>>, Bytes) is therefore not a reliable “JSON or raw body”
fallback. Keep a wrapped body extractor as the handler’s only body extractor.
For a fallback, read the body once as Bytes and parse the bytes you kept:
use ntex::http::HttpMessage;
use ntex::util::Bytes;
use ntex::web::{self, App, HttpRequest};
async fn ingest(req: HttpRequest, body: Bytes) -> String {
if req.content_type() == "application/json"
&& let Ok(value) = serde_json::from_slice::<serde_json::Value>(&body)
{
return format!("JSON: {value}");
}
format!("raw body: {} bytes", body.len())
}
App::default().route("/ingest", web::post().to(ingest));
This buffers the body once, under the PayloadConfig limit of 256 KiB by
default. The JsonConfig limit does not apply. Unless PayloadConfig requires
a content type, Bytes accepts any type, so the handler checks it itself.
Custom Extractors
Implement FromRequest to turn application-specific request data into a
handler argument. Your extractor receives the application state, the HTTP
request, and mutable access to the request body.
The body argument is the raw http::Payload stream. Use it directly in a
custom extractor. The Payload extractor in web::types is a separate type
that wraps this stream for use as a handler argument. For a tenant-specific
dashboard, a small extractor can parse the tenant ID header once:
use ntex::http::Payload;
use ntex::web::{self, App, FromRequest, HttpRequest, InternalError};
struct TenantId(u32);
impl<St: web::State> FromRequest<St> for TenantId {
type Error = InternalError<&'static str>;
async fn from_request(
_: &St,
req: &HttpRequest,
_: &mut Payload,
) -> Result<Self, Self::Error> {
let value = req
.headers()
.get("x-tenant-id")
.and_then(|value| value.to_str().ok())
.ok_or_else(|| web::error::ErrorBadRequest("Missing tenant ID"))?;
let id = value
.parse::<u32>()
.map_err(|_| web::error::ErrorBadRequest("Invalid tenant ID"))?;
Ok(TenantId(id))
}
}
async fn dashboard(tenant: TenantId) -> String {
format!("Dashboard for tenant {}", tenant.0)
}
fn main() {
let app = App::default().route("/dashboard", web::get().to(dashboard));
}
The extractor owns the parsed ID, so the handler does not borrow a header
value from the request. Missing or nonnumeric headers produce 400, and the
handler is never called. Because this extractor does not read the body, it
can safely accompany Json<T> or another body extractor.
Parsing a tenant header is not authorization. Before using it to select data, check that the authenticated caller may access that tenant. The same pattern works for an API key: extract its header, then verify the credential against trusted application state. Keep secrets out of error messages and logs.
Handlers registered with Route::to_with_state() receive application state
and request-local state before their extractor arguments. Extractors behave
the same way as with Route::to(). They can use application state, but they do
not receive the request-local state carried by WebRequest. See
Web Application State for details.
Responders
Return a responder to let ntex build the HTTP response for you. Your handler
can return any type that implements Responder.
Common responder types include:
| Responder | Result |
|---|---|
HttpResponse or HttpResponseBuilder | The response as configured |
String, &String, or &'static str | 200 OK, text/plain; charset=utf-8 |
Bytes, BytesMut, or &'static [u8] | 200 OK, application/octet-stream |
Json<T> | 200 OK, application/json |
Form<T> | 200 OK, application/x-www-form-urlencoded |
Option<T> | The inner response, or 404 Not Found for None |
Result<T, E> | The inner response, or the error response produced by E |
(T, StatusCode) | The inner response with a different status code |
Either<A, B> | The response of whichever variant is returned |
InternalError<T> | The error response with its configured status |
() | 200 OK with an empty body, for applications with () state |
ntex converts the responder after the handler completes. The conversion receives both application state and the original request.
The error type in Result<T, E> must implement WebResponseError. See
Web Application Errors for how errors become responses.
Either is available as ntex::util::Either.
Use Responder::with_status() to change a responder’s status. To set a
header, use Responder::with_header():
use ntex::http::StatusCode;
use ntex::web::{self, App, Responder};
#[derive(serde::Serialize)]
struct User {
id: u32,
}
async fn create_user() -> impl Responder {
web::types::Json(User { id: 42 })
.with_status(StatusCode::CREATED)
.with_header("x-api-version", "1")
}
App::default().route(
"/users",
web::post().to(create_user),
);
These methods wrap the original responder, keeping its body and other headers. The wrapper then applies your status and headers. A configured header replaces values with the same name from the inner responder.
Calling with_header() again for the same name adds another value. Use
CustomResponder::set_header() to replace the values set so far:
use ntex::web::Responder;
async fn negotiated() -> impl Responder {
"hello"
.with_header("vary", "accept")
.with_header("vary", "accept-encoding") // `vary: accept` and `vary: accept-encoding`
.set_header("vary", "*") // only `vary: *`
}
The status override applies to error responses too. On a Result,
with_status() replaces the status regardless of which variant is returned.
A (responder, StatusCode) tuple does the same.
For example, overriding the status with 201 Created sends a 400 Bad Request
error as 201, keeping its error body. To set only the success status, customize
the Ok value:
use ntex::http::StatusCode;
use ntex::web::{self, Responder, error::{ErrorBadRequest, InternalError}};
#[derive(serde::Serialize)]
struct User {
name: String,
}
async fn create_user(
name: web::types::Path<String>,
) -> Result<impl Responder, InternalError<&'static str>> {
if name.is_empty() {
return Err(ErrorBadRequest("name is required")); // stays 400
}
let user = User { name: name.into_inner() };
Ok(web::types::Json(user).with_status(StatusCode::CREATED))
}
The same applies to with_header(): headers configured on a Result are
added to error responses as well.
For simple handlers, a concrete responder such as Json<T> keeps the
signature clear. Use impl Responder when the concrete wrapper type does not
matter. Use Either<A, B> when branches produce different responder types.
Custom Responders
Implement Responder to return one of your own types directly from a
handler. The asynchronous conversion can inspect application state or request
metadata.
For example, several creation endpoints might share the convention that a
new user response includes a JSON body and a Location header:
use ntex::web::{self, App, HttpRequest, HttpResponse, Responder};
#[derive(serde::Serialize)]
struct CreatedUser {
id: u32,
name: String,
}
impl<St: web::State> Responder<St> for CreatedUser {
async fn respond_to(self, _: &St, _: &HttpRequest) -> HttpResponse {
HttpResponse::Created()
.header("location", format!("/users/{}", self.id))
.json(&self)
}
}
async fn create_user() -> CreatedUser {
CreatedUser {
id: 42,
name: "Ada".to_owned(),
}
}
fn main() {
let app = App::default().route("/users", web::post().to(create_user));
}
The handler returns a domain value; the responder keeps its HTTP convention
in one place. For a one-off response, building HttpResponse directly is
usually simpler. json(&self) serializes the value immediately, so the
response does not borrow self after this method returns.
Streaming Responses
Return a streaming response when you can produce output a piece at a time. For example, a CSV export can send its header before all rows are available:
use std::io;
use futures::stream;
use ntex::util::Bytes;
use ntex::web::{self, App, HttpResponse};
async fn export_users() -> HttpResponse {
let chunks = stream::iter([
Ok::<_, io::Error>(Bytes::from_static(b"id,name\n")),
Ok(Bytes::from_static(b"42,Ada\n")),
Ok(Bytes::from_static(b"43,Grace\n")),
]);
HttpResponse::Ok()
.content_type("text/csv; charset=utf-8")
.streaming(chunks)
}
fn main() {
let app = App::default().route("/users.csv", web::get().to(export_users));
}
This small example uses an in-memory stream so the mechanics are visible.
For a large export, replace it with a producer that fetches or formats rows
as needed, rather than first collecting every row in a Vec. The stream
must be Unpin + 'static and yield Result<Bytes, E>, where E implements
std::error::Error + 'static. It must own its data rather than borrow a
handler-local variable.
Chunk boundaries are not application-message boundaries: an HTTP client may read two chunks together or split one across several reads. CSV uses line endings to delimit records. Other formats need their own framing.
Check permissions and other conditions that affect the HTTP status before returning the response. A stream error after headers have been sent cannot replace the status with a new error response. Test the final body as well as the headers; Testing covers response bodies and real-server tests for connection behavior.
Request and Response Streaming covers producer tasks, framing, known lengths, slow readers, compression, and Server-Sent Events.
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.
Web Application Errors
You can give errors a consistent HTTP response format, even when they come
from reusable components or external libraries. In ntex, an error domain
chooses how errors become responses. Your handlers can return ordinary
Result values instead of building error responses by hand.
Each application state selects its domain with the State::Error associated
type. Every error that can reach the application must implement
WebResponseError for that domain. A missing implementation prevents the
application from compiling.
The domain type names a set of rendering rules. It does not have to be an error that handlers return. You can use your application’s error enum, as in the example below, or a separate empty marker type.
DefaultError provides plain-text responses for common ntex errors. Define a
custom domain if your API needs JSON bodies, extra headers, error codes, or
other metadata. You then choose how each error is rendered.
Where an error occurs determines when ntex converts it. Extractor and handler errors become responses inside the route. Errors from filters, middleware, and lower-level services remain service errors until they leave the application stack.
Default Error Handling
Use DefaultError for plain-text responses to common ntex errors. Every
application state chooses its error domain through the State trait:
use ntex::web;
#[derive(Clone)]
struct AppState;
impl web::State for AppState {
type Error = web::DefaultError;
}
Here, the application selects DefaultError. Its responses contain the
error’s Display text with the text/plain content type:
- Malformed request data returns
400 Bad Request. This includes invalid query strings, JSON or form bodies, and a wrongContent-Type. - JSON and form bodies over their configured limit return
413 Payload Too Large. - A malformed form
Content-Lengthreturns411 Length Required. - Path segments that fail to deserialize return
404 Not Found. - Response serialization failures return
500 Internal Server Error. For example, aJson<T>responder might fail to encode its value.
The Bytes and String extractors use their own PayloadError. Overflow
returns 413 Payload Too Large; other payload errors return 400 Bad Request,
including invalid text or a content-type check that fails.
Applications with () or AppState<T> state select DefaultError
automatically. They usually need no further error configuration.
DefaultError selects these implementations as a marker; ntex does not
construct it at runtime. It does not make every Rust error renderable. A
custom error still needs a WebResponseError<St, DefaultError> implementation
or an InternalError wrapper.
Returning Errors from Handlers
Return Result from a handler, as you would from another async Rust
function. ntex uses the successful value as the response or turns the error
into an error response.
The successful value must implement Responder. The error must implement
WebResponseError for the application’s domain. The Result responder
renders the error inside the route as soon as the handler returns.
For simple cases, use the helpers in web::error to choose an HTTP status
without defining a new error type:
use ntex::web::{self, App, InternalError};
async fn create_user(
) -> Result<&'static str, InternalError<&'static str>> {
Err(web::error::ErrorBadRequest("Invalid user"))
}
fn main() {
App::default().route(
"/users",
web::post().to(create_user),
);
}
The module has 39 Error* helpers, one for each common 4xx and 5xx status.
Examples include:
ErrorBadRequestErrorUnauthorizedErrorForbiddenErrorNotFoundErrorConflictErrorInternalServerError
Each helper returns an InternalError<T> with the chosen status and T’s
Display text as the body. These helpers are useful at an application
boundary, where you choose what the client should see.
The response body is public. Do not wrap database errors, tokens, internal paths, or other sensitive details directly. Log the original error and return a message that is safe for the client.
Use InternalError::from_response() when you need to supply a fully prepared
response instead of a status and plain-text body:
use ntex::web::{self, HttpResponse, InternalError};
async fn create_user(
) -> Result<&'static str, InternalError<&'static str>> {
Err(InternalError::from_response(
"duplicate user",
HttpResponse::Conflict()
.header("x-error-code", "user-exists")
.body("A user with that name already exists"),
))
}
Some error types implement WebResponseError for every domain. They work with
DefaultError and custom domains alike:
InternalError<T>, including everyError*helper.WebError<St, Err>, which holds a renderable error for that same state and domain. It erases the concrete type; it does not render the response yet.ntex::util::Either<A, B>, when bothAandBimplement the trait.std::convert::Infallible.
Custom Error Domains
Define a custom domain to control how your application renders errors,
including those from external components. Set State::Error to an
application-specific type. Then implement WebResponseError for each error
the application can produce.
The error_response() method receives application state, so it can use shared
configuration to build the response. By default, it returns
500 Internal Server Error with the error’s Display text as a plain-text
body. Override it to choose the status, headers, and body for each error.
For a JSON API, you can use a response builder’s json() method to serialize
a small error-body struct.
WebResponseError requires std::error::Error + 'static. Every error type
must therefore implement the standard Error trait. The example below derives
it with thiserror; add that crate to your Cargo.toml.
The example below keeps three application errors in one enum. It sends a
short, stable code for clients and a readable message for people. Duplicate
names return 409 Conflict; empty names and invalid JSON return 400 Bad Request. An unavailable dependency returns a generic 503 without exposing
its internal error:
use ntex::http::StatusCode;
use ntex::web::{
self, App, HttpResponse, WebResponseError, error::JsonPayloadError,
};
#[derive(Clone)]
struct AppState;
#[derive(Debug, thiserror::Error)]
enum ApiError {
#[error("User already exists")]
UserExists,
#[error("Name must not be empty")]
InvalidName,
#[error("Service temporarily unavailable")]
Unavailable,
}
impl web::State for AppState {
type Error = ApiError;
}
#[derive(serde::Serialize)]
struct ErrorBody {
code: &'static str,
message: &'static str,
}
fn error_json(
status: StatusCode,
code: &'static str,
message: &'static str,
) -> HttpResponse {
HttpResponse::builder(status).json(&ErrorBody { code, message })
}
impl WebResponseError<AppState, ApiError> for ApiError {
fn error_response(&self, _state: &AppState) -> HttpResponse {
let (status, code, message) = match self {
Self::UserExists => {
(StatusCode::CONFLICT, "user_exists", "User already exists")
}
Self::InvalidName => (
StatusCode::BAD_REQUEST,
"invalid_name",
"Name must not be empty",
),
Self::Unavailable => (
StatusCode::SERVICE_UNAVAILABLE,
"unavailable",
"Try again later",
),
};
error_json(status, code, message)
}
}
impl WebResponseError<AppState, ApiError> for JsonPayloadError {
fn error_response(&self, _state: &AppState) -> HttpResponse {
match self {
JsonPayloadError::Overflow => error_json(
StatusCode::PAYLOAD_TOO_LARGE,
"body_too_large",
"Request body is too large",
),
JsonPayloadError::ContentType => error_json(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"expected_json",
"Expected a JSON request",
),
_ => error_json(
StatusCode::BAD_REQUEST,
"invalid_json",
"Invalid JSON",
),
}
}
}
#[derive(serde::Deserialize)]
struct User {
name: String,
}
fn validate_name(name: &str) -> Result<&str, ApiError> {
let name = name.trim();
if name.is_empty() {
Err(ApiError::InvalidName)
} else if name == "admin" {
Err(ApiError::UserExists)
} else {
Ok(name)
}
}
async fn create_user(user: web::types::Json<User>) -> Result<String, ApiError> {
let name = validate_name(&user.name)?;
Ok(format!("Created {name}"))
}
fn main() {
let app =
App::<AppState>::new().route("/users", web::post().to(create_user));
}
The name check stands in for application logic; a real registration handler
would check uniqueness in its storage layer. Calling validate_name() with
? returns early on failure. ntex then renders the returned ApiError as,
for example, {"code":"user_exists","message":"User already exists"}. The
handler does not need to know how that error becomes JSON.
This example has two possible error types:
- The handler can return
ApiError. - The
Json<User>extractor can returnJsonPayloadErrorbefore ntex calls the handler.
Although ntex defines JsonPayloadError, your application can implement
WebResponseError<AppState, ApiError> for it. Rust’s orphan rules allow this
because AppState and ApiError are local types.
Selecting a custom domain replaces the application’s DefaultError
implementations. Add a mapping for every extractor, responder, filter,
middleware, or service error the application uses. Requiring these mappings
prevents an API from silently falling back to a response format or status it
did not choose.
Include errors that occur while ntex builds the response. A Json<T>
responder requires a mapping for web::error::JsonError. A Form<T> responder
requires one for serde_urlencoded::ser::Error.
Using ? and Converting Library Errors
? follows ordinary Rust conversion rules. It propagates the same error type,
or uses a From implementation to convert into the function’s declared error
type. Implementing WebResponseError only teaches ntex how to render an error;
it does not add a Rust conversion between errors.
When a library error needs an application-specific meaning, use map_err() at
the boundary. For example, invalid policy data loaded from your own storage
is a server problem, not a bad client request. Alongside the types above, you
could write:
#[derive(serde::Deserialize)]
struct AccountPolicy {
minimum_name_length: usize,
}
fn decode_policy(bytes: &[u8]) -> Result<AccountPolicy, ApiError> {
serde_json::from_slice(bytes).map_err(|err| {
log::error!("Cannot decode stored account policy: {err}");
ApiError::Unavailable
})
}
A handler returning Result<_, ApiError> can call decode_policy(bytes)?.
The original parsing error stays in the server log; the client sees only the
unavailable response. If callers need the original error for diagnostics,
store it as a source in your application error instead of discarding it.
thiserror can generate From implementations with #[from] when a direct
conversion is appropriate. Keep HTTP rendering separate from that decision.
Customizing Extractor Rejections
An invalid body fails before your handler runs. A handler’s return type does
not change that: Result<String, ApiError> does not turn a
JsonPayloadError into an ApiError. In the worked example, the separate
WebResponseError<AppState, ApiError> implementation for JsonPayloadError
provides the JSON rejection body.
That implementation deliberately differs from the default domain: a missing
or unsupported JSON content type returns 415 Unsupported Media Type, not
400. Overflow still returns 413, and malformed JSON returns 400. These
are your API’s choices, not changes to the extractor’s parsing rules.
JsonConfig configures the size limit and accepted content types; it has no
error_handler() callback. FormConfig and PayloadConfig do not provide
such a callback either. Use the error domain for application-wide formatting.
Map PathError, QueryPayloadError, UrlencodedError, or PayloadError in
the same way when you add those extractors to a custom-domain application.
For one route that needs to inspect a rejection itself, take
Result<Json<User>, JsonPayloadError> as its argument and match the result
inside the handler. This lets that handler choose its own response while
other routes keep the domain’s behavior. It also makes the handler responsible
for rejecting malformed or oversized input. Option<Json<User>> instead
hides the reason for failure, so it is a poor choice when you need distinct
error codes. See Optional Extractors
for the body-consumption caveats.
Logging Errors Without Exposing Them
Treat the response body and the diagnostic log as two different audiences.
An access log can record the 500 status, but it does not tell you which
query or dependency failed. Log useful context where you still have it, such
as the operation name and a nonsecret request identifier, before mapping a
library error to a safe application error.
Do not rely on every handler error being logged automatically. The Result
responder calls error_response(); that conversion does not itself log the
error. ntex emits some extractor diagnostics at debug level, but that is not
an application logging policy. Initialize a logger or tracing integration in
your executable, and choose where each unexpected failure is recorded so you
do not log it repeatedly at every layer. Expected validation failures usually
need less attention than an unavailable database.
Where Error Responses Travel
Where an error occurs determines what middleware sees. Errors converted inside a route reach middleware as responses. Service-layer errors remain errors until the outer application service renders them.
ntex converts extractor errors, handler Result errors, and responder
serialization errors while the route runs. These ordinary responses pass
through resource, scope, and application middleware. Response middleware can
inspect or modify them.
Filters, middleware services, and custom web services return errors through
the service layer. ntex erases their concrete types into WebError as they
travel out through the stack. The outer application service then calls
error_response().
Middleware using ctx.call(...).await? therefore sees an error before a
rendered response exists. To inspect that response or add headers, catch the
error and convert it in the middleware.
In normal handlers, return Result<T, E> and let the responder convert it.
You usually need WebError only when implementing a lower-level web service,
filter, or middleware whose error type is already type-erased.
The WebError::from_err Escape Hatch
WebError::from_err(error) stores an error that already implements
WebResponseError for the target state and domain. It preserves that
implementation for later rendering; it is not a way to make an arbitrary Rust
error renderable.
There is no blanket From<E> conversion into WebError, so ? alone cannot
perform this wrapping. Convert explicitly with map_err(WebError::from_err).
This standalone handler shows both decisions: first choose a safe 400
response, then erase the concrete error type:
use ntex::web::{self, WebError, types::Path};
async fn revision(value: Path<String>) -> Result<String, WebError> {
let number = value
.parse::<u32>()
.map_err(|_| {
web::error::ErrorBadRequest(
"Revision must be a nonnegative integer",
)
})
.map_err(WebError::from_err)?;
Ok(format!("Revision {number}"))
}
For this small handler, returning InternalError<&'static str> directly
would be simpler. The explicit wrapping becomes useful when a service
boundary requires WebError. Inside that boundary, ? still works normally
on calls that already return the matching WebError<St, St::Error>.
Test the Rendered Response
Test the HTTP response your client receives, including its status, headers, and body. Checking only the Rust error value does not test the HTTP contract. This example checks both the status and the public message of a conflict response:
use ntex::http::StatusCode;
use ntex::web::{self, App};
#[derive(Clone)]
struct AppState;
impl web::State for AppState {
type Error = web::DefaultError;
}
async fn create_user() -> Result<&'static str, web::InternalError<&'static str>>
{
Err(web::error::ErrorConflict("User already exists"))
}
#[ntex::test]
async fn duplicate_user_response() {
let app = web::test::init_service_st(
AppState,
App::<AppState>::new().route("/users", web::post().to(create_user)),
)
.await;
let request = web::test::TestRequest::post().uri("/users").to_request();
let response = web::test::call_service(&app, request).await;
assert_eq!(response.status(), StatusCode::CONFLICT);
assert_eq!(web::test::read_body(response).await, "User already exists");
}
For the JSON API above, also deserialize the response body and assert its
code and message fields. Cover failures before the handler as well as
inside it: malformed JSON, a wrong content type, and an over-limit body should
all keep the API’s error format. Testing covers the test
helpers and how to organize these checks.
WebSocket Support
In an HTTP exchange, the client sends a request and the server sends a response. An open WebSocket connection lets either side send a message at any time. Use it for interactive applications such as chat and live notifications. It can also carry another protocol, such as MQTT, over an ordinary web connection.
WebSocket support in ntex
Most web applications only need web::ws. ntex provides four APIs for
different ways of handling a WebSocket connection:
| API | Use it to |
|---|---|
web::ws | Add a WebSocket endpoint to a routed web application |
HttpService and HTTP/1 control services | Take over an upgraded connection and drive it yourself |
ws::WsClient | Connect to a WebSocket server |
ws::WsTransport | Run a byte-oriented protocol over binary WebSocket messages |
All four share the codec and protocol types in ntex::ws. WebSocket support
is enabled by default through the ws Cargo feature.
Every WebSocket connection starts with an HTTP/1.1 request. The client asks to
upgrade the connection, and the server accepts with 101 Switching Protocols.
The peers then exchange WebSocket frames instead of HTTP messages. The APIs
in this chapter support HTTP/1 upgrades, not HTTP/2 extended CONNECT.
A ws:// URL uses a plain connection; wss:// uses TLS. For wss://,
configure a TLS connector with a backend such as OpenSSL, rustls, or Windows
Schannel.
Changing the URL alone does not enable TLS on WsClient. See
WebSocket TLS configuration.
The optional compress feature adds permessage-deflate support to the codec
and client. web::ws::start() does not negotiate compression on its own.
Frames, messages, and fragmentation
The frame API gives you incoming data as a Frame. To send data, use a
Message. Both types have variants for text, binary, ping, pong, close, and
continuation frames.
A sender can split one message into several frames. The first fragment is
Frame::Continuation(Item::FirstText(_)) or FirstBinary(_). Zero or more
Continue(_) fragments may follow. The final fragment is Last(_).
The codec checks fragment order but does not join fragments. If your handler needs whole messages, collect the fragments yourself or reject fragmented input.
The codec also checks text encoding and size limits:
- Text frames arrive as raw bytes. The codec checks each text message for
valid UTF-8 and fails the connection if the check fails. A multi-byte
character can span fragments, so convert the joined message to a string
rather than converting each fragment.
Codec::validate_utf8(false)disables this check. - Each frame is limited to 64 KiB by
Codec::max_size(). Each message, including all its fragments, is limited to 4 MiB byCodec::max_message_size(). A larger frame or message fails withProtocolError::Overflow. Raise both limits to accept a single-frame message over 4 MiB.
Servers with web::ws
Add a WebSocket endpoint as an ordinary route with a GET handler. In the
handler, call web::ws::start with the request and a service for incoming
frames. The service returns Some(Message) to reply to a frame, or None to
send nothing.
This echo server handles text and binary messages that arrive in a single frame:
use std::io;
use ntex::web::{self, HttpRequest, ws};
async fn echo(frame: ws::Frame) -> Result<Option<ws::Message>, io::Error> {
let message = match frame {
ws::Frame::Text(bytes) => match String::from_utf8(bytes.to_vec()) {
Ok(text) => ws::Message::Text(text.into()),
Err(_) => ws::Message::Close(Some(ws::CloseCode::Invalid.into())),
},
ws::Frame::Binary(bytes) => ws::Message::Binary(bytes),
ws::Frame::Ping(bytes) => ws::Message::Pong(bytes),
ws::Frame::Pong(_) => return Ok(None),
ws::Frame::Close(reason) => ws::Message::Close(reason),
ws::Frame::Continuation(_) => {
ws::Message::Close(Some(ws::CloseCode::Unsupported.into()))
}
};
Ok(Some(message))
}
async fn socket(req: HttpRequest) {
if let Err(err) = ws::start(&req, None, echo).await {
eprintln!("WebSocket connection failed: {err:?}");
}
}
#[ntex::main]
async fn main() -> io::Result<()> {
web::server(async |_| {
web::App::new().route("/ws/", web::get().to(socket))
})
.bind("127.0.0.1:8080", ntex::SharedCfg::default())?
.run()
.await
}
Run the server, then connect a WebSocket client to ws://127.0.0.1:8080/ws/.
The client example below sends a text message and reads
the echo. An ordinary HTTP client does not switch protocols just because the
path ends in /ws/; it must send the WebSocket upgrade headers.
Follow one text message through the server: the route calls socket(), which
hands the connection to start(). The dispatcher decodes an incoming frame
and calls echo(). That function turns the text bytes into an outgoing
Message::Text, and the dispatcher writes it back. The Pong branch returns
None because a pong is an acknowledgement, not something to echo again.
The continuation branch closes rather than silently losing part of a message.
This is an echo endpoint, not a chat room: each connection replies only to its own sender. To broadcast to other users, keep authorized room membership and a sink for each connected peer. Remove a peer when its connection ends, and bound any per-peer queue. A slow reader should not make every other room member wait indefinitely or let queued messages exhaust server memory.
Your handler does not build an HTTP response. start() validates the
handshake, sends the 101 response, and takes over the connection from the
HTTP layer. It then runs the WebSocket dispatcher until the connection closes.
The await lasts for the connection’s lifetime, beyond the initial setup.
During the handoff, start() cancels the HTTP layer’s read timer. The
connection keeps the server’s I/O configuration, so its write timeout,
shutdown timeout, and frame read rate also apply to the WebSocket session.
The WebSocket dispatcher disables idle keepalive and lets the client stay
silent until it starts a frame. If the handshake is invalid, start() sends
the HTTP error response itself.
After takeover, returning an HttpResponse from your handler sends nothing
else. On failure, start() returns a WsError. This covers frame-service
errors, protocol errors, read and write timeouts, and I/O errors.
Sending outside the frame handler
Use a WsSink to send messages without waiting for an incoming frame. For
example, another task can use it to push a notification. Returning a message
from the frame handler remains the easiest way to reply to a frame.
The frame service receives the sink as its state. Use fn_service_st to access
it, or implement Service<WsSink, Frame> yourself.
A WsSink is cheap to clone. Every clone sends to the same connection. Give a
clone to tasks that push messages, such as timers, pub/sub subscriptions, or
chat room broadcasters. Each task can call sink.send(...) independently of
the frame handler and the other tasks.
This service answers pings through the sink instead of returning the pong:
use std::io;
use ntex::service::fn_service_st;
use ntex::web::ws;
let service = fn_service_st(async |sink: &ws::WsSink, frame: ws::Frame| {
if let ws::Frame::Ping(bytes) = frame {
sink.send(ws::Message::Pong(bytes))
.await
.map_err(io::Error::other)?;
}
Ok::<Option<ws::Message>, io::Error>(None)
});
The handler returns None because it has already sent the pong. start()
does not send another one.
Sink clones share the connection’s state. Once any clone sends a close
message, none of them can send more messages. The sink uses Rc for reference
counting and stays on the connection’s worker thread. Start sender tasks with
ntex::rt::spawn on that worker rather than on a separate thread.
send() waits while the connection is under write backpressure. If you keep
your own outgoing message queue, limit its size so a slow client cannot make
it grow without bound.
The basic WebSocket example uses a sink for its heartbeat and includes a browser page, a Rust client, and the server. The server’s readiness hook starts the heartbeat task once. Its shutdown hook stops the task.
The task sends pings and records when the client last sent a ping or pong. If the client stays quiet for too long, the task closes the connection.
Choosing a subprotocol
Use a subprotocol to agree on what the connection will carry. For example,
mqtt identifies MQTT. The client lists the protocols it supports, and the
server chooses one.
Read the client’s offers with web::ws::subprotocols. Pass your choice to
start():
let chosen = ntex::web::ws::subprotocols(&req)
.find(|protocol| *protocol == "my-application");
ntex::web::ws::start(&req, chosen, service).await?;
Pass Some(protocol) only for a valid token that the client offered. None
accepts the connection without a subprotocol. If your application needs a
subprotocol, reject clients that do not offer one you support.
The handshake checks the WebSocket protocol; it does not authorize clients.
Authenticate the client before calling start(). For browser clients, check
the Origin header before that call too.
Heartbeats and closing the connection
You can let start() answer control frames or handle them in your frame
service. Ping, pong, and close frames reach the service just like data frames.
If your service returns None for a ping without sending a pong through the
sink, start() sends a pong with the same payload. Return your own message to
answer differently.
When the peer sends a close frame and your service returns None, start()
echoes the peer’s close code unless you have already sent a close. It closes
the I/O stream after your service handles the peer’s close.
Answering pings is not the same as sending heartbeats. start() can answer a
peer’s ping, but it does not schedule periodic pings or decide how long a
silent peer may stay connected. If your application needs to detect broken
connections promptly, keep a last-seen timestamp per connection and run a
small timer task. For example, send a ping every five seconds and consider
thirty seconds without a ping or pong a failed connection. These are
application policy values, not ntex defaults.
Update that timestamp in the frame service when a ping or pong arrives. Keep the timer and frame service on the same worker, and arrange for the timer to stop when the dispatcher finishes. Decide whether ordinary data messages also count as activity; an application-level acknowledgement may matter more than a WebSocket pong for some protocols. The HTTP keepalive setting is not a replacement for this policy after the upgrade.
To close from your side, return or send Message::Close. This starts the
closing-handshake timeout. Set it with WsClientConfig::set_close_timeout()
in the connection’s shared configuration. Despite the type’s name, this
setting also applies to server-side sinks.
Stop background tasks such as heartbeats when the connection ends, as the
basic example does. If a peer stops responding, close the I/O stream with
sink.io().close(). Use the same call whenever you need to close without
waiting for further application messages.
Use web::ws::start_with to handle dispatcher events yourself. It performs
the same upgrade, but your service receives DispatchItem<WsSink> instead of
Frame. Your service must handle control and stop events, including errors
and shutdown. start_with() does not answer pings or close frames for you.
Testing the Upgrade and Message Exchange
Use a real test server for a WebSocket endpoint: the upgrade transfers an
actual connection, which an in-memory handler test cannot provide. Put this
test alongside the echo and socket functions from the server example:
use futures::StreamExt;
use ntex::{
SharedCfg, http::StatusCode, time::Seconds, util::Bytes, ws::WsClient,
};
#[ntex::test]
async fn echo_round_trip() {
let server = web::test::server(async |_| {
web::App::new().route("/ws/", web::get().to(socket))
});
ntex::time::timeout(Seconds(5), async {
let connection = WsClient::new(server.url("/ws/"), SharedCfg::default())
.connect().await.unwrap();
assert_eq!(connection.response().status(), StatusCode::SWITCHING_PROTOCOLS);
let sink = connection.sink();
let mut frames = connection.seal().receiver();
sink.send(ws::Message::Text("hello".into())).await.unwrap();
assert_eq!(
frames.next().await.unwrap().unwrap(),
ws::Frame::Text(Bytes::from_static(b"hello")),
);
sink.send(ws::Message::Ping(Bytes::from_static(b"alive"))).await.unwrap();
assert_eq!(
frames.next().await.unwrap().unwrap(),
ws::Frame::Pong(Bytes::from_static(b"alive")),
);
sink.send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
.await.unwrap();
assert!(matches!(
frames.next().await.unwrap().unwrap(),
ws::Frame::Close(Some(reason)) if reason.code == ws::CloseCode::Normal
));
}).await.expect("WebSocket exchange timed out");
}
The server binds an available port, so tests can run without claiming a fixed
port or starting a separate process. WsClient accepts the http:// URL
returned by server.url() for this plain WebSocket connection. The test waits
for actual protocol events rather than sleeping: it checks the upgrade, text
reply, pong payload, and close acknowledgement. The deadline makes a missing
reply fail the test instead of leaving it waiting indefinitely.
For a shorter setup, server.ws_at("/ws/").await connects with the server’s
configured WsClient for you. Use the explicit client when you need custom
headers, subprotocols, or connection limits. See Testing for
test-server configuration and the distinction between in-memory and network
tests.
Low-level servers with an HTTP control service
An HTTP control service can accept WebSocket connections without a web application. Use it for a lower-level server, a listener shared by several protocols, or your own I/O loop.
Attach the service with HttpService::h1(...).control(...). For the combined
HTTP service, use HttpService::new(...).h1_control(...).
Upgrade requests arrive as h1::Control::Upgrade. Inspect the request to
check its path, authentication, Origin, and any required subprotocol.
ws::handshake validates the WebSocket handshake and returns a response
builder. You still handle authorization and subprotocol selection yourself.
Choose how to handle each upgrade request:
- Reject the request with
upgrade.fail(error)orupgrade.fail_with(response). - Pass it on to the regular application service with
upgrade.ack(). This is the path aweb::wshandler relies on. - Take over the connection with
upgrade.handle().
handle() gives you the acknowledgement to return. It also returns the I/O
stream, request, and HTTP/1 codec. This excerpt from the
low-level WebSocket example passes those three values to a separate
ws_service:
.h1_control(async move |control: h1::Control<_, _>| {
let ack = if let h1::Control::Upgrade(upgrade) = control {
let (ack, io, request, http_codec) = upgrade.handle();
ws_service.call((request, io, http_codec)).await?;
ack
} else {
control.ack()
};
Ok::<_, io::Error>(ack)
})
ws_service checks the handshake and writes the HTTP response with the
HTTP/1 codec it received. It then switches to ws::Codec::new() for WebSocket
frames. That codec uses the server’s masking rules. A client needs the client
rules instead.
handle() transfers ownership without sending a response. Your code must send
either an HTTP rejection or the 101 response. Keep using the I/O stream you
received. It may already hold the start of the first WebSocket frame,
buffered immediately after the HTTP headers.
You also manage the connection’s lifetime:
- Stop the HTTP timer and choose timeouts for the new protocol. Otherwise the
old header-read timer can fire in the middle of the WebSocket session. An
I/O dispatcher stops it when it is created; build it with
.keepalive_timeout(Seconds::ZERO).skip_first_frame_timeout()to run without idle keepalive or a first-frame deadline, asweb::wsdoes. With your own loop, callio.stop_timer(). - Drive the connection with
io.recv()andio.send(), or use an I/O dispatcher. Your loop must handle ping/pong, fragmented messages, close frames, and protocol and transport errors. - Finish the closing handshake, shut down the I/O stream, and stop any background tasks that belong to the connection.
The example changes I/O settings with Io::set_config(). This call is unsafe.
Before calling it, ensure no reference borrowed from the old configuration
remains alive. The I/O chapter
explains why. The dispatcher options above need no unsafe code when only
keepalive or the first-frame deadline must change.
The complete example includes an OpenSSL acceptor and a web application that serves static files for ordinary HTTP requests. Its WebSocket loop echoes text and binary frames, answers pings, and uses pongs for its heartbeat. It rejects fragmented messages instead of assembling them.
The example’s README lists the server and client commands. It also explains how to set up the test certificate.
Clients with ntex::ws
Create a WsClient and call connect().await to connect to a WebSocket
server. Store client settings in a WsClientConfig inside a SharedCfg.
A successful handshake returns a WsConnection holding the server’s
response and a sink for sending messages.
This client connects to the echo server above, sends "hello", prints the
reply, and closes the connection:
use std::io;
use futures::StreamExt;
use ntex::{SharedCfg, time::Seconds, ws};
#[ntex::main]
async fn main() -> io::Result<()> {
let cfg = SharedCfg::new("WS-CLIENT").add(
ws::WsClientConfig::new()
.set_max_frame_size(128 * 1024)
.set_handshake_timeout(Seconds(5))
.set_close_timeout(Seconds(5)),
);
let connection = ws::WsClient::new("ws://127.0.0.1:8080/ws/", cfg)
.connect()
.await
.map_err(io::Error::other)?;
println!("Handshake: {}", connection.response().status());
let sink = connection.sink();
let mut frames = connection.seal().receiver();
sink.send(ws::Message::Text("hello".into()))
.await
.map_err(io::Error::other)?;
while let Some(frame) = frames.next().await {
match frame.map_err(|err| io::Error::other(format!("{err:?}")))? {
ws::Frame::Text(bytes) => {
println!("Echo: {bytes:?}");
sink.send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
.await
.map_err(io::Error::other)?;
}
ws::Frame::Close(_) => break,
_ => {}
}
}
Ok(())
}
The client reads frames with receiver() and futures::StreamExt, as in the
basic WebSocket client. The call to seal() erases the concrete I/O filter
type. Calling receiver() then starts the dispatcher in a background task
and returns a channel of frames and errors.
The receiver answers the server’s pings and close frame for you. Pings still reach your loop. Dropping the receiver starts the closing handshake.
To use a frame service instead of a channel, call
connection.seal().start(service).await. The service works like the
server-side service, but its state is () rather than a sink. It returns
Option<Message> and must reply to both pings and close frames.
Await or spawn start() to run the dispatcher. Keeping a connection or sink
alone does not run it.
Configuration and TLS
Use WsClientConfig to choose handshake options and connection limits:
- Offer subprotocols and add headers, such as
Originor authentication. - Limit frame size with
set_max_frame_size. - Limit message size with
set_max_message_size. - Set the handshake and close timeouts.
The handshake timeout starts after the connection is established. It covers only the HTTP exchange. Wrap the operation in your own timeout if you need a deadline for the whole connection attempt.
If the server selects a subprotocol, the client checks that it is valid and was offered. The server may also accept without selecting one. If your application requires a particular subprotocol, check the response before sending data.
For wss://, enable the matching Cargo feature and configure a TLS connector.
Use WsClient::openssl() for OpenSSL or WsClient::rustls() for rustls. The
low-level TLS client shows an OpenSSL setup for a local self-signed
certificate. It disables certificate verification for the demo. A real client
must verify the server’s certificate and hostname.
With the compress feature, call set_deflate(DeflateConfig::new()) to offer
permessage-deflate compression. The server may accept or decline, so enabling
it does not guarantee compression.
WebSocket as a byte transport
Use a byte transport to run another protocol without handling WebSocket frames in that protocol. MQTT, for example, already decodes its own packets, acknowledges messages, and keeps the connection alive.
WsTransport is an I/O filter that removes binary WebSocket framing from
incoming data and adds it to outgoing data:
socket <-> optional TLS <-> WebSocket filter <-> MQTT or another byte protocol
The protocol receives bytes from binary messages and their continuation fragments. The filter rejects text messages. Unlike the frame services above, it answers pings itself and ignores pongs. It also takes part in the closing handshake when the I/O stream shuts down.
The filter exposes a byte stream without WebSocket message boundaries. One protocol packet may span several WebSocket messages. A single WebSocket message may contain several protocol packets. The protocol’s decoder handles these boundaries. Use the frame API if you need to track where each WebSocket message begins and ends.
Installing the filter
On the server, send the 101 upgrade response first, then add the filter:
let io = ntex::ws::WsTransport::create(io, ntex::ws::Codec::new());
Pass the resulting Io<Layer<WsTransport, F>> to a protocol service. Call
io.boxed() if that service expects type-erased I/O.
To add the filter as a service-pipeline step, use WsTransportService.
Construct it with WsTransportService::new(ws::Codec::new()). Both approaches
require a completed HTTP handshake.
On the client, convert the connection returned by WsClient:
let io = connection.into_transport();
This keeps the client’s codec, including its masking mode and any compression negotiated during the handshake. A fresh codec would use the server’s masking rules, which are wrong for a client.
The inner protocol now owns the stream. Stop using any old frame sink so you do not mix two ways of writing to the same connection.
The I/O filter subsystem section explains how filters work with TLS, buffering, backpressure, and shutdown.
MQTT over WebSocket
The MQTT-over-WebSocket example connects an ntex-mqtt server and client
over WebSocket. Both speak MQTT 3.1.1 and use the standard mqtt subprotocol.
The server accepts upgrades only on /mqtt from clients that offer mqtt.
It checks the handshake and selects mqtt in its 101 response. It then stops
the HTTP timer, installs WsTransport, and passes the boxed stream to
v3::MqttServer. The MQTT server handles CONNECT and incoming publishes.
This minimal server receives publishes. It does not act as a broker, manage subscriptions, or forward messages.
The client offers mqtt with WsClientConfig::set_protocols() and checks the
server’s choice. A custom connector for v3::client::MqttConnector returns
connection.into_transport() instead of a plain socket. The MQTT client uses
that stream to send CONNECT and exchange packets as usual.
The client sends a QoS 1 publish and waits for its acknowledgement. The MQTT dispatcher runs at the same time to read that acknowledgement. The client then closes the MQTT session and lets the transport shut down.
MQTT still handles keepalive. WebSocket ping/pong is a separate mechanism and does not replace it.
AMQP over WebSocket
You can also carry AMQP 1.0 over WebSocket with an ntex-amqp server or a
custom client connector. The AMQP WebSocket binding uses the amqp
subprotocol. Both sides should check that it was negotiated.
Each opening AMQP protocol header must travel in its own WebSocket message. This includes the SASL header when SASL is used. After the headers, AMQP frames may span messages or share them freely.
WsTransport does not track AMQP protocol-header boundaries and cannot enforce
this rule alone. Your AMQP handshake integration must keep each header in its
own message. Test it against the peer you plan to use.
The AMQP implementation handles the rest, including authentication, sessions,
links, idle timeouts, and orderly shutdown. For TLS, use wss:// for the
WebSocket connection rather than negotiating TLS inside the AMQP stream.
Testing
Start with the smallest test that exercises the behavior you care about. For most web code, that means sending an in-memory request through an application, not starting a server. You still exercise routing, extractors, middleware, and response rendering, but there is no listener to configure or port to reserve.
Use #[ntex::test] for asynchronous tests. It supplies the ntex runtime, so
application services, I/O tasks, and timers run in the same environment as
other ntex code. Each example below is a complete test or a complete program
containing tests. The examples use ntex with the tokio feature; the JSON
examples also need serde with derive and serde_json, and the WebSocket
example needs ntex’s ws feature.
Start with an in-process application
web::test::init_service builds an application pipeline without opening a
socket. Build a request with TestRequest, turn it into an HTTP request with
to_request(), and pass it to call_service:
use ntex::http::StatusCode;
use ntex::web::{self, App, test};
async fn health() -> &'static str {
"ready"
}
#[ntex::test]
async fn health_returns_a_body() {
let app = test::init_service(
App::new().route("/health", web::get().to(health)),
)
.await;
let req = test::TestRequest::get().uri("/health").to_request();
let res = test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(test::read_body(res).await, "ready");
}
Check the status before consuming the response with read_body. That helper
collects the entire body into Bytes; it is convenient for small text and
binary responses, but it does not prove that a streaming response arrives
incrementally. Reading the body also catches failures that occur while
producing it rather than while selecting the response.
This test runs the handler through the router. Calling health().await
directly would test only its return value, not whether /health is registered
for GET. A direct handler call can still help when the handler has substantial
logic, but use an application test for the HTTP contract. See
Routing and Handlers for registration patterns.
Choose the request conversion for the layer being tested. The web builder’s
to_http_request() makes an HttpRequest for a direct handler call;
to_srv_request() makes a WebRequest for lower-level middleware tests.
Neither conversion runs application routing. For an app pipeline, use
to_request() as above. If you work directly with the lower-level HTTP API,
http::test::TestRequest has a different terminal method, build(), which
produces an http::Request.
init_service succeeding does not prove every route can be constructed.
Registered services are created on their first request; a failing service
factory produces a 500 Internal Server Error response at that point. Send a
request to each route you need to verify, and assert the resulting status.
Share routes with the executable
A test can pass while production is broken if it registers a different set of
routes. Put route registration in a configuration function, then call that
function from both main and the tests. Keep the tests in a #[cfg(test)]
module at the bottom of the file so they can use the same handlers and types.
The following program exposes a JSON preview endpoint. It returns the supplied note without storing it. Its tests cover successful serialization and a body that cannot be parsed:
use ntex::{SharedCfg, web};
use ntex::web::{App, HttpResponse, types::Json};
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, PartialEq, Serialize)]
struct Note {
title: String,
}
async fn preview(note: Json<Note>) -> HttpResponse {
HttpResponse::Ok().json(¬e.into_inner())
}
fn config(cfg: &mut web::ServiceConfig) {
cfg.route("/preview", web::post().to(preview));
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
web::HttpServer::new(async |_| App::new().configure(config))
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
#[cfg(test)]
mod tests {
use super::*;
use ntex::http::StatusCode;
use ntex::web::test;
#[ntex::test]
async fn preview_round_trips_json() {
let app = test::init_service(App::new().configure(config)).await;
let note = Note { title: "First draft".into() };
let req = test::TestRequest::post()
.uri("/preview")
.json(¬e)
.to_request();
let res = test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::OK);
let body = test::read_body(res).await;
let returned: Note = serde_json::from_slice(&body).unwrap();
assert_eq!(returned, note);
let req = test::TestRequest::post()
.uri("/preview")
.json(¬e)
.to_request();
let returned: Note = test::read_response_json(&app, req).await;
assert_eq!(returned, note);
}
#[ntex::test]
async fn malformed_json_is_rejected() {
let app = test::init_service(App::new().configure(config)).await;
let req = test::TestRequest::post()
.uri("/preview")
.header("content-type", "application/json")
.payload("{")
.to_request();
let res = test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
assert!(!test::read_body(res).await.is_empty());
}
}
TestRequest::json(&value) serializes the value and sets the JSON content
type. To test malformed input, use payload and set the content type yourself;
serializing a Rust value cannot produce invalid JSON. form(&value) is the
corresponding helper for URL-encoded form bodies. Headers, methods, and query
strings belong in the test request too, not just in direct extractor tests.
There are two JSON-reading patterns above. After call_service, deserialize
read_body(res) yourself when you need to inspect the status or headers.
read_response_json(&app, req) instead sends the request and deserializes its
body in one step. It takes an application and a request, not an already-read
response, and does not expose the status. The second request demonstrates that
shortcut; it is not needed to establish the first request’s HTTP contract.
The malformed-body test checks the status and that the response contains an explanation, without depending on the JSON parser’s exact wording. When your application promises a particular error schema or message, assert that schema or message instead. Add separate requests for other boundaries your endpoint has, such as a missing required field, a payload limit, an unknown path, or a method that is not registered. See Extractors and Responders for the corresponding request rules.
Test with application state
Use init_service_st(state, app) when the app has a state type other than
(). Supply the same kind of state that the server supplies, but build fresh
values for each test. A retained clone of a shared handle lets you check both
the HTTP response and the state change.
This counter uses AppState<Rc<Cell<usize>>>. Cloning it shares the counter;
it does not copy the numeric value into an independent counter:
use std::{cell::Cell, rc::Rc};
use ntex::http::StatusCode;
use ntex::web::{self, App, AppState, test};
type Hits = AppState<Rc<Cell<usize>>>;
async fn hit(hits: &Hits, (): ()) -> String {
hits.set(hits.get() + 1);
hits.get().to_string()
}
fn config(cfg: &mut web::ServiceConfig<Hits>) {
cfg.route("/hit", web::post().to_with_state(hit));
}
#[ntex::test]
async fn requests_share_the_supplied_counter() {
let hits = Hits::default();
let app = test::init_service_st(
hits.clone(),
App::<Hits>::new().configure(config),
)
.await;
for expected in ["1", "2"] {
let req = test::TestRequest::post().uri("/hit").to_request();
let res = test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(test::read_body(res).await, expected);
}
assert_eq!(hits.get(), 2);
}
to_with_state passes &Hits separately from extracted request arguments.
Here there are no request arguments, so the second argument is (). This
keeps the test setup close to the handler’s actual dependencies. For a database
or another external dependency, use a test implementation behind your own
state interface, or isolate a dedicated integration fixture; do not make a
routine route test depend on an external service being available.
Rc<Cell<_>> is suitable for this worker-local, in-process example. A real
test server runs in another thread, so you cannot capture this handle in its
Send factory. Create worker-local state inside the server factory, or use
appropriate Arc-based state when the test and worker must share it. The
Application State chapter explains the distinction between
worker state and request state in more detail.
Exercise middleware and error responses
Test middleware around an application, not only around a hand-built handler result. That checks its position relative to routing and error rendering. Include a request that reaches the handler and one that takes the rejection path.
This example requires a particular test API key and marks successful responses with an application header. It is a small middleware example, not a complete authentication scheme:
use ntex::http::{StatusCode, header::{HeaderName, HeaderValue}};
use ntex::web::{self, App, WebError, error, middleware::from_fn, test};
async fn report() -> &'static str {
"report ready"
}
#[ntex::test]
async fn middleware_allows_a_key_and_renders_rejections() {
let app = test::init_service(
App::new()
.middleware(from_fn(async |req, next| {
let allowed = req.headers().get("x-api-key")
.is_some_and(|value| value == "test-key");
if !allowed {
return Err(WebError::from_err(
error::ErrorForbidden("API key required"),
));
}
let mut res = next.call(req).await?;
res.headers_mut().insert(
HeaderName::from_static("x-application"),
HeaderValue::from_static("reports"),
);
Ok(res)
}))
.route("/report", web::get().to(report)),
)
.await;
let req = test::TestRequest::get().uri("/report").to_request();
let res = test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::FORBIDDEN);
assert_eq!(test::read_body(res).await, "API key required");
let req = test::TestRequest::get()
.uri("/report")
.header("x-api-key", "test-key")
.to_request();
let res = test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.headers().get("x-application").unwrap(), "reports");
assert_eq!(test::read_body(res).await, "report ready");
}
A rendered HTTP failure is normally a response you inspect, not an Err you
expect from call_service. That helper unwraps pipeline errors. The test
above checks the 403 and body the client would see after ntex renders the
middleware’s WebError. For custom handler errors, do the same through a route;
a unit test of the error’s Display implementation cannot verify the selected
HTTP status or the configured error domain.
Keep error assertions appropriate to the app’s public contract. Internal failures should not accidentally become successful responses, and private diagnostic details should not become part of a stable response schema. For response-path ordering and custom error domains, see Filters and Middleware and Web Application Errors.
Test a plain service with a pipeline
Services do not need HTTP requests or sockets. Wrap a service in
Pipeline::new(state, service) and call it with its ordinary request type.
The pipeline supplies the service context and waits for readiness before
calling the service. This is also the right level to test a reusable component
before putting it behind a web route or protocol dispatcher.
use std::io;
use ntex::service::{Pipeline, fn_service};
#[ntex::test]
async fn greeting_service_validates_names() {
let service = fn_service(async |name: String| {
let name = name.trim();
if name.is_empty() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "empty name"));
}
Ok::<_, io::Error>(format!("Hello, {name}!"))
});
let pipeline = Pipeline::new((), service);
assert_eq!(pipeline.call(" Ada ".into()).await.unwrap(), "Hello, Ada!");
let err = pipeline.call(" ".into()).await.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
pipeline.shutdown().await;
}
The first argument to Pipeline::new is service state, not the request. Use
() when none is needed. A function service needs an explicit result error
type, as in Ok::<_, io::Error>, so type inference has enough information.
Unlike the application test, the failure here is an actual service error, so
unwrap_err() is appropriate. HTTP error rendering has not happened. See the
Service Model and Service Pipelines chapters
for named services, composition, readiness, and shutdown. Test readiness or
shutdown explicitly when your own service has behavior there; successful
request assertions alone do not cover those hooks.
Test protocols with in-memory I/O
IoTest::create() returns a connected pair of in-memory transports. Wrap the
server end in Io, and use the client end to supply bytes and read replies.
This exercises your protocol’s real receive/send code without involving TCP.
use ntex::codec::BytesCodec;
use ntex::io::{Io, testing::IoTest};
use ntex::util::Bytes;
async fn echo_once(io: Io) {
let bytes = io.recv(&BytesCodec).await.unwrap().unwrap();
io.send(bytes, &BytesCodec).await.unwrap();
}
#[ntex::test]
async fn byte_protocol_echoes_in_memory() {
let (client, server) = IoTest::create();
client.remote_buffer_cap(1024);
let task = ntex::rt::spawn(echo_once(Io::from(server)));
client.write(b"ping");
assert_eq!(client.read().await.unwrap(), Bytes::from_static(b"ping"));
task.await.unwrap();
}
Set remote_buffer_cap on the client to allow the server transport to write
back. The default capacity is zero, so omitting it can leave an otherwise
correct reply waiting for write capacity. write makes input available to
the peer and wakes its reader; read().await waits for output. No sleep is
needed to give the server task a chance to run. Retaining and awaiting the task
also lets a panic in the protocol handler fail the test.
BytesCodec passes through available byte chunks. It does not impose message
boundaries, and neither TCP nor IoTest::read promises one read per application
message. For a framed protocol, use the same framing codec as production,
feed an incomplete frame and then its remainder, and test several frames
arriving together. Keep small decoder-only tests for invalid and truncated
frames as well; those do not need an I/O task at all.
IoTest can also inject transport failures with read_error and write_error,
or constrain write capacity to exercise backpressure. Add those cases when
your protocol handles them differently. The
I/O Abstraction Layer chapter covers the transport and
filter APIs used by these tests.
Use a real server for connection behavior
Move to a real listener when the behavior depends on the connection: HTTP client integration, streaming delivery, WebSocket upgrades, TLS negotiation, or connection shutdown. Keep ordinary route validation in-process so those tests stay small and independent of the networking stack.
Choose the helper at the layer you are testing:
web::test::servertakes a factory that returns an application.http::test::servertakes a factory that returns an I/O service, such as anHttpService, for lower-level HTTP tests.server::test_servertakes an I/O service factory for a custom TCP protocol.
These factories take async |_| ...; the argument is &(), even when it is
unused. The helpers bind an available loopback port. Use the returned server’s
address or URL instead of reserving a fixed port in the test.
Send a request with the HTTP client
Use an explicit client when the client configuration or client/server interaction is what you want to test:
use ntex::client::Client;
use ntex::http::StatusCode;
use ntex::web::{self, App, test};
async fn health() -> &'static str {
"ready"
}
#[ntex::test]
async fn client_receives_a_complete_response() {
let server = test::server(async |_| {
App::new().route("/health", web::get().to(health))
});
let client = Client::new();
let response = client.get(server.url("/health")).send().await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.body().await.unwrap(), "ready");
}
The server controller keeps the listener alive and stops the server when
dropped. The helper also offers server.get(path) and other request builders
using its own client. Use those when you do not need a separately configured
client. See Making HTTP Requests for client timeouts, JSON
bodies, TLS connectors, and streaming responses.
Collecting response.body() is enough to check the complete payload, but it
cannot prove when chunks arrived. A streaming test should consume the response
stream and coordinate the producer with explicit signals, asserting a chunk
before releasing the next one. For TLS, use a local test certificate and a
client that trusts that certificate or test CA; do not depend on a public HTTPS
site. See Securing Connections with TLS for connector setup.
Exchange WebSocket frames
A WebSocket test needs an actual upgrade and an upgraded connection. The test
server’s ws_at helper creates a WebSocket client for the selected route. This
example checks both the echoed text frame and a ping/pong exchange:
use ntex::util::Bytes;
use ntex::web::{self, App, HttpRequest, test, ws};
async fn echo(frame: ws::Frame) -> Result<Option<ws::Message>, std::io::Error> {
Ok(match frame {
ws::Frame::Text(text) => Some(ws::Message::Text(
String::from_utf8_lossy(&text).as_ref().into(),
)),
ws::Frame::Ping(bytes) => Some(ws::Message::Pong(bytes)),
ws::Frame::Close(reason) => Some(ws::Message::Close(reason)),
_ => None,
})
}
async fn socket(req: HttpRequest) {
let _ = ws::start(&req, None, echo).await;
}
#[ntex::test]
async fn websocket_echoes_text_and_answers_ping() {
let server = test::server(async |_| {
App::new().route("/ws", web::get().to(socket))
});
let (io, codec, _) = server.ws_at("/ws").await.unwrap().into_inner();
io.send(ws::Message::Text("hello".into()), &codec).await.unwrap();
assert_eq!(
io.recv(&codec).await.unwrap(),
Some(ws::Frame::Text(Bytes::from_static(b"hello"))),
);
io.send(ws::Message::Ping(Bytes::from_static(b"probe")), &codec)
.await
.unwrap();
assert_eq!(
io.recv(&codec).await.unwrap(),
Some(ws::Frame::Pong(Bytes::from_static(b"probe"))),
);
}
A successful ws_at call verifies that the handshake succeeded; receiving the
expected frames checks the upgraded protocol. Add close, binary, fragmentation,
or rejection cases only when they are part of your application’s behavior.
See WebSocket Support for frame handling and direct
WsClient configuration.
Keep asynchronous tests deterministic
Wait for the event you need: a response, a channel message, a task’s completion, or readable bytes. Sleeping for a guessed duration makes a test slow on a fast machine and unreliable on a busy one. Use a generous timeout as a failure bound when an operation might otherwise wait forever, not as evidence that another task has reached a particular point.
The ntex time utilities expose Sleep::elapse() and TimerHandle::elapse() to
complete an individual timer immediately. If your own component accepts such
a timer, retain access to it and trigger it when the test needs expiry. There
is no public pause-and-advance test clock in ntex-util: these methods do not
advance every timer, change now(), or expire an unrelated network timeout.
For other timing-dependent logic, separate the decision from the wait or pass
in a controllable dependency. See Timers and Time Utilities
for the timer APIs.
Give every test fresh application state, keep real listeners on dynamically assigned ports, and assert the exact status your client relies on. A green test should mean the intended route and response worked, not merely that the application builder returned successfully.
Making HTTP Requests
Use ntex::client when your service needs to call a payment provider, an
internal API, an object store, or a webhook.
If you have built a server with ntex, the client will feel familiar. It uses the same services, I/O layer, and shared configuration. It speaks HTTP/1.1 and HTTP/2, keeps connections open for reuse, and supports TLS through OpenSSL or rustls.
Optional features add response decompression and cookies. Middleware lets
you run your own logic on every request. To make a request, start with a
Client:
use ntex::client::Client;
#[ntex::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new();
let response = client
.get("http://127.0.0.1:8080/")
.header("user-agent", "ntex-guide")
.send()
.await?;
println!("status: {}", response.status());
let body = response.body().await?;
println!("body: {}", String::from_utf8_lossy(&body));
Ok(())
}
How the client works
Create a Client once and reuse it across requests. It owns connection
pools and configuration. An application usually keeps one client for each
kind of outgoing traffic throughout its lifetime. For example, a payment
provider and an internal API may need different timeouts and limits.
A Client is a lightweight handle. Cloning it is cheap, and all clones share
the same connection pools, so you can hand copies to every part of your code
that needs one. The handle is not Send, though: it belongs to the thread
that created it. In a server, the usual pattern is to create the clients once
per worker, for example in the application factory, and keep them in
application state.
When you send a request, it passes through a short chain of services:
ClientRequest ─► middleware ─► Sender ─► Connector ─┬─► plain pool ─► HTTP/1.1 connections
└─► TLS pool ─► HTTP/1.1 or HTTP/2 connections
A request starts as a ClientRequest. This is the builder you get from
client.get(...) and similar methods. It collects the method, URL, headers,
and body.
Next comes any middleware you installed. It can inspect or
change the outgoing request and the incoming response. Then the Sender
asks the Connector for a connection, writes the request, and waits for the
response head.
The Connector chooses a pool based on the URL scheme: http goes to
the plain pool, https to the TLS pool. Each pool keeps
connections grouped by host. An idle HTTP/1.1 connection is reused for the
next request to the same host. An HTTP/2 connection can carry many requests
at once, so concurrent requests to the same host share it.
You don’t pick the HTTP version yourself. For https URLs, client and server
settle it during the TLS handshake using ALPN: the client offers h2 and
http/1.1, and the server chooses. Plain http URLs always use HTTP/1.1.
An HTTP/1.1 connection goes back to the pool only after you read its response body to the end. If you drop a response without reading the body, the client can’t tell what is left on the wire, so it closes the connection instead. Read the body to reuse the connection, even when you don’t care what’s in it.
You don’t have to shut the client down explicitly. Once the last clone and every request made with it are dropped, the pools close idle connections in the background, and HTTP/2 connections close gracefully after their in-flight requests finish.
The client is for requests and responses. WebSockets have their own client,
ntex::ws::WsClient, covered in
WebSocket Support.
Configuration
Client::new() uses defaults that work for a quick script. For a service,
you will usually want to tune at least the timeouts.
Configuration works the same way as on an ntex server. You put
configuration objects into a SharedCfg and build the client from it. A
single SharedCfg can hold several configuration types, and each part of the
client picks out the one it cares about:
| Configuration | Read by | What it controls |
|---|---|---|
ClientConfig | The client | Timeouts, payload limits, pool sizes, default headers |
IoConfig | Connector and connections | Connect timeout, buffer sizes, backpressure, shutdown timeout |
TlsConfig | TLS connectors | TLS handshake timeout |
HttpServiceConfig | HTTP/1.1 response parser | Maximum number of headers and size of the response head |
Http2ServiceConfig | HTTP/2 connections | Window sizes, frame size, ping and handshake timeouts |
Anything you leave out keeps its defaults. The name you give the SharedCfg
shows up in logs, so choose one that tells you which client is talking.
Client settings
For an API client, start by deciding how long to wait and how much response
data to buffer. ClientConfig groups those limits with connection-pool
settings and headers that should accompany every request:
use ntex::client::{Client, ClientConfig};
use ntex::http::error::HttpError;
use ntex::{SharedCfg, time::Seconds};
fn api_client(token: &str) -> Result<Client, HttpError> {
let cfg = SharedCfg::new("API-CLIENT").add(
ClientConfig::new()
.set_response_timeout(Seconds(10))
.set_response_payload_limit(4 * 1024 * 1024)
.set_h1_connection_limit(32)
.set_header("user-agent", "my-service/1.0")?
.set_bearer_auth(token)?,
);
Ok(Client::with_config(cfg))
}
The timeout settings control individual requests; the connection settings control how the client shares and reuses connections:
| Setting | Default | Meaning |
|---|---|---|
set_response_timeout | 5 s | Time to wait for the response head after the request is sent; disable_timeout() sets it to zero |
set_response_payload_limit | 256 KiB | Largest body that body() and json() will buffer; 0 means no limit |
set_response_payload_timeout | 10 s | Time allowed for body() and json() to read the whole body; independent of the response timeout |
set_h1_connection_limit | 8 | HTTP/1.1 connections per pool, shared by all hosts |
set_h1_keepalive | 15 s | How long an idle HTTP/1.1 connection may wait in the pool |
set_h1_lifetime | 75 s | Maximum age of a pooled HTTP/1.1 connection |
set_h2_connection_limit | 16 | HTTP/2 connections per host |
set_h2_max_streams | 100 | Concurrent requests per HTTP/2 connection |
set_h2_keepalive | 60 s | How long an idle HTTP/2 connection is kept |
set_h2_lifetime | 1 h | Maximum age of an HTTP/2 connection |
Connection limits don’t make requests fail. When every connection is busy, new requests wait their turn. The plain and TLS pools count connections separately.
Use set_header to add a header to every request the client sends.
set_basic_auth and set_bearer_auth set authentication headers the same
way. If a request sets a header with the same name, the request wins.
These methods return a Result because a header name or value can be
invalid. The example uses ? to pass those errors to the caller.
I/O settings
Client connections are ordinary ntex I/O objects, so everything in
IoConfig from the I/O chapter applies to them. The setting
you are most likely to need is the connect timeout. It is off by default,
which means a request to an unreachable host waits for as long as the
operating system is willing to try. In production, set one:
use ntex::client::{Client, ClientConfig};
use ntex::io::IoConfig;
use ntex::{SharedCfg, time::Seconds};
fn client() -> Client {
let cfg = SharedCfg::new("API-CLIENT")
.add(ClientConfig::new().set_response_timeout(Seconds(10)))
.add(IoConfig::new().set_connect_timeout(Seconds(3)));
Client::with_config(cfg)
}
A request moves through several stages. Each timeout covers exactly one of them, and turning one off leaves the others in place:
- Waiting for a pooled connection when the connection limit is reached:
no timeout. Wrap
send()inntex::time::timeoutif you need one. - Connecting, including the DNS lookup:
IoConfig::set_connect_timeout, off by default. - The TLS handshake:
TlsConfig::set_handshake_timeout, 5 seconds. - Sending the request body: no client timeout. For HTTP/1.1,
IoConfig::set_write_timeout, off by default, bounds each wait for the socket to accept more data, but not a slow body stream. - Waiting for the response head:
ClientConfig::set_response_timeout, 5 seconds, ortimeout()on an individual request. - Reading the body with
body()orjson():ClientConfig::set_response_payload_timeout, 10 seconds, ortimeout()on the body future. Reading the response as a stream has no timeout.
ClientConfig::disable_timeout() only removes the response-head timeout.
So does timeout(Millis::ZERO). A slow body still fails after the payload
timeout unless you also set set_response_payload_timeout(Millis::ZERO).
There is no single deadline for the whole request. To set one, wrap the
whole exchange in ntex::time::timeout, including send() and reading the
body.
Secure connections
The client keeps two connectors, one for each kind of URL. http URLs go
through the plain connector, which opens a TCP connection. https URLs go
through the secure connector, which opens a TCP connection and then performs
the TLS handshake on it. The builder lets you replace each one separately:
connector() sets the plain connector and secure_connector() the secure
one.
You rarely need to set the secure connector by hand. TLS comes from the
openssl or rustls feature of ntex. Enable one, and Client::new() and
Client::builder() install a secure connector for you. Its default trust
roots depend on the backend.
The rustls connector checks server certificates against the webpki roots. OpenSSL uses its default trust store (the system roots) and checks that the certificate matches the request host. If your server uses a private root or a self-signed certificate for testing, supply a configuration that trusts it rather than disabling verification.
If both features are enabled, OpenSSL wins. If neither is, https requests
fail with ConnectError::SslIsNotSupported.
To use your own TLS configuration, hand it to the builder; .rustls() and
.openssl() build a secure connector from it. The builder uses
it exactly as given, so if you want HTTP/2, set the ALPN protocols yourself:
use ntex::{SharedCfg, client::Client};
use rustls::{ClientConfig, RootCertStore};
fn https_client() -> Client {
let roots = RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
let mut tls = ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
tls.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
Client::builder().rustls(tls).build(SharedCfg::new("HTTPS-CLIENT"))
}
OpenSSL works the same way: build an openssl::ssl::SslConnector, set ALPN
with set_alpn_protos(b"\x02h2\x08http/1.1"), and pass it to .openssl().
.rustls() wraps your configuration in
ntex::connect::rustls::TlsConnector. .openssl() uses
ntex::connect::openssl::SslConnector. Both pass the connector to
secure_connector().
You can also call secure_connector() directly with your own connector.
It might use OpenSSL or rustls with different settings, or another TLS
implementation, such as Schannel on Windows or Secure Transport on macOS.
The client does not depend on how the connection is secured.
A connector is a service that takes a ntex::connect::Connect holding the
target URL and returns an I/O object. If that object reports HTTP/2 as its
negotiated protocol, the client speaks HTTP/2 over it.
connector() takes the same kind of service for plain http URLs. Use it
when connections need something other than a direct TCP connection, for
example a tunnel through a proxy or a custom transport.
For certificate verification, private roots, and client certificates, see the TLS chapter.
Sending requests
Client has a method for each common HTTP verb: get, post, put,
patch, delete, head, options, and query. For anything else there is
request(method, url). Each returns a ClientRequest builder.
URLs must be absolute, with an http or https scheme and a host. The
builder methods never return errors. If a URL or header is invalid, or a
query won’t serialize, the builder saves the error until you send the
request. The builder chain needs no ?.
Common requests
A JSON API usually needs the same short sequence: build a request, send it,
then deserialize the response. This example looks up users by name and creates
one. It expects GET /users to return a JSON array and POST /users to return
the created user:
use ntex::{client::Client, time::Seconds};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct User {
id: u64,
name: String,
}
#[derive(Serialize)]
struct NewUser<'a> {
name: &'a str,
}
#[ntex::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new();
let response = client
.get("http://127.0.0.1:8080/users")
.query(&[("name", "Ferris")])
.header("accept", "application/json")
.timeout(Seconds(2))
.send()
.await?;
let users: Vec<User> = response.json().timeout(Seconds(5)).await?;
for user in users {
println!("{}: {}", user.id, user.name);
}
let response = client
.post("http://127.0.0.1:8080/users")
.header("accept", "application/json")
.send_json(&NewUser { name: "Ferris" })
.await?;
let user: User = response.json().await?;
println!("created user {}: {}", user.id, user.name);
Ok(())
}
The GET uses query() so you do not have to build or escape the query string
yourself. The Accept header asks for a JSON response; it does not describe the
request body. For the POST, send_json() serializes NewUser and sets
Content-Type: application/json unless you already set a content type.
The two timeouts cover different waits. On the request builder, timeout()
bounds the wait for response headers after sending. On json(), it bounds
reading the response body. Neither is an overall deadline; see the
timeout stages when you need to bound the complete exchange.
This example assumes successful responses have the expected JSON shape. If the
API uses a different shape for errors, check response.status() before
choosing how to read the body. An HTTP error status does not make send() fail;
request errors are a separate concern.
Building the request
Once the basic exchange works, you can adapt the builder to the API’s requirements. This search request adds pagination, optional authentication, and a per-request timeout:
use serde::Serialize;
use ntex::client::Client;
use ntex::time::Seconds;
#[derive(Serialize)]
struct Search<'a> {
q: &'a str,
page: u32,
}
async fn search(client: &Client, token: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
let response = client
.get("https://api.example.com/search")
.query(&Search { q: "ntex", page: 2 })
.header("accept", "application/json")
.if_some(token, |token, req| req.bearer_auth(token))
.timeout(Seconds(2))
.send()
.await?;
println!("{}", response.status());
Ok(())
}
query() serializes any serde::Serialize value into the query string,
replacing whatever was there.
Use if_some() to apply a change only when an Option has a value. Here,
it adds a token only when there is one. if_true() does the same for a
bool. Both keep conditional changes within the builder chain.
timeout() overrides the client’s response-head timeout for this request.
A zero duration turns that timeout off. It leaves the payload timeout and
any connect timeout in place.
Use header() when a header may have several values: it appends rather than
replaces. If you mean to override an earlier value, use set_header() instead.
set_header_if_none() is useful for a fallback that should leave an existing
value alone.
content_type() and content_length() are shortcuts for the two most
common headers. For authentication, use basic_auth(user, password) or
bearer_auth(token). With the cookie feature, cookie() attaches a
cookie.
A few methods control the connection itself. force_close() closes an
HTTP/1.1 connection after the response instead of returning it to the pool.
address() connects to a specific socket address and skips DNS. The URL
still decides the Host header and the TLS server name, which makes this
useful for testing a particular backend behind a load balancer.
With the compress feature, the client asks servers for compressed
responses and decompresses them for you. no_decompress() turns that off for
a single request, which is usually useful in a proxy.
client.request_from(url, head) also helps when writing a proxy. It starts
a request with the method and headers copied from an incoming one.
Sending a body
Choose the send method that matches your body:
| Method | Body |
|---|---|
send() | No body |
send_body(body) | Anything that converts to Body: &'static str, String, Bytes, Vec<u8>, … |
send_json(&value) | value serialized as JSON; sets Content-Type: application/json unless you set one |
send_form(&value) | value serialized as a URL-encoded form; sets the matching content type |
send_stream(stream) | A stream of Result<Bytes, E> chunks, sent as they arrive |
For a text endpoint, choose send_body and set the content type yourself.
For JSON and form endpoints, let send_json or send_form serialize your
value and set the matching content type:
use serde::Serialize;
use ntex::client::Client;
#[derive(Serialize)]
struct NewUser<'a> {
name: &'a str,
email: &'a str,
}
async fn send_bodies(client: &Client) -> Result<(), Box<dyn std::error::Error>> {
// Raw bytes or text
client.post("http://127.0.0.1:8080/notes")
.content_type("text/plain")
.send_body("remember the milk")
.await?;
// JSON
let user = NewUser { name: "ferris", email: "[email protected]" };
client.post("http://127.0.0.1:8080/users").send_json(&user).await?;
// A URL-encoded form
client.post("http://127.0.0.1:8080/login")
.send_form(&[("user", "ferris"), ("password", "secret")])
.await?;
Ok(())
}
send_stream() is for bodies that are large, or that are produced while the
request is already underway. The body never has to sit in memory all at
once. Any Stream of Result<Bytes, E> will do. In this example, a separate
task produces the chunks and passes them through a channel:
use ntex::{channel::mpsc, client::Client, util::Bytes};
async fn upload(client: &Client) -> Result<(), Box<dyn std::error::Error>> {
let (tx, rx) = mpsc::channel::<Result<Bytes, std::io::Error>>();
ntex::rt::spawn(async move {
for i in 0..10 {
let chunk = Bytes::from(format!("line {i}\n"));
if tx.send(Ok(chunk)).is_err() {
break; // the request was dropped
}
}
});
let response = client
.post("http://127.0.0.1:8080/upload")
.send_stream(rx)
.await?;
println!("{}", response.status());
Ok(())
}
Because the total length isn’t known up front, HTTP/1.1 sends the body with chunked transfer encoding. If the stream yields an error, the request fails.
When something goes wrong
Every send method returns Result<ClientResponse, Error<ClientError>>.
Error dereferences to ClientError, so you can match on what went wrong
and react accordingly:
use ntex::client::{Client, error::ClientError};
async fn fetch(client: &Client) {
match client.get("http://127.0.0.1:8080/").send().await {
Ok(response) => println!("status: {}", response.status()),
Err(err) => match &*err {
ClientError::Timeout => eprintln!("the server took too long to answer"),
ClientError::Connect(e) => eprintln!("could not connect: {e}"),
_ => eprintln!("request failed: {err}"),
},
}
}
A 404 or a 500 is not an error here. The server received the request and
answered it. Check response.status() to decide what that answer means for
your application.
Reading responses
send() completes as soon as the response head arrives. You can look at the
status and headers right away, while the body may still be on its way.
use ntex::client::ClientResponse;
use ntex::http::{StatusCode, header};
fn inspect(response: &ClientResponse) {
if response.status() == StatusCode::NOT_FOUND {
println!("no such resource");
}
println!("version: {:?}", response.version());
if let Some(value) = response.header(header::CONTENT_TYPE) {
println!("content type: {value:?}");
}
for (name, value) in response.headers() {
println!("{name}: {value:?}");
}
}
ClientResponse also implements HttpMessage, which brings helpers such as
content_type() and, with the cookie feature, cookies().
For a small JSON document or text response, buffer the body and work with the result. For a large download or an open-ended feed, read it as a stream so you do not have to keep the whole response in memory.
Buffering the body
If the body is reasonably small, read it all at once. body() collects it
into Bytes. json::<T>() deserializes it with serde and refuses responses
whose content type isn’t JSON.
Both enforce the payload limit and payload timeout from ClientConfig.
You can adjust either for a single response:
use serde::Deserialize;
use ntex::client::Client;
use ntex::time::Seconds;
#[derive(Deserialize)]
struct User {
id: u64,
name: String,
}
async fn read(client: &Client) -> Result<(), Box<dyn std::error::Error>> {
// Up to 10 MB, within 30 seconds
let response = client.get("http://127.0.0.1:8080/report.csv").send().await?;
let report = response.body().limit(10 * 1024 * 1024).timeout(Seconds(30)).await?;
println!("report: {} bytes", report.len());
// A JSON document
let response = client.get("http://127.0.0.1:8080/users/1").send().await?;
let user: User = response.json().await?;
println!("user {}: {}", user.id, user.name);
Ok(())
}
The limit is there to protect you. A misbehaving server could otherwise send
you gigabytes, and you’d buffer every byte. If the response declares a
Content-Length above the limit, the read fails right away without reading
any of the body.
The body can be read only once. body() and json() take the payload as
soon as you call them, before the future first runs. Dropping the future
also drops the body. Any later body(), json() or stream read fails with
PayloadError::AlreadyTaken instead of silently returning nothing. A
response that never had a body still reads as empty bytes.
json() checks the content type before taking the payload, so after a
ContentType error you can still read the body. Once the JSON fails to
parse, though, the bytes are gone. If you need the raw body on failure, for
example to log an error page, buffer it once and parse it yourself:
use serde::Deserialize;
use ntex::client::Client;
#[derive(Deserialize)]
struct User {
id: u64,
}
async fn read(client: &Client) -> Result<(), Box<dyn std::error::Error>> {
let response = client.get("http://127.0.0.1:8080/users/1").send().await?;
let body = response.body().await?;
match serde_json::from_slice::<User>(&body) {
Ok(user) => println!("user {}", user.id),
Err(e) => println!("bad response ({e}): {}", String::from_utf8_lossy(&body)),
}
Ok(())
}
Streaming the body
For large downloads, or bodies with no fixed end, read the response chunk by
chunk. ClientResponse is itself a Stream, and ntex::util::stream_recv
waits for the next chunk:
use ntex::{client::Client, util::stream_recv};
async fn download(client: &Client) -> Result<usize, Box<dyn std::error::Error>> {
let mut response = client.get("http://127.0.0.1:8080/large-file").send().await?;
let mut total = 0;
while let Some(chunk) = stream_recv(&mut response).await {
let chunk = chunk?;
total += chunk.len(); // write the chunk to a file, a socket, ...
}
Ok(total)
}
Since you only hold one chunk at a time, the payload limit and payload
timeout don’t apply here. If you need them, enforce them in the loop. To pass
the body on to something else, such as a response in a proxy, take it with
take_payload().
Middleware
Middleware wraps the client’s service chain. Each request passes through it on the way out, and each response on the way back. It is the same idea as web middleware, pointed in the other direction.
Why use middleware
Some things should happen on every request, no matter where in your code the request is made. Without middleware, you’d have to remember them at every call site. Middleware gives those concerns one place to live.
For example, authentication middleware can read an access token that a background task refreshes. Tracing middleware can add a request ID or trace context, while logging and metrics record the method, URL, status, and latency.
Middleware can also enforce policy by refusing calls to disallowed hosts, or rewrite requests to point at a test server. On the way back, it can adjust response headers before the caller sees them.
You don’t need middleware for headers that never change, such as a fixed
User-Agent or a static API key. The default headers in ClientConfig
handle those.
How middleware works
Install middleware with ClientBuilder::middleware(). For a closure-based
layer, use fn_layer from ntex::service. It turns an async closure into
middleware. The closure gets the request and the next service in the chain,
and returns whatever that service returns.
This layer adds an Authorization header. It reads the token for each
request, so a refreshed token is picked up immediately:
use std::{cell::RefCell, rc::Rc};
use ntex::client::{Client, ServiceRequest};
use ntex::http::header::{AUTHORIZATION, HeaderValue};
use ntex::{SharedCfg, service::fn_layer};
fn client(token: Rc<RefCell<HeaderValue>>) -> Client {
Client::builder()
.middleware(fn_layer(async move |mut req: ServiceRequest, svc| {
// Read the current token for every request
let value = token.borrow().clone();
req.headers().insert(AUTHORIZATION, value);
svc.call(req).await
}))
.build(SharedCfg::new("API-CLIENT"))
}
Middleware works with a ServiceRequest, the request as it is about to
be sent, rather than the ClientRequest builder. head() gives you the
method, URL, and headers.
headers() is a separate set of headers that take precedence over those in
the head. Use it to add or override a header. body() gives you the body,
and address() gives you the target address.
On the way back, middleware gets a ServiceResponse before it becomes a
ClientResponse. head() holds the status and headers. payload() holds
the body stream.
Middleware sees the response as soon as its head arrives, before the body is read. Timing a request in middleware measures the wait for the response head, not the full download.
Middleware can stop a request by returning an error instead of calling the next service. It can’t invent a response, though; every successful response comes from a real server.
You can stack several middleware. The first one you add is the outermost: it sees the request first and the response last.
For middleware you want to reuse, or that needs its own readiness or
shutdown logic, implement the Middleware trait and a service, just as you
would on a server. The only differences are the types: the configuration is
SharedCfg and the request is ServiceRequest. Here is middleware that logs
how each request went:
use std::time::Instant;
use ntex::client::{ServiceRequest, ServiceResponse, error::ClientError};
use ntex::{Ctx, Middleware, Service, SharedCfg, error::Error};
/// Logs the method, URL, status, and latency of every request.
pub struct Timing;
pub struct TimingService<S> {
service: S,
}
impl<S> Middleware<S, SharedCfg> for Timing {
type Service = TimingService<S>;
fn create(&self, _: &SharedCfg, service: S) -> Self::Service {
TimingService { service }
}
}
impl<S> Service<SharedCfg, ServiceRequest> for TimingService<S>
where
S: Service<SharedCfg, ServiceRequest, Res = ServiceResponse, Error = Error<ClientError>>,
{
type Res = ServiceResponse;
type Error = Error<ClientError>;
ntex::forward!(SharedCfg, service);
async fn call(
&self,
mut req: ServiceRequest,
ctx: Ctx<'_, Self, SharedCfg>,
) -> Result<ServiceResponse, Self::Error> {
let method = req.head().method.clone();
let url = req.head().uri.to_string();
let start = Instant::now();
let mut result = ctx.call(&self.service, req).await;
match &mut result {
Ok(res) => log::info!("{method} {url} -> {} in {:?}", res.head().status, start.elapsed()),
Err(err) => log::warn!("{method} {url} failed after {:?}: {err}", start.elapsed()),
}
result
}
}
Installing it looks just like the closure version:
use ntex::client::{ServiceRequest, ServiceResponse, error::ClientError};
use ntex::{Ctx, Middleware, Service, SharedCfg, error::Error};
pub struct Timing;
pub struct TimingService<S> { service: S }
impl<S> Middleware<S, SharedCfg> for Timing {
type Service = TimingService<S>;
fn create(&self, _: &SharedCfg, service: S) -> Self::Service { TimingService { service } }
}
impl<S> Service<SharedCfg, ServiceRequest> for TimingService<S>
where S: Service<SharedCfg, ServiceRequest, Res = ServiceResponse, Error = Error<ClientError>>,
{
type Res = ServiceResponse;
type Error = Error<ClientError>;
ntex::forward!(SharedCfg, service);
async fn call(&self, req: ServiceRequest, ctx: Ctx<'_, Self, SharedCfg>) -> Result<ServiceResponse, Self::Error> {
ctx.call(&self.service, req).await
}
}
let client = ntex::client::Client::builder()
.middleware(Timing)
.build(SharedCfg::new("API-CLIENT"));
Retries are usually easier in application code, where you can build the
request again. Sending consumes the request, and a streaming body can only
be sent once. Middleware has no copy of ServiceRequest left to resend.
To see a complete program, look at the HTTP client example and the HTTP proxy example.
HTTP/2 with ntex-h2
ntex-h2 is a separate crate that implements HTTP/2 for ntex. Most
applications use it indirectly through ntex::http or ntex::web. When a
connection negotiates HTTP/2, ntex-h2 handles frames, header compression,
streams, and flow control. ntex turns each stream into requests and
responses.
Use ntex-h2 directly when you only need HTTP/2, need trailers or long-lived bidirectional streams, or want to manage flow control yourself. ntex-grpc uses it this way for both its client and its server.
For outgoing requests, client::Client opens and reuses a pool of connections
to one server. Choose client::SimpleClient instead when you want to manage
one connection yourself. On the receiving side, server::Server is an ntex
service that handles HTTP/2 connections.
ntex-h2 speaks only HTTP/2 and does not negotiate the protocol. Any
transport you give it must already be committed to HTTP/2. Over TLS, ALPN
must have selected h2. Over plain TCP (h2c), both sides must know in
advance that they will use HTTP/2.
The HTTP/1.1 Upgrade mechanism and server push are not supported.
Here is a client that sends a GET request over plain TCP and prints the
response:
use ntex::SharedCfg;
use ntex::http::{HeaderMap, Method};
use ntex_h2::{MessageKind, StreamEof, client::Client};
#[ntex::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::builder("127.0.0.1:8080").build(SharedCfg::new("H2-CLIENT"));
let (_send, recv) = client
.send(Method::GET, "/index.html".into(), HeaderMap::new(), true)
.await?;
while let Some(msg) = recv.recv().await {
match msg.kind {
MessageKind::Headers { pseudo, .. } => println!("status: {:?}", pseudo.status),
MessageKind::Data(data, _) => println!("data: {data:?}"),
MessageKind::Eof(StreamEof::Data(data, _)) => println!("last data: {data:?}"),
MessageKind::Eof(_) | MessageKind::Disconnect(_) => break,
}
}
Ok(())
}
This API works with HTTP/2 streams and messages. Unlike
ntex::client, it has no URLs, body helpers, or Response
type.
Streams and messages
Each HTTP/2 stream carries one request and its response. Many independent streams can share a connection. The client opens a stream by sending request headers. Both sides can then send data, and each closes its own half when it is done.
Either side can cut a stream short with a reset. The connection and its other streams stay open.
A StreamRef identifies a stream and lets you send on it. It is cheap to
clone. Everything that arrives on a stream reaches you as a Message:
pub struct Message {
pub stream: StreamRef,
pub kind: MessageKind,
}
A client and a server see the same sequence. It begins with
Headers { pseudo, headers, eof }, the request or response head. The pseudo
field holds HTTP/2’s pseudo-headers: method, scheme, authority, and path
on requests, and status on responses. If eof is true, there is no body
and this is the only message.
Otherwise, any number of Data(Bytes, Capacity) messages carry body chunks.
Each Capacity represents the flow-control credit used by its chunk; the
flow-control section explains when to release it.
Exactly one Eof(StreamEof) or Disconnect(err) ends the sequence.
StreamEof::Data carries a final body chunk, StreamEof::Trailers carries
trailing headers, and StreamEof::Error reports a failed or reset stream.
Disconnect means the whole connection failed while the stream was open.
Send headers first, using send on a client or send_response on a
server. Then send body chunks with send_payload, as many times as needed.
To finish, set eof on the last call or send trailers with send_trailers.
Configuration
Start with limits that suit the requests your service handles. A large upload
may need different receive windows from a small JSON call, and a shared
connection needs room for several streams. ServiceConfig sets those limits and
timeouts. Add it to a SharedCfg to apply it to every connection created with
that configuration:
use ntex::{SharedCfg, time::Seconds};
use ntex_h2::ServiceConfig;
fn config() -> SharedCfg {
SharedCfg::new("H2")
.add(
ServiceConfig::new()
.set_max_concurrent_streams(128)
.set_initial_window_size(256 * 1024)
.set_initial_connection_window_size(4 * 1024 * 1024)
.set_ping_timeout(Seconds(30)),
)
.into()
}
ntex::http exposes this same type as Http2ServiceConfig. These
settings also apply to HTTP/2 in an ntex web server or HTTP client.
ntex-h2 connections use ordinary ntex I/O objects. Add an IoConfig to
the same SharedCfg to control buffers and backpressure, as described in
the I/O chapter.
The flow-control and frame settings determine how much data the peer may send:
| Setting | Default | Meaning |
|---|---|---|
set_initial_window_size | 64 KiB − 1 | Receive window of each stream: how much body data the peer may send on a stream before it must wait |
set_initial_connection_window_size | 4 MiB | Receive window shared by all streams of a connection |
set_max_frame_size | 16 KiB | Largest frame payload the peer may send. Allowed range is 16 KiB to 16 MiB − 1 |
Receive windows bound body data, but headers and stream bookkeeping also take space. Use these limits to bound the work and state a peer can create:
| Setting | Default | Meaning |
|---|---|---|
set_max_concurrent_streams | 256 | Streams the peer may have open at once. Further streams are refused with REFUSED_STREAM |
set_max_headers | 96 | Header fields allowed in one header block. A stream with more is refused |
set_max_header_list_size | 48 KiB | Total size of a header block |
set_max_header_continuation_frames | 5 | CONTINUATION frames allowed for one header block |
set_max_concurrent_reset_streams | 32 | Recently reset streams remembered so late frames for them are ignored; 0 disables the history |
set_reset_stream_duration | 30 s | How long a reset stream is remembered |
set_max_inflight_messages | 8192 | Messages waiting for your code. When the limit is reached, the connection stops reading until some are handled |
Finally, keep a stalled peer from holding connection resources indefinitely. These timeouts cover the handshake and ongoing protocol exchanges:
| Setting | Default | Meaning |
|---|---|---|
set_handshake_timeout | 5 s | Time allowed for the connection preface |
set_settings_timeout | 5 s | Time the peer has to acknowledge a SETTINGS frame |
set_ping_timeout | 10 s | Keep-alive interval. If a PING is not answered in time, the connection is closed |
set_capacity_timeout | 5 s | Longest a sender waits for flow-control window before the stream is reset; 0 disables it |
Stream limits apply only to streams the peer opens. On a server,
set_max_concurrent_streams caps how many requests a client may run at
once. A client is bound by the limit the server announces.
ntex-h2 also guards against rapid-reset attacks. It closes a connection
with GOAWAY if at least ten streams have been opened and half of them
were reset.
The client
A client sends requests to one server. You can let a pool manage its connections or manage a single connection yourself.
Connecting with a pool
Use client::Client to reuse connections without managing them yourself.
Like the HTTP client, create it once and keep it for the
life of the application. Clones are cheap and share the same connections.
Each request needs a free stream slot, not a connection of its own. The pool
looks for a connection that can open another stream and opens a new connection
when needed. You can also ask it to grow to a minimum size with minconn.
Create the pool with a builder. Pass the configuration for all its
connections to build:
use ntex::{SharedCfg, time::Seconds};
use ntex_h2::{ServiceConfig, client::Client};
fn backend() -> Client {
let cfg = SharedCfg::new("BACKEND").add(ServiceConfig::new().set_ping_timeout(Seconds(30)));
Client::builder("backend.internal:8080")
.connect_timeout(Seconds(3))
.connection_limit(4)
.lifetime(Seconds(600))
.build(cfg)
}
The builder has these options:
| Option | Default | Meaning |
|---|---|---|
connector | TCP | The transport connector, for example a TLS connector |
secure | false | Sets the :scheme of requests to https instead of http |
connect_timeout | 1 s | Time allowed to connect, including the TLS handshake |
minconn | 1 | Below this many connections, the pool opens a new one for a request even if an existing connection has room |
connection_limit | 16 | Maximum number of connections |
max_streams | 100 | Streams a connection is assumed to accept until the server announces its own limit |
lifetime | not set | Age after which a connection is closed gracefully and replaced |
disconnect_timeout | 15 s | Time a closing connection has to finish its streams |
skip_unknown_streams | off | Ignore frames for streams the client no longer knows instead of treating them as errors |
When every connection is full and the pool is at its limit, send waits
for a stream to free up. Errors before a stream opens, such as a failed
connection attempt or a timeout, are reported as ClientError.
The pool opens new connections one at a time and spreads requests across them. It prefers connections using less than half of their stream limit.
Secure connections
To connect over TLS, give the pool a TLS connector that offers h2
through ALPN. Also set secure(true) so requests carry the https scheme.
Here is an OpenSSL configuration:
use ntex::SharedCfg;
use ntex_h2::client::Client;
use openssl::ssl::{SslConnector, SslMethod};
fn secure_client() -> Result<Client, openssl::error::ErrorStack> {
let mut builder = SslConnector::builder(SslMethod::tls())?;
builder.set_alpn_protos(b"\x02h2")?;
Ok(Client::builder("api.example.com:443")
.connector(ntex::tls::openssl::SslConnector::new(builder.build()))
.secure(true)
.build(SharedCfg::new("API")))
}
The ALPN list b"\x02h2" is the protocol name h2 prefixed with its
length. With rustls, set alpn_protocols to vec![b"h2".to_vec()] in its
ClientConfig.
Unlike ntex::client, ntex-h2 cannot fall back to HTTP/1.1. If you also
offer http/1.1, make sure the server will pick h2.
A single connection
Use client::SimpleClient to keep a session on one connection or run
HTTP/2 over a transport you created. It wraps a single connection that you
have already established:
use ntex::{SharedCfg, io::Io, util::ByteString};
use ntex_h2::client::SimpleClient;
async fn connect() -> Result<SimpleClient, Box<dyn std::error::Error>> {
let cfg: SharedCfg = SharedCfg::new("H2").into();
let io: Io = ntex::connect::connect_with("127.0.0.1:8080", &cfg).await?;
Ok(SimpleClient::new(io, false, ByteString::from("127.0.0.1")))
}
The arguments are the transport, whether requests use the https scheme,
and the :authority sent with each request. The connection reads its
ServiceConfig from the transport’s SharedCfg.
To avoid setting this up by hand, use client::Connector. This ntex
service takes an address and returns a SimpleClient.
SimpleClient is cheap to clone. The connection stays open while any clone
exists and closes gracefully when the last one is dropped.
To stop earlier, call close(): open streams may finish, but no new ones can
start. If you also need to wait until the connection is gone, use
disconnect().await, with .disconnect_timeout(..) on the returned future to
bound the wait. Reserve force_close() for cases where you must drop the
connection immediately.
Use is_closed() to check whether the connection has closed.
on_disconnect() tells you when it closes, whether you or the server
initiated it.
A pool manages the connection lifecycle for you. If you need access to one
of its connections, call Client::client(). It returns a SimpleClient
from the pool that can open another stream.
Sending a request
Call send to start a request. Pass the method, the :path including any
query string, the headers, and an eof flag.
It returns the two halves of the new stream. Use the SendStream for the
request body and the RecvStream for the response.
use ntex::http::{HeaderMap, Method, header};
use ntex::util::Bytes;
use ntex_h2::client::Client;
async fn upload(client: &Client, body: Bytes) -> Result<(), Box<dyn std::error::Error>> {
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, header::HeaderValue::from_static("application/octet-stream"));
let (send, recv) = client.send(Method::POST, "/upload".into(), headers, false).await?;
send.send_payload(body, true).await?;
// ... read the response from `recv`
drop(recv);
Ok(())
}
Set eof to true when the request has no body, as with most GET
requests. Otherwise, send the body with send_payload, which accepts
anything that converts to Bytes. Pass eof: true on the last call. If the
request has trailers, finish with send_trailers(headers) instead.
To stream a large body, call send_payload for each chunk:
use ntex::util::Bytes;
use ntex_h2::client::SendStream;
async fn stream_body(
send: &SendStream,
chunks: Vec<Bytes>,
) -> Result<(), ntex::error::Error<ntex_h2::OperationError>> {
for chunk in chunks {
send.send_payload(chunk, false).await?;
}
send.send_payload(Bytes::new(), true).await
}
You can read the response while still sending the request body. The two halves are independent, which supports bidirectional streaming protocols. Only one task should send on a stream at a time.
send_payload returns once it has handed the data to the connection. It
splits the data into frames that fit the peer’s maximum frame size and the
flow-control window. If the window is closed, it waits for the peer to
reopen it (see Flow control).
It also waits while the connection’s write buffer is full. A fast sender cannot outrun the network.
Reading the response
Read a response from its RecvStream with recv().await. Each call
returns the next message, or None once the
response is complete. You can also use stream combinators because
RecvStream implements Stream.
This function collects a whole response:
use ntex::http::{HeaderMap, StatusCode};
use ntex::util::{Bytes, BytesMut};
use ntex_h2::{MessageKind, StreamEof, client::RecvStream};
async fn read_response(
recv: RecvStream,
) -> Result<(StatusCode, HeaderMap, Bytes), Box<dyn std::error::Error>> {
let mut status = StatusCode::OK;
let mut headers = HeaderMap::new();
let mut body = BytesMut::new();
while let Some(msg) = recv.recv().await {
match msg.kind {
MessageKind::Headers { pseudo, headers: hdrs, .. } => {
status = pseudo.status.unwrap_or(StatusCode::OK);
headers = hdrs;
}
MessageKind::Data(chunk, _capacity) => body.extend_from_slice(&chunk),
MessageKind::Eof(StreamEof::Data(chunk, _capacity)) => {
body.extend_from_slice(&chunk);
break;
}
MessageKind::Eof(StreamEof::Trailers(_)) => break,
MessageKind::Eof(StreamEof::Error(err)) => return Err(err.into()),
MessageKind::Disconnect(err) => return Err(err.into()),
}
}
Ok((status, headers, body.freeze()))
}
Each Data message comes with a Capacity. The example drops it right
away, letting the server keep sending. Hold it to slow the server down, as
Flow control explains.
Resets and cancellation
To cancel a request, drop either unfinished half of its stream. Dropping
the RecvStream before the response is complete resets the stream with
CANCEL. Dropping the SendStream before the request body is complete does
the same. The server can then stop working on the request.
A timeout needs no extra cancellation code:
use ntex_h2::client::RecvStream;
async fn read_response(_: RecvStream) -> Result<(), Box<dyn std::error::Error>> { Ok(()) }
async fn example(recv: RecvStream) {
use ntex::time::{Seconds, timeout};
// If the timeout fires, `recv` is dropped and the stream is reset.
let result = timeout(Seconds(10), read_response(recv)).await;
}
Either side can reset a stream. Each reset carries a Reason code from
ntex_h2::frame::Reason, such as CANCEL or INTERNAL_ERROR. To choose a
reason, call reset(reason) on the SendStream or the StreamRef.
Use is_reset() to check whether either side has reset the stream.
on_reset() tells you when a reset happens.
When the server resets a stream, you receive Eof(StreamEof::Error(..)).
Further sends fail. When the whole connection fails, every open stream gets
a Disconnect message instead.
Stream limits
A server announces how many streams it accepts at once on each connection.
At that limit, SimpleClient::send waits until a stream finishes. The pool
uses another connection or opens a new one.
On a SimpleClient, compare active_streams() with max_streams() to see
how many slots are in use and what limit the server announced. Use is_ready()
to check for a free slot or ready().await to wait for one. If your code is
driven by callbacks, on_capacity(callback) runs whenever a stream is released.
Another task may take the free slot between your check and your send. Use
reserve() to claim a slot immediately. It returns a StreamReservation,
or None if the connection is full. The reservation’s send opens the
stream without waiting. Dropping an unused reservation releases the slot.
Flow control
Flow control keeps one slow consumer from stalling every stream on a connection. TCP’s own flow control is not enough when many HTTP/2 streams share that connection.
HTTP/2 gives each stream a window of credit, measured in bytes of body data. The connection has another window, shared by all streams. A sender can send only as much data as both windows allow. Headers do not count against either window.
Each DATA frame uses credit from both windows. When either reaches zero,
the sender must wait. The receiver grants more credit with a
WINDOW_UPDATE frame.
Receiving data
Keep each chunk’s Capacity until you have handled the data. It represents
the window credit the chunk used. Holding it keeps that credit in use, so
the sender’s pace follows your consumer’s pace.
Drop the Capacity to return the credit to both the stream and connection
windows. To release only part of it, call consume(n).
When you queue data for another task, pass the Capacity along with it.
The task should drop it only after handling the data:
use ntex::channel::mpsc;
use ntex::util::Bytes;
use ntex_h2::{Capacity, MessageKind, StreamEof, client::RecvStream};
// Forward the body to a consumer task. The server can only send as fast
// as the consumer drops the capacities.
async fn forward(recv: RecvStream, tx: mpsc::Sender<(Bytes, Capacity)>) {
while let Some(msg) = recv.recv().await {
match msg.kind {
MessageKind::Data(data, cap) => {
if tx.send((data, cap)).is_err() {
break; // consumer is gone, dropping `recv` resets the stream
}
}
MessageKind::Eof(StreamEof::Data(data, cap)) => {
let _ = tx.send((data, cap));
break;
}
MessageKind::Headers { .. } => {}
MessageKind::Eof(_) | MessageKind::Disconnect(_) => break,
}
}
}
ntex-h2 batches WINDOW_UPDATE frames. It waits until released credit
reaches a third of initial_window_size for a stream, or a quarter of
initial_connection_window_size for the connection.
Unreleased data also counts against the shared connection window. A stream that buffers a lot of data without releasing its credit can slow down the others. The default connection window is therefore much larger than the stream window: 4 MiB versus 64 KiB per stream.
Size the windows together. The stream window limits how much a single request can buffer. The connection window limits the total across all requests.
If you merge chunks into one buffer, combine their capacities with + or
+= so you can release the credit together. Start with
StreamRef::empty_capacity() for a zero-sized capacity belonging to that
stream. Only combine capacities from the same stream; mixing streams panics.
If a peer sends more data than the window allows, the stream fails with
StreamError::RecvWindowExceeded.
Sending data
Use send_payload to send data within the peer’s flow-control window.
ntex-h2 tracks the granted credit and sends as much as the window allows.
It waits for more credit when needed, until all the data is out.
If you produce data on demand, check capacity before generating a chunk.
This avoids producing data that would sit in memory while you wait for the
peer. available_send_capacity() reports the current window, which is the
smaller of the stream’s and the connection’s window. To wait for credit before
producing the next chunk, use send_capacity().await; it returns the available
window size:
use ntex::util::Bytes;
use ntex_h2::client::SendStream;
fn produce(_: usize) -> Option<Bytes> { None }
async fn send_generated(send: &SendStream) -> Result<(), ntex::error::Error<ntex_h2::OperationError>> {
loop {
let window = send.send_capacity().await? as usize;
match produce(window) {
Some(chunk) => send.send_payload(chunk, false).await?,
None => return send.send_payload(Bytes::new(), true).await,
}
}
}
A peer that never opens its window could leave a sender waiting forever.
set_capacity_timeout bounds that wait to 5 seconds by default. If the wait
exceeds the timeout, ntex-h2 resets the stream with CANCEL. The send fails
with StreamError::CapacityTimeout.
The server
An ntex-h2 server gives your handlers direct access to stream messages. Your handlers send responses and keep any state they need for each stream.
Running a server
Use server::Server to serve HTTP/2 on an I/O object until the connection
closes. It is an ntex service, so you can run it with
ntex::server::build(), as described in the server chapter:
use ntex::http::{HeaderMap, StatusCode};
use ntex::{SharedCfg, error::Error};
use ntex_h2::{Message, MessageKind, OperationError, ServiceConfig, server};
#[ntex::main]
async fn main() -> std::io::Result<()> {
let cfg = SharedCfg::new("H2-SRV").add(ServiceConfig::new().set_max_concurrent_streams(100));
ntex::server::build()
.bind("h2", "127.0.0.1:8080", cfg, async |_| {
server::Server::new(async |msg: Message| {
if let MessageKind::Headers { pseudo, .. } = msg.kind {
println!("{:?} {:?}", pseudo.method, pseudo.path);
msg.stream.send_response(StatusCode::OK, HeaderMap::new(), false)?;
msg.stream.send_payload("hello world", true).await?;
}
Ok::<_, Error<OperationError>>(())
})
})?
.run()
.await
}
Connections take their ServiceConfig from the SharedCfg passed to
bind. This listener accepts plain TCP, so clients must know in advance
that it speaks HTTP/2. For example, use
curl --http2-prior-knowledge http://127.0.0.1:8080/.
For TLS, put a TLS acceptor in front of the server and have it select h2
during ALPN:
use ntex::{Service, SharedCfg, error::Error};
use ntex::tls::openssl::SslAcceptor;
use ntex_h2::{Message, OperationError, server};
use openssl::ssl::{self, AlpnError, SslFiletype, SslMethod};
#[ntex::main]
async fn main() -> std::io::Result<()> {
let mut builder = ssl::SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder.set_private_key_file("key.pem", SslFiletype::PEM).unwrap();
builder.set_certificate_chain_file("cert.pem").unwrap();
builder.set_alpn_select_callback(|_, protos| {
if protos.windows(3).any(|w| w == b"\x02h2") {
Ok(b"h2")
} else {
Err(AlpnError::NOACK)
}
});
let acceptor = builder.build();
ntex::server::build()
.bind("h2", "127.0.0.1:8443", SharedCfg::new("H2-TLS"), async move |_| {
SslAcceptor::new(acceptor.clone())
.map_err(|e| server::ServerError::from(std::io::Error::other(e)))
.and_then(server::Server::new(async |_msg: Message| {
// handle messages
Ok::<_, Error<OperationError>>(())
}))
})?
.run()
.await
}
To serve an I/O object you already have, call
server::handle_one(io, publish, control) with services you have already
created. The I/O object might come from your own acceptor or a connection
that switched protocols. ntex-grpc runs its server this way.
Handling streams
Handle incoming messages in the publish service you pass to
Server::new. ntex-h2 creates a new publish service for each connection.
It calls the service for every message on every stream the client opens.
The request headers, each body chunk, and the end of the stream arrive in
separate calls.
These calls run concurrently. ntex-h2 starts the next call without waiting
for the previous one to finish, so a slow request does not hold up others.
The call that receives the headers cannot await the request body as part
of that same call. Body data arrives through separate calls to the service.
Keep per-stream state in the publish service and route each message to
where it is needed. A map keyed by StreamRef works for this because the
handle implements Hash and Eq.
This service buffers each request body up to a size limit. Once the request is complete, it echoes the body back:
use std::{cell::RefCell, collections::HashMap};
use ntex::http::{HeaderMap, StatusCode};
use ntex::service::{Ctx, Service};
use ntex::util::BytesMut;
use ntex_h2::{Message, MessageKind, OperationError, StreamEof, StreamRef, frame::Reason};
const MAX_BODY: usize = 1024 * 1024;
#[derive(Default)]
struct Echo {
bodies: RefCell<HashMap<StreamRef, BytesMut>>,
}
impl Service<(), Message> for Echo {
type Res = ();
type Error = ntex::error::Error<OperationError>;
async fn call(&self, msg: Message, _: Ctx<'_, Self, ()>) -> Result<(), Self::Error> {
let Message { stream, kind } = msg;
let body = match kind {
MessageKind::Headers { eof: true, .. } => BytesMut::new(),
MessageKind::Headers { .. } => {
self.bodies.borrow_mut().insert(stream, BytesMut::new());
return Ok(());
}
MessageKind::Data(data, _) => {
let mut bodies = self.bodies.borrow_mut();
if let Some(body) = bodies.get_mut(&stream) {
body.extend_from_slice(&data);
if body.len() > MAX_BODY {
bodies.remove(&stream);
stream.reset(Reason::CANCEL);
}
}
return Ok(());
}
MessageKind::Eof(StreamEof::Data(data, _)) => {
let Some(mut body) = self.bodies.borrow_mut().remove(&stream) else {
return Ok(());
};
body.extend_from_slice(&data);
body
}
MessageKind::Eof(StreamEof::Trailers(_)) => {
let Some(body) = self.bodies.borrow_mut().remove(&stream) else {
return Ok(());
};
body
}
MessageKind::Eof(StreamEof::Error(_)) | MessageKind::Disconnect(_) => {
self.bodies.borrow_mut().remove(&stream);
return Ok(());
}
};
if body.len() > MAX_BODY {
stream.reset(Reason::CANCEL);
return Ok(());
}
stream.send_response(StatusCode::OK, HeaderMap::new(), false)?;
stream.send_payload(body.freeze(), true).await
}
}
The final Eof can carry data too, so the size limit must cover that last
chunk as well as ordinary Data messages. Release each RefCell borrow before
an await: other calls on the same service can run while this call is waiting.
Remove the map entry on Eof(StreamEof::Error(..)) or Disconnect. This
keeps the map from leaking when a client goes away mid-request.
Wrap a service type like this in a factory. fn_factory takes an async
function and calls it for each new connection:
use ntex::service::{Ctx, Service};
use ntex_h2::{Message, OperationError};
#[derive(Default)] struct Echo;
impl Service<(), Message> for Echo {
type Res = ();
type Error = ntex::error::Error<OperationError>;
async fn call(&self, _: Message, _: Ctx<'_, Self, ()>) -> Result<(), Self::Error> { Ok(()) }
}
use ntex::service::fn_factory;
use ntex_h2::server;
fn server() -> server::Server<ntex::io::IoBoxed, ntex::error::Error<OperationError>, std::convert::Infallible> {
server::Server::new(fn_factory(async |_: &()| {
Ok::<_, std::convert::Infallible>(Echo::default())
}))
}
For large or streaming bodies, store a channel sender in the map instead
of buffering the body. Pass each chunk to a task that handles the request.
Send the Capacity with the data, as in the flow control
example. The client’s pace will then follow the task’s pace.
ntex::http builds request payloads on top of ntex-h2 this way.
Sending the response
Send a response through the request’s StreamRef. Start with
send_response(status, headers, eof), setting eof to true if there is no
body. Otherwise, follow it with send_payload(data, eof), just as on the client.
You can finish with send_trailers(headers) instead of a final data chunk;
gRPC uses trailers to carry its status.
If you need to send a 1xx response, such as 103 Early Hints, call
send_informational(status, headers) before the final response head.
You can respond after the call that received the request has returned.
Clone the StreamRef to store it or move it into another task.
StreamRef also has the client’s flow-control helpers. Use
available_send_capacity to check capacity or send_capacity to wait for
it.
Errors and resets
For a problem with one request, send an error response or reset its stream
with stream.reset(reason). The connection and its other streams carry on.
REFUSED_STREAM tells the client it may safely retry. CANCEL and
INTERNAL_ERROR tell it the request failed.
Returning an error from the publish service affects the whole connection.
ntex-h2 treats it as a connection fault and sends GOAWAY with
INTERNAL_ERROR. It then closes the connection, failing every stream on
it.
You can still use ? on send_response and send_payload. They fail only
when the stream or connection is already gone. For request-level problems,
reset the stream instead of returning an error.
If the client resets a stream while one of your calls for it is still
running, that call is cancelled. You still receive an Eof message with the
error, so you can clean up per-stream state as shown above.
The control service
Use a control service to log or react to connection-level events. The
default control service accepts everything, and most servers can keep it.
Pass your own service to .control(..) when you need different handling:
use ntex::error::Error;
use ntex_h2::{Control, Message, OperationError, server};
fn server() -> server::Server<ntex::io::IoBoxed, Error<OperationError>, std::io::Error> {
server::Server::new(async |_msg: Message| Ok::<_, Error<OperationError>>(()))
.control(async |msg: Control<Error<OperationError>>| {
if let Control::Disconnect(reason) = &msg {
log::info!("connection closed: {reason:?}");
}
Ok::<_, std::io::Error>(msg.ack())
})
}
Answer every control message with msg.ack().
Control::Disconnect tells you why a connection ended. The cause may be a
protocol error, a GOAWAY from the client, the client going away, or an
error returned by the publish service.
Server state
A request handler often needs both application data and connection details, such as a request counter and the peer address. Give the publish and control services that context through connection state. It travels with the I/O object and becomes the state of their pipelines, as described in Carrying state with a request.
A plain Io carries no state, so its state is (). This is why Echo
implements Service<(), Message> and its factory takes &().
Worker state created by build_with_config() does not reach these services
automatically. To pass it on, put a service in front of Server that reads the
worker state and wraps the connection in a State. That is also a convenient
place to record the peer address. See
Worker and request state for how worker state is created.
The connection state must implement Clone because ntex-h2 clones it for the
publish and control factories. Keep shared resources behind an Rc so those
copies refer to the same data.
State-aware functions receive the
connection state as their first argument. Service factories receive it in
create:
use std::{cell::Cell, convert::Infallible, net::SocketAddr, rc::Rc};
use ntex::http::{HeaderMap, StatusCode};
use ntex::io::{Io, types::PeerAddr};
use ntex::service::{State, service};
use ntex::{SharedCfg, error::Error};
use ntex_h2::{Message, MessageKind, OperationError, server};
/// Worker state, created once per worker.
#[derive(Clone)]
struct AppState {
requests: Rc<Cell<u64>>,
}
/// Connection state, shared by all streams of one connection.
#[derive(Clone)]
struct Conn {
app: AppState,
peer: Option<SocketAddr>,
}
async fn accept(
app: &AppState,
io: Io,
) -> Result<State<Conn, Io>, server::ServerError<Infallible>> {
let peer = io.query::<PeerAddr>().get().map(|addr| addr.into_inner());
let conn = Conn { app: app.clone(), peer };
Ok(State { req: io, state: conn })
}
async fn publish(conn: &Conn, msg: Message) -> Result<(), Error<OperationError>> {
if let MessageKind::Headers { pseudo, .. } = msg.kind {
let requests = &conn.app.requests;
requests.set(requests.get() + 1);
println!("{:?} from {:?}, request #{}", pseudo.path, conn.peer, requests.get());
msg.stream.send_response(StatusCode::OK, HeaderMap::new(), false)?;
msg.stream.send_payload("hello world", true).await?;
}
Ok(())
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
ntex::server::build_with_config(async || {
Ok(AppState {
requests: Rc::new(Cell::new(0)),
})
})
.bind("h2", "127.0.0.1:8080", SharedCfg::default(), async |_: &AppState| {
service(accept).and_then(server::Server::new(publish))
})?
.run()
.await
}
Each worker has its own AppState. The requests counter therefore
counts only requests handled by that worker. Use an Arc for values that
must be shared across workers.
Keep per-stream state in the publish service itself, as in the Echo
example. A request body that is still arriving belongs there.
With handle_one, you create the publish and control pipelines yourself,
so they hold whatever state you gave them.
Shutting down
During shutdown, let existing requests finish without accepting new work.
Call ServiceConfig::shutdown() to shut down HTTP/2 connections gracefully.
Servers on the current thread then refuse new streams, let active streams
finish, and close their connections.
When the ntex server stops, its workers wait for connections to finish, as described in the server chapter.
What you take on
When you use ntex-h2 directly, you take responsibility for policies that
ntex::http would otherwise handle. Plan to check that each body matches
its content-length, enforce body size limits, and guard against floods
of empty DATA frames. You also map stream messages onto requests and
responses yourself.
The HTTP/2 example shows a server with buffered and streaming request bodies, backpressure, and trailers, plus a client that calls it. For more examples, see the ntex-h2 examples and the gRPC chapter.
Building gRPC Services and Clients
gRPC lets processes call each other through an API described in a .proto
file. Clients and servers written in any language can use that API. Calls
carry compact Protocol Buffers messages over HTTP/2, with many calls sharing
one connection.
ntex-grpc is a separate crate built on the ntex
service model. It uses ntex-h2 for HTTP/2. A gRPC client
is a service you call. A gRPC server is a service that the ntex
server runs for each connection.
ntex-grpc describes the protocol with ordinary traits. It does not use derive macros or build scripts. Each message field knows how to encode itself, and the message uses those implementations. A method type defines its request path and its input and output messages. A client is generic over the transport that carries its calls.
The ntex-grpc-codegen generator writes the boilerplate: a struct for each
message, a type for each method, and a typed client for each service. You
commit the output and read it like the rest of your code. Nothing is
generated during the build. The only macro is #[server], which connects
the methods of a .proto service to the methods of your type.
These traits let you replace each part. You can use your own Rust types for message fields, put a custom transport between a client and the network, or handle raw, undecoded calls on the server.
The snippets come from the gRPC examples. Each example is a
complete program. Its README includes run commands and a grpcurl session
you can try.
| Example | What it shows |
|---|---|
| grpc-helloworld | the smallest service, server and client |
| grpc-custom-types | your own Rust types for message fields |
| grpc-routing-client | a custom client transport that routes calls to different servers |
| grpc-server | all four kinds of methods, several services, a fallback, server tuning |
| grpc-tls | gRPC over TLS with rustls |
Quick start: hello, gRPC
The helloworld example gives you a greeting service with one method. Clone the examples repository and start the server:
git clone https://github.com/ntex-rs/examples
cd examples/protocols/grpc-helloworld
cargo run --bin grpc-helloworld-server
In a second terminal, call it:
cargo run --bin grpc-helloworld-client -- ntex
The client prints Hello ntex!. The server speaks standard gRPC, so you can
also call it with tools such as grpcurl:
grpcurl -plaintext -proto helloworld.proto -d '{"name": "ntex"}' \
127.0.0.1:50051 helloworld.Greeter/SayHello
The service implementation is short:
#[server(crate::helloworld::Greeter)]
impl GreeterServer {
#[method(SayHello)]
async fn say_hello(&self, req: HelloRequest) -> HelloReply {
let name = if req.name.is_empty() { "world" } else { &req.name };
HelloReply {
message: format!("Hello {name}!").into(),
}
}
}
The client builds a request, sets a timeout, and sends it:
let client = connect(ADDR);
let msg = HelloRequest { name: "ntex".into() };
let mut req = client.say_hello(&msg);
req.timeout(Duration::from_secs(3));
let reply = req.send().await?;
println!("{}", reply.message);
The generated file src/helloworld.rs defines the request and reply
messages, HelloRequest and HelloReply. It also defines the Greeter
service and the client’s say_hello method.
To use ntex-grpc in your own project, add these dependencies:
[dependencies]
ntex = "4"
ntex-grpc = "4"
ntex-h2 = "4"
gRPC in a nutshell
You do not need to know the wire protocol to use ntex-grpc. Its basic structure helps you decide how to handle errors and retries.
A gRPC call is an HTTP/2 POST request. Its path identifies the RPC:
/{package}.{Service}/{Method}, such as /helloworld.Greeter/SayHello.
The headers identify gRPC with content-type: application/grpc and may
carry a timeout in grpc-timeout. Your own headers travel alongside them;
gRPC calls these metadata.
The body carries messages, each with a 5-byte prefix holding a compression
flag and the message length. The response sends headers, reply messages,
and then trailers. These carry the call’s result in grpc-status, where
0 means OK, and may include a grpc-message explaining an error.
That last part matters for error handling: a gRPC failure still has HTTP status 200. The client must read the trailers to know how the call ended, not just check the HTTP status.
All gRPC methods use this request structure. They differ in how many messages each side sends:
| Kind | .proto | Client sends | Server sends |
|---|---|---|---|
| unary | rpc M(Req) returns (Res) | one message | one message |
| server streaming | rpc M(Req) returns (stream Res) | one message | any number |
| client streaming | rpc M(stream Req) returns (Res) | any number | one message |
| bidirectional | rpc M(stream Req) returns (stream Res) | any number | any number |
Each call uses one HTTP/2 stream. A connection can run many calls in parallel without a slow call blocking the others.
How ntex-grpc fits together
Generated Rust code connects your .proto definitions to the client and
server. The client passes calls through a transport; the server routes
incoming calls to your methods:
.proto ── ntex-grpc-codegen ──▶ src/helloworld.rs
(messages, MethodDefs, typed client)
client: GreeterClient<T> ─▶ Request ─▶ Transport ─▶ ntex-h2 pool ─▶ network
server: network ─▶ ntex Server ─▶ GrpcServer ─▶ #[server] type ─▶ your method
Start with the message itself. NativeType reads and writes one field
value: an integer, a string, a nested message, or your own type. Message
encodes and decodes the whole message by calling NativeType for each
field. You normally use the generated implementations and only implement
NativeType yourself when a field needs a custom Rust type.
The generated method and service types describe the API. Each RPC is a
zero-sized type implementing MethodDef, which supplies its request
path and input and output types. ServiceDef groups those methods under
the service’s full name.
Finally, Transport carries the call. A generated client is generic
over this trait, so calling send() hands the request to whichever
transport you gave it. You can keep the generated API while replacing how
calls reach the server.
From .proto to Rust
Run the code generator to turn your .proto definitions into Rust types.
You keep the generated file in your project, with no code generation during
builds.
Running the code generator
Install ntex-grpc-codegen to get the ntex-grpc command. It uses
protoc, the Protocol Buffers compiler, to parse .proto files. Install
protoc through your package manager first. If it is outside your PATH,
set the PROTOC environment variable to its path.
cargo install ntex-grpc-codegen
The helloworld example defines its service in this .proto file:
syntax = "proto3";
package helloworld;
// The greeting service.
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
// The request message with the user's name.
message HelloRequest {
string name = 1;
}
// The reply message with the greeting.
message HelloReply {
string message = 1;
}
Run the generator whenever the .proto file changes. The examples keep
this command in a generate.sh script next to the file:
ntex-grpc helloworld.proto helloworld.rs --out-dir ./src --include-dir ./ \
--rustfmt-path ../../rustfmt.toml
The proto package determines the output file’s name; the second argument
does not. Use separate output directories if you generate the same package
twice, for example with different options.
| Option | Effect |
|---|---|
--out-dir DIR | where to write the generated file |
--include-dir DIR | where to look for imported .proto files; can be repeated |
--map NAME=TYPE | use your own Rust type for a field, see using your own field types |
--rustfmt-path FILE | rustfmt configuration used to format the output |
--optional-messages | generate singular message fields as Option<T>, so you can tell an unset field from an empty one |
--open-enums | generate enum fields as i32, so values your code does not know yet are kept |
--well-known-types | generate the google.protobuf types instead of using ntex_grpc::google_types |
Commit the generated file so builds do not depend on protoc.
What gets generated
Add the generated file to your project with pub mod helloworld;. You can
then use its types directly. Each protobuf message becomes a plain Rust
struct:
/// The request message with the user's name.
#[derive(Clone, PartialEq, Debug)]
pub struct HelloRequest {
pub name: ::ntex_grpc::ByteString,
}
For the Greeter service, the generator also writes a unit struct named
Greeter. It implements ServiceDef with the full service name,
helloworld.Greeter. The typed client, GreeterClient<T>, is generic over
its transport and has one method per rpc.
Each RPC gets its own unit struct implementing MethodDef. For
SayHello, that definition looks like this:
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct GreeterSayHelloMethod;
impl ::ntex_grpc::MethodDef for GreeterSayHelloMethod {
const NAME: &'static str = "SayHello";
const PATH: ::ntex_grpc::ByteString =
::ntex_grpc::ByteString::from_static("/helloworld.Greeter/SayHello");
type Input = HelloRequest;
type Output = HelloReply;
const CLIENT_STREAMING: bool = false;
const SERVER_STREAMING: bool = false;
}
MethodDef ties a method to its request path and message types at compile
time. The client uses it to choose the request path and decode the reply.
The server uses it to decode requests and encode replies. If you pass the
wrong message to a method, compilation fails.
Each message struct also gets a Message implementation. It calls
NativeType for each field, passing the field’s tag:
impl ::ntex_grpc::Message for HelloRequest {
#[inline]
fn write(&self, dst: &mut ::ntex_grpc::BytePages) {
::ntex_grpc::NativeType::serialize(
&self.name,
1,
::ntex_grpc::types::DefaultValue::Default,
dst,
);
}
// `read`, `merge_from` and `encoded_len` follow the same pattern
}
The generated implementation is straight-line code that the compiler can
inline. There is no runtime reflection or table of field descriptors.
Any type that implements NativeType works with this code, including your
own field types.
How protobuf types map to Rust
The generator uses ntex types where they are available. String and byte fields share memory with the received buffer without copying:
| Protobuf | Rust |
|---|---|
double, float | f64, f32 |
int32, sint32, sfixed32 | i32 |
int64, sint64, sfixed64 | i64 |
uint32, fixed32 | u32 |
uint64, fixed64 | u64 |
bool | bool |
string | ByteString |
bytes | Bytes |
enum E | E, a Rust enum (i32 with --open-enums) |
M, a message field | M (Option<M> with --optional-messages) |
optional T | Option<T> |
repeated T | Vec<T> |
map<K, V> | ntex_grpc::HashMap<K, V> |
oneof name { .. } | Option<message::Name>, an enum with one variant per field |
google.protobuf.Timestamp, Duration, wrappers | the types in ntex_grpc::google_types |
google.protobuf.Empty | () |
For example, this message uses enums, optional fields, a map, and a oneof:
enum Color {
COLOR_UNSPECIFIED = 0;
RED = 1;
GREEN = 2;
}
message Shape {
Color color = 1;
optional uint32 weight = 2;
map<string, uint64> labels = 3;
oneof kind {
double radius = 4;
Side side = 5;
}
}
The generated Rust types look like this:
pub struct Shape {
pub color: Color,
pub weight: Option<u32>,
pub labels: ::ntex_grpc::HashMap<::ntex_grpc::ByteString, u64>,
pub kind: Option<shape::Kind>,
}
/// Nested message and enum types in `Shape`.
pub mod shape {
pub enum Kind {
Radius(f64),
Side(super::Side),
}
}
#[repr(i32)]
pub enum Color {
Unspecified = 0,
Red = 1,
Green = 2,
}
Two generator defaults deserve attention when your API changes over time.
By default, enums are closed: an unknown value decodes as the enum’s
default variant. A sender using a newer .proto file can therefore send a
value your code cannot distinguish from the default. Use --open-enums to
keep the numeric value, then convert it with Color::from_i32() where
needed.
Singular message fields are also always present in the default Rust
output. An unset field decodes as the default message. Use
--optional-messages if your handler needs to distinguish an unset field
from an empty one.
Using your own field types
Use --map when a field needs stricter rules than its protobuf type
provides. A bytes field might hold a 16-byte UUID, or a string might
hold only product codes. With the default generated types, each handler
must check those rules.
The option replaces a field’s Rust type with your own. That type checks the value once, during decoding:
message ReserveRequest {
// Client-chosen request id, a 16-byte UUID.
bytes request_id = 1;
// Stock keeping unit, e.g. "BOOK-42".
string sku = 2;
uint32 quantity = 3;
}
message ReserveReply {
bytes request_id = 1;
string sku = 2;
bool reserved = 3;
uint32 remaining = 4;
}
ntex-grpc inventory.proto inventory.rs --out-dir ./src --include-dir ./ \
--map request_id=crate::types::RequestId \
--map sku=crate::types::Sku
The left side of --map is a field path. A leading dot makes it fully
qualified, as in .inventory.ReserveRequest.sku. Without the dot, it
matches a suffix. Here, sku covers both messages, while
ReserveRequest.sku covers only the request.
The right side is a Rust path. The generator copies it into the output unchanged:
pub struct ReserveRequest {
pub request_id: crate::types::RequestId,
pub sku: crate::types::Sku,
pub quantity: u32,
}
The wire format stays the same. Other gRPC clients and servers still send
plain bytes and string fields. On the Rust side, your type decides which
values are valid. Decoding fails for anything else.
The server answers INVALID_ARGUMENT before calling your handler if an id
or SKU is malformed. Your handler receives a ReserveRequest whose field
types enforce those rules.
Writing a custom field type
Implement NativeType to use your own type in a message field. The type
also needs Default, PartialEq and Debug because the generated structs
derive traits that require them.
| Item | What it does |
|---|---|
const TYPE: WireType | the protobuf wire type: LengthDelimited for bytes, string and messages, Varint for integers and bool, ThirtyTwoBit or SixtyFourBit for fixed-width numbers |
value_len(&self) | the encoded length of the value, without the tag and length prefix |
merge(&mut self, src) | decode a value; for length-delimited types src holds exactly the value, the length prefix is already removed |
encode_value(&self, dst) | write the value, without the tag and length prefix |
is_default(&self) | true if the value is the default, so the field is left out of the message |
The custom-types example uses this request id. Its default value is a nil
UUID. Like an empty bytes field, that value is left out of the encoded
message:
use ntex_grpc::{BytePages, Bytes, DecodeError, NativeType, WireType};
use uuid::Uuid;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
pub struct RequestId(Uuid);
impl NativeType for RequestId {
const TYPE: WireType = WireType::LengthDelimited;
fn value_len(&self) -> usize {
16
}
/// `src` holds exactly the field value, the length prefix is already
/// removed.
fn merge(&mut self, src: &mut Bytes) -> Result<(), DecodeError> {
let id =
Uuid::from_slice(src).map_err(|_| DecodeError::new("request id must be 16 bytes"))?;
*self = Self(id);
Ok(())
}
fn encode_value(&self, dst: &mut BytePages) {
dst.extend_from_slice(self.0.as_bytes());
}
fn is_default(&self) -> bool {
self.0.is_nil()
}
}
A wrapper around a built-in type can delegate wire-format handling to that
type. It can then add its own validation. Here, Sku lets ByteString
check for valid UTF-8 before validating the string:
impl NativeType for Sku {
const TYPE: WireType = WireType::LengthDelimited;
fn value_len(&self) -> usize {
self.0.value_len()
}
fn merge(&mut self, src: &mut Bytes) -> Result<(), DecodeError> {
let mut s = ByteString::default();
s.merge(src)?;
*self = Self::try_from(s).map_err(|e| DecodeError::new(e.to_string()))?;
Ok(())
}
fn encode_value(&self, dst: &mut BytePages) {
self.0.encode_value(dst);
}
fn is_default(&self) -> bool {
self.0.is_empty()
}
}
The custom type still has to obey protobuf’s encoding rules. For a
length-delimited field, encode_value() must write exactly value_len()
bytes: the length prefix has already been written using that value. A
mismatch corrupts the message.
For types that are not length-delimited, override encoded_len(tag) as
well. Its default implementation adds a length prefix, which is correct
only for LengthDelimited. A Varint newtype, such as a u64 id, must
return key_len(tag) + value_len(), as the built-in integer types do.
Otherwise, encoded messages get the wrong size.
Validation should return an error from merge, never panic. That error
becomes INVALID_ARGUMENT on the server or InvalidResponse on the client.
Also keep is_default consistent with protobuf: other implementations
treat a missing field as empty, zero or false, so your default must mean
the same thing.
Calling services
Call a generated client method to build a request. Each method corresponds
to one rpc. You can configure the request before calling send();
building it sends nothing:
use std::time::Duration;
use grpc_helloworld::{ADDR, connect, helloworld::HelloRequest};
#[ntex::main]
async fn main() {
let client = connect(ADDR);
let msg = HelloRequest { name: "ntex".into() };
let mut req = client.say_hello(&msg);
req.timeout(Duration::from_secs(3));
match req.send().await {
// `Response` derefs to the reply message
Ok(res) => println!("{}", res.message),
Err(err) => eprintln!("call failed with {:?}: {err}", err.status()),
}
}
The request borrows the client and message. Nothing is copied until the message is encoded. Settings such as the timeout, headers or compression apply only to this call.
Connecting to a server
Use ntex_grpc::client::Client to connect through an ntex-h2
connection pool. It adds a thin gRPC layer over the pool:
use ntex::SharedCfg;
use ntex_grpc::client::Client;
use ntex_h2::client as h2;
pub fn connect(addr: impl Into<String>) -> GreeterClient<Client> {
let pool = h2::Client::builder(addr.into()).build(SharedCfg::new("GRPC-CLIENT"));
GreeterClient::new(Client::new(pool))
}
Building the pool does not touch the network. The first call opens a connection. Later calls share it, each on its own HTTP/2 stream.
When a connection closes, the pool opens a new one for the next call that needs it. You do not need to manage connections yourself.
Cloning a Client is cheap, and its clones share the pool. Build one per
server. Clone it into each typed client that talks to that server:
let pool = h2::Client::builder(addr.into()).build(SharedCfg::new("GRPC-CLIENT"));
let client = ntex_grpc::client::Client::new(pool);
let echo = EchoClient::new(client.clone());
let stats = StatsClient::new(client);
The pool builder controls the connections:
| Method | Effect |
|---|---|
connector(..) | how to connect, e.g. through a TLS connector, see running over TLS |
secure(true) | send the https scheme; use it together with TLS |
connect_timeout(..) | time limit for the TCP connect and the TLS handshake |
minconn(..) / connection_limit(..) | how many connections to keep open and how many to allow |
max_streams(..) | how many calls can share one connection |
lifetime(..) | retire connections after a while, e.g. to pick up DNS changes |
For HTTP/2 settings such as window sizes and the ping interval, use
ntex_h2::ServiceConfig. Add it to the SharedCfg you pass to build().
This works the same way as on the server.
What happens during a call
The request builder keeps your message separate from the work of sending
it. A Request holds the transport and input message, while its
RequestContext holds the headers, timeout and limits. Calling send()
passes them through the Transport trait. The transport handles the
HTTP/2 stream and returns a Response containing the decoded reply,
headers and trailers:
pub trait Transport<T: MethodDef, St = ()> {
type Error;
async fn request(
&self,
args: &T::Input,
ctx: &mut RequestContext<St>,
) -> Result<Response<T>, Self::Error>;
}
The trait is generic over the method T. The transport therefore knows
the method’s PATH, Input and Output at compile time.
The built-in gRPC Client delegates to the HTTP/2 pool client,
ntex_h2::client::Client. Once it has a connection, it uses that
connection’s ntex_h2::client::SimpleClient to do the following:
- Check for invalid request headers. If any were set, fail with
InvalidRequestwithout sending anything. - Encode the input with its
Messageimplementation. Compress it if requested, then add the 5-byte message prefix. - Open a stream with
POST T::PATH. Include the request’s headers and the gRPC headers:content-type: application/grpc,te: trailers, andgrpc-timeoutif a timeout is set. - Send the message and close the stream’s sending side.
- Read the response headers, message and trailers. Check the HTTP status,
content type, message size and
grpc-status. - Decode the message as
T::Outputand return aResponse.
The timeout covers the whole call, including the wait for a connection.
When it runs out, the transport resets the stream with CANCEL. The call
fails with DeadlineExceeded.
To pass per-call state to the transport, use send_with(&state). The
transport reads the reference with ctx.request_state(). Calling send()
is equivalent to send_with(&()).
Headers, compression and message limits
Set request headers when you need to send metadata, such as authentication tokens or trace ids. Configure them before sending the request:
use ntex_grpc::encode_binary_header;
let mut req = client.say_hello(&msg);
req.header("x-request-id", "42")
.header("trace-bin", encode_binary_header(&trace_id))
.timeout(Duration::from_secs(3));
let (reply, headers, trailers) = req.send().await?.into_parts();
Use header() to replace a header. Use append_header() to add another
value. By gRPC convention, names ending in -bin carry binary values.
Encode those with encode_binary_header() and decode received values
with decode_binary_header().
A successful Response derefs to the reply message. Read its metadata
with headers() and trailers(). Use into_parts() to take the message,
headers and trailers apart.
The client sets protocol headers itself, including content-type, te,
grpc-timeout and grpc-encoding. It ignores any values you set for them.
If you set an invalid header name or value, the call fails with
InvalidRequest without sending it.
For large messages, you can also enable optional compression with the
compression feature:
ntex-grpc = { version = "4", features = ["compression"] }
use ntex_grpc::Compression;
req.compression(Compression::Gzip); // or Compression::Zstd
Compression costs CPU on both sides. Use it for large, repetitive messages
and leave it off for small ones. Empty messages are always sent
uncompressed. If the server does not support the encoding, it fails the
call with UNIMPLEMENTED.
Whether or not you compress, message limits protect the client from
oversized replies. On Client,
max_message_size() limits received messages to 4 MiB by default. Use
max_send_message_size() to limit sent messages. You can override both
limits on a request for a single call.
Streaming calls
Use streaming methods when either side needs to send more than one
message. These methods return a StreamRequest, which you configure like
a unary request. You open it through the StreamTransport trait.
A SendStream sends messages. A RecvStream receives them:
// server streaming: one request, a stream of replies
let mut rx = echo.server_streaming_echo(&msg).open().await?;
while let Some(reply) = rx.recv().await {
println!("{}", reply?.message);
}
// client streaming: send while `send()` waits for the reply
let tx = SendStream::new();
let (res, sent) = join(echo.client_streaming_echo(&tx).send(), async {
for word in ["one", "two", "three"] {
tx.send(&echo_request(word)).await?;
}
// the end of the stream, the server answers now
tx.close();
Ok::<_, StreamError>(())
})
.await;
sent?;
println!("{}", res?.message);
// bidirectional streaming: send and receive at the same time
let (tx, mut rx) = echo.bidi_streaming_echo().open().await?;
The example uses ntex::util::join so sending messages and waiting for the
reply can both make progress. When the server reads until the stream ends,
tx.close() tells it to finish and reply. Awaiting send() before sending
those messages would leave both sides waiting for each other.
After a stream ends, rx.status() returns its final grpc-status.
Writing your own transport
Write a custom transport when you need behavior that applies to every call. You can add authentication headers, record metrics or logs, retry calls, or route them to different servers.
Generated clients are generic over their transport. Any type implementing
Transport can replace Client. For streaming methods, implement
StreamTransport too.
A custom transport usually wraps a built-in one. It adjusts the request context, then delegates the call:
use ntex::Error;
use ntex_grpc::MethodDef;
use ntex_grpc::client::{Client, ClientError, RequestContext, Response, Transport};
/// Adds an `authorization` header to every call.
#[derive(Clone)]
pub struct WithToken {
inner: Client,
token: String,
}
impl<M: MethodDef, St> Transport<M, St> for WithToken {
type Error = Error<ClientError>;
async fn request(
&self,
args: &M::Input,
ctx: &mut RequestContext<'_, St>,
) -> Result<Response<M>, Self::Error> {
ctx.header("authorization", self.token.as_str());
Transport::<M, St>::request(&self.inner, args, ctx).await
}
}
Pass this wrapper to GreeterClient::new(WithToken { .. }) to send the
token with every call. Keep the implementation generic over the request
state St. This preserves support for both send() and send_with().
Implement StreamTransport the same way for streaming calls. Its open()
returns a StreamCall representing the call’s HTTP/2 stream. Only the
built-in transports can create one. A custom streaming transport must
finish by calling a built-in transport’s open().
Generated clients own their transport. To share one between typed clients,
make it cheap to clone. Keep shared parts behind an Rc or in the pool,
as Client does.
Routing calls to different backends
A routing transport lets one client setup reach services on different
servers. The routing example hosts shop.Catalog and shop.Orders on
separate backends. Its Router transport chooses a backend from the
service name in M::PATH:
use std::{collections::HashMap, rc::Rc};
use ntex::{Error, SharedCfg};
use ntex_grpc::client::{
CallFailure, Client, ClientError, RequestContext, Response, StreamCall, StreamTransport,
Transport,
};
use ntex_grpc::{GrpcStatus, MethodDef};
use ntex_h2::client as h2;
/// Routes calls by service name, e.g. `shop.Catalog`, to a backend client.
#[derive(Clone, Default)]
pub struct Router {
routes: Rc<HashMap<&'static str, Client>>,
}
impl Router {
/// Sends the calls of `service` to the server at `addr`.
pub fn route_to(mut self, service: &'static str, addr: impl Into<String>) -> Self {
let pool = h2::Client::builder(addr.into()).build(SharedCfg::new("GRPC-ROUTER"));
Rc::make_mut(&mut self.routes).insert(service, Client::new(pool));
self
}
/// The backend for the service of method `M`.
fn backend<M: MethodDef>(&self) -> Result<&Client, Error<ClientError>> {
let path = M::PATH;
let service = service_name(&path);
self.routes.get(service).ok_or_else(|| {
// Nothing is sent and trying again fails the same way.
Error::from(ClientError::InvalidRequest(CallFailure::new(
GrpcStatus::Unimplemented,
format!("no backend for {service}"),
)))
})
}
}
/// The service part of a request path: `/shop.Catalog/GetItem` gives
/// `shop.Catalog`.
pub fn service_name(path: &str) -> &str {
path.trim_start_matches('/')
.split_once('/')
.map_or("", |(service, _)| service)
}
impl<M: MethodDef, St> Transport<M, St> for Router {
type Error = Error<ClientError>;
async fn request(
&self,
args: &M::Input,
ctx: &mut RequestContext<'_, St>,
) -> Result<Response<M>, Self::Error> {
Transport::<M, St>::request(self.backend::<M>()?, args, ctx).await
}
}
/// Only the built-in transports can open a `StreamCall`, so pick a backend
/// and let it open the stream.
impl<M: MethodDef, St> StreamTransport<M, St> for Router {
async fn open(
&self,
ctx: &mut RequestContext<'_, St>,
) -> Result<StreamCall, Error<ClientError>> {
StreamTransport::<M, St>::open(self.backend::<M>()?, ctx).await
}
}
Both typed clients use the same router. Its clones share the routes and
connection pools. Use the generated ServiceDef::NAME constants as route
names. If a service is renamed in the .proto file, these references fail
to compile:
let router = Router::default()
.route_to(Catalog::NAME, "127.0.0.1:50053")
.route_to(Orders::NAME, "127.0.0.1:50054");
let catalog = CatalogClient::new(router.clone());
let orders = OrdersClient::new(router);
The router uses the same error type as the built-in transports. Callers handle a missing route like any other failed call.
Errors, deadlines and retries
A lost reply does not tell you whether the server handled the request. Before retrying, check what the error says about that: repeating a greeting is harmless, but repeating an order might not be.
The built-in transports return ntex::Error<ClientError>. It derefs to
ClientError, so you can match on &*err. Use err.status() for a gRPC
status code on any variant. Use err.message() for a description of the
cause.
The error variant tells you what is known about the request:
| Variant | Did the server see the request? | What you can do |
|---|---|---|
Status | yes | apply the rules for the status code |
InvalidRequest | no | fail the call; retrying fails the same way |
NotProcessed | no | retry at once, for any method |
Connection | maybe, see request_sent | retry, ideally on another connection |
StreamFailed | maybe | retry if the method is idempotent |
NotGrpc | not by a gRPC server | check the address, or back off on HTTP 429, 502, 503 and 504 |
InvalidResponse | yes | fail the call; asking again gets the same answer |
DeadlineExceeded | maybe | the time for the call is up |
Only Status carries a status from the server. It also carries the
server’s trailers.
NotProcessed means the request never reached your service. It covers
connections that were already closing when the call started and streams
the server refused.
For an idempotent call, you can write a retry loop like this:
use ntex_grpc::client::ClientError;
let mut attempts = 0;
let reply = loop {
let mut req = client.say_hello(&msg);
req.timeout(Duration::from_secs(3));
match req.send().await {
Ok(res) => break res.into_inner(),
Err(err) => {
let retry = match &*err {
ClientError::NotProcessed(_) => true,
ClientError::Connection { request_sent, .. } => !request_sent,
_ => false,
};
attempts += 1;
if !retry || attempts == 3 {
return Err(err);
}
}
}
};
Retries also need a time limit. Set a timeout on every call; without one, a stalled server can hold the call and anything waiting for it as long as the connection lives.
The client sends the value from timeout() in the grpc-timeout header,
rounding up to the precision the gRPC format allows. The client enforces
its own deadline, including time spent waiting for a connection. The
server uses the header to limit service execution and answers
DEADLINE_EXCEEDED if that limit runs out. These are separate timers, not
a synchronized clock. A zero client timeout fails at once without sending
anything.
Streaming calls fail in the same ways. The stage of the call determines where you receive the error:
open()returns errors from opening the stream.recv()returns aStreamErrorif the stream fails later.rx.status()gives the final status.
Serving gRPC
On the server side, your main job is to implement one async method per
rpc. The #[server] attribute turns your type into an ntex service, so
you do not have to decode packets or dispatch method names yourself.
Two layers sit in front of it. GrpcServer speaks the gRPC protocol and
routes calls by service name. The ntex Server accepts
connections, optionally runs TLS, and hands each connection to
GrpcServer.
Implementing a service
Implement a service with async methods, then register it with the server. This is the complete helloworld server:
use std::convert::Infallible;
use ntex::{ServiceFactory, SharedCfg, server::Server};
use ntex_grpc::server;
#[derive(Clone, Debug, Default)]
pub struct GreeterServer;
#[server(crate::helloworld::Greeter)]
impl GreeterServer {
#[method(SayHello)]
async fn say_hello(&self, req: HelloRequest) -> HelloReply {
let name = if req.name.is_empty() { "world" } else { &req.name };
HelloReply {
message: format!("Hello {name}!").into(),
}
}
}
/// `GrpcServer` creates the service for every connection.
impl ServiceFactory<(), server::ServerRequest> for GreeterServer {
type Res = server::ServerResponse;
type Error = server::ServerError;
type Service = GreeterServer;
type InitError = Infallible;
async fn create(&self, _: &()) -> Result<Self::Service, Self::InitError> {
Ok(self.clone())
}
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
Server::builder()
.bind("grpc", "127.0.0.1:50051", SharedCfg::new("GRPC"), async |_| {
server::GrpcServer::new(GreeterServer)
})?
.run()
.await
}
Pass the generated service definition to #[server(path)]. Mark each
method with #[method(Name)], using the name from the .proto file. The
attribute checks argument and return types against the generated
MethodDef at compile time. A misspelled method name or wrong message type
fails to compile.
The attribute implements Service<(), ServerRequest> for your type. It
also implements NamedService. The rest is ordinary Rust.
The signature of a method depends on its kind:
| Kind | Arguments | Returns |
|---|---|---|
| unary | req: Input or req: Request<Input> | Output, Response<Output>, Result<Output, E> with E: Into<Output>, or Result<Response<Output>, E> with E: Into<ServerError> |
| server streaming | req, tx: SendStream<Output> | () or Result<(), E> with E: Into<ServerError> |
| client streaming | rx: RecvStream<Input> | as unary |
| bidirectional | rx: RecvStream<Input>, tx: SendStream<Output> | as server streaming |
Use Request<Input> when you need request headers. It derefs to the
message, so you can still access the fields:
#[method(UnaryEcho)]
async fn unary_echo(&self, req: Request<EchoRequest>) -> EchoReply {
let prefix = req
.headers
.get(PREFIX_HEADER)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
EchoReply {
message: format!("{prefix}{}", req.message.message).into(),
}
}
GrpcServer calls create() for each connection to make a service
instance. State stored in that returned service belongs to the connection.
If you need to share it more widely, create it outside create() and
clone a handle into each instance.
For state shared by one worker, use the closure passed to bind(). It runs
for each worker, so an Rc is enough. The closure may run again after a
worker restarts; keep the setup safe to repeat. For a counter or data store
shared by the whole server, use an Arc shared by all clones, because
workers run on different threads.
Import the attribute with use ntex_grpc::server;. This imports both the
server module and the attribute. An import such as
use ntex_grpc::server::{self, ..} brings in only the module. If you use
that form, the error says that NamedService is not implemented.
Streaming methods
Streaming methods let you send or receive messages throughout a call. Use
RecvStream to receive messages and SendStream to send them. A
server-streaming method receives one request and a sender:
#[method(ServerStreamingEcho)]
async fn server_streaming_echo(
&self,
req: EchoRequest,
tx: SendStream<EchoReply>,
) -> Result<(), ServerError> {
if req.repeat > MAX_REPEAT {
return Err(ServerError::new(
GrpcStatus::InvalidArgument,
encode_grpc_message(&format!("repeat must be at most {MAX_REPEAT}")),
None,
));
}
let reply = EchoReply { message: req.message };
for _ in 0..req.repeat {
tx.send(&reply).await?;
}
Ok(())
}
A client-streaming method reads messages until the client closes its side. It then returns one reply:
#[method(ClientStreamingEcho)]
async fn client_streaming_echo(&self, mut rx: RecvStream<EchoRequest>) -> EchoReply {
let mut messages = Vec::new();
while let Some(Ok(req)) = rx.recv().await {
messages.push(req.message);
}
EchoReply {
message: messages.join(" ").into(),
}
}
A bidirectional method gets both streams. It can reply to each message as it arrives:
#[method(BidiStreamingEcho)]
async fn bidi_streaming_echo(
&self,
mut rx: RecvStream<EchoRequest>,
tx: SendStream<EchoReply>,
) -> Result<(), ServerError> {
while let Some(req) = rx.recv().await {
let req = req?;
tx.send(&EchoReply { message: req.message }).await?;
}
Ok(())
}
Use ? to return early after a failed send or receive. If the client goes
away, the next send() fails. When the method returns, the call ends. Its
result becomes the call’s grpc-status.
Reporting errors to clients
Use your method’s return value to report errors to clients. A
ServerError sets the call’s grpc-status and grpc-message. Its optional
HeaderMap adds trailers. Build the error with ServerError::new().
Pass error text through encode_grpc_message(). gRPC requires
grpc-message to be percent-encoded.
Streaming methods can return Result<(), ServerError>, as shown above.
For unary and client-streaming methods, return
Result<Response<Output>, ServerError> to fail the call with a status.
Those methods return a reply, so the return type must distinguish an error
status from an error encoded in the reply.
A successful Response can carry extra trailers. You can turn a plain
message into a Response with .into():
use ntex::http::header::HeaderValue;
use ntex_grpc::server::{Response, ServerError};
#[method(Reserve)]
async fn reserve(
&self,
req: ReserveRequest,
) -> Result<Response<ReserveReply>, ServerError> {
let Some(seats) = self.store.free_seats(&req.show) else {
return Err(ServerError::new(
GrpcStatus::NotFound,
encode_grpc_message(&format!("no show {}", req.show)),
None,
));
};
let reply = self.store.reserve(&req)?; // a store error converts into ServerError
Ok(Response {
message: reply,
headers: vec![(SEATS_LEFT, HeaderValue::from(seats - 1))],
})
}
The trailers in Response::headers follow grpc-status: 0. The server
ignores any grpc-status or grpc-message among them. A Response
therefore always represents a successful call. The client reads these
trailers with trailers() on its response.
A method returning Result<Output, E> always ends with OK. Its error
type converts into a reply message through E: Into<Output>. The error
must therefore be part of the reply.
Use this form when your protocol models errors as reply data. For example,
a oneof can represent success or failure:
message ReserveReply {
oneof outcome {
Reservation reserved = 1;
Problem problem = 2;
}
}
impl From<Problem> for ReserveReply {
fn from(problem: Problem) -> Self {
ReserveReply {
outcome: Some(reserve_reply::Outcome::Problem(problem)),
}
}
}
#[method(Reserve)]
async fn reserve(&self, req: ReserveRequest) -> Result<ReserveReply, Problem> {
let reservation = self.store.reserve(&req)?;
Ok(ReserveReply {
outcome: Some(reserve_reply::Outcome::Reserved(reservation)),
})
}
An error in the reply gives clients a typed Problem rather than a status
code and string. Use a gRPC status for generic failures, such as a missing
resource or denied permission. Use a oneof when clients need to act on
the details.
The server handles these errors before your method runs:
| Situation | Status |
|---|---|
| unknown service or method | UNIMPLEMENTED |
| request message that cannot be decoded, including a custom field type that rejects its value | INVALID_ARGUMENT |
request message larger than max_message_size | RESOURCE_EXHAUSTED |
| compressed request in an encoding the server does not support | UNIMPLEMENTED |
deadline from grpc-timeout runs out | DEADLINE_EXCEEDED |
Hosting several services
Register several services on one GrpcServer to share a listener. It
routes calls by the service name in the request path:
pub fn grpc_server(calls: Arc<AtomicU64>) -> GrpcServer {
GrpcServer::new(EchoServer {
calls: calls.clone(),
})
.service(StatsServer { calls })
.default_service(Fallback)
.max_message_size(MAX_MESSAGE_SIZE)
}
| Method | Effect |
|---|---|
new(service) / service(service) | add a #[server] service under its NamedService::NAME |
service_named(name, service) | add a service under another name, e.g. a hand-written one |
default_service(service) | take the calls for every service that is not added |
Without a default service, calls to an unknown service fail with
UNIMPLEMENTED. Registering the same name twice panics at server startup,
before any calls arrive.
Write the default service and service_named services as plain ntex
services of ServerRequest. They receive the call before decoding, with
its service and method names, request headers and encoded payload.
Return a ServerResponse with an encoded reply, or a ServerError with
any status. These hand-written services handle only unary calls.
#[derive(Clone, Copy, Debug, Default)]
pub struct Fallback;
impl Service<(), server::ServerRequest> for Fallback {
type Res = server::ServerResponse;
type Error = ServerError;
async fn call(
&self,
req: server::ServerRequest,
_: Ctx<'_, Self, ()>,
) -> Result<Self::Res, Self::Error> {
let msg = format!(
"unknown service {}, this server has echo.Echo and echo.Stats",
req.service
);
Err(ServerError::new(
GrpcStatus::Unimplemented,
encode_grpc_message(&msg),
None,
))
}
}
Implement ServiceFactory for Fallback too, as you would for a
#[server] type.
Tuning the server
Start with message limits when you need to bound the requests your service
accepts. GrpcServer::max_message_size(size) defaults to 4 MiB and checks
the size again after decompression. A larger request fails the call with
RESOURCE_EXHAUSTED. To limit replies as well, set
max_send_message_size(size).
For connection settings below gRPC, configure HTTP/2. GrpcServer reads
these settings from its listener’s configuration. Add an
ntex_h2::ServiceConfig to the SharedCfg you pass to bind():
use ntex::{SharedCfg, time::Seconds};
use ntex_h2 as h2;
pub fn server_cfg() -> SharedCfg {
SharedCfg::new("GRPC")
.add(
h2::ServiceConfig::new()
// parallel calls per connection
.set_max_concurrent_streams(256)
// per-call and per-connection receive windows
.set_initial_window_size(256 * 1024)
.set_initial_connection_window_size(1024 * 1024)
// close connections that stop answering pings
.set_ping_timeout(Seconds(20))
.set_handshake_timeout(Seconds(5)),
)
.into()
}
Server::builder()
.bind("grpc", ADDR, server_cfg(), async move |_| grpc_server(calls.clone()))?
.run()
.await
Start with the defaults and adjust them for your traffic:
| Setting | Default | Why change it |
|---|---|---|
set_max_concurrent_streams | 256 | the number of calls a client can run in parallel on one connection |
set_initial_window_size | 65,535 | larger windows speed up large messages and streams |
set_initial_connection_window_size | 4 MiB | the receive window shared by all calls on a connection |
set_ping_timeout | 10 seconds | detect dead connections; zero disables pings |
set_handshake_timeout | 5 seconds | how long a new connection has to complete the HTTP/2 handshake |
With the compression feature, the server accepts gzip and zstd requests.
It uses the request’s encoding to compress the reply, unless the client’s
grpc-accept-encoding header rules that out.
Running over TLS
Put a TLS service in front of GrpcServer to serve gRPC over TLS. The
server accepts any Io, but speaks only HTTP/2, as gRPC requires.
The TLS acceptor runs first and passes the decrypted stream to it:
use ntex::io::Io;
use ntex::tls::rustls::TlsAcceptor;
use ntex::Service;
pub fn grpc_tls_service(
config: Arc<ServerConfig>,
) -> impl Service<(), Io, Res = (), Error = Box<dyn std::error::Error>> {
ntex::service(TlsAcceptor::new(config))
.map_err(Box::<dyn std::error::Error>::from)
.and_then(grpc_server())
}
On the client, give the pool a TLS connector. Set secure(true) so
requests carry the https scheme:
use ntex::tls::rustls::TlsConnector;
pub fn connect(addr: impl Into<String>, config: ClientConfig) -> GreeterClient<Client> {
let pool = h2::Client::builder(addr.into())
.connector(TlsConnector::new(config))
.secure(true)
.build(SharedCfg::new("GRPC-TLS-CLIENT"));
GreeterClient::new(Client::new(pool))
}
Both sides must offer h2 in ALPN. Set
config.alpn_protocols = vec![b"h2".to_vec()]. Many gRPC clients refuse a
server that does not select it.
Connect to a host name that matches the server certificate, such as
localhost:50056. See the TLS chapter for certificates, trust
roots and other TLS backends.
Without TLS, ntex-grpc uses HTTP/2 with prior knowledge. The client sends
the HTTP/2 preface immediately, without an HTTP/1.1 upgrade. gRPC clients
expect this for plaintext connections. Use -plaintext with tools such as
grpcurl to call a server without TLS.
Testing your services
Use the ntex test server to test your service with real gRPC calls. Clients and servers are ordinary ntex services. Start the gRPC server on a random port, then connect a generated client:
use ntex::server::TestServerBuilder;
#[ntex::test]
async fn unary_echo_reads_request_headers() {
let calls = Arc::new(AtomicU64::new(0));
let srv = TestServerBuilder::new(async move |_| grpc_server(calls.clone()))
.config(server_cfg())
.start();
let (echo, _) = connect(srv.addr().to_string());
let msg = echo_request("hello");
let mut req = echo.unary_echo(&msg);
req.header(PREFIX_HEADER, "> ").timeout(Seconds(3));
assert_eq!(req.send().await.unwrap().message, "> hello");
}
Pass the binary’s SharedCfg to TestServerBuilder::config() to test with
the production HTTP/2 settings. Keep the timeout on every test call: a
broken server should fail the test rather than hang it.
Once the successful call works, exercise the routing failures too.
Implement MethodDef by hand with a PATH that the server does not have,
then send it with ntex_grpc::client::Request::new. Check for UNIMPLEMENTED
or your fallback’s answer.
Custom field types need both local and wire-compatibility tests. For a
local round trip, encode with Message::write, decode with Message::read,
and compare the messages. Also check that merge returns an error for
invalid input. To test compatibility, generate the same .proto with and
without --map, then use the plain client to call the custom-types server.
That exercises the wire format other implementations see.
Troubleshooting
Match the symptom to a likely cause before changing your client or server configuration.
| Symptom | Likely cause | Fix |
|---|---|---|
The code generator cannot find protoc | protoc is not installed or not in PATH | install it, or set PROTOC to its path |
| The generated file has an unexpected name | the file is named after the proto package | use the package name in mod declarations |
“the trait NamedService is not implemented” | the server attribute is not imported | use use ntex_grpc::server;, not use ntex_grpc::server::{self} |
| A client-streaming call never returns | send() was awaited before the messages were sent | send and await the reply at the same time, with join |
Every call fails with UNIMPLEMENTED | the client and the server disagree on the package or service name | compare the request path with ServiceDef::NAME on both sides |
Calls fail with INVALID_ARGUMENT “Cannot decode grpc message” | the .proto files differ, or a custom field type rejected a value | regenerate from the same .proto; check your merge |
Calls fail with RESOURCE_EXHAUSTED | a message is larger than max_message_size | raise the limit on the side that receives the message |
Calls fail with NotGrpc | the address points at something that is not a gRPC server, or a proxy answered | check the address and the HTTP status in the error |
grpcurl reports a TLS error against a plaintext server | grpcurl uses TLS by default | add -plaintext |
grpcurl cannot list services | the server does not offer reflection | pass the .proto file with -proto |
| A TLS client refuses to talk to the server | ALPN does not select h2 | add h2 to alpn_protocols on both sides |
| A call hangs forever | no timeout and a stalled server | set timeout() on every call |
MQTT with ntex-mqtt
MQTT is a lightweight publish/subscribe protocol used in IoT, telemetry and messaging systems. Small devices often use it to keep long-lived connections to a broker. ntex-mqtt provides an MQTT client and server for ntex. Both support the two protocol versions in use, MQTT 3.1.1 and MQTT 5.0. A single server can accept both versions on the same port.
ntex-mqtt uses the same building blocks as the rest of ntex. Connections are
ntex I/O objects, and handlers are ntex services. You pass settings through a
SharedCfg and run MQTT servers inside the ntex server.
These pieces will be familiar if you have written an ntex web service.
Add the crate alongside ntex:
[dependencies]
ntex = { version = "4", features = ["tokio"] }
ntex-mqtt = "9"
Here is a server that accepts both protocol versions and prints every message it receives:
use ntex::SharedCfg;
use ntex_mqtt::{MqttServer, v3, v5};
#[derive(Debug)]
struct ServerError;
impl TryFrom<ServerError> for v5::PublishAck {
type Error = ServerError;
fn try_from(err: ServerError) -> Result<Self, Self::Error> {
Err(err)
}
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
ntex::server::build()
.bind("mqtt", "127.0.0.1:1883", SharedCfg::default(), async |_| {
MqttServer::new()
.v3(
v3::MqttServer::new(async |publish: v3::Publish| {
println!("v3 publish to {}", publish.publish_topic());
Ok::<_, ServerError>(())
})
.build(async |connect: v3::Connect| {
Ok::<_, ServerError>(connect.ack((), false))
}),
)
.v5(
v5::MqttServer::new(async |publish: v5::Publish| {
println!("v5 publish to {}", publish.publish_topic());
Ok::<_, ServerError>(publish.ack())
})
.build(async |connect: v5::Connect| {
Ok::<_, ServerError>(connect.ack(()))
}),
)
})?
.run()
.await
}
Most server examples in this chapter use an error type like ServerError.
Its TryFrom implementation decides how to handle an error. It can turn
the error into a PUBACK that refuses the message, or close the connection.
Returning Err closes it. Handling publishes shows
how to return a negative ack instead.
How ntex-mqtt is organized
Choose ntex_mqtt::v3 for MQTT 3.1.1 or ntex_mqtt::v5 for MQTT 5.
The modules have the same structure, so code for one version translates to
the other almost line by line. MQTT 5 adds reason codes, properties and a
few new packets, so its types carry more information.
Within either module, start with MqttServer to accept connections or
client::MqttConnector to open one. Incoming messages arrive as Publish
values; a Router can dispatch them by topic. Use MqttSink to send
packets back, and look in codec when you need the packet types themselves.
The crate root holds the combined MqttServer, the shared
MqttServiceConfig settings, and the Control messages for connection
events.
Once connected, your application splits its work between up to three
services. The publish service handles incoming PUBLISH packets. On a
server, this is where most application logic lives. On a client, router
handlers and the protocol service fill that role.
The protocol service handles packets that need an answer but are not
publishes. On the server these are SUBSCRIBE, UNSUBSCRIBE, PINGREQ,
DISCONNECT, PUBREL and, in MQTT 5, AUTH. It returns the response to
send back. The client has a corresponding service for packets from the
server, described below.
The control service handles connection events rather than MQTT packets. It reports write backpressure and tells you when the connection stops, including the reason. Both the protocol and control services have default implementations; replace them when your application needs different behavior.
Use a sink (MqttSink) to send packets to the peer, including publishes,
subscriptions and the final DISCONNECT. It is a cheap, cloneable handle.
A session (v3::Session<St> or v5::Session<St>) bundles the sink with
your per-connection state St. It dereferences to St, and its sink()
method returns the sink.
Configuration
A device sending telemetry and a client uploading files may need different
packet limits. Put those limits and protocol timeouts in
MqttServiceConfig, then add it to a SharedCfg as you would with other
ntex configuration. Connections created with that SharedCfg use the
settings that apply to their protocol version and role:
use ntex::{SharedCfg, time::Seconds};
use ntex_mqtt::{MqttServiceConfig, QoS};
fn config() -> SharedCfg {
SharedCfg::new("MQTT")
.add(
MqttServiceConfig::new()
.set_max_qos(QoS::ExactlyOnce)
.set_max_size(1024 * 1024)
.set_max_receive(32)
.set_connect_timeout(Seconds(10)),
)
.into()
}
An IoConfig in the same SharedCfg controls the connection’s buffers,
write backpressure and I/O timeouts. MQTT connections use ordinary ntex I/O
objects; see the I/O chapter.
The first group of protocol settings limits what a peer may send you:
| Setting | Default | Meaning |
|---|---|---|
set_max_qos | AtLeastOnce | Highest QoS a peer may publish with. A higher QoS is a protocol violation and closes the connection. An MQTT 5 server announces it in CONNACK |
set_max_size | 256 KiB | Largest incoming packet for MQTT 3.1.1 connections and MQTT 5 servers; 0 means the protocol maximum of 256 MiB. An MQTT 5 server announces it in CONNACK |
set_max_topic_alias | 32 | Topic aliases an MQTT 5 client may use when publishing to the server |
set_check_subs_availability | true | MQTT 5 server only. Close the connection when a client subscribes to a shared or wildcard filter that CONNACK declared unavailable. When disabled, the protocol service decides |
The next group controls how much work a connection handles at once. See Flow control for details:
| Setting | Default | Meaning |
|---|---|---|
set_max_receive | 16 | Concurrent incoming publishes in MQTT 3.1.1; extra publishes wait, and 0 disables the limit. An MQTT 5 server advertises this as Receive Maximum for QoS 1 and 2; 0 means 65535 |
set_max_receive_size | 65,535 bytes | Total size of incoming packets being handled. When it is reached, the connection stops reading |
set_max_queue | 64 | Responses waiting to be sent. Acks go out in the order the publishes arrived; when the queue is full, the connection stops reading |
set_max_send | 16 | Outgoing QoS 1 and 2 publishes waiting for an ack on servers and MQTT 3.1.1 clients. An MQTT 5 server also applies the client’s Receive Maximum |
set_min_chunk_size | 32 KiB | How much of a large payload to collect before handing a chunk to your handler |
set_max_payload_buffer_size | 32 KiB | Unread payload to buffer for a streaming publish before the connection stops reading |
set_handle_qos_after_disconnect | None | Highest QoS of received publishes that are still handed to the publish service after the connection starts closing. By default they are dropped |
MQTT 5 clients announce their own incoming packet-size and receive limits
through Connect::max_packet_size() and Connect::max_receive(), rather
than the corresponding MqttServiceConfig settings. Their outgoing send
credit comes from the server’s CONNACK, not set_max_send.
The remaining settings control timeouts:
| Setting | Default | Meaning |
|---|---|---|
protocol_version_timeout | 5 s | Combined server only. Time a client has to send enough of CONNECT to reveal its protocol version |
set_connect_timeout | 5 s | Server only. Time a client has to send its CONNECT packet |
set_handshake_timeout | disabled | Client only. Time allowed for connecting, sending CONNECT and receiving CONNACK |
A client chooses its keep-alive in the CONNECT packet. The server may
override it while accepting the connection. This setting is separate from
MqttServiceConfig.
The client
Use the client service to open a connection and perform the MQTT handshake.
It returns a Client when the handshake succeeds. The examples here use
MQTT 5. The MQTT 3.1.1 client in v3::client works the same way, with the
differences described where they apply.
Connecting
To connect, wrap v5::client::MqttConnector in a Pipeline with your
SharedCfg. The connector is an ntex service. Call it with a
v5::client::Connect describing the connection:
use ntex::{Pipeline, SharedCfg, time::Seconds};
use ntex_mqtt::v5;
#[ntex::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let connector = Pipeline::new(SharedCfg::default(), v5::client::MqttConnector::new());
let client = connector
.call(
v5::client::Connect::new("127.0.0.1:1883")
.client_id("sensor-17")
.keep_alive(Seconds(30))
.max_packet_size(64 * 1024)
.max_receive(32),
)
.await?;
println!("session present: {}", client.session_present());
Ok(())
}
Connect builds the CONNECT packet. The client_id identifies the
session the server should look up. If you want to discard any stored
session instead, set clean_start; MQTT 3.1.1 calls this clean_session.
For authentication, set username and password, or use MQTT 5’s auth
for enhanced authentication.
Use keep_alive to choose how often the client pings an idle connection;
it is disabled by default. A last_will gives the server a message to
publish if the client disappears without disconnecting.
MQTT 5 also lets you announce the client’s limits with max_packet_size
and max_receive. To set user properties, use properties; for direct
access to the remaining packet fields, use packet.
The connector returns a Client once the server accepts the connection. If
the server rejects it, the error carries the server’s CONNACK, including
its reason code. Use client.packet() to read the full CONNACK after a
successful handshake.
A successful MQTT 5 CONNACK also tells the client how much it may send.
Receive Maximum limits unacknowledged QoS 1 and 2 publishes, and Maximum
Packet Size limits the size of outgoing packets. If the server supplies a
Server Keep Alive, it replaces the client’s own keep-alive interval.
Secure connections
To connect over TLS, pass a transport connector to connector(). Without
one, the connector opens a plain TCP connection. You can use any ntex
connector, such as openssl:
use ntex::{Pipeline, SharedCfg, connect::openssl::SslConnector};
use ntex_mqtt::v5;
use openssl::ssl;
#[ntex::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut tls = ssl::SslConnector::builder(ssl::SslMethod::tls())?;
tls.set_alpn_protos(b"\x04mqtt")?;
let connector = Pipeline::new(
SharedCfg::default(),
v5::client::MqttConnector::new().connector(SslConnector::new(tls.build())),
);
let client = connector
.call(v5::client::Connect::new("broker.example.com:8883").client_id("sensor-17"))
.await?;
drop(client);
Ok(())
}
The standard ports are ntex_mqtt::TLS_PORT (8883) and TCP_PORT (1883).
You can use the same transport mechanism for MQTT over WebSockets. The
mqtt-ws-client example in the ntex-mqtt repository shows how. The
MQTT over WebSocket example includes a complete client and server.
Running the connection
Start the client’s dispatcher to read packets, answer pings and deliver
acks to waiting publishes. A Client does none of this on its own. Each
start method consumes the Client:
start_default()runs the connection with default handlers. Any publish from the server closes the connection, so this suits a client that only sends.start(service)runs it with your protocol service. That service sees every publish and every other packet the server sends.start_with_control(service, control)also replaces the control service.
Each of these returns a future that completes when the connection closes. Take the sink first, then spawn the dispatcher on the current thread:
use ntex::{Pipeline, SharedCfg};
use ntex_mqtt::v5;
#[ntex::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let connector = Pipeline::new(SharedCfg::default(), v5::client::MqttConnector::new());
let client = connector.call(v5::client::Connect::new("127.0.0.1:1883")).await?;
let sink = client.sink();
ntex::rt::spawn(client.start_default());
let ack = sink.publish("sensors/17/temperature").send_at_least_once("21.5".into()).await?;
println!("reason: {:?}", ack.reason_code);
sink.close();
Ok(())
}
The client sends keep-alive pings while the dispatcher runs. The dispatcher also reads acks. If you never start it, a publish waiting for an ack waits forever.
Publishing
To send a message, call sink.publish(topic) to get a PublishBuilder.
Set the packet options you need, then send the payload with your chosen QoS:
| Method | QoS | Completes when | Returns |
|---|---|---|---|
send_at_most_once | 0 | The packet is written | () |
send_at_least_once | 1 | The server sends PUBACK | PublishAck (() in MQTT 3.1.1) |
send_exactly_once | 2 | The server sends PUBREC | PublishReceived |
A QoS 1 publish completes with the server’s PUBACK. In MQTT 5, the ack’s
reason code can refuse a message without closing the connection. For
example, the server might return NotAuthorized or QuotaExceeded. Check
reason_code when it matters.
An error from the call itself means the publish could not be sent or acknowledged. This usually happens because the connection closed.
QoS 2 takes two round trips. send_exactly_once returns once the server has
received the message. Call release() on the result to send PUBREL and
wait for PUBCOMP. If you drop the PublishReceived instead, ntex-mqtt
releases the publish for you.
Use properties() to add MQTT 5 properties to a publish. These include user
properties, content type and message expiry. You can also set a response
topic and correlation data for request/response messages, among other
properties:
use ntex_mqtt::v5;
async fn example(sink: v5::MqttSink) -> Result<(), v5::error::SendPacketError> {
let ack = sink
.publish("sensors/17/temperature")
.retain(true)
.properties(|props| {
props.content_type = Some("text/plain".into());
props.message_expiry_interval = Some(60);
props.user_properties.push(("unit".into(), "celsius".into()));
})
.send_at_least_once("21.5".into())
.await?;
drop(ack);
Ok(())
}
ntex-mqtt assigns packet ids automatically. You can set them yourself with
packet_id(). Do not mix automatic and manual ids on one connection, or
they will collide.
Publishing without waiting
Awaiting each ack limits a task to one message per round trip. To keep
several publishes in flight from one task, register an ack callback. Then
send with send_at_least_once_no_block():
use ntex_mqtt::v5;
fn example(sink: v5::MqttSink) -> Result<(), v5::error::SendPacketError> {
sink.publish_ack_cb(|ack, disconnected| {
if disconnected {
println!("publish {} was not acknowledged", ack.packet_id);
}
});
if sink.is_ready() {
sink.publish("events").send_at_least_once_no_block("started".into())?;
}
Ok(())
}
For these non-blocking sends, the callback reports acks in arrival order.
When the connection closes, it also reports each non-blocking publish
still in flight, with disconnected set to true.
The callback runs while the sink is borrowed, so it must not call any sink method. Hand that work to a channel or a task instead.
send_at_least_once_no_block() panics if the sink is not ready. Always
check is_ready() first, or wait for ready() as described below.
Streaming large payloads
A publish normally carries its whole payload in one Bytes. For large
messages, you can send it in pieces instead. Give the builder the total
size to get a StreamingPayload, then send each piece through it:
use ntex::util::Bytes;
use ntex_mqtt::v5;
async fn example(sink: v5::MqttSink, chunks: Vec<Bytes>) -> Result<(), v5::error::SendPacketError> {
let size = chunks.iter().map(|c| c.len() as u32).sum();
let (ack, payload) = sink.publish("files/report.csv").stream_at_least_once(size);
let send = async {
for chunk in chunks {
payload.send(chunk).await?;
}
Ok::<_, v5::error::SendPacketError>(())
};
let (ack, sent) = ntex::util::join(ack, send).await;
sent?;
println!("reason: {:?}", ack?.reason_code);
Ok(())
}
The example joins the ack future and the payload sender so both can make
progress. payload.send() waits until the publish header has been written.
The ack only arrives after the last chunk.
The total size of all chunks must match the declared size exactly. Use
stream_at_most_once(size) to stream a QoS 0 publish.
Other publishes on the same connection wait until the streaming publish finishes. MQTT cannot interleave packets inside a payload.
Incoming publishes can be streamed as well; see Reading payloads.
Flow control
Send credit limits how many QoS 1 and 2 publishes can wait for an ack at once. The server tells the client this limit through its Receive Maximum, and ntex-mqtt tracks the available send credit.
Each QoS 1 or 2 publish takes one unit of credit when sent. The credit
returns when the ack arrives. When none is left, send_at_least_once() and
send_exactly_once() wait for an ack to free some. Waiting publishes get
credit in the order they requested it; QoS 0 publishes do not use credit.
The sink also follows the connection’s write backpressure. Sends wait for the write buffer to drain when it grows past its high watermark. See the I/O chapter for details.
To check before sending, use credit() for the remaining credit or
is_ready() for both credit and the absence of write backpressure. When
you need to wait, ready().await returns once the sink is ready, or
returns false if the connection has closed.
This lets a producer slow down rather than queue up. For example, wait for readiness before sending each sensor reading:
use ntex::util::Bytes;
use ntex_mqtt::v5;
async fn next_reading() -> Option<Bytes> { None }
async fn example(sink: v5::MqttSink) -> Result<(), v5::error::SendPacketError> {
while let Some(reading) = next_reading().await {
if !sink.ready().await {
break; // connection closed
}
sink.publish("sensors/17").send_at_least_once_no_block(reading)?;
}
Ok(())
}
ready() does not reserve credit. If several tasks share a sink, another
task may use the credit between your ready() call and your send. An
awaiting send waits again if needed. The non-blocking send would panic, so
check is_ready() immediately before calling
send_at_least_once_no_block().
For incoming publishes, the client announces its Receive Maximum with
Connect::max_receive(). The settings in Configuration
also limit how much incoming data it buffers.
Subscribing
To receive messages, subscribe to one or more topic filters. In MQTT 5 each filter comes with options:
use ntex_mqtt::v5::{self, codec};
async fn example(sink: v5::MqttSink) -> Result<(), v5::error::SendPacketError> {
let ack = sink
.subscribe(None)
.topic_filter(
"commands/sensor-17/#".into(),
codec::SubscriptionOptions {
qos: codec::QoS::AtLeastOnce,
no_local: false,
retain_as_published: false,
retain_handling: codec::RetainHandling::AtSubscribe,
},
)
.send()
.await?;
for status in &ack.status {
println!("subscription: {status:?}");
}
Ok(())
}
The argument to subscribe() is an optional subscription identifier. The
server attaches it to every publish delivered through this subscription.
The SUBACK holds one status per filter, in filter order. Each status gives
the granted QoS or a reason the server refused that filter.
sink.unsubscribe() works the same way.
In MQTT 3.1.1, subscribe() takes no identifier. Its topic_filter() takes
just a QoS, and the ack is a list of SubscribeReturnCodes.
Subscribing does not use send credit. The dispatcher must still be running to read the server’s answer.
Receiving publishes
Attach handlers to topic patterns with resource() to receive publishes
from your subscriptions. This turns the Client into a ClientRouter.
Start the router as you would a client:
use ntex::{Pipeline, SharedCfg};
use ntex_mqtt::v5;
#[derive(Debug)]
struct Error;
impl TryFrom<Error> for v5::PublishAck {
type Error = Error;
fn try_from(err: Error) -> Result<Self, Self::Error> {
Err(err)
}
}
async fn command(publish: v5::Publish) -> Result<v5::PublishAck, Error> {
let id = publish.topic().get("id").unwrap_or_default().to_string();
let payload = publish.read_all().await.map_err(|_| Error)?;
println!("command for {id}: {payload:?}");
Ok(publish.ack())
}
async fn status(publish: v5::Publish) -> Result<v5::PublishAck, Error> {
println!("status: {:?}", publish.read_all().await);
Ok(publish.ack())
}
#[ntex::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let connector = Pipeline::new(SharedCfg::default(), v5::client::MqttConnector::new());
let client = connector.call(v5::client::Connect::new("127.0.0.1:1883")).await?;
let sink = client.sink();
let router = client
.resource("commands/{id}/#", command)
.resource("status", status);
ntex::rt::spawn(router.start_default());
sink.subscribe(None)
.topic_filter("commands/sensor-17/#".into(), Default::default())
.topic_filter("status".into(), Default::default())
.send()
.await?;
ntex::time::sleep(ntex::time::Seconds(60)).await;
Ok(())
}
Resource patterns match topic levels. A {name} segment matches and
captures one level; read it with publish.topic().get("name"). A trailing
# matches the rest of the topic.
A handler is any service that takes a Publish and returns a PublishAck.
It can also take &v5::Session<()> as its first argument. MQTT 3.1.1
handlers return ().
The router uses the handler’s response to acknowledge each publish. It
sends PUBACK for QoS 1 and PUBREC for QoS 2. In MQTT 5, a handler can
refuse a message with PublishAck::new(reason).
A handler error closes the connection unless it converts to a PublishAck.
The TryFrom implementation above controls this. Returning Ok(ack) from
it turns the error into a negative ack.
With start_default(), a publish whose topic matches no resource closes the
connection. To handle those, and every other packet from the server, use
start() with a protocol service.
The protocol service
Routing covers the topics you expect, but a client also needs a policy for
anything else the server sends. A client protocol service receives these
packets as v5::client::ProtocolMessage values. An unrouted publish arrives
as Publish; PublishRelease carries the server’s PUBREL for a QoS 2
publish. The service also sees Ping for a PINGRESP and, in MQTT 5,
Disconnect for a server DISCONNECT.
For an unrouted Publish, MQTT 5’s ProtocolMessage::ack() closes the
connection because publishing is unsupported by default. Match that variant
and use publish.ack(reason) to accept or reject it. In MQTT 3.1.1,
ProtocolMessage::ack() and publish.ack() both acknowledge the publish.
Other variants’ ack() methods provide their default responses.
To close instead, MQTT 5’s ProtocolMessage::disconnect() takes a
codec::Disconnect packet. MQTT 3.1.1 has no public equivalent on
ProtocolMessage; use the sink’s close().
This MQTT 5 service reads and accepts unrouted publishes:
use ntex::{Pipeline, SharedCfg};
use ntex_mqtt::v5::{self, client::ProtocolMessage, client::ProtocolMessageAck, codec};
async fn protocol(msg: ProtocolMessage) -> Result<ProtocolMessageAck, ()> {
Ok(match msg {
ProtocolMessage::Publish(publish) => {
println!("unrouted {:?}: {:?}", publish.packet().topic, publish.read_all().await);
publish.ack(codec::PublishAckReason::Success)
}
msg => msg.ack(),
})
}
#[ntex::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let connector = Pipeline::new(SharedCfg::default(), v5::client::MqttConnector::new());
let client = connector.call(v5::client::Connect::new("127.0.0.1:1883")).await?;
ntex::rt::spawn(client.start(protocol));
Ok(())
}
A ClientRouter accepts a protocol service the same way, with start().
The control service
Use the control service for events outside the MQTT packet exchange, such
as logging a lost connection or observing a slow peer. It receives
ntex_mqtt::Control values: WrBackpressure reports when write
backpressure starts and stops, while Stop(reason) arrives once as the
connection shuts down.
The stop reason tells you where the failure came from. Error means one
of your services returned an error. Protocol means the peer broke the
protocol or a keep-alive timed out; PeerGone means the underlying
connection closed.
The service returns an optional packet to send before closing, usually a
DISCONNECT with a reason code. The default control service returns no
packet. Set your client control service with start_with_control(); the
server section shows a full example.
Closing
Call sink.close() to send DISCONNECT, flush buffered data and close the
connection gracefully. In MQTT 5, use close_with_reason() to choose the
DISCONNECT packet. For example, you can include a session expiry interval
or a reason code.
To drop the connection immediately, use force_close(). This discards
buffered data and fails any publishes still in flight.
sink.is_open() becomes false as soon as either side starts closing the
connection.
The server
An MQTT server is a service factory that you plug into the
ntex server. Use v3::MqttServer to serve MQTT 3.1.1 or
v5::MqttServer to serve MQTT 5. To accept both versions, combine them with
ntex_mqtt::MqttServer.
A server for one version
To build a server for one protocol version, pass a publish service to
new(). Then pass a handshake service to build(). The handshake service
receives the client’s CONNECT and decides whether to accept the
connection:
use ntex::SharedCfg;
use ntex_mqtt::v5;
#[derive(Debug)]
struct ServerError;
impl TryFrom<ServerError> for v5::PublishAck {
type Error = ServerError;
fn try_from(err: ServerError) -> Result<Self, Self::Error> {
Err(err)
}
}
#[derive(Debug)]
struct Device {
id: String,
}
async fn handshake(connect: v5::Connect) -> Result<v5::ConnectAck<Device>, ServerError> {
let packet = connect.packet();
if packet.username.as_deref() != Some("device") {
return Ok(connect.failed(v5::codec::ConnectAckReason::BadUserNameOrPassword));
}
let device = Device {
id: packet.client_id.to_string(),
};
Ok(connect.ack(device))
}
async fn publish(
session: &v5::Session<Device>,
publish: v5::Publish,
) -> Result<v5::PublishAck, ServerError> {
println!("{} published to {}", session.id, publish.publish_topic());
Ok(publish.ack())
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
ntex::server::build()
.bind("mqtt", "127.0.0.1:1883", SharedCfg::default(), async |_| {
v5::MqttServer::new(publish).build(handshake)
})?
.run()
.await
}
The value you pass to ack() becomes the connection’s session. Publish,
protocol and control handlers can read it by taking &Session<Device> as
their first argument, as publish does above.
The handshake covers this step in detail.
A v3 server has the same structure. Its publish service returns ().
Its ack() also takes a second argument, the “session present” flag. This
tells the client whether you already hold state for it:
use ntex::SharedCfg;
use ntex_mqtt::v3;
#[derive(Debug)]
struct ServerError;
#[ntex::main]
async fn main() -> std::io::Result<()> {
ntex::server::build()
.bind("mqtt", "127.0.0.1:1883", SharedCfg::default(), async |_| {
v3::MqttServer::new(async |publish: v3::Publish| {
println!("publish to {}", publish.publish_topic());
Ok::<_, ServerError>(())
})
.build(async |connect: v3::Connect| Ok::<_, ServerError>(connect.ack((), false)))
})?
.run()
.await
}
The handshake
The handshake is where you turn an incoming connection into an accepted client with application state. For example, you can check credentials, look up the device, and put its identity into the session before allowing it to publish.
The service receives the client’s first packet wrapped in a Connect.
Read packet() for the decoded CONNECT: the client id, username and
password, keep-alive, last will and, in MQTT 5, properties. Use
packet_mut() if you need to take fields out rather than copy them.
The wrapper also gives you context beyond the packet. Use io() to query
the connection’s peer address or TLS details, and st() for data collected
before the handshake; see Server state. Keep a handle from
sink() if another part of your application will send to this client.
To accept the client, return ack() with its session state. To refuse it,
return failed() with a reason code. Both produce a ConnectAck, which
holds the CONNACK packet; after a refusal, the server sends it and closes
the connection. Returning an error instead closes the connection without a
CONNACK, so the client does not get a refusal reason.
For an MQTT 5 refusal, fail_with() takes a complete CONNACK packet.
Use it to include a reason string or other properties. MQTT 3.1.1 has fewer
codes and a helper for each: identifier_rejected(), bad_username_or_pwd(),
not_authorized() and service_unavailable().
Acceptance is also your chance to adjust settings for this client. In
MQTT 5, keep_alive() adjusts the idle timeout and advertises Server Keep
Alive when needed. Use with() to edit the CONNACK packet directly,
including an assigned client id, session expiry, response information,
limits and other properties.
In MQTT 3.1.1, use idle_timeout() for how long the connection may stay
silent and max_packet_size() to limit incoming packets. Both versions
provide max_send() to set the connection’s send credit.
Before calling your service, the server checks the first packet. It must be
CONNECT and arrive within the connect timeout; see
Configuration. Otherwise, the server closes the connection
without calling the handshake service.
From acknowledgement to session
The value you pass to ack() becomes the state your handlers see through
Session<T>. This cheap, reference-counted handle dereferences to your
value and also provides the client’s sink through session.sink() and
the connection’s configuration through session.cfg().
Because handlers share the session, changing your value during the
connection requires interior mutability, such as a Cell or a RefCell.
When the handshake service returns an accepted ConnectAck, the server
finishes setting up the connection:
- It applies the acknowledgement’s settings. In MQTT 5, the server enforces
the limits you advertise in
CONNACK. These include maximum QoS, receive maximum, topic alias maximum and maximum packet size. Send credit never exceeds the receive maximum the client announced inCONNECT. - It sends the
CONNACK. - It creates the publish, protocol and control services from their
factories, passing the session to
create(). Each factory runs once per connection and can use the session to prepare per-connection resources. If a factory fails, the server closes the connection. - It starts reading packets. The session becomes the connection pipeline’s
state, so every handler receives it as
&Session<T>.
The session lives as long as something holds a clone of it. Normally, the
connection’s services are its only owners, so it is dropped when they
finish. To keep a handle elsewhere in your application, use
ack_and_session(), which returns the session alongside the
acknowledgement.
For example, the handshake can register each device in a shared map so other handlers can reach it. The control service removes the entry when the connection stops:
use std::{cell::RefCell, collections::HashMap, rc::Rc};
use ntex::SharedCfg;
use ntex_mqtt::{Control, v5};
#[derive(Debug)]
struct ServerError;
impl TryFrom<ServerError> for v5::PublishAck {
type Error = ServerError;
fn try_from(err: ServerError) -> Result<Self, Self::Error> {
Err(err)
}
}
type Registry = Rc<RefCell<HashMap<String, v5::Session<Device>>>>;
struct Device {
id: String,
registry: Registry,
}
async fn control(
session: &v5::Session<Device>,
msg: Control<ServerError>,
) -> Result<Option<v5::codec::Encoded>, ServerError> {
if let Control::Stop(_) = msg {
session.registry.borrow_mut().remove(&session.id);
}
Ok(None)
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
ntex::server::build()
.bind("mqtt", "127.0.0.1:1883", SharedCfg::default(), async |_| {
let registry = Registry::default();
v5::MqttServer::new(async |p: v5::Publish| Ok::<_, ServerError>(p.ack()))
.control(control)
.build(async move |connect: v5::Connect| {
let device = Device {
id: connect.packet().client_id.to_string(),
registry: registry.clone(),
};
let (ack, session) = connect.ack_and_session(device);
registry.borrow_mut().insert(session.id.clone(), session);
Ok::<_, ServerError>(ack)
})
})?
.run()
.await
}
Any handler can now look up another device and publish to it through its
sink(). The server calls the factory closure once per worker. Each worker
therefore has its own registry, with no need for locking.
Remove the registry entry when the connection stops. The entry holds a clone of the session; without this cleanup, the session would never be dropped.
Serving both versions
To accept both protocol versions on one port, use the combined
ntex_mqtt::MqttServer, as in the opening example. Build each version’s
server as usual. Pass the MQTT 3.1.1 server to v3() and the MQTT 5 server
to v5().
The combined server reads the version from the client’s CONNECT and
passes the connection to the matching server. It refuses versions you have
not configured. Both servers must use the same error type, though each has
its own handlers and session type.
The client must send enough of CONNECT to reveal its version within
protocol_version_timeout, set in MqttServiceConfig.
Server state
Choose where to keep state based on how long you need it and which connections need access. An MQTT server uses worker, connection and session state. All three use the mechanisms described in the state chapter.
A database pool or device registry usually belongs in worker state, shared
by all connections on that worker. With build_with_config(), each worker
creates its own state, held by the pipeline that runs the MQTT server;
see Worker and request state. To read it in the
handshake, use a state-aware function
with worker state as its first argument.
Data collected for one connection before MQTT starts, such as the peer
address or TLS server name, belongs in connection state. A service in
front of the MQTT server can wrap that data and the connection in a
State. Create the MQTT server
with MqttServer::with() rather than new() to accept it. Your handshake
then receives a Connect<T> and reads the value with connect.st().
The handshake brings these sources together in session state: the value
you pass to ack(). Publish, protocol and control services receive that
value through &Session<T>, not the original worker or connection state.
Copy or clone what those handlers need into the session. For shared worker
resources, cloning an Rc gives every handler access without copying the
resource itself. A session belongs to one MQTT connection, though retained
clones can keep its state alive after the connection closes.
The example below uses all three kinds of state. Worker state holds a list
of allowed devices and a message counter. The accept service records the
peer address, and the handshake combines both into the session:
use std::{cell::Cell, collections::HashSet, net::SocketAddr, rc::Rc};
use ntex::io::{Io, types::PeerAddr};
use ntex::service::{State, service};
use ntex::SharedCfg;
use ntex_mqtt::{MqttError, v5};
#[derive(Debug)]
struct ServerError;
impl TryFrom<ServerError> for v5::PublishAck {
type Error = ServerError;
fn try_from(err: ServerError) -> Result<Self, Self::Error> {
Err(err)
}
}
/// Worker state, created once per worker.
#[derive(Clone)]
struct AppState {
allowed: Rc<HashSet<String>>,
received: Rc<Cell<u64>>,
}
/// Connection state, collected before the MQTT handshake.
struct Peer {
addr: Option<SocketAddr>,
}
/// Session state, one per MQTT connection.
struct Device {
id: String,
peer: Option<SocketAddr>,
app: AppState,
}
async fn accept(
_: &AppState,
io: Io,
) -> Result<State<Peer, Io>, MqttError<ServerError>> {
let addr = io.query::<PeerAddr>().get().map(|addr| addr.into_inner());
Ok(State { req: io, state: Peer { addr } })
}
async fn handshake(
app: &AppState,
connect: v5::Connect<Peer>,
) -> Result<v5::ConnectAck<Device>, ServerError> {
let id = connect.packet().client_id.to_string();
if !app.allowed.contains(&id) {
return Ok(connect.failed(v5::codec::ConnectAckReason::NotAuthorized));
}
let device = Device {
id,
peer: connect.st().addr,
app: app.clone(),
};
Ok(connect.ack(device))
}
async fn publish(
session: &v5::Session<Device>,
publish: v5::Publish,
) -> Result<v5::PublishAck, ServerError> {
let received = &session.app.received;
received.set(received.get() + 1);
println!(
"{} ({:?}) published to {}, {} messages so far",
session.id,
session.peer,
publish.publish_topic(),
received.get(),
);
Ok(publish.ack())
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
ntex::server::build_with_config(async || {
Ok(AppState {
allowed: Rc::new(HashSet::from(["sensor-1".to_string()])),
received: Rc::new(Cell::new(0)),
})
})
.bind("mqtt", "127.0.0.1:1883", SharedCfg::default(), async |_: &AppState| {
service(accept).and_then(v5::MqttServer::with(publish).build(handshake))
})?
.run()
.await
}
Each worker has its own AppState. Its received counter only counts
messages handled by that worker. Share a value through an Arc if it must
be visible across workers.
Configuring the server
Pass your SharedCfg to bind() to apply the settings described in
Configuration.
An MQTT 5 server announces its maximum QoS, maximum packet size, Receive
Maximum and topic alias limit in CONNACK. MQTT 3.1.1 cannot announce these
limits. A client that exceeds them is disconnected.
For TLS, put an ntex TLS acceptor in front of the server when binding it.
The openssl example in the ntex-mqtt repository shows how. For MQTT over
WebSockets, upgrade an HTTP/1 connection and pass the WebSocket transport to
the MQTT server. See the MQTT over WebSocket example.
Handling publishes
Use the publish service to process messages from clients. It receives a
Publish for each PUBLISH packet and returns the acknowledgement.
Read the topic with publish_topic(). Use qos() to read the QoS level.
The retain(), dup() and id() methods expose the other packet details.
In MQTT 5, use packet().properties to read properties.
ntex-mqtt resolves topic aliases before calling your service, so the topic is always complete.
Returning from the service means you have taken responsibility for the
message, so store, forward or reject it before returning. For QoS 1,
ntex-mqtt then sends PUBACK; for QoS 2, it sends PUBREC. The client’s
later PUBREL goes to the protocol service, whose default answers with
PUBCOMP to complete the QoS 2 exchange. QoS 0 sends no acknowledgement.
In MQTT 5, publish.ack() creates a successful PublishAck. Use
PublishAck::new(reason) to refuse a message without closing the
connection. You can also add a reason string or user properties:
use ntex_mqtt::v5::{self, codec::PublishAckReason};
#[derive(Debug)] struct ServerError;
fn allowed(_: &str) -> bool { true }
async fn publish(publish: v5::Publish) -> Result<v5::PublishAck, ServerError> {
if !allowed(publish.publish_topic()) {
return Ok(v5::PublishAck::new(PublishAckReason::NotAuthorized)
.reason("topic is read-only".into()));
}
Ok(publish.ack())
}
A service error closes the connection unless it converts to a negative
ack. The TryFrom<ServerError> for v5::PublishAck implementation in the
examples makes that decision. Returning Err keeps the error. Returning
Ok(ack) sends the ack and keeps the connection open.
MQTT 3.1.1 has no negative acks. A service error therefore always closes the connection.
Acks go out in the order publishes arrived, even if the services finish in
a different order. An ack that is ready early waits in the response queue.
The set_max_queue setting limits that queue’s size.
Reading payloads
Call publish.read_all().await to read the whole payload. For small
payloads, this returns at once because the payload arrives with the packet.
To avoid holding a large message in memory, read it one chunk at a time.
If only part of a publish has arrived, ntex-mqtt calls your service as soon
as it has the header. It streams the remaining payload in chunks of at
least set_min_chunk_size bytes. You can still use read_all(), or process
each chunk as it arrives:
use ntex_mqtt::v5;
#[derive(Debug)] struct ServerError;
async fn upload(publish: v5::Publish) -> Result<v5::PublishAck, ServerError> {
let mut total = 0;
while let Some(chunk) = publish.read().await.map_err(|_| ServerError)? {
total += chunk.len();
}
println!("received {total} of {} bytes", publish.payload_size());
Ok(publish.ack())
}
Use payload_size() to get the full size before reading. You can move the
payload to another task with take_payload(), but that task must keep
reading it. Dropping a payload before reading it to the end closes the
connection, because the rest of the stream has nowhere to go.
Routing
Use a Router to send publishes to handlers by topic. Pass it to new()
as the publish service, with a default handler for topics that do not
match. This avoids putting all your topic handling in one large match:
use ntex_mqtt::v5;
#[derive(Debug)] struct ServerError;
impl TryFrom<ServerError> for v5::PublishAck {
type Error = ServerError;
fn try_from(err: ServerError) -> Result<Self, Self::Error> { Err(err) }
}
#[derive(Debug)] struct Device;
fn run() -> std::io::Result<()> {
let _ = ntex::server::build().bind("mqtt", "127.0.0.1:1883", ntex::SharedCfg::default(), async |_| {
let server = v5::MqttServer::new(
v5::Router::new(async |publish: v5::Publish| {
println!("unrouted publish to {}", publish.publish_topic());
Ok::<_, ServerError>(publish.ack())
})
.resource(["alerts", "alarms"], async |publish: v5::Publish| {
Ok(publish.ack())
})
.resource(
"devices/{id}/telemetry",
async |session: &v5::Session<Device>, publish: v5::Publish| {
let id = publish.topic().get("id").unwrap_or_default();
println!("telemetry from {id} via {session:?}");
Ok(publish.ack())
},
),
)
.build(async |connect: v5::Connect| Ok::<_, ServerError>(connect.ack(Device)));
server
})?;
Ok(())
}
A resource takes one pattern or a list of patterns, using the syntax
described for the client. Each handler is a full
service with its own readiness, but the router waits for all handlers and
the default service to be ready. A handler that is not ready can therefore
pause the whole connection, not just its own topics. v3::Router works the
same way.
Sending to clients
To send a message to a client, publish through that client’s sink. Get it
with connect.sink() during the handshake and keep it in session state or
a shared registry. Inside a handler, you can use session.sink() instead:
use ntex_mqtt::v5;
#[derive(Debug)] struct ServerError;
async fn handshake(connect: v5::Connect) -> Result<v5::ConnectAck<()>, ServerError> {
let sink = connect.sink();
ntex::rt::spawn(async move {
let _ = sink
.publish("welcome")
.send_at_least_once("hello".into())
.await;
});
Ok(connect.ack(()))
}
A server sink has the same publishing API as a client sink. It supports the
same QoS levels, properties, streaming and ack callbacks. Send credit and
ready() work the same way too. It refuses subscribe() and
unsubscribe(), since only clients send those packets.
Call close() on the sink to close the connection gracefully. An MQTT 5
server sends DISCONNECT first; use close_with_reason() to include a
reason code. An MQTT 3.1.1 server closes without a DISCONNECT, since that
version only allows clients to send it.
Do not await an ack inside a publish handler when sending to the same client. The connection reads both the client’s publishes and its acks. It stops reading while busy, as described in the next section. The handler can therefore wait forever for an ack that cannot be read until it returns.
Spawn these sends, as the handshake above does. You can also use
send_at_least_once_no_block() with an ack callback.
Flow control
Flow control limits how much work a connection can put on the server. It protects the server when clients send too fast or break protocol limits.
For MQTT 5, set_max_receive limits how many QoS 1 and 2 publishes a
connection may have in flight. The server announces this as Receive
Maximum, and a client that exceeds it breaks the protocol. MQTT 3.1.1 has
no such announcement: the setting limits concurrent publish handling at
all QoS levels, with extra publishes waiting in order for a free slot.
Other limits pause reading rather than reject a packet. The connection stops reading new packets while:
- the publish or protocol service is not ready;
- the response queue is full (
set_max_queue); - the packets being handled total
set_max_receive_sizebytes; - a streaming payload has
set_max_payload_buffer_sizebytes your handler has not read yet.
For a streaming payload, reading resumes once the handler drains the buffer to half that size.
During a read pause, the client’s data waits in its TCP buffers. TCP flow control eventually slows the client down. No read timeout runs during the pause, because the server is causing the delay.
The other direction has its own limit. Publishes to a client use send
credit, just as on the client side. Set it with set_max_send or with
max_send() on the ConnectAck. In MQTT 5, it cannot exceed the client’s
Receive Maximum.
Sends wait for credit and for write backpressure to clear, so a slow client slows its senders down instead of letting them keep adding packets to the write buffer.
Your services also control the connection through readiness. For example, a publish handler can report that it is not ready when a downstream queue is full. The connection stops reading until the handler is ready again.
Services whose readiness can change must notify ntex-mqtt through
ReadyNotifier in bind(). The pipeline chapter explains
how.
The protocol service
Provide a protocol service to handle subscriptions and other packets
besides publishes. A broker always needs one. Without a custom protocol
service, the server answers pings, DISCONNECT and PUBREL. It closes the
connection on anything else, including subscriptions.
The service receives a ProtocolMessage and returns a ProtocolMessageAck:
use ntex::util::ByteString;
use ntex_mqtt::v5::{self, ProtocolMessage, ProtocolMessageAck, QoS};
use std::cell::RefCell;
#[derive(Debug)] struct ServerError;
impl TryFrom<ServerError> for v5::PublishAck {
type Error = ServerError;
fn try_from(err: ServerError) -> Result<Self, Self::Error> { Err(err) }
}
#[derive(Default)]
struct Client {
topics: RefCell<Vec<ByteString>>,
}
async fn protocol(
session: &v5::Session<Client>,
msg: ProtocolMessage,
) -> Result<ProtocolMessageAck, ServerError> {
Ok(match msg {
ProtocolMessage::Subscribe(mut subscribe) => {
for mut sub in subscribe.iter_mut() {
if sub.topic().starts_with("$SYS") {
sub.fail(v5::codec::SubscribeAckReason::NotAuthorized);
} else {
session.topics.borrow_mut().push(sub.topic().clone());
sub.confirm(QoS::AtLeastOnce);
}
}
subscribe.ack()
}
ProtocolMessage::Unsubscribe(unsubscribe) => {
let mut topics = session.topics.borrow_mut();
topics.retain(|t| unsubscribe.iter().all(|u| u != t));
unsubscribe.ack()
}
msg => msg.ack(),
})
}
fn run() -> std::io::Result<()> {
let _ = ntex::server::build().bind("mqtt", "127.0.0.1:1883", ntex::SharedCfg::default(), async |_| {
let server = v5::MqttServer::new(async |p: v5::Publish| Ok::<_, ServerError>(p.ack()))
.protocol(protocol)
.build(async |c: v5::Connect| Ok::<_, ServerError>(c.ack(Client::default())));
server
})?;
Ok(())
}
For a SUBSCRIBE, visit each topic filter. Call confirm() with the QoS
you grant, or call fail() to refuse it. Filters you leave alone are
refused.
In MQTT 5, each filter’s options() gives the client’s QoS, no-local,
retain-as-published and retain-handling choices. Use packet() to access
the whole packet. Unsubscribe works the same way, with success() and
fail().
For routine packets, you can usually keep the default response with
msg.ack(). A Ping gets PINGRESP, and PublishRelease answers the
PUBREL that finishes a QoS 2 publish. Disconnect carries the client’s
DISCONNECT; in MQTT 5, that packet includes a reason code and may update
the session expiry interval.
Enhanced authentication needs an explicit response. MQTT 5 delivers each
step as Auth; answer it with auth.ack(packet).
Use disconnect() to turn any message into a disconnect. In MQTT 5,
disconnect_with() lets you choose the reason code.
The server handles protocol messages one at a time, in order. It buffers up to 16.
The control service
Use the control service to observe connection events and clean up when a
connection stops. It receives the same Control messages as the client
control service. You can return a packet to send before the connection
closes:
use ntex_mqtt::{Control, Reason, v5};
#[derive(Debug)] struct ServerError;
impl TryFrom<ServerError> for v5::PublishAck {
type Error = ServerError;
fn try_from(err: ServerError) -> Result<Self, Self::Error> { Err(err) }
}
#[derive(Debug)] struct Device;
async fn control(
session: &v5::Session<Device>,
msg: Control<ServerError>,
) -> Result<Option<v5::codec::Encoded>, ServerError> {
match msg {
Control::Stop(Reason::Error(err)) => {
println!("{session:?}: service error {:?}", err.get_ref());
let disconnect = v5::codec::Disconnect::new(
v5::codec::DisconnectReasonCode::ImplementationSpecificError,
);
Ok(Some(v5::codec::Packet::from(disconnect).into()))
}
Control::Stop(Reason::Protocol(err)) => {
println!("{session:?}: protocol error {:?}", err.get_ref());
Ok(None)
}
Control::Stop(Reason::PeerGone(_)) => {
println!("{session:?}: connection lost");
Ok(None)
}
Control::WrBackpressure(bp) => {
println!("{session:?}: write backpressure {}", bp.enabled());
Ok(None)
}
}
}
fn run() -> std::io::Result<()> {
let _ = ntex::server::build().bind("mqtt", "127.0.0.1:1883", ntex::SharedCfg::default(), async |_| {
let server = v5::MqttServer::new(async |p: v5::Publish| Ok::<_, ServerError>(p.ack()))
.control(control)
.build(async |c: v5::Connect| Ok::<_, ServerError>(c.ack(Device)));
server
})?;
Ok(())
}
Stop arrives exactly once per accepted connection. Use it for cleanup,
such as removing a client from a registry, publishing its presence or
releasing resources. A graceful DISCONNECT from the client reaches the
protocol service before the connection stops.
When an MQTT 5 connection closes because of a protocol error, ntex-mqtt
sends the matching DISCONNECT reason code. You should usually return
None in that case. MQTT 3.1.1 has no server DISCONNECT, so return None.
MQTT 5 features
MQTT 5 exposes more information through packet fields and properties.
For outgoing topic aliases, set properties.topic_alias on your publishes
and stay within the limit the client gave in CONNECT. For subscription
identifiers, read them from SUBSCRIBE and attach them to matching
publishes with properties.subscription_ids.
Some properties describe work your application must do. Will delay, for
example, is available in the CONNECT packet’s last-will properties, but
your application must schedule the will.
This is the boundary between the protocol framework and a broker. ntex-mqtt handles protocol rules, ordering, flow control and limits. Your application matches subscriptions to publishes, stores retained messages and manages persistent sessions, choosing how to store that data.
The MQTT over WebSocket example is a complete program with an MQTT 3.1.1 server behind an HTTP/1 WebSocket upgrade. It also includes a client that publishes to the server. The ntex-mqtt examples include TLS, sessions, routing and subscriptions.
Securing Connections with TLS
When your service leaves localhost, its traffic crosses networks you do not
control. TLS protects that traffic from being read or altered in transit. It
also lets peers authenticate each other so they can check who they are talking
to.
In ntex, you configure TLS when setting up a connection. Your HTTP handlers, WebSocket services, and custom protocols still work with ordinary application bytes.
All ntex TLS backends work on in-memory byte streams through the I/O filter layer. They do not read from or write to sockets themselves. You can use them with any ntex-supported I/O or runtime backend, provided the TLS backend supports your platform.
The x509 module gives you a platform-independent API for certificates and
identities. You use the same API to load identities, inspect certificates, and
check trust. ntex uses the appropriate platform or backend functionality
underneath.
If you are new to TLS, start with the HTTPS server, then read the certificate primer. If you already have a TLS configuration, skip to connecting it to ntex.
For services that identify clients by certificate, the client-authentication section separates TLS verification from application access checks. Use the production checklist before deploying either kind of service.
The snippets focus on configuration. For complete programs, use the ntex examples repository. Each example’s README includes its dependencies, certificate setup, and run commands.
Supported backends
ntex supports three TLS backends. Their types are available through ntex::tls,
or directly from ntex_tls.
| Backend | Enable it | Platform and configuration |
|---|---|---|
| OpenSSL | ntex/openssl or ntex-tls/openssl | Platforms with OpenSSL; requires its native libraries and headers |
| rustls | ntex/rustls or ntex-tls/rustls | Configured with rustls ClientConfig and ServerConfig; choose a crypto provider |
| Schannel | Available automatically on Windows | Windows-native identities, trust policy, protocol versions and cipher suites |
Enable the corresponding feature to use OpenSSL or rustls. Neither is enabled
by default in ntex-tls. Schannel is available automatically on Windows; you do
not need its compatibility-only schannel feature.
For an OpenSSL application, start with:
[dependencies]
ntex = { version = "4", features = ["tokio", "openssl"] }
openssl = "0.10"
For rustls, you also need a crypto provider to implement the cryptographic algorithms. The examples in this chapter use ring:
[dependencies]
ntex = { version = "4", features = ["tokio", "rustls"] }
ntex-tls = { version = "4.7", features = ["rustls-ring"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
rustls-pemfile = "2"
Here, ntex-tls/rustls-ring enables rustls and makes ring available to the
X.509 helpers when no process-wide provider has been installed.
Both examples choose Tokio, but you can use another ntex-supported runtime without changing the TLS configuration.
Choosing a backend
Choose a backend based on your platform and deployment needs. All three use the same ntex integration.
For a new service, rustls is a good starting point. It is written in Rust and needs no system TLS library, which simplifies cross-compilation and static builds. You choose its crypto provider explicitly.
Choose OpenSSL if your organization already standardizes on it, you need to reuse an existing configuration, or you need a feature only it provides here, such as pre-shared-key (PSK) identities.
For a Windows-first deployment, Schannel uses the certificate stores and trust policy already on the machine. It can also use keys without exporting them.
Your protocol code does not depend on the backend. Switching later usually requires changes only to the configuration code shown here.
TLS and X.509 backend selection are different
You can choose different backends for TLS connections and certificate operations. Enabling both TLS features lets you choose a transport for each connection.
The x509 helpers select their backend separately. On Windows, they always
use native APIs. Elsewhere, they use rustls when enabled and OpenSSL otherwise.
This means a certificate operation may not use the backend you chose for the
connection.
If verification fails, the helpers do not retry with another backend. The
x509 module is always available on Windows. On other platforms, you must
enable OpenSSL or rustls; enabling x509 alone is not enough.
On Unix, loading a PKCS#12 archive requires OpenSSL. This requirement applies even if rustls handles your TLS connections and certificate verification.
Quick start: an HTTPS server
This program serves one route over HTTPS. It uses rustls and the dependencies listed above:
use std::sync::Arc;
use ntex::tls::{rustls::certified_key, x509::Identity};
use ntex::web::{self, App, HttpResponse};
use rustls::{ServerConfig, sign::SingleCertAndKey};
#[ntex::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// The server's certificate chain and private key.
let identity = Identity::from_pem(
&std::fs::read("certs/server.pem")?,
&std::fs::read("certs/server.key")?,
)?;
let key = certified_key(&identity)?;
let config = ServerConfig::builder_with_provider(Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()?
.with_no_client_auth()
.with_cert_resolver(Arc::new(SingleCertAndKey::from(key)));
web::server(async |_| {
App::new().service(
web::resource("/").to(|| async { HttpResponse::Ok().body("Hello over TLS!") }),
)
})
.bind_rustls("127.0.0.1:8443", &config, ntex::SharedCfg::new("HTTPS"))?
.run()
.await?;
Ok(())
}
You need a certificate to run the server. Clone the
examples repository and run sh tls/generate-certs.sh from its
root. Copy server.pem, server.key, and ca.pem from tls/certs into a
certs directory next to your project.
Start the server, then run this command in another terminal:
curl --cacert certs/ca.pem https://localhost:8443/
The --cacert option tells curl to trust the example certificate authority.
Without it, curl refuses the connection because it cannot verify the server
through an authority it trusts.
The application, routes, and handler stay the same as for a plain HTTP server.
The setup code loads an identity and builds a rustls ServerConfig. It then
calls bind_rustls instead of bind. The rustls example
provides a fuller version of this program.
TLS as an I/O filter
TLS sits between the socket and your protocol. It decrypts incoming bytes before your application sees them and encrypts the bytes your application writes:
socket <-> TLS <-> HTTP
socket <-> TLS <-> WebSocket <-> application protocol
Reads move from left to right in these diagrams; writes move in the opposite direction. The filters transform buffers, while the I/O backend handles the socket. The I/O filter subsystem chapter explains this model in more detail.
Write your client or server protocol against ntex I/O to keep it independent of the TLS backend. Using ntex I/O instead of a bare TCP socket leaves the transport choice to connection setup.
On a server, the listener accepts a transport connection and a TLS acceptor
upgrades the existing Io through a handshake. On a client, a TLS connector
establishes the transport and performs the client handshake. After that, your
protocol service or codec handles application bytes without needing to know
which TLS backend is installed.
Adding TLS preserves any filters already installed on the connection. The type
Io<Layer<TlsFilter, F>> describes that stack. Your protocol can stay generic
over F: Filter.
To hide the concrete filter type, use Io::seal or Io::boxed. Encryption and
metadata remain available. Readiness and shutdown behavior also stay the same.
For example, this byte-stream service has no TLS imports:
use ntex::codec::BytesCodec;
use ntex::io::IoBoxed;
async fn echo(io: IoBoxed) -> std::io::Result<()> {
while let Some(bytes) = io.recv(&BytesCodec).await? {
io.send(bytes, &BytesCodec).await?;
}
Ok(())
}
The same function accepts plain I/O or io.boxed() after a TLS handshake.
It echoes byte chunks rather than complete application messages. If your
protocol has message boundaries, use a framing codec instead of BytesCodec.
You can see this separation in the examples. The connection-state example performs a handshake after accepting a connection and before constructing its HTTP state. The WebSocket example uses the same frame handlers for plain and encrypted connections.
If your application uses certificates to decide who may connect, its access checks do need to inspect and verify the peer’s certificate.
Certificates in a nutshell
Understanding certificates helps you diagnose TLS failures. If you already know how certificate chains work, skip ahead.
A certificate is a signed statement that a public key belongs to certain
names. Its subject alternative names (SANs) can include DNS:api.example.com
or IP:10.0.0.5. They can also contain a URI such as
spiffe://example.org/billing. The certificate records a validity period and
its issuer, the party that signed it.
The matching private key stays with its owner. During the handshake, a peer proves that it holds the key. A stolen certificate alone cannot provide that proof. In ntex, a certificate chain together with its private key is called an identity.
Issuers are themselves identified by certificates, which forms a chain:
leaf (api.example.com) -> intermediate CA -> root CA
The leaf identifies the endpoint. Intermediates connect it to a root. A root is self-signed and proves nothing by itself. It is useful only because you decided to trust it.
Locally configured trusted certificates are called trust anchors. Certificate authorities (CAs) are the organizations or internal services that issue certificates.
To verify a peer, a TLS implementation checks that:
- the peer proves it owns the leaf’s private key;
- the chain leads from the leaf to one of your trust anchors;
- every certificate in the path is within its validity period and allowed for this use;
- for a server, the leaf’s names include the host the client meant to reach.
Nearly every certificate failure corresponds to one of these steps. An unknown issuer, an expired certificate, or a name mismatch can each prevent a connection. Use these checks to interpret error messages, then fix the configuration rather than disabling verification.
Configuring a backend
Your TLS configuration defines how peers identify and verify each other. It also controls which application protocols they can negotiate.
Start with the identity you will present: a certificate chain and its private key. Then choose the certificate authorities you trust to identify the other side. A client also needs the server name it expects to reach. Finally, list the application protocols you support. TLS chooses between those protocols through Application-Layer Protocol Negotiation (ALPN).
The connector normally checks the host from the request, not just the address
it connects to. A certificate for localhost does not also identify
127.0.0.1 unless it lists that IP address. Server Name Indication (SNI) helps
the server choose which certificate to present. SNI does not replace the
client’s verification.
To try the examples, first run tls/generate-certs.sh from the
examples repository root:
sh tls/generate-certs.sh
The script creates a local certificate authority (CA) and certificates with subject alternative names (SANs). These names identify hosts or application identities. The script also creates unencrypted PKCS#8 private keys. The files are gitignored and meant only for local development; never deploy them.
Run each program from its own example directory so the relative certificate paths resolve correctly. The following sections build the client and server configurations separately. Then attach them to your application as shown in configuring ntex components.
OpenSSL
To use OpenSSL, configure client verification and the server’s identity separately. The OpenSSL example includes an HTTPS server and client, plus a mutual TLS (mTLS) server that authenticates clients.
Start the client configuration by enabling verification and loading the CA certificates it should trust:
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
fn client_config() -> Result<SslConnector, openssl::error::ErrorStack> {
let mut config = SslConnector::builder(SslMethod::tls())?;
config.set_verify(SslVerifyMode::PEER);
config.set_ca_file("../certs/ca.pem")?;
config.set_alpn_protos(b"\x02h2\x08http/1.1")?;
Ok(config.build())
}
The ntex connector also checks the server name against the connection host. For production, replace the example CA with the appropriate system or organization trust roots.
The server needs an identity to present to clients. Load it and add it to the acceptor configuration:
use ntex::tls::{openssl::set_identity, x509::Identity};
use openssl::ssl::{SslAcceptor, SslAcceptorBuilder, SslMethod};
fn server_config() -> Result<SslAcceptorBuilder, Box<dyn std::error::Error>> {
let identity = Identity::from_pem(
&std::fs::read("../certs/server.pem")?,
&std::fs::read("../certs/server.key")?,
)?;
let mut config = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls())?;
set_identity(&mut config, &identity)?;
Ok(config)
}
set_identity installs the private key and the endpoint’s certificate (the
leaf). It includes intermediate certificates in chain order and leaves out
the self-signed root. It does not change how peers are verified.
The mozilla_intermediate_v5 preset supports modern TLS, including TLS 1.3.
You can pass these configurations to the HTTP helpers below. For direct use,
build a ntex::tls::openssl::SslConnector service or an SslAcceptor service.
If you are building a custom protocol, set its ALPN instead of copying the HTTP
protocol list.
rustls
To configure rustls, choose a crypto provider and the certificates you trust.
The rustls example selects ring explicitly for TLS. It also
enables rustls-ring for the portable identity and trust helpers.
Loading or converting an identity does not install a process-wide crypto provider. A client needs both a provider and a root store:
use std::{fs::File, io::BufReader, sync::Arc};
use rustls::{ClientConfig, RootCertStore};
fn client_config() -> Result<ClientConfig, Box<dyn std::error::Error>> {
let mut roots = RootCertStore::empty();
for cert in rustls_pemfile::certs(&mut BufReader::new(File::open("../certs/ca.pem")?)) {
roots.add(cert?)?;
}
let mut config = ClientConfig::builder_with_provider(Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()?
.with_root_certificates(roots)
.with_no_client_auth();
config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
Ok(config)
}
Here, with_no_client_auth means “do not send a client certificate.”
The client still verifies the server.
On the server side, convert the portable identity into a rustls signing key. A certificate resolver then makes that identity available during the handshake:
use std::sync::Arc;
use ntex::tls::{rustls::certified_key, x509::Identity};
use rustls::{ServerConfig, sign::SingleCertAndKey};
fn server_config() -> Result<ServerConfig, Box<dyn std::error::Error>> {
let identity = Identity::from_pem(
&std::fs::read("../certs/server.pem")?,
&std::fs::read("../certs/server.key")?,
)?;
let key = certified_key(&identity)?;
let mut config = ServerConfig::builder_with_provider(Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()?
.with_no_client_auth()
.with_cert_resolver(Arc::new(SingleCertAndKey::from(key)));
config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
Ok(config)
}
On this side of the connection, with_no_client_auth means “do not ask for a
client certificate.” The server still presents its own identity. To require
client certificates, configure a client verifier instead.
If your dependencies enable more than one rustls crypto provider, choose the
process-wide provider explicitly. Install it before using a default builder
that needs a provider. builder_with_provider configures only that builder.
It does not select a provider for other builders or X.509 operations.
Windows Schannel
The Schannel example uses Windows’ native TLS backend. Its default client configuration verifies server certificates and names using Windows trust policy:
#[cfg(windows)]
fn client_config() -> ntex::tls::schannel::ClientConfig {
ntex::tls::schannel::ClientConfig::new()
}
This client offers h2 and http/1.1 and sends no client certificate.
To send one, call set_client_cert explicitly. Schannel does not choose an
identity from the user’s certificate stores for you.
A server requires a native identity:
#[cfg(windows)]
fn server_config(
identity: &ntex::tls::x509::Identity,
) -> std::io::Result<ntex::tls::schannel::ServerConfig> {
ntex::tls::schannel::ServerConfig::new(identity.schannel().clone())
}
By default, the server does not ask for client certificates. You can change
ALPN with set_alpn_protocols on either configuration. The available TLS
versions and cipher suites depend on Windows policy and OS support.
This client configuration has no separate root store for verifying servers. For local development, follow the example README to add the example CA in an isolated Windows account, then remove it afterward. Keep verification enabled and configure Windows trust rather than bypassing it.
Configuring ntex components
Once you have a backend configuration, attach it to the client or server that opens the connection. The APIs differ slightly between HTTP and WebSocket clients, so use the section that matches your application.
HTTP client
For HTTPS, install a secure connector on the client builder. Pass an OpenSSL
configuration to ClientBuilder::openssl(config). For rustls, use
ClientBuilder::rustls(config). Request and response handling stay the same:
async fn fetch(config: rustls::ClientConfig) -> Result<(), Box<dyn std::error::Error>> {
let client = ntex::client::Client::builder()
.rustls(config)
.build(ntex::SharedCfg::new("HTTPS"));
let response = client.get("https://localhost:8443/").send().await?;
println!("{}: {}", response.status(), String::from_utf8_lossy(&response.body().await?));
Ok(())
}
Build the client once and reuse it. Its connection pool lets later requests to the same host skip the TLS handshake.
If you have a custom TLS connector service, including Schannel, pass it to
secure_connector:
#[cfg(windows)]
fn client() -> ntex::client::Client {
use ntex::tls::schannel::{ClientConfig, TlsConnector};
ntex::client::Client::builder()
.secure_connector(TlsConnector::with_config(ClientConfig::new()))
.build(ntex::SharedCfg::new("HTTPS"))
}
ClientBuilder::connector configures unsecured connections. It leaves
the HTTPS connector unchanged.
The built-in default OpenSSL connector verifies server certificates against OpenSSL’s default trust store (the system roots) and checks the request host. To trust a private root, supply your own configuration, such as the OpenSSL configuration above.
The default rustls configuration uses webpki roots and sends no client identity.
If you enable both backend features, the default HTTP client selects OpenSSL.
On Windows without either feature, install Schannel explicitly through
secure_connector.
The HTTP client example shows a custom HTTPS connector. The backend examples also show how to use private trust roots and client identities. Once the client is built, request and body handling stay the same.
When wrapping connection errors, preserve the original error in an application
error type or Box<dyn std::error::Error>. Avoid converting it to an
io::Error that contains only a string.
WebSocket client
WsClient has its own connector and does not inherit settings from an HTTP
Client. Its default connector uses plain TCP: a wss:// URL alone does
not enable TLS.
Install a TLS connector explicitly. These WebSocket APIs use an HTTP/1.1
upgrade rather than HTTP/2 extended CONNECT. Offer http/1.1 instead of h2:
use ntex::{SharedCfg, ws::WsClient};
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
#[ntex::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut config = SslConnector::builder(SslMethod::tls())?;
config.set_verify(SslVerifyMode::PEER);
config.set_ca_file("../../tls/certs/ca.pem")?;
config.set_alpn_protos(b"\x08http/1.1")?;
let connection = WsClient::new("wss://localhost:8443/ws/", SharedCfg::default())
.openssl(config.build())
.connect()
.await?
.seal();
println!("Upgrade response: {:?}", connection.response());
Ok(())
}
With rustls, set config.alpn_protocols = vec![b"http/1.1".to_vec()].
Then pass the configuration to .rustls(Arc::new(config)).
With Schannel, restrict ALPN in ClientConfig. Pass the configuration to
.connector(TlsConnector::with_config(config)).
Unlike the HTTP client’s connector, WsClient::connector replaces the whole
connector for this connection, including its TLS behavior.
The secure WebSocket example calls seal for both plain and TLS
connections. That lets both paths use the same message-handling loop.
HTTP and WebSocket servers
For web applications, use the backend-specific HTTP server helpers:
| Method | Arguments after self |
|---|---|
bind_openssl | address, SslAcceptorBuilder, shared configuration |
bind_rustls | address, &ServerConfig, shared configuration |
listen_openssl | existing listener, shared configuration, SslAcceptorBuilder |
listen_rustls | existing listener, shared configuration, ServerConfig |
These helpers perform the TLS handshake before serving HTTP and configure HTTP ALPN for you. Keep your existing routes, middleware, and handlers.
A WebSocket connection starts as HTTP. Use an HTTPS listener and keep your
upgrade and frame handlers. TLS stays in place after the upgrade;
web::ws::start does not remove it.
Use the lower-level server builder when you need Schannel, a custom protocol, or a certificate check before serving any requests. Compose the services in the order you want them to run:
listener -> TLS acceptor -> optional authorization gate -> HttpService / protocol service
There is no bind_schannel web-server helper. The
Schannel server and both mutual-authentication examples
show this service chain. Their HTTP service does not depend on the concrete
TLS filter. They use a shared boxed error type to preserve errors from the
handshake, authentication, and HTTP layers.
Shared handshake configuration
Use TlsConfig to control how long a TLS handshake may take. Attach it to
the server’s accepted I/O configuration or the client connector’s SharedCfg:
use ntex::{SharedCfg, time::Seconds, tls::TlsConfig};
let cfg: SharedCfg = SharedCfg::new("TLS")
.add(TlsConfig::new().set_handshake_timeout(Seconds(10)))
.into();
Pass cfg to the server’s bind/listen call, to ClientBuilder::build for an
HTTP client, or to WsClient::new for a WebSocket client. The default TLS
handshake timeout is five seconds; zero disables the deadline.
This timeout covers only TLS negotiation. DNS lookup, establishing a TCP connection, waiting for an HTTP response, and the WebSocket opening handshake have separate settings in their respective components.
X.509 certificates and identity loading
Use the x509 API to load certificates and identities across platforms.
Supported features and verification behavior can still differ by backend.
The API distinguishes certificates, identities, and trust anchors:
| Type | Meaning |
|---|---|
Certificate | A parsed public certificate, without a private key |
Identity / ClientIdentity | Certificate chain plus a matching private key |
CaCerts | Certificates you explicitly trust when verifying clients |
Loading an identity checks that its data is well-formed and the key matches the certificate. It does not establish trust or grant access. It also does not check whether the identity is valid for a particular hostname. Parsing a certificate reads its contents without authenticating whoever sent it.
The X.509 example includes an inspector you can run against your files, plus the authentication helpers shared by all three backend examples.
PEM and DER
PEM stores certificate data as text; DER stores it as binary. Load a PEM
identity with Identity::from_pem(certificates, private_key). Put the leaf
certificate first in the chain and supply an unencrypted PKCS#8 private
key.
For DER inputs, use Identity::from_der(&[&[u8]], private_key). Convert PKCS#1,
SEC1, or encrypted PEM keys before using these portable loaders.
If you only need to inspect a certificate, you do not need a private key.
Use Certificate::from_pem for one PEM certificate, from_pem_multi for a
PEM bundle, or Certificate::from_der for owned DER bytes.
For an identity stored in files, IdentitySource handles the file reads for
you:
use ntex::tls::x509::{Identity, IdentitySource};
fn load() -> Result<Identity, ntex::tls::x509::Error> {
IdentitySource::PemFiles {
certificates: "../certs/server.pem".into(),
private_key: "../certs/server.key".into(),
}
.load()
}
In the examples, load_identity("../certs/server") is a convenience helper
that loads server.pem and server.key.
PKCS#12 and Windows stores
PKCS#12 archives bundle certificates and private keys. For a password-protected
archive, use Identity::from_pkcs12(bytes, password). The file loader,
IdentitySource::Pkcs12File(path), uses an empty password.
Parsing a plain string as IdentitySource treats it as a PKCS#12 path,
not a PEM path. Load passwords from a secret source or protected environment
configuration. Do not pass them as command-line arguments or write them to logs.
PKCS#12 loading uses native APIs on Windows and requires the openssl feature
on Unix. You can still use rustls for TLS; using OpenSSL to import an archive
does not choose the connection’s TLS backend.
On Windows, you can also select an identity and its key from a certificate store:
cert:CurrentUser\MY\<40-hex-SHA1-thumbprint>
cert:LocalMachine\MY\subject=<name>
A thumbprint selector does not check whether the certificate is currently valid. A subject selector picks a currently valid match with an accessible private key. If several match, it chooses the one with the latest expiry. Neither selector verifies trust, and both work only on Windows.
Windows keys may be non-exportable. A backend can use such a key to sign without reading its bytes.
When importing an identity, consider how long the key stays on the system.
Identity keeps an isolated imported key for Schannel until its last owner is
dropped, then normally deletes it. An abnormal process exit can leave the key
behind. ClientIdentity imports use ephemeral native keys instead, which is
useful when only a client needs the identity.
Using an identity with each backend
Once you have loaded an identity, adapt it to your TLS backend. The adapter determines whether the backend can use the identity’s private key.
| Backend | Adapter | Important limitation |
|---|---|---|
| OpenSSL | ntex::tls::openssl::set_identity(&mut context, &identity) | Requires an exportable PKCS#8 key; cannot use opaque Windows CNG keys through this adapter |
| rustls | certified_key(&identity) or client_certified_key(&client_identity) | Install the result through a certificate resolver; native Windows keys can sign without being exported |
| Schannel | identity.schannel().clone() | Windows-only native identity for client/server configuration |
For rustls, use SingleCertAndKey when you have one configured identity. It
works for both clients and servers.
To prepare an ordered client chain from an existing identity, use
ClientIdentity::from_identity. You can also load a ClientIdentity directly
from PEM, DER, or PKCS#12.
The OpenSSL and rustls adapters order the chain for you. They use
Identity::ordered_chain(false) to arrange the intermediates and leave out the
self-signed root. It drops unrelated certificates with a warning.
Sending a root certificate does not make the other side trust it. Trusted certificates belong in the verifier’s configuration, not in a chain supplied by the peer.
Client-certificate authentication
Use mutual TLS when clients need to prove their identities with certificates. Ordinary HTTPS authenticates the server to the client. Mutual TLS also asks the client to present a certificate and prove that it owns the corresponding private key.
Your application still needs to answer three separate questions:
- Did the client provide a certificate?
- Is that certificate trusted?
- Is that identity allowed to use this application?
Start by configuring the server to ask for or require a client certificate:
| Backend | Requiring or requesting a client identity |
|---|---|
| OpenSSL | Set PEER | FAIL_IF_NO_PEER_CERT and configure client trust anchors |
| rustls | Configure WebPkiClientVerifier with client roots; do not enable anonymous clients when a certificate is mandatory |
| Schannel | request_client_cert(true) requests an optional certificate and proof of key possession; the application must require and verify it |
The client needs its own identity as well as roots for checking the server.
Install that identity with OpenSSL’s set_identity, a rustls certificate
resolver, or Schannel’s set_client_cert. Keep these two parts of the
configuration separate: sending a client certificate does not replace
checking the server’s name and certificate chain.
In OpenSSL, PEER alone does not require the client to send a certificate.
In rustls, making the verifier optional is not the same as turning off client
authentication altogether.
Schannel only requests a certificate; it does not enforce your authentication policy. The handshake can succeed without a certificate. It also does not check trust in the client’s certificate here. Your application must reject missing or unacceptable identities before doing any protected work.
The example checks the identity before HttpService. A rejection therefore
closes the connection without sending an HTTP response.
To try the OpenSSL example, run these from tls/openssl in separate terminals:
cargo run --bin openssl-mtls-server
cargo run --bin openssl-client -- https://localhost:8443/ ../certs/client
With the expected client identity, the response is authorized. Try again
without an identity, with untrusted-client, and with other-client. Each
connection should be rejected.
The other-client certificate is valid and comes from a trusted issuer. Its
identity is still not one this application allows.
The rustls and Schannel READMEs provide equivalent commands.
Reading peer certificates
Use PeerCertDer to read the peer’s leaf certificate. Use
PeerCertChainDer to read its certificate chain. These queries work across
backends; native certificate-chain queries follow different conventions.
This helper works with IoRef from any supported TLS backend:
use ntex::io::IoRef;
use ntex::tls::{PeerCertChainDer, PeerCertDer};
use ntex::tls::x509::{self, PeerCerts};
fn peer_certs(io: &IoRef) -> Result<Option<PeerCerts>, x509::Error> {
let Some(leaf) = io.query::<PeerCertDer>().into_inner() else {
return Ok(None);
};
let chain = io.query::<PeerCertChainDer>()
.into_inner()
.map(|item| item.0)
.unwrap_or_default();
PeerCerts::from_der(leaf.0, chain).map(Some)
}
QueryItem::into_inner() moves out the query values, which own their DER
buffers. PeerCerts::from_der parses those buffers. It removes a duplicated
leaf if one appears at the start of the supplied chain.
PeerCerts::chain holds the remaining chain. That chain may be incomplete or
untrusted.
In a web handler, use HttpRequest::io() to reach the connection. The
peer_certs helper above then parses its certificates. This example returns
the leaf certificate’s SHA-256 thumbprint:
async fn certificate(req: ntex::web::HttpRequest) -> ntex::web::HttpResponse {
use ntex::tls::x509::digest::Algorithm;
use ntex::web::HttpResponse;
let Some(io) = req.io() else {
return HttpResponse::Unauthorized().build();
};
match peer_certs(io) {
Ok(Some(peer)) => HttpResponse::Ok().body(peer.leaf().thumbprint(Algorithm::Sha256)),
Ok(None) => HttpResponse::Unauthorized().build(),
Err(_) => HttpResponse::Forbidden().build(),
}
}
This handler reports metadata. It does not decide whether the peer is allowed to use your application.
The two Unauthorized paths cover a synthetic request with no connection
and a real connection without a peer certificate.
Protect endpoints like this. Do not expose certificate fields or stable identity identifiers as public diagnostics.
You can also read a Certificate’s subject, issuer, SANs, and validity dates.
For connection metadata, query Servername, TlsVersion, TlsCipher, or
ntex::io::types::HttpProtocol. Their availability depends on the backend and
negotiated session. PskIdentity is available only with OpenSSL.
Trust and application authorization
Once you have a peer certificate, checking trust and deciding access are
separate steps. CaCerts handles client-certificate trust; it is not a
hostname verifier for outbound HTTPS connections.
Build the store from certificates your application explicitly trusts, called trust anchors. Never build it from the chain a client sends you. Every certificate you register becomes an anchor, even an intermediate or a pinned leaf. An empty store trusts nothing.
First verify the peer’s chain at the current time, then check the application identity. For example, this function accepts only the expected URI:
use std::time::SystemTime;
use ntex::tls::x509::{CaCerts, PeerCerts, TrustError, auth};
#[derive(Debug)]
enum AuthError {
Trust(TrustError),
Name(auth::Failure),
}
fn authorize(peer: &PeerCerts, trust: &CaCerts) -> Result<SystemTime, AuthError> {
let expires = trust.is_trusted(peer, SystemTime::now())
.map_err(AuthError::Trust)?;
auth::name_matches(
peer.leaf(),
auth::NameField::Uri,
"spiffe://ntex.example/client",
)
.map_err(AuthError::Name)?;
Ok(expires)
}
The shared example helpers use this policy. AuthError keeps
trust failures separate from name mismatches so callers can tell them apart.
The URI is an example application identity; matching it is not a complete
implementation of SPIFFE policy.
Check for import errors. The from_certs method logs and skips rejected
anchors. Use from_certs_with to handle those rejections yourself. The examples
reject an incomplete import rather than continuing with fewer roots than
configured.
Expiry and long-lived connections
Close authenticated connections when their verified certificate path
expires. The is_trusted method returns the earliest expiry in that path,
including the trust anchor. An authenticated connection must not stay open
beyond that deadline.
The examples schedule the connection to close at that time and cancel the timer if it disconnects earlier. For long-lived sessions, also decide how your application will respond to configuration changes and revoked identities.
Other authorization checks
Use the auth helpers to choose the identity fields or thumbprints your
application accepts. Some helpers also check certificate validity:
| Helper | Behavior |
|---|---|
name_matches | Matches any SAN of the chosen kind, or the first subject common name (CN); names are compared case-insensitively |
field | Extracts one identity field; rejects multiple SAN values of the chosen kind |
validity | Checks the certificate’s validity window |
thumbprint_matches | Matches an allow-list without checking dates |
verify_thumbprint | Checks both the allow-list and validity |
Use SHA-256 for new thumbprint policies. SHA-1 remains useful for Windows store selectors and compatibility. These helpers do not verify certificate chains, regardless of the digest you choose.
Backend differences
If your application runs on several platforms, check how each backend applies your trust policy. Crypt32, WebPKI, and OpenSSL do not necessarily accept the same certificates. They differ in supported algorithms and Extended Key Usage (EKU) checks for client authentication. They also handle directly trusted leaf certificates differently.
CaCerts does not check revocation.
For example, Windows checks validity rather than performing ordinary chain
validation for a pinned leaf. OpenSSL also handles EKU on intermediate
certificates differently from Crypt32 and WebPKI. Check the
CaCerts documentation when your policy needs to work consistently
across platforms.
Operational guidance
TLS configuration also affects how your service handles load and closes connections.
Handshake limits
TLS handshakes cost work before your application handles any requests. Use
max_concurrent_ssl_accept to limit concurrent handshakes per worker.
Acceptors on the same thread share the limit, which defaults to 256. Set it
before starting workers. Later changes do not update counters that other
threads have already initialized.
This is a soft limit. Readiness slows acceptance without reserving a slot, so independently ready pipelines can exceed it. Setting the limit to zero keeps acceptor readiness pending. Zero does not mean unlimited.
Low-level handshake functions and filter constructors do not use this acceptor
limit. They have their own timeout behavior. OpenSSL’s free accept and
connect functions apply neither the service timeout nor its concurrency
limit. Use the services when you need those controls.
Shutdown
Let the connection or server shut down gracefully when possible. TLS filters participate in normal I/O shutdown. Forcing the transport to close can lose queued bytes or prevent the TLS close notification from reaching the peer.
Troubleshooting
When a connection fails, first check whether the problem is in TLS negotiation, certificate verification, or the application protocol:
| Symptom | Check |
|---|---|
wss:// fails before the upgrade | Install a TLS connector on WsClient; the URL does not choose one |
| WebSocket upgrade fails after TLS | Offer HTTP/1.1, not HTTP/2 |
| Unknown issuer | Configure the verifier’s roots; sending a root from the peer does not establish trust |
| Hostname mismatch | Check SANs and the request host separately from the destination address and SNI |
| No compatible rustls provider | Select a provider and configure X.509’s provider/fallback too |
| Identity import fails | Check PKCS#8 encoding, encryption, key/leaf matching, and PKCS#12 backend support |
| Only some clients fail verification | Check missing intermediates, validity, EKU and platform policy |
| No peer certificate | Make sure the server requests one and the client explicitly supplies an identity |
| Schannel accepts an anonymous TLS handshake | Expected with its request-only setting; the application must reject missing identities |
| Windows store identity is unusable | Check store location, key permissions, selector and backend support for non-exportable keys |
Log failures without private keys or passwords. Treat peer certificate fields as identity data, not harmless debugging output.
Production checklist
Before deploying, check each item:
- Verification is on everywhere. Every client, including the HTTP client
with OpenSSL and every
WsClient, uses a verifying configuration with the right trust roots. Nothing disables verification “temporarily.” - Names match. Server certificates list every hostname and IP address that clients use to connect.
- Identities are real. Example certificates and keys are not deployed. Private keys and PKCS#12 passwords come from protected storage and never appear in logs, command lines, or source control.
- Renewal is planned. You know when each certificate expires and how a replacement reaches the running service.
- ALPN matches the protocol. HTTP servers and clients offer the protocols
they actually speak; WebSocket clients offer
http/1.1. - Client authentication is enforced, not just requested. For mutual TLS, reject missing certificates and configure client trust anchors explicitly. Check which identity connected; a valid certificate alone does not grant access.
- Long-lived connections respect expiry. Authenticated connections close when their verified certificate path expires.
- Handshakes are bounded. The handshake timeout and
max_concurrent_ssl_acceptsuit your expected load.
Byte Buffers
Use BytesMut to build a buffer and Bytes to hand its data to other code.
For example, a decoder may receive two messages in one socket read. It can
hand the first message to your application and keep the second for later.
The application gets an owned view that keeps the data alive without borrowing
the decoder’s read buffer.
Copying each message into a new Vec<u8> would add allocations and memory
copies to every request. On the write side, you can queue a small header and
a large body separately instead of copying them into one growing buffer.
Sharing costs more than copying for tiny values, so ntex-bytes stores short
byte strings directly in their handles. Per-thread page caches reduce trips
to the allocator for frequently reused I/O buffers.
The ntex crate re-exports the buffer types in ntex::util. These include
Bytes and BytesMut, along with ByteString for text. For chunked
output, it provides BytePages, BytePage and BytePageSize. The
Buf and BufMut traits provide read and write helpers.
set_page_cache_size is available directly from ntex_bytes for cache
tuning.
The mental model
Use BytesMut while filling or changing a contiguous buffer. Switch to
Bytes when the data is ready to share. Use BytePages when output can stay
in separate chunks. ByteString is the text version of Bytes and
guarantees valid UTF-8.
A handle and its allocation have separate lifetimes. Several handles
can keep one allocation alive, but they do not all have permission to change
it. A BytesMut owns the writable tail. Bytes views can own earlier,
read-only portions of the same allocation.
Splitting off a message gives it an independent lifetime, though it may still share storage. Share data while it moves through the pipeline. Copy or trim a small part when it needs to live much longer than its original buffer.
Here, “zero-copy” means avoiding a copy between application buffers. It does not promise that the operating system or a TLS layer will avoid copying. Copying a handful of bytes is often cheaper than maintaining another shared reference.
Types at a glance
Bytesis immutable. Use it for decoded frames, payloads and header values. Cloning usually shares storage or copies inline data; external storage decides how it is cloned.BytesMuthas unique write access. Use it for read buffers and building output. Cloning copies the data.ByteStringis immutable UTF-8 text, useful for header names, paths and topics. Cloning has the same cost asBytes.BytePageshas unique write access. Use it for write queues. Cloning shares or copies data according to page storage and append rules.BytePageis one immutable chunk of aBytePagesqueue. Cloning shares data, except forVecpages, which copy it.BytePageSizedefines allocation size classes.
Bytes
Use Bytes when you need an immutable, owned view of contiguous data.
Heap-backed values normally share a reference-counted allocation when you
clone, slice or split them.
Bytes is Send + Sync, so you can pass it between threads. Small values
and static data use simpler storage, described below.
use ntex_bytes::Bytes;
let mut msg = Bytes::copy_from_slice(&[1u8; 1024]);
// These two views share the original allocation.
let first = msg.split_to(256);
assert_eq!(first.len(), 256);
assert_eq!(msg.len(), 768);
let part = msg.slice(100..200); // shares the allocation too
let cloned = msg.clone(); // another handle, not another 768-byte buffer
drop(msg);
assert_eq!(part.len(), 100); // the other handles still own their data
assert_eq!(cloned.len(), 768);
The cost of cloning depends on which of four storage kinds the value uses.
Most large values use a shared heap buffer, usually from BytesMut, so a
clone only increments its reference count.
Small values use inline storage instead: at most 23 bytes, or 11 bytes on
32-bit targets, fit inside the handle. Cloning copies those bytes without
allocating. Static data, created by Bytes::from_static,
From<&'static [u8]> or From<&'static str>, needs only a pointer copy.
The fourth kind is external storage, created by Bytes::from_ext or from
an Arc<str> through ByteString. Its owner’s vtable handles cloning;
Externally owned data explains that integration.
Inline storage also changes the cost of taking a small view.
Bytes::slice copies a small result inline instead of taking another
reference to the heap buffer. Bytes::split_to does the same, as do
BytesMut::split_to and BytesMut::freeze. A short header name can
outlive a request without keeping its read buffer alive.
Use Bytes::is_inline to check the storage kind. Static constructors keep
their static representation even for short strings.
The examples below assume a 64-bit target, where the inline limit is 23 bytes.
On 32-bit targets it is 11 bytes. These limits and the layouts later in the
chapter describe the current implementation, not a stable memory-layout API.
Unless stated otherwise, allocation capacities and header sizes assume the
tracker feature is disabled.
Tracking buffer memory explains how enabling it
enlarges the header.
When sharing retains too much memory
When you keep a small part of a large buffer for a long time, consider
Bytes::trimdown. A 100-byte token from a 16 KiB read buffer can keep the
whole allocation alive. The allocation is still owned, so this retention is
not a leak.
A view that is too large to inline keeps the allocation alive even if it
uses only a small part. trimdown moves data inline when it fits. Otherwise,
it copies the data into an exactly sized buffer if at least 64 bytes of the
backing capacity are unused. It leaves inline and static values alone.
use ntex_bytes::Bytes;
let packet = Bytes::copy_from_slice(&[b'x'; 16 * 1024]);
let mut token = packet.slice(100..200);
token.trimdown(); // copy 100 bytes so `token` no longer retains the packet
drop(packet);
assert_eq!(token.len(), 100);
Trim long-lived values where the retained memory matters. Trimming every frame loses the benefit of sharing. Trimming one view also cannot release the original allocation while other handles still own it.
Externally owned data
Use external storage to share memory that another type owns. For example,
ByteString::from(Arc<str>) shares the string without copying it. A normal
decoder does not need to implement this integration API.
The owner implements the unsafe StorageExt trait. It supplies a static
vtable with as_ptr, len, clone and drop functions. If clone returns
None, clones copy the data into native storage instead. Arc<str>
implements this trait.
The unsafe contract requires the exposed bytes to stay valid and immutable for every live handle, including across threads. The vtable must clone and release ownership correctly.
BytesMut
Use BytesMut to build output or receive data into a growable buffer.
Like Vec<u8>, it gives you unique write access to its data. You can split
completed data off the front as Bytes while continuing to fill the tail.
The handles can share a heap allocation, but only BytesMut can write into
its part. In a decoder, that allocation might look like this:
| completed frame | completed frame | unread data | spare capacity |
|<------ immutable Bytes views ---->|<--------- BytesMut -------->|
Only one BytesMut can own the writable part of an allocation. When you
hand out a prefix as Bytes, the mutable view advances past it and cannot
overwrite it. The decoder can fill the tail while the application reads
earlier frames, without locking the data.
use ntex_bytes::{BufMut, BytesMut};
let mut buf = BytesMut::with_capacity(1024);
buf.put_slice(b"hello ");
buf.put_u16(0x1234);
buf.extend_from_slice(b"world");
// 6 bytes fit inline, so `head` is a copy and `buf` stays unique
let head = buf.split_to(6);
assert!(head.is_inline());
assert!(buf.is_unique());
buf.extend_from_slice(&[0u8; 100]);
let body = buf.take(); // shares the allocation with `buf`
assert!(!buf.is_unique());
drop(body);
assert!(buf.is_unique());
// a unique buffer gets its whole capacity back
buf.clear();
assert_eq!(buf.capacity(), 1024);
Choose how to hand off data based on what should happen to the mutable
handle. After decoding a complete prefix, use BytesMut::split_to. It
returns the first at bytes as Bytes, leaving the remainder for further
reads. When all current bytes form one message, BytesMut::take returns
them and keeps the spare capacity for self. In either case, the
connection can keep using the mutable handle.
When you are finished with that handle, use BytesMut::freeze instead.
It consumes the buffer and returns Bytes. None of these operations is
always faster: small results are copied inline, while larger results
usually share the allocation. Choose the ownership behavior you need,
then measure if that path matters.
To discard input rather than hand it off, BytesMut::advance_to drops
the first cnt bytes in O(1) time. BytesMut::clear empties the view
and reclaims its full capacity if it is unique. Use BytesMut::reserve
when you need more spare space; Growth explains how it reuses
or replaces the allocation.
BytesMut::is_unique tells you whether any Bytes still shares the
allocation. The same distinction matters when converting back from
Bytes: BytesMut::from(Bytes) reuses a unique shared heap allocation,
but copies inline, static, external or still-shared data.
BytesMut::new currently starts with 112 bytes of data capacity. Including
the header, its allocation is 128 bytes. BytesMut::with_capacity
allocates exactly the requested capacity. BytesMut::with_page_size takes
a pooled page; see Pooled buffers.
Cloning a BytesMut always copies the data.
Length, capacity and spare space
Use len() to find how many bytes are initialized. capacity() tells you
how much the current mutable view can hold, including those bytes. The
difference is spare space at the end.
Capacity can be smaller than the whole allocation. Splitting or advancing the front shrinks the mutable view. Dropping a frame does not immediately move the read cursor backward.
A later clear() reclaims the whole allocation if it is unique. When more
space is needed, reserve() can move unread data to the front.
Use clear() to discard data while keeping the allocation for another use.
Drop the buffer when you no longer need it. Its memory is then freed or
cached, depending on how it was allocated.
A buffer’s typical journey
These operations let a decoder reuse one allocation for many messages. A typical cycle looks like this:
- The transport writes socket data into the spare tail of a
BytesMut. - The decoder examines the initialized prefix.
- A complete frame is removed with
split_to. - The returned
Bytestravels through services and application code. - The
BytesMutstays with the connection and receives more input. - When all shared frames are dropped,
reserveorclearcan reclaim the space at the front.
Frames that share storage keep the whole allocation alive and prevent reuse of their bytes. Tiny inline frames do neither. The mutable tail stays writable while earlier frames are alive.
If the tail fills before those frames are dropped, growth copies only the remaining data into a new allocation. Existing frames stay valid in the old one.
BytesMut implements the ntex BufMut trait and the bytes crate’s
BufMut trait. Their BufMut::remaining_mut() methods differ. The ntex
version reports current spare capacity. The bytes version reports
usize::MAX - len because the buffer grows on demand.
All put_* methods reserve capacity as needed in both cases.
Zero-copy decoding
In an ntex codec, split completed frames off the read buffer to hand them to the application. Large frames share the read buffer; tiny ones are copied inline. This decoder reads a two-byte, big-endian length followed by a payload:
use ntex_bytes::{Bytes, BytesMut};
fn decode(src: &mut BytesMut) -> Option<Bytes> {
if src.len() < 2 {
return None;
}
let len = u16::from_be_bytes([src[0], src[1]]) as usize;
if src.len() < 2 + len {
// make room for the rest of the frame
src.reserve(2 + len - src.len());
return None;
}
src.advance_to(2);
Some(src.split_to(len))
}
let mut src = BytesMut::copy_from_slice(b"\0\x03one");
assert_eq!(decode(&mut src).unwrap(), b"one"[..]);
assert!(src.is_empty());
The decoder treats the length field as untrusted input. It checks for a
complete frame before calling advance_to. The same check makes the later
split_to safe. Both methods panic if asked to move past the end.
Use BytesMut::split_to_checked if you have not already validated the
index:
use ntex_bytes::{Bytes, BytesMut};
fn take_prefix(src: &mut BytesMut, len: usize) -> Option<Bytes> {
src.split_to_checked(len)
}
let mut src = BytesMut::copy_from_slice(b"hello");
assert_eq!(take_prefix(&mut src, 2).unwrap(), b"he"[..]);
assert_eq!(src, b"llo"[..]);
Bounds checks do not impose a size limit. A real decoder should reject a
declared length above its protocol or application limit before calling
reserve. Otherwise, a peer can make the connection retain a very large
buffer without ever sending the promised frame.
ByteString
When a decoded field is text, ByteString lets you keep the sharing
behavior of Bytes while guaranteeing valid UTF-8. It is backed by Bytes
and dereferences to &str, with the same storage kinds and cloning costs.
use ntex_bytes::{ByteString, Bytes};
let header = ByteString::from("content-type: text/plain");
let name = header.slice(0..12); // copies this short result inline on 64-bit targets
assert_eq!(name, "content-type");
// validates UTF-8, takes over the bytes without copying
let s = ByteString::try_from(Bytes::from_static(b"utf-8 text")).unwrap();
assert_eq!(s.as_str(), "utf-8 text");
Convert an owned Bytes or BytesMut into ByteString to validate UTF-8
and reuse the bytes. The usual small-value inlining still applies.
Converting back with ByteString::into_bytes is free.
A String or Vec<u8> conversion copies into native byte storage.
ByteString::from(Arc<str>) shares the Arc instead.
use ntex_bytes::{ByteString, BytesMut};
let bytes = BytesMut::copy_from_slice("hello".as_bytes()).freeze();
let text = ByteString::try_from(bytes).unwrap();
assert_eq!(text, "hello");
let bytes = text.into_bytes();
assert_eq!(bytes, b"hello"[..]);
Indices are byte offsets, not character positions. slice panics if an
index is not on a UTF-8 character boundary. So do split_to and split_off.
Take care when working with non-ASCII text.
ByteString::from_bytes_unchecked skips validation and is unsafe. You must
guarantee valid UTF-8 when calling it. Use the checked conversion unless you
have already established that guarantee. With the simd feature, UTF-8
validation uses SIMD instructions.
Like Bytes, a ByteString can keep a larger allocation alive. Call
ByteString::trimdown when moving a short string from a request buffer
into long-lived state.
Buf and BufMut
Use Buf to read values from a buffer with a cursor. Use BufMut to
write them. The traits provide get_* and put_* helpers for integers and
floats in big- and little-endian order.
Unsuffixed integer methods use big-endian order. Methods ending in _le
use little-endian order.
use ntex_bytes::{Buf, BufMut, BytesMut};
let mut buf = BytesMut::with_capacity(16);
buf.put_u32(0xDEAD_BEEF);
buf.put_u8(1);
let mut b = buf.freeze();
assert_eq!(b.get_u32(), 0xDEAD_BEEF);
assert_eq!(b.get_u8(), 1);
assert!(!b.has_remaining());
Reading advances the cursor. After get_u32(), those four bytes are no
longer part of the remaining input. Reads panic if there are not enough
bytes, so check remaining() or len() before reading a field.
The traits also work with other buffer types. A &[u8] can serve as a read
cursor, and a generic Buf need not store all its data contiguously.
Bytes and BytesMut implement the bytes crate’s Buf trait.
BytesMut also implements that crate’s BufMut trait. You can use these
types with libraries built on bytes.
For formatting with write!, BytesMut and BytePages implement
std::io::Write. BytesMut also implements std::fmt::Write. Bytes and
ByteString implement serde’s Serialize and Deserialize.
Panicking and checked operations
Prefer checked methods for indices and lengths taken directly from input.
A failed check returns None rather than panicking. Checked variants include:
Methods such as slice assume you have already validated the range or
length. The same applies to split_to and split_off, as well as
advance_to and the get_* methods. They panic on an invalid range or
insufficient input. After a codec has checked its bounds, these methods keep
its hot path simple.
Internal organization
You can use the buffer types without knowing their layouts. These details explain the cost of copying tiny values and how a mutable buffer shares an allocation while keeping its writable bytes private.
Handles
The handles stay small even when they refer to large buffers. Bytes takes
three machine words, and BytesMut takes one.
A Bytes handle holds a data pointer, a length and an offset word. The two
low bits of offset select the storage kind. The remaining bits hold the
distance from the heap buffer’s start to the data pointer.
Inline storage reuses all three words for data. It keeps the kind and length in one byte, leaving room for 23 bytes of data on a 64-bit target.
A BytesMut handle is a single pointer to its heap buffer. The buffer header
stores the start and length of its data view.
Heap buffers
Sharing a buffer does not require a separate allocation for its metadata.
A native shared heap buffer puts a 16-byte header directly before the data.
External storage and Vec-backed pages have their own layouts.
header (16 bytes) data
+--------+-----+----------+-----------+---------+---------+------------+-------+
| offset | len | capacity | ref_count | Bytes 1 | Bytes 2 | BytesMut | spare |
+--------+-----+----------+-----------+---------+---------+------------+-------+
^ ^ ^ ^
allocation data start offset offset + len
The header holds four fields:
offset: the start of theBytesMutview, measured from the beginning of the allocation.len: the length of theBytesMutview.capacity: the data capacity of the whole allocation. It never changes while the buffer is shared.ref_count: the number of handles, including theBytesMutand everyBytesview.
The other properties follow from these fields. Spare capacity after the
BytesMut view is 16 + capacity - offset - len. The allocation size,
16 + capacity, determines the BytePageSize class; see
Pooled buffers.
Lengths, capacities and offsets use u32. The reference count is an
AtomicU32. A native heap buffer holds at most u32::MAX - 16 bytes of data,
just under 4 GiB. Requests for larger capacities panic.
Each Bytes view stores its own pointer and length. It computes the header
address from its offset. Views split off a BytesMut cover memory in
front of the mutable view. The BytesMut never writes to memory that a
Bytes can read.
Reference counting and threads
You can reuse a unique buffer even if its other handles were dropped on
another thread. BytesMut::is_unique uses an Acquire load. When it
returns true, all accesses through dropped handles happen before the
buffer is reused.
The atomic reference count follows the same memory ordering as
std::sync::Arc. Decrements use Release, and an Acquire fence runs
before the last handle frees the buffer.
Apart from the reference count, Bytes handles read only the header’s
capacity field. That field does not change while the buffer is shared.
The BytesMut handle can therefore update its view without synchronization.
Allocation strategy
Use regular buffers when you want a specific capacity. For repeatedly reused I/O buffers, pooled pages can avoid fresh allocations. Appending data grows either kind of buffer as needed.
Regular buffers
Use BytesMut::with_capacity when you know how much space you need.
BytesMut::capacity is exactly the requested capacity. The buffer uses
one allocation of 16 + capacity bytes.
If you are building data to share as Bytes, start with a BytesMut to
avoid a conversion copy. Bytes::from(Vec<u8>) copies into the crate’s
storage, or inline for small values. It cannot adopt the vector allocation
because the shared-buffer header needs space before the data.
Buffers made with with_capacity have no page size unless the requested
capacity is exactly a page capacity. The same applies to copy_from_slice
and conversions such as Bytes::from(Vec<u8>). Regular buffers are freed
when their last handle is dropped.
Growth
Call reserve(additional) when you need room for more data. The argument
counts bytes after the current data, rather than a total capacity.
Appending data also reserves space as needed.
BytesMut::reserve tries these options in order:
- If the buffer has enough spare capacity, nothing happens.
- If the buffer is unique and the whole allocation is large enough, the data
is moved to the front of the allocation, reusing the space of dropped
Bytesviews. - If the buffer is unique and has no page size, the allocation is grown with
realloc, which can often extend it in place. - If the buffer has a page size, its data moves to a pooled page, see Pooled buffers.
- Otherwise, the data is copied into a new allocation without a page size.
Bytesviews split off the buffer keep the old allocation alive.
When growth needs more storage, the target capacity is at least twice the
current capacity and at least 8 bytes, the same policy as Vec<u8>. Repeated
small appends therefore do not allocate each time.
realloc may extend an allocation in place or move it. The buffer makes no
promise that its address stays the same.
The usual BytesMut::reserve is a good fit when you expect the buffer
to keep growing. If you know exactly how many more bytes you will write,
use BytesMut::reserve_exact to avoid the doubling policy. When it
allocates, the size is exactly the new capacity plus the 16-byte header.
It does not round pooled buffers up to a page class; they keep a class only
if the new capacity is a page capacity.
Before a socket read, you may not know how much data is coming. Use
BytesMut::reserve_more to grow by one step when spare capacity is low.
It acts when less than BytePageSize::low remains. That
threshold is 1 KiB for Size16, or 4 KiB without a page size. It reuses the
allocation when it can hold the data plus half_capacity(). A unique buffer
is compacted in place; a shared page moves to a page of the same class.
Otherwise, a pooled buffer moves to the next page class. Any other buffer grows by its capacity, with growth of at least 112 bytes and at most 64 KiB.
Do not use reserve or reserve_exact as general-purpose shrinking
operations. They leave the buffer alone when it already has enough spare
capacity.
Page sizes
Choose a BytePageSize to set the size class of a pooled buffer. Data
capacity is the class size minus the 16-byte header. These classes describe
allocations; they are unrelated to operating-system virtual-memory pages.
A page allocation requests exactly the class size, including its header. It does not add metadata on top of a class-sized payload, which would overshoot the size boundary. The allocator’s own size classes remain an implementation detail.
| Class | Allocation | Capacity | half_capacity() | low() | Cached pages by default |
|---|---|---|---|---|---|
Size4 | 4 KiB | 4,080 bytes | 2 KiB | 256 bytes | 128 |
Size8 | 8 KiB | 8,176 bytes | 4 KiB | 512 bytes | 64 |
Size16 | 16 KiB | 16,368 bytes | 8 KiB | 1 KiB | 64 |
Size24 | 24 KiB | 24,560 bytes | 12 KiB | 1.5 KiB | 32 |
Size32 | 32 KiB | 32,752 bytes | 16 KiB | 2 KiB | 16 |
Size48 | 48 KiB | 49,136 bytes | 16 KiB | 3 KiB | 8 |
Size64 | 64 KiB | 65,520 bytes | 16 KiB | 4 KiB | 16 |
Size128 | 128 KiB | 131,056 bytes | 16 KiB | 8 KiB | 2 |
Size256 | 256 KiB | 262,128 bytes | 16 KiB | 16 KiB | 1 |
Unset | - | 65,520 bytes | 16 KiB | 4 KiB | never cached |
Size16 is the default class. Use BytePageSize::for_capacity to find
the smallest class that holds a given capacity. It returns Unset above
the largest data capacity, 262,128 bytes.
BytePageSize::next steps to the next class. BytePageSize::prev
steps to the previous one. The enum is #[non_exhaustive], so more classes
may be added.
use ntex_bytes::BytePageSize;
assert_eq!(BytePageSize::for_capacity(100), BytePageSize::Size4);
assert_eq!(BytePageSize::for_capacity(20_000), BytePageSize::Size24);
assert_eq!(BytePageSize::Size16.next(), BytePageSize::Size24);
assert_eq!(BytePageSize::Size256.next(), BytePageSize::Unset);
half_capacity() is the recommended write-buffer threshold for a page
size. low() is 2/32 of the class size and sets the free-capacity threshold
for BytesMut::reserve_more.
Pooled buffers
Use BytesMut::with_page_size when buffers are created and released
repeatedly, so their pages can be reused. It first looks in the current
thread’s cache for the requested class. If none is cached, it tries the
next smaller class before allocating a new page of the requested size.
Use BytesMut::page_size to check the class you actually received.
Growth uses the required class directly, without this fallback.
with_page_size(BytePageSize::Unset) requests a Size64 page because the
two have the same allocation size. The same cache fallback applies.
When a pooled buffer grows, its data moves to a page of the smallest class
that fits the new capacity. The new class is never smaller than the current
one. Growth copies the data; the old page can return to the cache once its
Bytes views are dropped.
If the growth target exceeds the largest page’s data capacity, the buffer becomes a regular buffer without a page size. It then grows like any regular buffer and is freed when its last handle drops.
use ntex_bytes::{BytePageSize, BytesMut};
let mut buf = BytesMut::with_page_size(BytePageSize::Size4);
assert_eq!(buf.capacity(), 4096 - 16);
buf.extend_from_slice(&[0; 5000]);
assert_eq!(buf.page_size(), BytePageSize::Size8);
buf.extend_from_slice(&[0; 10_000]);
assert_eq!(buf.page_size(), BytePageSize::Size16);
// beyond the largest class, a regular buffer
buf.reserve(300 * 1024);
assert_eq!(buf.page_size(), BytePageSize::Unset);
Freezing a pooled buffer with at most 23 bytes of data on a 64-bit target
copies the result inline. If no earlier Bytes views still share the
allocation, the page can return to the cache right away.
use ntex_bytes::{BytePageSize, BytesMut};
let mut buf = BytesMut::with_page_size(BytePageSize::Size32);
buf.extend_from_slice(b"small");
let small = buf.freeze();
assert!(small.is_inline());
assert_eq!(small, b"small"[..]);
// `small` no longer needs the page; a later allocation can reuse it.
The header does not store a page class. The class is looked up from the
capacity field. A buffer belongs to a class when its allocation, including
the header, is exactly the class size.
Any buffer whose allocation matches a page class is pooled. This includes
buffers created by with_capacity or copy_from_slice with exactly a page
capacity. A buffer grown to that size by realloc is pooled too.
The last handle may be the BytesMut or a Bytes view split from it. When
that handle is dropped, the page returns to its class’s cache on the thread
that drops it. If the cache is full, the page is freed. Only buffers with
a page size are cached; buffers with Unset are always freed.
Pages handed to another thread return to that thread’s cache. A thread that only receives data fills its cache up to the limits and frees the rest. For example, this happens on a thread that writes data produced on other threads.
The cache is unavailable while a thread’s thread-local storage is being destroyed. Pages released during that time are freed.
Tuning the page cache
Start with the default cache limits, then adjust them for your workload’s buffer sizes and concurrency. Caching retains memory to reduce allocations. An idle worker can hold cached pages ready for reuse, even though no live messages need them.
set_page_cache_size sets the number of cached pages of one class for the
current thread. With all caches full, a thread retains about 5 MiB.
The defaults in the table above favor the classes I/O uses most. They retain more 4 to 16 KiB pages, where connection reads start and which include the default write page, as well as 64 KiB pages for busy connections. Larger classes retain fewer pages.
use ntex_bytes::{BytePageSize, set_page_cache_size};
// retain more large pages for a thread that handles large messages
set_page_cache_size(BytePageSize::Size256, 4);
// stop returning 4 KiB pages to this thread's cache
set_page_cache_size(BytePageSize::Size4, 0);
The setting affects only the calling thread. Call it on every thread that uses pooled buffers, for example when each worker thread starts.
Lowering a limit immediately frees cached pages above the new limit. It
also limits how many released pages can return to the cache. The older
set_pages_cache(), which sets one limit for all classes, is deprecated.
These limits count cached pages, not pages in use. They do not bound the memory held by live requests or slow consumers. Each worker has its own cache, so retention scales with the worker count.
BytePages
Use BytePages when your output can stay in separate chunks. You can
write new bytes into its current page and queue owned payloads separately.
When the current page fills, the queue starts another one without moving
earlier output.
For example, a response might contain a short header, a large existing body and a trailer. A contiguous buffer may move earlier output as it grows. Queuing the body separately also avoids copying it into that buffer.
use ntex_bytes::{BufMut, BytePageSize, BytePages, Bytes};
let mut pages = BytePages::new(BytePageSize::Size4);
pages.extend_from_slice(b"HTTP/1.1 200 OK\r\n\r\n");
let body = Bytes::copy_from_slice(&[b'x'; 8192]);
pages.append(body); // moves the existing body into the queue, no extra copy
pages.put_slice(b"trailer");
assert_eq!(pages.num_pages(), 3);
// the transport consumes pages in order
while let Some(page) = pages.take() {
// write `page` to the socket
assert!(!page.is_empty());
}
Build small pieces such as headers with put_slice(),
extend_from_slice(), or another BufMut method. They copy bytes into the
current page and take new pages from the page cache as needed, requesting
the queue’s page size. For an owned payload, use BytePages::append instead.
Use BytePages::prepend when a page must go at the front.
A transport can drain the queue with BytePages::take, which returns
the next BytePage and leaves the current page until last. To pass only
a byte prefix to another queue, use BytePages::split_to or
BytePages::split_into; they split a page if needed. To get all data as
one Bytes, use BytePages::freeze, with the copying costs described
below.
append decides whether to copy based on the current page and buffer size.
If the current page holds data, buffers of up to 4 KiB are copied into it.
Larger buffers become separate pages without copying. The current page
keeps its spare capacity for later writes.
If the current page is empty, append adds the buffer without copying.
A unique BytesMut with spare capacity becomes the new current page.
To pass output to another queue without draining it yourself,
BytePages::copy_to appends cloned pages and leaves the source unchanged.
It follows append’s small-buffer copy rules and copies Vec-backed pages
when cloning them. BytePages::move_to instead transfers the pages as
they are, without copying or merging, and leaves the source empty.
With freeze, a single page is converted according to its storage kind.
Native heap storage can be reused, tiny data may be inlined, and Vec
storage is copied. If the queue has several pages, they are copied into
one buffer.
A BytePage holds a Bytes, the storage of a BytesMut, or a Vec<u8>.
Splitting or advancing a Vec page copies its data, so prefer the other
kinds when output will be split or shared. Queuing an owned Vec directly
can still avoid an initial copy; that is different from converting the
vector to Bytes first.
Keep data paged for as long as the consumer accepts chunks. Calling
freeze() before passing several pages to a chunk-aware transport combines
them into one allocation and loses the benefit of paging.
Paging does not limit queued output. A producer can outpace the transport and retain many pages, including large buffers appended without copying. Stop producing when the I/O layer reports write backpressure.
BytePages::default() uses Size16. The page size cannot be Unset;
BytePages::new panics on it, as does BytePages::set_page_size.
Changing the size affects future page allocations, leaving the current page
and queued data alone.
Creating an empty queue does not immediately allocate a payload page.
Page buffers are allocated lazily. The page list itself is reused too;
each thread keeps up to 128 empty lists for new BytePages values.
Buffers in the I/O layer
The I/O Abstraction Layer uses these buffers for connection
input and output. You can tune their page sizes through IoConfig.
Reads and writes share the same per-thread page cache.
The transport reads into a pooled BytesMut. Codecs use split_to to
hand off frames. Large decoded messages share the read buffer; tiny ones
are copied inline.
The connection adapts the requested size of new read buffers to the read
load. This target stays between the minimum and maximum read sizes in
IoConfig, Size4 and Size64 by default. The page cache can supply a
page one class smaller, as described in Pooled buffers.
A buffer grows when less than
BytePageSize::low() of its page remains free. Larger input moves it to
bigger classes; beyond Size256, it becomes unpooled and is freed when
empty.
Encoders write into BytePages. IoConfig::write_size sets its page
size, Size16 by default. Use IoRef::encode_bytes to append owned buffers
without copying large payloads. The write threshold controls when a transport
may start writing while output is still being produced. By default, it is
half_capacity() of the page size.
An empty read buffer is released immediately. Its page returns to the cache only when the last frame split from it is dropped. Holding a whole request or frame keeps the full page alive. Copy the field when only a small part needs to survive.
set_page_cache_size tunes the cache for both read and write pages.
What memory usage means in practice
High memory usage can mean several different things. Start with live data: bytes still owned by requests, responses, transports or application state. Pending work needs this data, so reducing the work in flight can reduce its memory use.
Retained allocations are a different cost. A small live view may keep a
much larger shared buffer alive. If that view is intentionally long-lived,
trimdown can reduce the retained storage without discarding its data.
Cached allocations hold empty pages or read buffers for reuse. Cache limits control this category, not live data. Both retention and caching can keep resident memory high after a traffic spike without indicating an ownership leak. The tracker below distinguishes memory still owned by buffers from pages that have returned to the cache.
Tracking buffer memory
Use the tracker feature to see which part of your application keeps buffer
memory alive. You can charge any heap allocation to a BytesTracker.
A tracker can represent a cache, a tenant or another subsystem, down to a
single connection.
The charge follows the allocation until its last handle is dropped. A single frame in a cache can keep a large buffer alive long after the allocating code has moved on. The allocator reports that memory as in use; the tracker helps you identify who owns it.
The feature is off by default. Enable it on ntex to turn it on in the I/O
and network layers too. This also re-exports BytesTracker and
BytesTrackerSnapshot in ntex::util:
ntex = { version = "4", features = ["tracker"] }
If you use ntex-bytes on its own, enable ntex-bytes/tracker instead.
The I/O layer can charge connection read buffers to trackers; see the
read-buffer example.
The feature has a small cost even for buffers that are never charged. Every heap buffer’s header grows from 16 to 32 bytes to hold a tracker pointer. On 32-bit targets it grows to 20 bytes.
The tracker updates its atomic counters when a charged allocation is created, grown or released, not when another handle simply shares it. Freezing a tiny buffer can release its allocation because the result is stored inline.
How charges work
Call snapshot() to read the memory charged to a tracker. All handles of
the tracker share the same atomic counters. The snapshot contains two
numbers:
live_bytes: the total size of the charged allocations, including headers. It measures allocation size rather than data length. ASize4buffer counts as 4096 bytes whether empty or full.live_allocations: how many allocations are charged.
Charges follow the allocation, not the handle. A frame split off a buffer keeps the whole allocation charged for as long as it keeps that allocation alive. If the mutable buffer grows into a new allocation, the new one uses the same tracker. Shared frames may keep the old allocation charged too.
The charge ends when the last handle is dropped, on whichever thread drops
it. A page returns to the cache uncharged; its next user can charge it
again. Copies do not inherit a charge. That includes a cloned BytesMut,
small data stored inline in Bytes, copies made by trimdown, and data
converted into other types.
use ntex_bytes::{BytePageSize, BytesMut, BytesTracker};
let tracker = BytesTracker::new();
let mut buf = BytesMut::with_page_size_in(BytePageSize::Size4, &tracker);
buf.extend_from_slice(&[b'x'; 1000]);
let frame = buf.split_to(600); // shares the allocation
let tag = frame.slice(..8); // short enough to be copied inline
drop(buf);
// `frame` alone keeps the whole page charged
let snap = tracker.snapshot();
assert_eq!(snap.live_allocations, 1);
assert_eq!(snap.live_bytes, 4096);
// `tag` is a copy, so dropping `frame` ends the charge
drop(frame);
assert_eq!(tracker.snapshot().live_bytes, 0);
assert_eq!(&tag[..], b"xxxxxxxx");
Compared with the categories in What memory usage means in practice, a tracker counts live data and retained allocations. It never counts cached ones. If tracked memory drops after a traffic spike but resident memory stays high, check page-cache metrics before treating that difference as a leak. A tracker does not account for every allocation in the process.
Building your own tracker
Create a tracker for the part of your application whose memory you want to
measure. For example, track a response cache, a per-tenant queue or a
decompression stage. For a new buffer, pass the tracker to
BytesMut::with_page_size_in. It uses the page cache like
with_page_size, including treating BytePageSize::Unset as a request for
Size64.
For a buffer you already have, call BytesMut::set_tracker. If another
tracker owns its charge, the charge moves, even while Bytes frames split
from the allocation are still alive. Setting the same tracker again does
nothing.
BytesMut::tracker tells you which tracker a buffer is charged to.
Only a BytesMut can change the charge. Set it before freezing the buffer
and handing out Bytes.
This cache charges the buffers it stores to its own tracker:
use std::collections::HashMap;
use ntex_bytes::{Bytes, BytesMut, BytesTracker, BytesTrackerSnapshot};
#[derive(Default)]
struct BodyCache {
items: HashMap<String, Bytes>,
tracker: BytesTracker,
}
impl BodyCache {
fn insert(&mut self, key: String, mut body: BytesMut) {
// moves the charge from any previous tracker to the cache
body.set_tracker(&self.tracker);
self.items.insert(key, body.freeze());
}
fn usage(&self) -> BytesTrackerSnapshot {
self.tracker.snapshot()
}
}
The cache keeps whole allocations alive, so its charge includes spare
capacity. Entries that hold small slices of large buffers will show up in
the numbers. Use trimdown before storing them to reduce that retention.
You can read the cache’s usage from a metrics task on another thread.
BytesTracker is Send and Sync, and its clones share the same counters.
Use ptr_eq to check whether two handles refer to the same tracker. The
tracker lives while any handle or charged allocation exists, so dropping
the cache’s handle does not affect buffers still alive elsewhere.
Trackers report usage; they do not enforce limits. To enforce a budget,
check snapshot() before accepting more data. Its two counters are read
one after the other, so a snapshot taken during allocation or release is
only approximately consistent.
Example: read buffers in the I/O layer
To track connection input without charging each buffer yourself, choose a
policy in IoConfig. Set it with IoConfig::set_buf_tracker. ntex-io
uses the same tracker API to charge every read buffer a connection allocates.
Choose BufTracker::Shared to measure a listener or
service across all workers. Choose PerConnection to give each connection
its own tracker, created on first use. The default, Disabled, leaves
read buffers uncharged. Here, all connections using cfg charge the same
tracker:
use ntex::{SharedCfg, io::{BufTracker, IoConfig}, util::BytesTracker};
let api_input = BytesTracker::new();
let cfg = SharedCfg::new("API").add(
IoConfig::new().set_buf_tracker(BufTracker::Shared(api_input.clone())),
);
Keep the clone and read api_input.snapshot() from a metrics task. Frames
split off a read buffer keep it charged. The number includes every request
body or message the application still holds, even after its connection has
closed. The I/O metrics no longer see that input.
Only read buffers are charged; write buffers are not. With PerConnection,
IoRef::buf_tracker returns the connection’s tracker.
IoContext::buf_tracker does the same inside filters. You can use the
tracker to close a client that holds too much input.
Do not use the reference after Io::set_config. Clone the tracker if you
need it for longer. The clone keeps reporting buffers that outlive the
connection without keeping the connection alive.
You can also charge your own buffers to a connection’s tracker. For example,
you might assemble a body from many frames or decompress a payload. Pass
the tracker from io.buf_tracker() to with_page_size_in. That memory
appears alongside the connection’s read buffers because the tracker is an
ordinary BytesTracker.
A Shared tracker uses a single cache line updated by every worker thread.
It becomes contended under load, so prefer one tracker per listener or
service over one for the whole server.
The server chapter explains how TLS
and io-uring buffers are counted and how Io::set_config moves charges.
It also shows how to read tracker numbers alongside I/O metrics.
Performance guidelines
Choose buffer operations based on lifetime as well as size. A decoded
frame going straight to a consumer is a good fit for split_to or take,
so large payloads can share the input allocation. A field entering a
long-lived cache is a better candidate for trimdown or an explicit copy.
Drop shared frames as soon as you no longer need them: a cheap clone can
extend the lifetime of a large allocation. Inline clones instead copy a
few bytes without allocation or reference counting.
For output, reserve once when you know the message size, or start with
BytesMut::with_capacity. Use with_page_size with a class matching the
usual size for short-lived I/O buffers; cache hits avoid fresh payload
allocations. Keep an existing large body separate with BytePages::append
rather than copying it with put_slice. An owned Vec<u8> can go directly
into that queue too, avoiding the copy of converting it to Bytes first.
For constant protocol bytes, from_static neither allocates nor copies.
Measure allocation volume and retained memory alongside throughput. Fewer copies do not necessarily mean less memory retained between requests.
Timers and Time Utilities
A network server needs deadlines for TLS handshakes and clients that stop sending. It must also close idle keep-alive connections and limit waits for upstream requests.
Almost none of these timers fire. The handshake completes, the next request arrives, or the upstream answers. Timers are armed, then cancelled or pushed further into the future, thousands of times per second.
ntex-util provides ntex’s timer utilities. The ntex crate re-exports them as
ntex::time, with the same behavior on every runtime backend. Use sleep
to delay a task, timeout to put a limit on another future, or interval
for periodic work. Their shared timer design explains the trade-off between
precision and cost.
How the timer works
ntex’s timer design makes it cheap to cancel timers before they expire. It is ported from the Linux kernel timer wheel.
The kernel faces the same problem as a network server. Most timers wait for an expected event, such as a network packet or an I/O completion. They are cancelled long before they expire. Reinventing the timer wheel on LWN explains the design and its reasoning.
A wheel of buckets
A timer wheel groups timers by expiry time, so adding and cancelling timers
costs O(1) regardless of their number. A sorted list or binary heap gives
exact ordering, but every insert and cancel costs O(log n) or more.
The wheel is an array of buckets, like a clock face. Each bucket holds timers that expire during the same slice of time. To add a timer, the wheel computes a bucket index and pushes an entry. To cancel it, the wheel removes that entry.
The wheel counts time in units. By default, one unit is 16 milliseconds. Every delay is converted to units before storage. One unit is therefore the finest resolution an ntex timer can have. You can make the unit smaller; see Choosing the resolution.
Each bucket on the first level covers one unit. Its 64 buckets reach only about one second ahead. To cover longer delays, ntex uses 8 levels of 64 buckets. Each level is 8 times coarser than the one below it.
With the default 16 ms unit, the levels cover these ranges:
| Level | Granularity | Range |
|---|---|---|
| 0 | 16 ms | 0 .. ~1 s |
| 1 | 128 ms | ~1 s .. ~8 s |
| 2 | ~1 s | ~8 s .. ~64 s |
| 3 | ~8 s | ~64 s .. ~8.6 m |
| 4 | ~65 s | ~8.6 m .. ~69 m |
| 5 | ~8.7 m | ~69 m .. ~9.2 h |
| 6 | ~70 m | ~9.2 h .. ~3 d |
| 7 | ~9.3 h | ~3 d .. ~24.5 d |
A timer goes on the first level that can hold its delay. A 100 ms timeout lands on level 0; a 30-second keep-alive lands on level 2. Delays longer than the whole wheel, about 24 days, are clamped to that maximum.
No cascading
ntex leaves each timer in its original bucket, avoiding work to move it between levels. Its expiry is rounded up to that level’s granularity. This modified wheel was added to Linux in 2016.
In a classic hierarchical wheel, timers cascade. When a coarse bucket comes due, its timers move into finer levels so that each fires at its exact time. That work comes in bursts. Most of it is wasted because most of those timers would have been cancelled before expiry anyway.
For delays within the wheel’s range, this rounding means a timer never fires early: its delay counts from when it is armed and is rounded up. The rounding adds at most one granularity of its level, less than about 13% for delays over one second. It can add up to 128 ms to a 5-second timer, or about a second to a 30-second timer. A busy runtime can delay execution further.
Insertion, cancellation, and per-timer expiry bookkeeping stay O(1).
Expiring a bucket still requires visiting every timer in it, but no timers
need to move between levels first.
Finding the next expiry
A mostly idle server should not wake up to inspect empty time slots. The wheel finds the next expiry without scanning empty buckets: each level keeps a 64-bit bitmap with one bit per non-empty bucket. It rotates that bitmap to the current position, then counts trailing zeros to find the next timer due.
One driver per thread
Create a timer on the thread that awaits it. Every runtime thread, including
each server worker, has its own wheel. Timer operations need no locks or
atomics, and timer handles are !Send.
One driver task per thread serves all timers on its wheel. It sleeps until the earliest non-empty bucket is due, then wakes every timer in that bucket. The driver advances the wheel clock to the bucket’s scheduled time, even if it woke up late, so one late wakeup does not shift later timers’ deadlines.
The driver starts with the first timer. A thread that never uses timers never wakes up for them. When the runtime stops, every pending timer is marked as elapsed.
Low precision by design
Use ntex timers for network work such as timeouts, keep-alives, retries, and
periodic housekeeping. They trade precision for constant-time operations.
Use std::time::Instant to measure elapsed time.
Timer resolution is one unit, or 16 ms by default. Even a zero-duration
sleep waits for the next timer tick. Do not use these timers for
millisecond rate limits or animations.
The ntex I/O layer groups per-connection dispatcher timeouts into one-second
slots. These include keep-alive and frame read rate timeouts. All connections
on a thread share a single timer. This is one reason most I/O configuration
methods take Seconds.
Choosing the resolution
Keep the default resolution unless short sleeps or timeouts affect your latency. A smaller unit helps with short delays, at the cost of more frequent driver wakeups while short timers are pending. It also shortens the maximum delay; longer timers are clamped to the end of the wheel.
The unit is a per-system setting. It must be a power of two between 1 and
16 milliseconds; other values panic. Use the timer_resolution argument of
#[ntex::main] to set it:
#[ntex::main(timer_resolution = 2)]
async fn main() {
// timers on this system tick every 2 ms
assert_eq!(ntex::rt::System::current().timer_resolution(), 2);
}
When you build the system yourself, use Builder::timer_resolution:
let sys = ntex::rt::System::build()
.name("server")
.timer_resolution(2)
.build(ntex::rt::DefaultRuntime);
Every thread in the system, including server workers, reads the setting when its timer driver starts. It keeps that setting until the runtime stops and the wheel is empty. A thread without a running system uses 16 ms.
The level layout stays the same. All granularities and ranges in the table above scale with the unit. With a 2 ms unit, level 0 has 2 ms buckets and covers about 128 ms. Level 1 has 16 ms buckets, and the whole wheel shrinks in the same proportion:
| Unit | Level 0 range | Whole wheel |
|---|---|---|
| 16 ms | ~1 s | ~24.5 d |
| 8 ms | ~512 ms | ~12 d |
| 4 ms | ~256 ms | ~6 d |
| 2 ms | ~128 ms | ~3 d |
| 1 ms | ~64 ms | ~1.5 d |
For example, a 10 ms sleep is scheduled on 16 ms ticks at the default resolution. A smaller unit reduces the rounding added to that short delay. Longer delays gain little because they land on a higher level with about the same granularity as before.
Millis and Seconds
Millis and Seconds are compact Copy duration types used throughout
ntex’s configuration APIs. Network timeouts do not need the 16 bytes or the
billions-of-years range of std::time::Duration:
| Type | Inner value | Size | Longest span |
|---|---|---|---|
Millis | u32 | 4 bytes | about 49 days |
Seconds | u16 | 2 bytes | about 18 hours |
Both types are plain tuple structs. You can write them directly and use them
in const items. They implement Eq, Ord, and Hash. Their default value
is zero:
use std::time::Duration;
use ntex::time::{Millis, Seconds};
const CONNECT_TIMEOUT: Millis = Millis(5_000);
const KEEP_ALIVE: Seconds = Seconds(30);
fn conversions() {
assert_eq!(Millis::from_secs(2), Millis(2_000));
assert_eq!(Millis::from(Seconds(2)), Millis(2_000));
assert_eq!(Millis::from(Duration::from_millis(1_500)), Millis(1_500));
let d: Duration = KEEP_ALIVE.into();
assert_eq!(d, Duration::from_secs(30));
let d: Duration = CONNECT_TIMEOUT.into();
assert_eq!(d, Duration::from_secs(5));
// Mixed arithmetic produces `Millis`.
assert_eq!(Millis(250) + Seconds(1), Millis(1_250));
assert_eq!(Duration::from_secs(1) + Millis(250), Duration::from_millis(1_250));
}
Conversions and arithmetic saturate rather than overflowing or panicking.
Converting a Duration or usize that does not fit gives the maximum value
and logs an error:
use std::time::Duration;
use ntex::time::{Millis, Seconds};
fn saturation() {
assert_eq!(Millis(u32::MAX) + Millis(1), Millis(u32::MAX));
assert_eq!(Seconds::checked_new(100_000), Seconds(u16::MAX));
assert_eq!(Millis::from(Duration::from_secs(u64::MAX)), Millis(u32::MAX));
}
Millis::from(Duration) rounds any sub-millisecond part up. Only
Duration::ZERO becomes zero. A short positive timeout stays enabled and
never fires early:
use std::time::Duration;
use ntex::time::Millis;
fn rounding() {
assert_eq!(Millis::from(Duration::from_micros(500)), Millis(1));
assert_eq!(Millis::from(Duration::from_micros(1_500)), Millis(2));
assert_eq!(Millis::from(Duration::ZERO), Millis::ZERO);
}
A negative i32 is invalid input and panics in debug builds. Release builds
log an error and use zero, which disables the timeout.
The supported conversions are:
Millisconverts fromSeconds,Duration,u32,i32, andusize.Secondsconverts fromu16,i32, andusize.- Both types convert into
Duration.
There is no conversion from Duration to Seconds. It would silently drop
the sub-second part.
Zero means “disabled”
A zero timeout usually turns off a feature or deadline in ntex configuration,
but the meaning depends on the setting. For example, zero disables the idle
timer in IoConfig, while HttpServiceConfig::set_keepalive_timeout with
Seconds::ZERO disables HTTP persistent connections.
Use the is_zero and non_zero helpers to follow this convention in your own
code. The map helper calls a closure only for a non-zero value. When you call
it on Seconds, the closure receives the value as Millis:
use ntex::time::{Millis, Seconds, Sleep, sleep};
fn idle_timer(timeout: Seconds) -> Option<Sleep> {
timeout.map(sleep)
}
fn retry_delay(base: Millis, attempt: u32) -> Millis {
if base.is_zero() {
Millis::ZERO
} else {
Millis(base.0.saturating_mul(attempt))
}
}
Passing durations to timers
The convenience functions sleep, deadline, interval, timeout, and
timeout_checked accept impl Into<Millis>, so you can pass any supported
duration type directly. The corresponding Sleep, Deadline, and Interval
constructors take Millis instead. For example:
use std::time::Duration;
use ntex::time::{Millis, Seconds, sleep};
async fn waits() {
sleep(Millis(100)).await;
sleep(Seconds(1)).await;
sleep(Duration::from_millis(100)).await;
}
Reading the clock
Use the cached clocks in ntex::time when you can tolerate approximate time.
Reading the system clock is cheap, but a busy server pays that cost on every
request. It checks deadlines, writes a Date header, or logs access times.
For deadline checks, now returns an Instant for the start of the
current runtime turn. On the neon and compio backends, all tasks polled in
the same turn see the same value. On tokio, it is Instant::now.
For wall-clock values, system_time returns a cached SystemTime,
refreshed roughly every 150 ms. Use it where that lag is acceptable, such as
log lines and HTTP Date headers. These clocks favor inexpensive reads over
precision; call Instant::now yourself when exact elapsed time matters.
Asynchronous timers
Use asynchronous timers when a task needs to wait for time to pass. Each timer is a future woken by the shared timer driver, not a separate task. Dropping a timer cancels it.
sleep
sleep returns a Sleep future that completes after the given delay:
use ntex::time::{Millis, sleep};
#[ntex::main]
async fn main() {
sleep(Millis(100)).await;
println!("at least 100 ms have elapsed");
}
You can reuse a Sleep without consuming it through .await. Its methods
take &self, so you can wait on it, inspect it, and rearm it repeatedly:
| Method | Effect |
|---|---|
wait().await | waits without consuming the Sleep |
reset(dur) | rearms the timer to expire dur from now, before or after it has elapsed |
elapse() | completes the timer immediately and wakes the waiting task |
is_elapsed() | true once the timer has fired or was elapsed |
poll_elapsed(cx) | polls the timer from a hand-written future or service |
Reset a Sleep for an idle timeout that restarts on every message. Resetting
moves the existing entry to another bucket and keeps the registered waker.
It is cheaper than creating a new timer:
use ntex::channel::mpsc;
use ntex::time::{Seconds, sleep};
use ntex::util::{Either, select};
const IDLE: Seconds = Seconds(30);
async fn read_until_idle(rx: mpsc::Receiver<String>) {
let idle = sleep(IDLE);
loop {
match select(rx.recv(), idle.wait()).await {
Either::Left(Some(msg)) => {
idle.reset(IDLE);
println!("received {msg}");
}
Either::Left(None) => break, // all senders are gone
Either::Right(()) => {
println!("no messages for {} seconds", IDLE.0);
break;
}
}
}
}
select polls its first future first, so a message that arrives at the same
moment as the timeout is still processed.
deadline
Use deadline when a zero duration should disable a timeout. It works like
sleep for non-zero durations. A zero-duration Deadline never
completes; a zero-duration sleep waits for one timer tick.
You can await an optional timeout without a separate code path:
use ntex::channel::mpsc;
use ntex::time::{Seconds, deadline};
use ntex::util::{Either, select};
/// Returns `None` if no message arrives in time. `Seconds::ZERO` waits forever.
async fn recv_within(rx: &mpsc::Receiver<String>, limit: Seconds) -> Option<String> {
match select(rx.recv(), deadline(limit)).await {
Either::Left(msg) => msg,
Either::Right(()) => None,
}
}
Deadline::reset takes &mut self. Resetting to zero disables the deadline.
Resetting a disabled deadline to a non-zero value arms it again.
is_elapsed() agrees with awaiting the deadline. It is true only once an
armed deadline has fired, and always false for a disabled one.
timeout and timeout_checked
Use timeout to run a future with a time limit. It returns Ok with the
future’s output if the future finishes in time. If time runs out first, it
returns Err(()) and drops the inner future:
use ntex::time::{Seconds, sleep, timeout};
#[ntex::main]
async fn main() {
let fast = timeout(Seconds(1), async { "done" }).await;
assert_eq!(fast, Ok("done"));
let slow = timeout(Seconds(1), sleep(Seconds(5))).await;
assert_eq!(slow, Err(()));
}
If the future and timer become ready during the same poll, the future wins.
Like sleep, a zero-duration timeout waits one timer tick. It fails almost
immediately unless the future is already ready.
Use timeout_checked when the limit comes from configuration. It treats
zero as “no timeout” and runs the future without a time limit:
use ntex::time::{Seconds, timeout_checked};
async fn call_upstream(limit: Seconds) -> Result<String, &'static str> {
timeout_checked(limit, async { String::from("response") })
.await
.map_err(|()| "upstream timed out")
}
interval
For recurring work such as collecting statistics, use interval. It returns
an Interval that ticks repeatedly, with the first tick completing
immediately:
use ntex::time::{Seconds, interval};
async fn report_stats() {
let ticks = interval(Seconds(10));
loop {
ticks.tick().await;
println!("collecting statistics");
}
}
Each later tick completes one period after the previous tick was observed. If a busy task picks up a tick late, the schedule shifts. It does not deliver a burst of missed ticks. Use this for periodic housekeeping rather than precise timing.
Interval also implements Stream with () items. Use poll_tick in
hand-written futures. Dropping the interval stops it.
Timers in hand-written futures
You can store a timer as a plain field in a service or future. Poll it from
your own poll method or readiness check. Sleep, Deadline, and Interval
are Unpin; each has a poll_* method that takes &self:
use std::{future::Future, pin::Pin, task::Context, task::Poll};
use ntex::time::{Millis, Sleep};
struct Throttle {
delay: Sleep,
}
impl Future for Throttle {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
self.delay.poll_elapsed(cx)
}
}
fn throttle(delay: Millis) -> Throttle {
Throttle { delay: Sleep::new(delay) }
}
Callback timers
Use CallbackTimer when expiry needs only a short action, such as setting a
flag or waking another task. It runs a closure directly from the timer driver.
No task is spawned and nothing is polled.
This avoids a task or an extra branch in an existing select just to observe
expiry. A callback timer needs only a small wheel entry and the closure, so
it suits per-connection or per-request state.
The ntex KeepAlive middleware uses a callback timer to notice idle services.
Using a callback timer
Call CallbackTimer::new to arm a single invocation of a closure. Keep the
handle alive for as long as you want the callback to run. The timer is
reusable: after it fires or is cancelled, reset arms another invocation
of the same closure.
use std::{cell::Cell, rc::Rc};
use ntex::time::{CallbackTimer, Millis, sleep};
#[ntex::main]
async fn main() {
let fired = Rc::new(Cell::new(0));
let counter = fired.clone();
let timer = CallbackTimer::new(Millis(50), move || {
counter.set(counter.get() + 1);
});
sleep(Millis(100)).await;
assert_eq!(fired.get(), 1);
// Rearm, then change our mind.
timer.reset(Millis(50));
timer.cancel();
sleep(Millis(100)).await;
assert_eq!(fired.get(), 1);
// Rearm again; this time it fires.
timer.reset(Millis(50));
sleep(Millis(100)).await;
assert_eq!(fired.get(), 2);
}
| Method | Effect |
|---|---|
new(dur, f) | arms one invocation of f after dur |
reset(dur) | arms a new invocation, replacing any pending one |
cancel() | disarms the timer and keeps the closure for later |
is_elapsed() | true when disarmed: fired, cancelled or stopped by shutdown |
| drop | cancels any pending invocation and releases the closure |
Lazy rearming
On a busy connection, most activity only pushes the idle deadline further
away. You can avoid changing the timer on every request by recording the
activity time in a Cell. When the callback runs, it checks whether the
deadline has passed and rearms itself for the remaining time if needed.
This is how KeepAlive works:
use std::{cell::Cell, rc::Rc, rc::Weak, time::Duration, time::Instant};
use ntex::time::{CallbackTimer, Millis, now};
struct IdleTracker {
timeout: Millis,
last_seen: Cell<Instant>,
expired: Cell<bool>,
timer: CallbackTimer,
}
impl IdleTracker {
fn new(timeout: Millis) -> Rc<Self> {
Rc::new_cyclic(|this: &Weak<IdleTracker>| {
let this = this.clone();
IdleTracker {
timeout,
last_seen: Cell::new(now()),
expired: Cell::new(false),
timer: CallbackTimer::new(timeout, move || {
if let Some(tracker) = this.upgrade() {
tracker.check();
}
}),
}
})
}
/// Called on every request. It only stores the time; the timer is untouched.
fn touch(&self) {
self.last_seen.set(now());
}
fn check(&self) {
let deadline = self.last_seen.get() + Duration::from(self.timeout);
let current = now();
if deadline <= current {
self.expired.set(true);
} else {
self.timer.reset(Millis::from(deadline - current));
}
}
}
For a thousand requests within one timeout period, a connection needs a
thousand Cell writes and at most one or two timer resets.
The callback captures a Weak reference to avoid a cycle. The tracker owns
the timer, and the timer owns the closure. A strong Rc in the closure would
keep the tracker from ever being dropped.
Rules for callbacks
Callbacks run inside the thread’s timer driver, so a slow callback delays every other timer on that thread. Keep callbacks short, synchronous, and non-blocking. To do asynchronous work, wake a task, notify a waiter, or send to a channel from the callback.
The closure implements Fn, not FnMut, because it can run many times.
Store changing state in Cell, RefCell, or a similar type. Capturing Rc
state is fine: the timer handle is local, neither Send nor Sync, and
cannot be cloned.
The driver releases the wheel before invoking a callback, so the callback can create, reset, cancel, or drop timers, including its own. Resetting its own timer arms a new invocation.
A zero duration still waits for the next timer tick, like sleep; it never
runs the callback inline. Do not depend on an order between callbacks due on
the same tick.
Panics propagate through the runtime and may stop that thread’s timer driver. Do not use them for control flow in callbacks.
Shutdown cancels pending callbacks. A surviving handle can be reset in a new
runtime on the same thread, but is not rearmed automatically. As the method
table above shows, is_elapsed() reports that the timer is disarmed, not
whether the callback ran. Track execution in your own state if it matters.
Cookbook
These recipes are small applications you can copy into src/main.rs. Each
runs independently; stop one before starting another on port 8080. They use
ntex 4.7 with the tokio feature. The JSON recipes also need serde with
derive and serde_json; the logging recipe needs env_logger. Static files
and compression list their additional requirements beside the example.
The examples keep error responses short so you can see the wiring. A real application should log internal errors without returning credentials, database errors, or upstream response details to clients. See Error Handling for application-specific errors and Testing for checking these applications without fixed ports.
A JSON API with shared in-memory state
Use this when you need a small REST API before introducing a database. This
example stores notes by numeric ID. POST creates a note, GET reads it,
PUT updates an existing note, and DELETE removes it. All workers see the
same map because the application creates one Arc<Mutex<_>> before starting
the server, then clones that handle into each worker’s application.
use ntex::web::{
HttpResponse,
types::{Json, Path},
};
use ntex::{SharedCfg, web};
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
sync::{Arc, Mutex},
};
#[derive(Clone, Deserialize, Serialize)]
struct Note {
text: String,
}
type Notes = web::AppState<Arc<Mutex<BTreeMap<u64, Note>>>>;
async fn create(state: &Notes, (): (), id: Path<u64>, note: Json<Note>) -> HttpResponse {
let Ok(mut notes) = state.lock() else {
return HttpResponse::InternalServerError().build();
};
if notes.contains_key(&id) {
return HttpResponse::Conflict().build();
}
let note = note.into_inner();
notes.insert(id.into_inner(), note.clone());
HttpResponse::Created().json(¬e)
}
async fn read(state: &Notes, (): (), id: Path<u64>) -> HttpResponse {
let Ok(notes) = state.lock() else {
return HttpResponse::InternalServerError().build();
};
match notes.get(&id) {
Some(note) => HttpResponse::Ok().json(note),
None => HttpResponse::NotFound().build(),
}
}
async fn update(state: &Notes, (): (), id: Path<u64>, note: Json<Note>) -> HttpResponse {
let Ok(mut notes) = state.lock() else {
return HttpResponse::InternalServerError().build();
};
let Some(current) = notes.get_mut(&id) else {
return HttpResponse::NotFound().build();
};
*current = note.into_inner();
HttpResponse::Ok().json(current)
}
async fn delete(state: &Notes, (): (), id: Path<u64>) -> HttpResponse {
let Ok(mut notes) = state.lock() else {
return HttpResponse::InternalServerError().build();
};
if notes.remove(&id).is_some() {
HttpResponse::NoContent().build()
} else {
HttpResponse::NotFound().build()
}
}
fn routes(cfg: &mut web::ServiceConfig<Notes>) {
cfg.service(
web::resource("/notes/{id}")
.route(web::post().to_with_state(create))
.route(web::get().to_with_state(read))
.route(web::put().to_with_state(update))
.route(web::delete().to_with_state(delete)),
);
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
let notes = Arc::new(Mutex::new(BTreeMap::new()));
web::HttpServer::new(async move |_| {
web::App::<Notes>::new()
.configure(routes)
.build_with(web::AppState::new(notes.clone()))
})
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
Send application/json, for example {"text":"Buy bread"}, to
POST /notes/1. Creating that ID twice returns 409; reading, updating, or
removing a missing ID returns 404. The mutex keeps the existence check and
insertion together, so two workers cannot both create the same ID. A
poisoned lock produces 500 instead of panicking on another request.
These handlers do no asynchronous work while holding the lock. Keep critical
sections short: a contended standard mutex blocks the worker thread. For a
worker-local cache, construct an Rc<RefCell<_>> inside the worker factory
instead, but then each worker has different contents. Neither choice makes
the data persistent across process restarts. See
Application State and
Worker and Request State.
Serving a directory of static files
Use this for a small site’s assets or downloads that live in a dedicated
public directory. Directory serving comes from the separate ntex-files
crate, not ntex::web itself. Add ntex-files = "4.4" alongside ntex. Create a
public directory containing index.html before starting this application;
requests under /static are resolved inside that directory.
use ntex::{SharedCfg, web};
use ntex_files::Files;
#[ntex::main]
async fn main() -> std::io::Result<()> {
let public = std::fs::canonicalize("./public")?;
web::HttpServer::new(async move |_| {
web::App::new().service(Files::new("/static", public.clone()).index_file("index.html"))
})
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
Directory listings are off by default. index_file selects a document to
serve for directory requests; it does not enable listing. Files supports
GET and HEAD, conditional requests, and byte ranges. It checks decoded
path segments and confines resolved paths to its configured base directory
unless you explicitly enable following paths outside it with
follow_symlinks(true). Keep that option off for public downloads.
Treat the public directory as deployment-owned, not writable by untrusted users. Filesystem validation cannot make arbitrary concurrent changes to the directory safe. Do not mount your project root just to expose a few assets: non-hidden configuration files and source files would also become public.
If you write a file handler instead, never join an unchecked URL onto a disk
path. An ordinary Path<String> segment is percent-decoded and can contain
/; a {tail}* remainder stays encoded and needs explicit decoding before
validation. Reject traversal and platform-specific separators, and enforce
containment after resolving filesystem paths. See
Extractors and Responders for path extraction and
Routing and Handlers for mounting services.
Rejecting requests without an API key
Use this for a simple service-to-service endpoint whose callers share an API
key. Set API_KEY in the process environment and send its value in the
x-api-key request header. The middleware checks the key before calling the
handler, so rejected requests receive 401 without reaching protected code.
Use HTTPS when the key crosses a network you do not trust.
use ntex::web::{HttpResponse, middleware::from_fn};
use ntex::{SharedCfg, web};
#[ntex::main]
async fn main() -> std::io::Result<()> {
let key = std::env::var("API_KEY")
.ok()
.filter(|value| !value.is_empty())
.expect("set a nonempty API_KEY");
web::HttpServer::new(async move |_| {
let key = key.clone();
web::App::new()
.middleware(from_fn(async move |req, next| {
let mut values = req.headers().get_all("x-api-key");
let allowed = values
.next()
.is_some_and(|v| v.as_bytes() == key.as_bytes())
&& values.next().is_none();
if !allowed {
return Ok(
req.into_response(HttpResponse::Unauthorized().body("invalid API key"))
);
}
next.call(req).await
}))
.route("/private", web::get().to(async || "allowed"))
})
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
The comparison is exact and rejects missing, incorrect, or duplicate keys. It is an intentionally small example, not a credential-management system. For production secrets, use a reviewed authentication implementation with appropriate constant-time comparison, rotation, and rate limiting. Do not log the key. An API key identifies its holder; authorization rules still need to decide what that holder may do.
Attach middleware before adding routes. If only one URL subtree needs a key,
put it on a scope rather than the whole application. Returning
req.into_response(...) is the normal early-response path; successful
requests must call next.call(req).await. See
Filters and Middleware,
Error Handling, and TLS.
Logging requests and their duration
Use this when you want an access log with status codes, response sizes, and
elapsed time. ntex includes Logger, so you do not need to implement timing
middleware for the usual access-log fields. Initialize the logging backend
once in main, not in the worker factory, and run with RUST_LOG=info.
use ntex::web::middleware::Logger;
use ntex::{SharedCfg, web};
#[ntex::main]
async fn main() -> std::io::Result<()> {
env_logger::init();
web::HttpServer::new(async |_| {
web::App::new()
.middleware(Logger::new("%U %s %b %Dms").exclude("/health"))
.route("/health", web::get().to(async || "ok"))
.route("/hello", web::get().to(async || "hello"))
})
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
%U logs the path without the query string, %s the response status, %b
the body bytes, and %D elapsed milliseconds. Logger records the response
when its wrapped body is dropped, rather than only when the handler returns.
That distinction matters for streaming responses and clients that disconnect.
Excluding a health endpoint keeps frequent probes out of the access log.
Avoid logging authorization headers, cookies, or sensitive query parameters.
For a custom metric around handler execution, use from_fn, start an
Instant before next.call, and observe the result afterward; that measures
a different interval from consuming the response body. See
Filters and Middleware.
Graceful shutdown, including Ctrl-C
Use this when Ctrl-C should drain active requests instead of stopping
immediately. ntex normally stops gracefully on SIGTERM, but immediately
on SIGINT/Ctrl-C; graceful_shutdown() does not change SIGINT. This
example disables the server’s own signal reaction, enables runtime signal
handling, and translates interrupt, termination, or quit into stop(true).
use ntex::rt::signals::{self, Signal};
use ntex::{SharedCfg, rt, time::Seconds, web};
#[ntex::main]
async fn main() -> std::io::Result<()> {
rt::System::current().enable_signals();
let server = web::HttpServer::new(async |_| {
web::App::new().route("/", web::get().to(async || "running"))
})
.disable_signals()
.graceful_shutdown_timeout(Seconds(20))
.bind("127.0.0.1:8080", SharedCfg::default())?
.run();
let handle = server.clone();
let mut incoming = signals::signal();
rt::spawn(async move {
while let Ok(batch) = incoming.await {
if batch
.iter()
.any(|signal| matches!(signal, Signal::Int | Signal::Term | Signal::Quit))
{
handle.stop(true).await;
break;
}
incoming = signals::signal();
}
});
server.await
}
Signal subscriptions receive one batch, so register again after an unrelated
signal. Windows delivers Ctrl-C as Signal::Int; Unix also supplies the
termination and quit signals shown here. Only one ntex system can own
process signal handling at a time. If an embedding application already owns
signals, let it call a cloned server handle instead of installing another
handler.
run() starts the server and returns its controller/completion future.
stop(true).await requests graceful worker shutdown; stop(false) requests
an immediate stop. The worker deadline above bounds draining, so requests
still active after it can be dropped. It is not a guarantee that every
request completes, nor a timeout for individual handlers. See
Server and
Worker and Request State for lifecycle details.
Body limits and separate timeout budgets
Use this when endpoints accept small JSON documents but you also need to
bound slow clients and slow application work. These are separate controls:
extractor configuration limits a buffered body, HTTP configuration controls
connection behavior, and time::timeout bounds the future you wrap. This
example caps JSON at 1 KiB and raw byte bodies at 4 KiB.
use ntex::web::{
HttpResponse, WebAppConfig,
types::{Json, JsonConfig, PayloadConfig},
};
use ntex::{
SharedCfg,
http::HttpServiceConfig,
time::{self, Seconds},
web,
};
async fn json(body: Json<serde_json::Value>) -> HttpResponse {
HttpResponse::Ok().json(&body.into_inner())
}
async fn raw(body: ntex::util::Bytes) -> String {
format!("{} bytes", body.len())
}
async fn bounded() -> HttpResponse {
let work = async { "finished" };
match time::timeout(Seconds(2), work).await {
Ok(result) => HttpResponse::Ok().body(result),
Err(_) => HttpResponse::GatewayTimeout().build(),
}
}
fn limits() -> WebAppConfig {
WebAppConfig::new()
.set_value(JsonConfig::default().limit(1024))
.set_value(PayloadConfig::new(4096))
}
fn routes(cfg: &mut web::ServiceConfig) {
cfg.route("/json", web::post().to(json));
cfg.route("/raw", web::post().to(raw));
cfg.route("/work", web::get().to(bounded));
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
let transport = SharedCfg::new("bounded-api")
.add(
HttpServiceConfig::new()
.set_client_timeout(Seconds(3))
.set_keepalive_timeout(Seconds(10))
.set_write_timeout(Seconds(15)),
)
.build();
web::HttpServer::new(async |_| web::App::new().with_config(limits()).configure(routes))
.bind("127.0.0.1:8080", transport)?
.run()
.await
}
An oversized JSON or byte body returns 413 with the default error domain.
JsonConfig does not configure the Bytes extractor; PayloadConfig does.
Neither is a universal streaming-body cap: code consuming Payload directly
must enforce its own bound. Store these settings in WebAppConfig, not
application state. They are extractor settings, separate from SharedCfg.
set_client_timeout sets the initial request-header timeout and the
header-read rate’s measurement interval, not a handler deadline or a total
body-read deadline. set_keepalive_timeout controls idle persistent
connections. set_write_timeout bounds HTTP/1 write backpressure. HTTP/1
protocol timers have one-second resolution, so allow for that when testing.
For slow uploads, HTTP configuration also has set_payload_read_rate; choose
its rate and budget for your expected traffic rather than treating the header
timeout as upload protection.
Replace work with the operation you want to bound. A timeout drops its
future; it does not roll back external side effects or interrupt blocking
code. Wrapping work inside the handler also does not time the extraction
that happened before entering it. See
Extractors and Responders,
Server Configuration,
and Timers.
Calling another HTTP service
Use this when a handler needs data from another HTTP endpoint. Build one
ntex::client::Client per worker, then clone its handle with application
state so connections can reuse its pool. The upstream URL here is fixed;
set UPSTREAM_URL to a trusted service address rather than accepting an
arbitrary destination from the request.
use ntex::web::HttpResponse;
use ntex::{SharedCfg, client::Client, time::Seconds, web};
#[derive(Clone)]
struct Upstream {
client: Client,
url: String,
}
type State = web::AppState<Upstream>;
async fn fetch(state: &State, (): ()) -> HttpResponse {
let response = match state
.client
.get(state.url.as_str())
.timeout(Seconds(2))
.send()
.await
{
Ok(response) if response.status().is_success() => response,
_ => return HttpResponse::BadGateway().build(),
};
match response.body().limit(64 * 1024).timeout(Seconds(2)).await {
Ok(body) => HttpResponse::Ok().content_type("text/plain").body(body),
Err(_) => HttpResponse::BadGateway().build(),
}
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
let url = std::env::var("UPSTREAM_URL")
.unwrap_or_else(|_| "http://127.0.0.1:9000/message".to_owned());
web::HttpServer::new(async move |_| {
let state = web::AppState::new(Upstream {
client: Client::new(),
url: url.clone(),
});
web::App::<State>::new()
.route("/message", web::get().to_with_state(fetch))
.build_with(state)
})
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
The client lives in the worker factory, not inside fetch or a per-connection
service constructor. Its clones share connection pools and are worker-local;
do not move this client between worker threads. The request timeout and body
read timeout are separate budgets. Reading the full body allows the client
to reuse a healthy connection; the limit keeps buffering bounded.
This is not a transparent proxy. It accepts successful upstream responses, returns plain text, and maps transport errors and other statuses to 502. Do not blindly copy hop-by-hop headers or let callers choose internal URLs. HTTPS needs an enabled TLS backend or a configured secure connector. See HTTP Client and TLS.
Keeping a database pool in state
Use this pattern when a handler needs a database pool but you do not want
routing code tied to one database library. The small trait below is an
application boundary: implement it for a wrapper around your chosen pool.
MemoryPool is only an in-memory stand-in so the example compiles without a
database dependency; it does not open connections or implement a real pool.
use ntex::web::{HttpResponse, types::Path};
use ntex::{SharedCfg, web};
use std::{collections::BTreeMap, rc::Rc};
trait UserPool: Clone + 'static {
async fn name(&self, id: u64) -> Option<String>;
}
#[derive(Clone)]
struct MemoryPool(Rc<BTreeMap<u64, String>>);
impl UserPool for MemoryPool {
async fn name(&self, id: u64) -> Option<String> {
self.0.get(&id).cloned()
}
}
#[derive(Clone)]
struct Database<P> {
pool: P,
}
impl<P: UserPool> web::State for Database<P> {
type Error = web::DefaultError;
}
async fn user<P: UserPool>(state: &Database<P>, (): (), id: Path<u64>) -> HttpResponse {
match state.pool.name(id.into_inner()).await {
Some(name) => HttpResponse::Ok().json(&name),
None => HttpResponse::NotFound().build(),
}
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
web::HttpServer::with_config(
async || {
let pool = MemoryPool(Rc::new(BTreeMap::from([(1, "Ada".to_owned())])));
Ok(Database { pool })
},
async |_| {
web::App::new().route("/users/{id}", web::get().to_with_state(user::<MemoryPool>))
},
)
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
Replace construction in the zero-argument configuration factory with your
pool’s asynchronous initialization. That factory runs once per worker
incarnation; initialization failures return an io::Error. The state is
cloned for connections, so your real pool type should clone a shared handle,
not open a new pool on every clone. Do not initialize a pool in a handler or
in a lazily created route service.
For a real database, make the trait return a Result as well as Option, so
missing rows remain distinct from connection and query failures. A per-worker
pool’s configured capacity is multiplied by the number of workers. If your
chosen pool is thread-safe and intended to be process-wide, initialize one
outside the server and share its handle instead. See
Application State,
Worker and Request State, and
Error Handling.
A periodic task per worker
Use this for worker-local cache refreshes or housekeeping. Start the task in
the worker state factory, not in a handler or per-connection application
service. This example increments a local counter once per interval and
exposes it at /ticks. Each worker has its own counter, so separate requests
can observe different values when they reach different workers.
use ntex::{
SharedCfg, rt,
time::{self, Seconds},
web,
};
use std::{cell::Cell, rc::Rc};
#[derive(Clone)]
struct Worker {
ticks: Rc<Cell<u64>>,
_task: Rc<rt::JoinHandle<()>>,
}
type State = web::AppState<Worker>;
async fn ticks(state: &State, (): ()) -> String {
state.ticks.get().to_string()
}
fn start_worker() -> State {
let ticks = Rc::new(Cell::new(0));
let counter = ticks.clone();
let task = rt::spawn(async move {
let interval = time::interval(Seconds(5));
loop {
interval.tick().await;
counter.set(counter.get() + 1);
}
})
.cancel_on_drop();
web::AppState::new(Worker {
ticks,
_task: Rc::new(task),
})
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
web::HttpServer::with_config(
async || Ok(start_worker()),
async |_| web::App::new().route("/ticks", web::get().to_with_state(ticks)),
)
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
The first tick completes immediately, so the job runs once at startup and then once per period. To wait a full period first, await one tick before entering the loop. Await each refresh before the next tick to avoid overlapping runs. Use a single task to wait on each interval, and avoid blocking calls in that task.
The state keeps the task handle in an Rc, shared by its connection clones.
cancel_on_drop() requests cancellation when the last state handle is
dropped; worker runtime teardown also drops pending tasks. The task captures
only the counter, not its owning state, so it does not create an ownership
cycle. Dropping an ordinary task handle without cancel_on_drop would detach
the task instead.
Cancellation drops a pending future; it is not an asynchronous cleanup hook. If a job must flush or commit work, arrange a stop notification and await its completion before stopping the server, with an explicit deadline. Do not rely on worker teardown to finish that work. See Timers, Runtime, and Server Shutdown.
Compression and a fixed-origin CORS policy
Use this for a browser-facing endpoint that serves substantial text and is
readable by one known frontend origin. Enable ntex’s compress feature.
Compress negotiates the response encoding from Accept-Encoding; the
second middleware adds a small, fixed CORS policy and handles preflight
requests for this read-only API.
use ntex::web::{
HttpResponse,
middleware::{Compress, from_fn},
};
use ntex::{
SharedCfg,
http::{
Method,
header::{HeaderName, HeaderValue},
},
web,
};
#[ntex::main]
async fn main() -> std::io::Result<()> {
web::HttpServer::new(async |_| {
web::App::new()
.middleware(Compress::default())
.middleware(from_fn(async |req, next| {
let mut response = if req.method() == Method::OPTIONS {
req.into_response(HttpResponse::NoContent().build())
} else {
next.call(req).await?
};
for (name, value) in [
("access-control-allow-origin", "https://frontend.example"),
("access-control-allow-methods", "GET, OPTIONS"),
] {
response.headers_mut().insert(
HeaderName::from_static(name),
HeaderValue::from_static(value),
);
}
Ok(response)
}))
.route(
"/report",
web::get().to(async || {
HttpResponse::Ok()
.content_type("text/plain")
.body("report\n".repeat(500))
}),
)
})
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
Known-size bodies below 1 KiB stay uncompressed. For negotiated responses,
compression middleware adds Vary: Accept-Encoding so shared caches do not
mix encodings. Streaming responses keep the encoder until the body ends;
account for that memory when many streams remain open.
The CORS origin is constant, not reflected from an arbitrary request. This example allows no credentials and no extra request headers. A browser asking for an unlisted method or non-safelisted header will not get permission. If you need authenticated browser calls, a changing origin allowlist, or route-specific preflight rules, use a complete CORS implementation instead of growing this example into one. CORS controls browser access, not which clients may call your server. It is not authentication. See Filters and Middleware for layering and Routing and Handlers for method-specific routes.
Listening on more than one address
Use this when the same application should accept connections on several
interfaces or ports. Chain bind calls on one HttpServer; each listener
gets its own SharedCfg, so you can choose different protocol settings
without running separate applications. These two listeners deliberately
share one application definition and the same health endpoint.
use ntex::{SharedCfg, web};
#[ntex::main]
async fn main() -> std::io::Result<()> {
web::HttpServer::new(async |_| web::App::new().route("/health", web::get().to(async || "ok")))
.bind("127.0.0.1:8080", SharedCfg::new("first-listener"))?
.bind("127.0.0.1:8081", SharedCfg::new("second-listener"))?
.run()
.await
}
Binding errors are returned before run(): a port already in use should
fail startup rather than silently leave one address unavailable. A hostname
can resolve to multiple socket addresses as well. Choose explicit interface
addresses when you need predictable exposure; loopback listeners are not
reachable from other machines.
The factory is used for each listener on each worker. Do not assume mutable
state constructed inside that closure is shared between listeners. Put
worker-wide resources in HttpServer::with_config state, or clone a
process-wide Arc into every application.
For HTTP and HTTPS together, keep a plain bind and add a backend-specific
bind_openssl or bind_rustls with its configured TLS acceptor. Certificate
loading, backend features, and a complete compiling HTTPS example are in
TLS; keep those checks rather than disabling verification to
get a listener running. See Server for binding existing
listeners and controlling the resulting server.
Migrating from ntex 3 to ntex 4
ntex 4 requires Rust 1.97 and upgrades the service stack to ntex-service 5.
Most migration work involves the new service state and lifecycle APIs.
Server
Server service factories now create a Service directly. They no longer
create a ServiceFactory whose initialization configuration is SharedCfg.
The factory is called once per worker and receives a reference to that
worker’s application state.
For a server without custom application state, continue to use
ntex::server::build(). The factory receives &():
use std::io;
use ntex::http::{HttpService, Response};
use ntex::SharedCfg;
#[ntex::main]
async fn main() -> io::Result<()> {
ntex::server::build()
.bind(
"http",
"127.0.0.1:8080",
SharedCfg::default(),
async |_| {
HttpService::new(async |_| {
Ok::<_, io::Error>(Response::Ok().body("Hello"))
})
},
)?
.run()
.await
}
Use ntex::server::build_with_config() when each worker needs application
state. Its argument implements ServerAppConfig and creates the state for each
worker. An asynchronous closure can be used directly:
use std::io;
use ntex::SharedCfg;
#[derive(Clone)]
struct WorkerState;
#[ntex::main]
async fn main() -> io::Result<()> {
ntex::server::build_with_config(
async || Ok::<_, io::Error>(WorkerState),
)
.bind(
"service",
"127.0.0.1:8080",
SharedCfg::default(),
async |state: &WorkerState| {
let state = state.clone();
ntex::service::fn_service(move |_| {
let _state = state.clone();
async { Ok::<_, io::Error>(()) }
})
},
)?
.run()
.await
}
ntex-service 5 also removes Service::poll(). The Service trait now uses
the asynchronous ready() and shutdown() lifecycle methods, while service
chains provide readiness() and shutdown() callbacks. Pipeline and
middleware APIs have been updated to bind and propagate service state.
Pipeline::call_nowait() and PipelineBinding::call_nowait() have been
removed; use call(). With notification-based readiness, successful readiness
is cached until a subscribed ReadyNotifier invalidates it; calls do not
consume that success.
Ctx::call_nowait() was removed. Use ctx.call(&inner, req).await for
nested dispatch, even after explicitly checking readiness. Valid cached
readiness avoids another readiness check or allocation. Unlike the removed
bypass, call() can wait or fail after readiness changes. Forward
Service::bind through wrappers, and notify every readiness-changing
transition before relying on persistent caching. Raw Ctx::ready() calls do
not populate the upstream cache; use ready(svc) for independent child caching.
Primitive Service::call() is not deprecated.
Server builder
Several ServerBuilder and web HttpServer methods have been renamed or
removed:
| ntex 3 | ntex 4 |
|---|---|
maxconn() | max_connections() |
shutdown_timeout() | graceful_shutdown_timeout() |
HttpServer::maxconnrate() | HttpServer::max_tls_handshakes() |
ServerBuilder::config(), HttpServer::config() | pass SharedCfg to bind() or listen() |
on_worker_start(), on_accept() | build_with_config() or HttpServer::with_config() |
WorkerPool::shutdown_timeout() is also renamed to
graceful_shutdown_timeout().
Runtime features
The deprecated neon feature has been removed from ntex, ntex-rt and
ntex-net, the native runtime is used without it. Remove it from ntex and
direct ntex-rt or ntex-net dependencies. The neon-iocp feature has been
removed as well, Windows always uses IOCP. Select the tokio, compio,
neon-polling or neon-uring feature when a specific runtime backend is
required.
HTTP services
HttpService::openssl() and HttpService::rustls() have been replaced by the
http::openssl() and http::rustls() service wrappers.
OpenSSL:
let service = ntex::http::openssl(
acceptor,
ntex::http::HttpService::new(handler),
);
rustls now accepts the ALPN protocol names separately:
let service = ntex::http::rustls(
config,
&["h2", "http/1.1"],
ntex::http::HttpService::new(handler),
);
HTTP configuration
HttpServiceConfig::set_enable_headers_vec()is replaced byset_headers_vec(bool).h1::Codec::upgrade()has been removed; useRequest::upgrade()to detect upgrade andCONNECTrequests.- New settings:
set_half_close(),set_host_validation(),set_max_start_line_size(), andset_write_timeout().
URLs
ntex 4 uses urly::Url, re-exported as ntex::url, instead of http::Uri:
ntex::http::Uriand thentex::http::urimodule have been removed.RequestHead::uri,Request::uri(),HttpRequest::uri(), andWebRequest::uri()areUrlvalues.Url::path()andUrl::query()returnntex::url::Pathandntex::url::Query; useas_str()to get string slices.HttpRequest::path()andHttpRequest::query_string()still return&str.HttpRequest::url_for()returnsntex::url::Urlinstead ofurl::Url.- The
urlfeature has been removed; URL support is always available. - The HTTP and WebSocket clients accept any type that converts to
Url, including&str,String, andhttp::Uri. Client connectors useConnect<Url>instead ofConnect<Uri>. - Server request targets are normalized: dot segments are removed, a fragment
is dropped, and an origin-form path starting with
//is a path, not an authority.
HTTP client
The HTTP client builder, connector, and connection pool have been redesigned:
ClientBuildernow owns the connector configuration; the separate client connector builder has been removed.- Custom connector factories are replaced by connector
Servicevalues. ClientBuilder::build()is synchronous and takes aSharedCfg.- Client settings are stored in
ClientConfiginsideSharedCfg.
The default connector is configured automatically:
use ntex::SharedCfg;
use ntex::client::{Client, ClientConfig};
fn create_client() -> Client {
let cfg = SharedCfg::new("client").add(
ClientConfig::new()
.set_h1_connection_limit(8)
.set_response_payload_limit(256 * 1024),
);
Client::builder().build(cfg)
}
Use ClientBuilder::connector() or ClientBuilder::secure_connector() to
install a custom connector service.
Request defaults have moved from ClientBuilder to ClientConfig:
ntex 3 ClientBuilder | ntex 4 ClientConfig |
|---|---|
header() | set_header() |
basic_auth(), bearer_auth() | set_basic_auth(), set_bearer_auth() |
response_timeout(), disable_timeout() | set_response_timeout(), disable_timeout() |
response_payload_limit() | set_response_payload_limit() |
response_payload_timeout() | set_response_payload_timeout() |
The ClientConfig getters timeout(), payload_limit(), and
payload_timeout() are now response_timeout(), response_payload_limit(),
and response_payload_timeout().
ClientBuilder::disable_redirects(), max_redirects(), and
no_default_headers() have been removed.
The error variants ClientError::TunnelNotSupported, ConnectError::Timeout,
ConnectError::SslError, ConnectError::SslHandshakeError, and
EncodeError::Fmt have been removed. InvalidUrl::Http is replaced by
InvalidUrl::Parse.
WebSocket client
WebSocket client settings have moved to WsClientConfig. Construct
WsClient directly with the URI and configuration; a separate builder is no
longer required:
use ntex::ws::{WsClient, WsClientConfig};
let client = WsClient::new(
"ws://127.0.0.1:8080/ws",
WsClientConfig::new().set_max_frame_size(128 * 1024),
);
let connection = client.connect().await?;
URL validation errors are now reported by connect() rather than by
WsClient::new(), as WsConfigError::Parse instead of WsConfigError::Http.
Custom connectors and TLS are still selected with connector(), openssl(),
or rustls() on WsClient.
WsSink::on_disconnect() now returns ntex::io::Waiter<'static>; the
OnDisconnect future type has been removed.
Web applications
Web application state and error handling have been redesigned.
Application state in handlers
The application state type implements web::State. For common state that uses
the default web error type, web::AppState<T> provides a ready-made wrapper.
State is created once per worker with web::server_with_config() and is
passed to state-aware handlers by reference.
The web::types::State<St> extractor has been removed. Replace handlers that
use it with Route::to_with_state(). A state-aware handler receives:
- A shared reference to the application state.
- The request-local state.
- Any request extractors.
use std::io;
use ntex::{web, SharedCfg};
#[derive(Clone)]
struct TestAppState {
value: &'static str,
}
impl web::State for TestAppState {
type Error = web::DefaultError;
}
async fn index(
state: &TestAppState,
_request_state: (),
) -> web::HttpResponse {
web::HttpResponse::Ok().body(state.value)
}
#[ntex::main]
async fn main() -> io::Result<()> {
web::server_with_config(
async || {
Ok::<_, io::Error>(TestAppState {
value: "Hello",
})
},
async |_| {
web::App::<TestAppState>::new()
.route("/", web::get().to_with_state(index))
},
)
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
The state-aware variants are available as web::to_with_state(),
Route::to_with_state(), Resource::to_with_state(), and
ResourceServices::to_with_state(). Continue to use to() when a handler only
needs request extractors.
The old App::state() model is replaced by service state for the primary
application state. Additional configuration values can be stored with
WebAppConfig::set_value() and retrieved with HttpRequest::app_value()
(named set_state() and app_state() before ntex 4.7).
Request-local state is available through WebRequest::st() and
WebRequest::st_mut(). Filters and middleware can change its type with
WebRequest::map_state().
Custom implementations of the Handler trait must change call() from a
method returning impl Future to an async fn. Ordinary async fn handlers
do not need this change.
Error handling
The ErrorRenderer API has been removed. The state’s associated Error type
defines the application’s error type, and errors are rendered through
WebResponseError<St, Err>. Error rendering receives the application state
instead of an HttpRequest. Service initialization errors now use
ntex::error::Failure and IntoFailure.
Middleware order
Middleware registered with App::middleware(), Scope::middleware(), and
Resource::middleware() now runs in registration order. The first registered
middleware is the outermost one: it receives the request first and the
response last. In ntex 3 the order was reversed, and the last registered
middleware was the outermost one.
use ntex::web::{self, App, middleware};
App::default()
.middleware(middleware::DefaultHeaders::new().header("x-app", "example"))
.middleware(middleware::Logger::default())
.route("/", web::get().to(async || "Hello"));
In ntex 4, DefaultHeaders receives the request before Logger, and Logger
processes the response before DefaultHeaders. In ntex 3 the same code ran
Logger first. To keep the ntex 3 behavior, reverse the order of
middleware() calls.
Custom codecs and I/O
This section applies to code that implements codecs, filters, or dispatchers
directly on top of ntex::io and ntex::codec.
Codecs
ntex-codec 2 writes encoded data into BytePages. The deprecated
encode(BytesMut) method has been removed and encodev() has been renamed to
encode(), which is now required:
impl Encoder for MyCodec {
type Item = Bytes;
type Error = io::Error;
fn encode(&self, item: Bytes, dst: &mut BytePages) -> Result<(), io::Error> {
dst.append(item);
Ok(())
}
}
Decoder::decode_eof() is called when the peer closes the stream. Its default
implementation calls decode(); override it to decode a final frame that has
no terminator. If undecodable bytes remain after a clean EOF, Io::recv() and
the dispatcher report an io::ErrorKind::UnexpectedEof error.
IoConfig
set_disconnect_timeout()/disconnect_timeout()are renamed toset_shutdown_timeout()/shutdown_timeout(). A zero timeout panics.- Read and write buffers are
ntex-bytespages and share one page cache, configured per thread withntex_bytes::set_page_cache_size().BufConfigandIoConfig::read_buf()/write_buf()have been removed. - Each connection adapts its read page size to its reads, between the sizes set
with
set_read_size(min, max)(4 KiB to 64 KiB by default). - Backpressure is configured with a single high watermark and is released at half of it:
| ntex 3 | ntex 4 |
|---|---|
set_read_buf(high, low, cache_size) | set_read_backpressure(high) and set_read_size(min, max) |
set_write_buf(high, low, cache_size) | set_write_backpressure(high) |
set_write_page_size(), write_page_size() | set_write_size(), write_size() |
set_write_timeout()closes connections whose peer stops reading.
Io and IoRef
| ntex 3 | ntex 4 |
|---|---|
IoRef::force_close() | IoRef::terminate() |
IoRef::wants_shutdown() | IoRef::close() |
IoRef::with_read_buf() | IoRef::with_read_dst() |
IoRef::with_read_src_buf() | IoRef::with_read_src() |
IoRef::with_write_buf() | IoRef::with_write_src() |
IoRef::with_write_dst_buf() | IoRef::with_write_dst() |
IoRef::on_disconnect() returning OnDisconnect | returns Waiter<'static> |
Io::read_ready(), Io::poll_read_ready() | Io::read_more(), Io::poll_read_more() |
Io::poll_dispatch() | Io::register_dispatch() |
Io::pause() | removed; reads resume via poll_read_more() |
Io::set_config() | pass the configuration to Io::new() |
Io::take() | unsafe Io::take() |
IoRef::resize_read_buf(), IoContext::resize_read_buf() | BytesMut::reserve_more() |
IoStatusUpdate::KeepAlive | IoStatusUpdate::Timeout |
IoRef::is_closed() now reports whether closing has finished. Use the new
IoRef::is_active() to check whether the connection is still usable.
Dispatcher
Reason::KeepAliveTimeout is renamed to Reason::KeepAlive, and the new
Reason::WriteTimeout is reported when IoConfig::set_write_timeout()
expires.
Other API changes
ntex::rt:System::stop_on_panic()has been removed andBuilder::stop_on_panic()no longer has an effect. UseBuilder::panic_handling()or#[ntex::main(panic_handling = true)].System::set_latency_callback()requires aSend + Synccallback.ntex::time:query_system_time()has been removed; usesystem_time().ntex_util::channel::bstream::Receiver::max_buffer_size()is deprecated in favor ofset_watermarks().ntex::http::HeaderMapno longer implementsFromIterator; build maps withinsert()orappend().HeaderValue::to_str()accepts any valid UTF-8 value, not only visible ASCII.
Router
ntex::router (ntex-router 2) renames several APIs:
| ntex 3 | ntex 4 |
|---|---|
Router::recognize_mut_checked() | Router::recognize_checked_mut() |
ResourceDef::resource_path(), resource_path_named() | ResourceDef::build_path(), build_path_named() |
ResourceDef::name_mut() | ResourceDef::set_name() |
RouterBuilder::rdef() | RouterBuilder::resource() |
Path::unprocessed() | Path::path() |
Path::query() | Path::get() |
Router::build(), RouterBuilder::finish() | removed |
RouterBuilder registration methods return &mut RouterEntry instead of a
tuple; use set_id(), set_name(), set_check_value(), and
resource_mut(). Path::skip() takes a u32. Path segments that do not
decode to valid UTF-8 are kept percent-encoded.
Connection and protocol configuration
SharedCfg remains the container for connection and protocol configuration,
but it is separate from worker application state:
- Pass
SharedCfgto serverbind()orlisten()methods. - Pass
SharedCfgtoClientBuilder::build(). - Use
build_with_config()orweb::server_with_config()for per-worker application state.
See Connection and Protocol Configuration for a complete example.