nacelle documentation
nacelle is an experimental Tokio-based Rust library for streaming application handlers across TCP and HTTP transports.
This book is the narrative documentation site. It follows the same broad delivery model as the Rust Book: chapter-oriented Markdown, search, keyboard navigation, and a local/offline build. Its content is organized like Django's documentation:
- Tutorials take you through a working path.
- Topic guides explain concepts and design choices.
- How-to guides solve specific operational tasks.
- Reference pages document exact behavior and APIs.
Rust API reference is still generated separately with cargo doc.
Start here
If you are new to nacelle, read:
If you are validating performance, read:
Internal readiness plans and assessments live under docs/internal and are not
part of this public book.
Getting started
This tutorial gets a minimal TCP service running with the repository's example length-delimited protocol.
Add nacelle
In this workspace, the umbrella crate is nacelle. The unpublished reference
protocol package is an example consumer of its TCP and codec APIs:
#![allow(unused)] fn main() { use nacelle::core::pipeline::handler_fn; use nacelle::core::{NacelleError, NacelleTelemetry}; use nacelle::tcp::{TcpRequestContext, TcpResponse, TcpServer}; use nacelle::NacelleApp; use nacelle_reference_protocol::LengthDelimitedProtocol; }
Build a handler
TCP handlers receive a protocol-specific TcpRequestContext and must complete
it through its typed responder.
#![allow(unused)] fn main() { let handler = handler_fn( |mut context: TcpRequestContext<LengthDelimitedProtocol>| async move { while let Some(chunk) = context.request_mut().body.next_chunk().await { let _ = chunk?; } context.respond(TcpResponse::bytes("ok")).await }); }
Start the app
#![allow(unused)] fn main() { let addr = "127.0.0.1:8080".parse().map_err(NacelleError::protocol)?; let server = TcpServer::<LengthDelimitedProtocol>::builder() .protocol(LengthDelimitedProtocol) .handler(handler) .build()?; NacelleApp::with_telemetry(NacelleTelemetry::default()) .with_ctrl_c_shutdown() .tcp("echo", addr, server) .run() .await?; Ok::<(), NacelleError>(()) }
For application dependencies, construct the app with
NacelleApp::with_state(...), annotate the handler context as
TcpRequestContext<LengthDelimitedProtocol, AppState>, and borrow the root with
context.app_state(). The same typed root is available to every TCP and HTTP
listener registered on that app.
Next steps
- Run
cargo run -p nacelle-examples --bin app_coreto see one app core served through multiple protocol adapters. - Read the architecture guide to understand the request path.
- Read runtime limits and backpressure before raising connection counts.
- Use Run the stress harness to validate a local build.
Run the stress harness
The stress harness has two binaries:
nacelle-stress-server, fromnacelle-stress-servernacelle-stress-test, fromnacelle-stress-test
Run the convenience script:
./examples/run-stress-test.sh
The script reads root config.toml by default. Pass --config to select a
repeatable benchmark profile. If the effective tls_self_signed value is true,
it passes --tls-insecure to the client so the server and client speak the
same transport.
For a plain TCP baseline, use
examples/nacelle-stress-server/configs/tcp.toml.
For full details, see the how-to guide:
Run the server:
cargo run --release --package nacelle-stress-server -- --config examples/nacelle-stress-server/configs/tcp.toml
Run a bounded client smoke test:
cargo run --release --package nacelle-stress-test -- --connections 32 --pipeline 16 --duration-secs 15
The examples/run-stress-test.sh and examples/run-stress-test.ps1 helpers
accept --config/-Config and pass --tls-insecure to the stress client only
when the effective tls_self_signed value is true.
The stress client enables its Rustls support by default so --tls-insecure
works with the local self-signed server. For a Rustls-free plain TCP build, run
both stress binaries with --no-default-features and use
examples/nacelle-stress-server/configs/tcp.toml.
Repeatable profiles:
examples/nacelle-stress-server/configs/tcp.toml: plain TCP baseline.examples/nacelle-stress-server/configs/tcp-tls.toml: TCP wrapped in self-signed TLS.
Linux example:
./examples/run-stress-test.sh --config examples/nacelle-stress-server/configs/tcp.toml --server-threads 48 --connections 256 --pipeline 8 --duration-secs 30 --payload-bytes 256
PowerShell example:
.\examples\run-stress-test.ps1 -Config examples/nacelle-stress-server/configs/tcp.toml -ServerThreads 48 -Connections 256 -Pipeline 8 -DurationSecs 30 -PayloadBytes 256
The stress server installs a metrics-util recorder and prints a compact
metrics snapshot every 5 seconds. Its [telemetry] table defaults to
request_metrics = "counters-and-bytes"; use "counters" to omit body-size
histograms or "off" to suppress request counters and byte histograms. Use
--request-metrics counters for a lower-overhead recorder run. Use
--no-default-features with the plain TCP config for a Rustls-free,
system-allocator baseline; metrics collection remains active.
The Tokio stress server default build includes tls-self-signed support. The
checked-in root config.toml enables tls_self_signed = true, so the local
stress client should use --tls-insecure with that default config. Use
--no-default-features with examples/nacelle-stress-server/configs/tcp.toml when
you need a Rustls-free plain TCP baseline.
CI-friendly scenarios should stay short and deterministic:
- baseline echo throughput
- max connection cap
- max request cap
- slow reader
- slow writer
- graceful shutdown under load
Heavy RPS and soak tests should run manually or nightly on dedicated Linux hosts.
Serve TCP with self-signed TLS
Use tls-self-signed for local load tests and auto-deploy flows that need a
certificate immediately. It implies the rustls provider.
#![allow(unused)] fn main() { use nacelle::core::pipeline::handler_fn; use nacelle::core::NacelleError; use nacelle::rustls::NacelleTlsConfig; use nacelle::tcp::{TcpRequestContext, TcpResponse, TcpServer}; use nacelle_reference_protocol::LengthDelimitedProtocol; let generated = NacelleTlsConfig::self_signed(["localhost", "127.0.0.1"])?; let server = TcpServer::<LengthDelimitedProtocol>::builder() .protocol(LengthDelimitedProtocol) .handler(handler_fn( |mut context: TcpRequestContext<LengthDelimitedProtocol>| async move { let mut response = Vec::new(); while let Some(chunk) = context.request_mut().body.next_chunk().await { response.extend_from_slice(&chunk?); } context.respond(TcpResponse::bytes(response)).await })) .build()?; server .serve_tcp_tls("127.0.0.1:8443".parse()?, generated.tls_config) .await?; Ok::<(), NacelleError>(()) }
Self-signed certificates are for local and automated test flows. Public edge deployments should use managed certificate material and a documented rotation process.
For OpenSSL-backed TCP TLS, enable openssl and use
NacelleOpenSslConfig::from_pem_files(...) with serve_tcp_openssl(...). Use
openssl-vendored only when the build machine has the tooling needed to compile
OpenSSL from source. Select either rustls or openssl; the backends are
mutually exclusive compile-time choices and cannot be swapped at runtime.
How the documentation is organized
This book uses four kinds of documentation:
- Tutorials are guided paths. They assume little context and aim for a working result.
- Topic guides explain how nacelle works and why it is shaped the way it is.
- How-to guides are recipes for specific tasks.
- Reference pages are precise descriptions of behavior, APIs, and protocol contracts.
Use tutorials when you are new, topic guides when you need a model of the system, how-to guides when you have a concrete job, and reference pages when you need exact details.
Architecture
Nacelle is organized as a small core plus protocol-specific transport crates.
Crate Layout
nacelle-core: shared handler and admission contracts, request/response body, limits, lifecycle, telemetry, and negotiated TLS connection metadata.nacelle-openssl: OpenSSL configuration reload and negotiated metadata extraction.nacelle-rustls: Rustls configuration reload, certificate parsing, SNI policy, and negotiated metadata extraction.nacelle-tcp: TCP/Unix socket server, protocol trait, connection loop, and listener runtime.nacelle-http: Hyper HTTP/1 server, HTTP request policy, and HTTP TLS listener integration.nacelle: convenience crate withcore,codec,tcp,http, andruntimecapability namespaces.examples/nacelle-reference-protocol: unpublished length-delimited protocol fixture used by examples, tests, benchmarks, and stress tools.examples/nacelle-examples: unpublished runnable examples and benchmarks.
The reference protocol intentionally stays out of nacelle-core and
nacelle-tcp. It demonstrates the public protocol and codec contracts without
becoming part of the published library API.
App Core And Protocol Adapters
Nacelle is organized so application behavior lives behind statically dispatched
handler boundaries. TCP handlers receive TcpRequestContext<P, AppState> and
complete requests with the response type associated with P, or explicitly
finish silently with context.complete(). Both TCP outcomes share one decoder,
handler, body-processing, and admission pipeline. Protocols map eligible
framework failures through Protocol::error_response; any returned typed
response uses the same encoder and bounded delivery path as handler responses.
HTTP handlers
receive HttpRequestContext<ConnectionState, AppState> and complete through
HttpResponse. Both state parameters default to ().
TCP Protocol implementations are adapters: they decode a wire format into
request metadata and encode responses back into frames. Swapping protocols
should not require rewriting the app core. The app-first serving path wires
concrete typed servers together with
NacelleApp::new().tcp(...).http(...).run(). Applications that need shared
dependencies start with NacelleApp::with_state(...). The app owns one stable
Arc<AppState> shared by every registered listener, plus runtime state,
telemetry, shutdown, and supervision. Handlers receive only &AppState through
RequestContext::app_state(); Nacelle provides no mutable accessor or runtime
replacement for the whole dependency root. nacelle::runtime::NacelleHost
remains available for services that need manual listener control.
Reloadable configuration belongs behind the application root rather than in
Nacelle. A configuration service may use ArcSwap or another snapshot mechanism
internally. A handler should acquire one owned snapshot for a request and avoid
holding a reload guard across .await.
Per-connection TLS metadata lives in nacelle-core. Concrete configuration,
certificate handling, reload policy, and negotiated metadata extraction live
in nacelle-rustls and nacelle-openssl. Transport crates retain listener
lifecycle and async I/O adaptation so provider crates do not depend back on TCP
or HTTP. The nacelle facade exposes mutually exclusive rustls and openssl
features plus the Rustls-based tls-self-signed helper. The backend is fixed at
compile time; there is no runtime provider abstraction or selection path. The
workspace defaults to its Rustls members, while validation runs OpenSSL through
explicit package and feature lanes.
Request Flow
listener
-> connection limit
-> connection task
-> protocol/HTTP decode
-> request limit
-> optional typed admission
-> handler
-> response body encode/stream
TCP and Unix socket listeners use the nacelle-tcp Protocol trait and its
associated request, response, and connection-state types to decode request
heads and encode bounded response frames. HTTP uses nacelle-http with Hyper
HTTP/1 and a transport-owned typed request/response pipeline.
Connection metadata carries the transport, a stable connection id, listener
label, peer and local addresses, local Unix socket path, effective peer IP, and
TLS metadata. The typed TCP pipeline presents this immutable metadata to
handlers as ConnectionInfo through RequestContext.
The pipeline model for connection-local application state is
ConnectionContext<State>. TCP protocols construct Protocol::ConnectionState
once per accepted connection. TcpServer and LocalTcpServer expose shared
state as Arc<P::ConnectionState>. SerialTcpServer and
LocalSerialTcpServer instead lend &mut ConnectionContext<P::ConnectionState>
to exactly one awaited handler at a time, avoiding an async mutex for state
confined to one serial connection loop. No dynamic extension map participates
in either request path.
The shared multi-thread Tokio runtime remains the default. Experimental
thread-per-core execution requires experimental-thread-per-core and currently
supports TCP, HTTP, Rustls TCP/HTTPS, required OpenSSL TCP, and optional
plaintext/OpenSSL TCP on Linux. Each selected worker owns a current-thread Tokio
runtime, LocalSet, reuse-port listener, protocol, and LocalHandler pipeline.
Accepted streams, handshakes, and connection tasks remain on the accepting
worker. Unsupported platforms fail configuration; Nacelle does not silently
switch runtime topology.
Serial mutable-state listeners support plain TCP, required OpenSSL, optional
OpenSSL detection, and Unix sockets in the shared runtime. Worker-local serial
listeners support plain TCP, required OpenSSL, and optional OpenSSL detection.
Rustls serial and worker-local Unix socket serial variants are not exposed.
Optional plaintext/OpenSSL detection requires
experimental-openssl-detection; required OpenSSL remains available with the
ordinary openssl feature.
ThreadPerCoreConfig::with_max_threads(...) caps the selected worker set after
automatic or explicit selection and before any worker thread is created. It
does not configure the caller-owned shared Tokio runtime.
Thread-per-core resource accounting is selected statically at startup. Global
mode shares all existing counters. Worker mode partitions finite connection,
request, streaming, and per-peer capacities in configured worker order.
Startup-budget partitioning lives in core so peer feature gates follow Cargo
dependency unification rather than the facade's feature selection.
Worker factories execute once per worker. Process-wide client pools, backend
limits, and other external resource budgets must be shared explicitly when they
must not scale with worker count. LocalTcpRuntimeConfig::with_state(...) and
LocalHttpRuntimeConfig::with_state(...) share one Arc<AppState> across
workers while protocol, handler, and connection state remain worker-local.
HTTP-specific edge policy remains in nacelle-http: Host, method, URI/header
shape checks, per-peer request rate limits, access logging, and security header
injection. TCP keeps protocol semantics in the protocol implementation and
shared lifecycle/limit enforcement in core.
Typed request admission
Admission<Context> returns an owned associated Permit, or a bounded
AdmissionRejection. LocalAdmission permits worker-local !Send state,
futures, and permits. Policies borrow the decoded head, connection metadata
and state, and the same typed application root as the handler. There is one
concrete policy, not a chain or a dynamically dispatched future.
TCP owns bounded head reads, prior-output delivery, and protocol error responses. HTTP owns Hyper parser configuration, effective peer resolution, status mapping, and the head-to-body transition. Core owns neither protocol's scheduling. Existing handler traits remain the application interface; internal service adapters carry admission and handling together through every server mode.
flowchart LR
Head["Decoded head"] --> Cheap["Size, policy and runtime capacity checks"]
Cheap --> Admit["One concrete admission future"]
Admit -->|"Pending"| Wait["Finite waiter count and deadline; no body work"]
Wait -->|"Allow"| Work["Body resolution and handler"]
Admit -->|"Ready allow"| Work
Admit -->|"Reject"| Reject["Transport error response; close unread body"]
Wait -->|"Deadline or reject"| Reject
Work --> Produce["Response production owns permit"]
Produce --> Release["Drop application permit"]
Release -.-> Deliver["Transport output and flush may remain"]
Only a pending policy starts an admission timer. TCP also flushes prior output
before awaiting that same pinned future, including buffers inside AsyncWrite.
Ready policies do not force a flush. HTTP creates no body bridge before
allowance and does not trigger 100 Continue by polling an unadmitted body.
Hyper may already have read body bytes with the head; this is not TCP's H/B
read allowance.
The application permit covers body resolution, handler work, and response production, not remote receipt. HTTP cancels or completes its body pump before transferring the permit into its concrete response body. TCP releases it after encoding, before any completion-callback flush. Error, cancellation, and drop release owned capacity. Runtime request gauges and response-byte metrics keep their separate existing completion boundaries.
Runtime State
NacelleRuntimeState owns shared budgets and counters. Connection, request, and
streaming-task limits are non-blocking atomic bounded counters.
NacelleLimits stores startup-only configuration. NacelleRuntimeControl
publishes total connection, global connection admission rate, and per-peer
connection-open rate thresholds through atomics on those same states. The
optional global rate checks all metered transports before total and peer limits
or setup; later rejections do not refund its fixed-window budget. Default request
handling does not read the live connection fields. Administrative updates
neither reset counters nor revoke permits; rate-state initialization is lazy,
bounded, and completed before enable. The global limiter uses one synchronized
window per state, independent of bounded peer tables. Optional per-peer
concurrency retains its sharded locks. The default-off peer-limits feature
compiles in peer concurrency maps, connection-open rate tables, HTTP request-rate
tables, and their configuration APIs. Global controls, connection metadata,
trusted-proxy resolution, and access logging do not require it.
App, host, and direct-server handles remain attached to installed state. Replacing shared builder state is a configuration error. Global worker accounting shares one handle; partitioned accounting exposes aggregate totals and deterministic shares, including zero. Fan-out is administrative, not an instantaneous cross-worker cutover. Startup rate-table capacity is divided before first enable rather than allocated independently from the process budget on each worker. See runtime control for update and installation contracts.
Optional TCP/Unix/HTTP connection tracking adds a bounded core registry of metadata
and administrative signals. TCP's opt-in owned admission token reuses that
registration across application-owned setup and direct serving, validates
runtime identity, and never reacquires connection capacity or rate budget.
Core controlled setup drops owned work before releasing its registration.
The transport owns setup, activity classification, and
I/O teardown; existing listener JoinSets still own tasks. The registry never
owns sockets or worker-local state. Partitioned states share duplicate-ID
detection while enforcing worker-local capacities and reclaim targets.
TCP arbitrates input against idle reclaim. HTTP cannot prove live parser/output
idleness and reports idle reclaim as unsupported; its explicit graceful
retirement delegates to Hyper with a registration-owned cancellation deadline.
The driver selects tracked/untracked activity outside the request loop; registry
locks occur at registration, removal, and administration, not request dispatch.
See tracked connections.
Bodies
NacelleBody has three internal shapes:
- empty/single chunk for fast small responses
- buffered chunks for decoded TCP bodies already in memory
- streaming channel for request/response bodies that move asynchronously
TCP protocols can override Protocol::max_request_body_bytes(...) to choose a
phase-aware body limit from the decoded head, immutable connection metadata,
and concrete connection state immediately after head decoding and before
additional body reads.
Shutdown
Listeners own a JoinSet of accepted connection tasks. Shutdown proceeds in
stages:
- signal shutdown
- stop accepting
- drain active connection tasks
- abort remaining tasks after the drain deadline
- emit shutdown telemetry
Task tracking is at the connection boundary, not the per-request hot path.
Observability
Telemetry is deliberately low-cardinality. Reasons are static strings such as
connections, request_body_bytes, or http_body_read.
Nacelle emits through the backend-neutral metrics facade and does not own an
exporter. NacelleTelemetry owns lifecycle, request, phase, error, and byte
metrics for all transports. Transports that can
provide extra low-cardinality detail attach a NacelleMetricsContext with
listener, protocol, transport, and TLS labels. Applications must install their
recorder before constructing these values so cached handles bind to it; without
a recorder the handles are no-ops.
NacelleTelemetryConfig separates connection, request, runtime, error, and
diagnostic costs. NacelleRequestMetrics has three modes: Off, Counters,
and the default CountersAndBytes. NacelleTelemetryDiagnostics independently
opts into request duration, the labelled request in-flight gauge, and TCP phase
timing; all three are off by default. with_metrics(false) gates every metric
domain without replacing those settings, so re-enabling metrics restores the
configured policy. Telemetry observers remain active while metrics are disabled.
TCP phase histograms additionally require the non-default phase-timing Cargo
feature. Enable them deliberately through with_diagnostics(...) on the server
or app when you need diagnostic detail and can afford the extra timers and
metric writes. Without phase-timing, TCP phase timer storage
and Instant calls are not compiled. Core/HTTP request paths do not start a
request timer unless duration metrics or HTTP access logging are enabled.
Runtime limits and backpressure
Runtime limits are enforced through NacelleRuntimeState. They are intended to
make overload predictable rather than perfectly invisible.
Key budgets include:
- active connections
- optional global connection admission attempts per second
- in-flight requests
- streaming body tasks
- optional per-peer connections
- request and response body size
- core handler timeout
- optional application-admission deadline and finite policy waiter capacity
- TCP read, write, final shutdown, and idle timeouts through
NacelleTcpLimits - HTTP header, body, write, keep-alive, and connection-age limits through
NacelleHttpLimits - TLS handshake timeouts through the TLS config types
The important production habit is to size limits together. A high connection count with large read and response buffers is a memory budget decision, not just a concurrency decision.
Live connection control
NacelleLimits contains startup-only request, streaming, body, handler-timeout,
per-peer concurrency, and rate-table capacity settings.
NacelleRuntimeControl changes connection thresholds on the installed state
without restarting listeners or resetting counters. Per-peer settings require
the default-off peer-limits Cargo feature; global controls do not.
To use both global and peer controls, enable the feature on the facade:
nacelle = { version = "0.4.0-rc.1", features = ["peer-limits"] }
Applications depending directly on nacelle-core, nacelle-tcp, or
nacelle-http can enable peer-limits on that crate instead. The following
example includes peer configuration:
#![allow(unused)] fn main() { use nacelle::core::{NacelleLimits, NacelleRuntimeState}; use nacelle::NacelleApp; let state = NacelleRuntimeState::new( NacelleLimits::default().with_connection_rate_limit_table_capacity(16_384), ); let app = NacelleApp::new().with_runtime_state(state)?; let control = app.runtime_control(); // Retain before moving the app into run(). control.set_max_connections(Some(8_000))?; control.set_global_connection_open_rate(Some(1_000))?; control.set_peer_connection_open_rate(Some(100))?; // Register listeners on app, then run it. The same handle remains live. control.set_max_connections(Some(0))?; // Pause new connections, not existing work. control.set_max_connections(None)?; // Unlimited total connections. control.set_global_connection_open_rate(None)?; // Disable the global budget. control.set_peer_connection_open_rate(None)?; // Disable the per-peer budget. let observed = control.snapshot(); }
The default total is Some(16_384) and both rates default to None.
set_global_connection_open_rate limits admission attempts across all listeners
sharing the state, including Unix sockets. set_peer_connection_open_rate
requires peer-limits and limits each IP independently. Configure either rate
independently or enable both. control.snapshot().max_connections_per_second
observes the global rate, while max_connection_opens_per_peer_per_second
observes the peer rate when the feature is enabled. Without peer-limits,
per-peer settings, methods, concurrency maps, and rate tables are compiled out.
Trusted-proxy resolution, connection metadata, and access logging remain
available.
Some(0) rejects all metered admissions for the total or global rate cap, or all
IP-based admissions for the peer rate cap. None disables the respective
ceiling. Unlimited connections still consume permits and update the existing
gauges. Unix sockets have no invented peer IP: they consume total capacity and
global rate budget but bypass IP-based concurrency and rate checks.
Connections are metered by default. For a dedicated internal listener, such as
an HTTP health endpoint that must remain reachable during overload,
with_connection_accounting(NacelleConnectionAccounting::Exempt) bypasses the
total, global rate, per-peer, and administrative connection registry checks. Direct TCP
serving can select the same behavior with
NacelleConnectionMeta::with_accounting(...). Exemption does not bypass request,
streaming, body, timeout, or application-admission limits. HTTP path-based
request exemption is a separate request-accounting concern because the path is
not known when the connection is accepted.
Lowering below occupancy does not evict connections. Admissions already racing an update may finish with the threshold observed by that check; later checks read the new value. The order is optional global rate, total capacity, optional peer concurrency, then optional peer rate. Global rate budget is not refunded after a later rejection, transport setup failure, disconnect, or permit drop. Earlier rejection does not consume peer rate budget, and peer rate rejection releases previously acquired capacity.
The global limiter uses fixed one-second windows anchored at first enable.
Changing or disabling it retains its window and count; admissions while disabled
are not counted. Re-enabling within the same window does not grant a fresh
budget. Fixed windows can admit bursts across a boundary and are not a sliding
one-second guarantee. Disabled global rate admission does not read the clock or
lock a window. An enabled global rate uses one constant-size synchronized window
per state and needs no peer-table capacity. Exhaustion reports
NacelleResourceLimitReason::ConnectionRate with telemetry reason
connection_rate. Listener rejection closes the accepted socket before setup,
including TLS; it is not an HTTP 429 response.
First peer rate enable allocates the bounded table on the administrative path
before publishing the rate. Changing or disabling it retains entries and their
fixed-window clocks. Opens while disabled are not counted retroactively.
Table capacity cannot change at runtime. Zero startup capacity prevents peer
rate enable, not global rate enable. Finite total caps and global rates must be
below usize::MAX; peer rates must also fit u32. Invalid updates return
NacelleError::Configuration without changing the threshold.
For applications migrating from 0.3.3, replace
NacelleLimits::with_max_connections_per_second(n) with
control.set_global_connection_open_rate(Some(n))? on the installed 0.4 state.
The global budget remains disabled until configured. Do not substitute
set_peer_connection_open_rate: a per-peer budget is not a global budget.
For applications using the earlier 0.4 RC API, rename
set_connection_open_rate(...) to set_peer_connection_open_rate(...) and
enable peer-limits. Invalid global and peer rates both return
NacelleConfigurationError::ConnectionOpenRate. Per-peer concurrency and
HTTP request-rate APIs also require this feature. Their behavior is unchanged
when enabled; compiling the feature does not enable any rate threshold.
state.control(), app/host runtime_control(), and direct-server
runtime_control() address their installed state. Use the app/host handle when
that object owns the listeners. A transport's own handle cannot be silently
rebound to the app/host state: installation returns a configuration error
instead. Configure startup state before exporting handles or cloning servers.
Fallible with_runtime_state(...) calls permit reinstalling the same state but
reject replacing one still shared by a handle, listener, server clone, or permit.
startup_limits() borrows only immutable configuration; control.snapshot()
returns owned live thresholds. This replaces the removed connection fields and
setters on NacelleLimits, the old limits() accessor, and facade with_limits
setters. Host enable_* methods and runtime-state installation now return
Result; propagate configuration failures with ?.
App *_dual_stack* registration also returns Result: it installs app runtime
state before cloning the server for IPv4 and IPv6. Select startup state before
registering those listeners.
Worker accounting
control.scope() distinguishes Shared from Partitioned { partitions }.
ThreadPerCoreLimits::global(state) shares one state across workers.
ThreadPerCoreLimits::worker(startup_limits, count) returns independent counters
with an aggregate control(). Pass that policy into
LocalTcpRuntimeConfig::new(...) or LocalHttpRuntimeConfig::new(...); their
fallible constructors check the effective worker count. Obtain the installed
aggregate handle through the resulting config's runtime_control().
Aggregate finite values are process totals, divided by quotient and remainder in configured worker order. A total below the worker count leaves zero shares, which reject rather than becoming unlimited. Spare capacity is not borrowed between workers. This includes global connection admission rates: each worker has its own fixed window, and unused quota is not borrowed. Disabling a global rate disables it on every worker, including zero-share workers. Peer rate-table capacity is also divided at startup, even while peer rates are disabled; enabling peer rates requires at least one reserved entry per worker. No peer table is allocated until enable, and the process budget is not multiplied by worker count. Global rate limits do not allocate peer tables.
Peer budgets remain partitioned when peer-limits is enabled through a direct
dependency on nacelle-core or a transport crate rather than through the facade.
Administrative fan-out and aggregate snapshots are serialized; admission on
different workers does not switch instantaneously. Use the aggregate handle,
not independent updates through state_for(...).control(). Each worker keeps
its own rate window and counter history. A shared scope identifies one state,
not necessarily the entire process if the caller constructed separate states.
Startup configuration
Initial connection thresholds
NacelleRuntimeState::new_with_connection_limits(startup, thresholds)? configures
initial live thresholds before installing the state in an app, host, or server.
It uses the live setters' validation and state rather than a second admission
policy:
#![allow(unused)] fn main() { use nacelle::core::{NacelleConnectionLimits, NacelleLimits, NacelleRuntimeState}; let state = NacelleRuntimeState::new_with_connection_limits( NacelleLimits::default(), NacelleConnectionLimits { max_connections_per_second: Some(1_000), ..Default::default() }, )?; }
This example retains the default 16,384 concurrent-connection cap. The
max_connection_opens_per_peer_per_second field is available with peer-limits.
None, zero, numeric bounds, and peer-table requirements match the live
controls. Rate windows start during construction; subsequent live updates
retain their history. Invalid configuration returns no partially configured
state. NacelleRuntimeState::new(startup) retains its existing defaults.
Application-owned transport setup
TCP and Unix applications that perform their own TLS or transport setup can
reserve an owned TcpConnectionAdmission before setup and transfer it into
shared or serial serving. The same runtime admission, rate budgets, connection
gauges, and optional tracking apply exactly once. Automatic admission remains
the default. See the ownership and cancellation contract.
Tracked connections
Tracking is off by default. Enable a finite registry before installing runtime state, then obtain the control handle from the app, host, or direct server that owns that state:
#![allow(unused)] fn main() { use nacelle::core::{NacelleConnectionTracking, NacelleLimits, NacelleRuntimeState}; use nacelle::NacelleApp; let state = NacelleRuntimeState::new(NacelleLimits::default() .with_connection_tracking(NacelleConnectionTracking::new(8_000)?)); let app = NacelleApp::new().with_runtime_state(state)?; let control = app.runtime_control(); control.set_max_connections(Some(8_000))?; // Register listeners and move app into run(); retain control for administration. let snapshots = control.connections(64); // None if disabled; otherwise owned metadata. control.set_max_connections(Some(4_000))?; let reclaim = control.reclaim_idle(128); // Explicit, best-effort idle selection. if let Some(connection) = snapshots.and_then(|mut entries| entries.pop()) { let lookup = control.connection(connection.connection.connection_id); if connection.capabilities.graceful_retirement { let retire = control.retire_connection( connection.connection.connection_id, std::time::Duration::from_secs(5)); } else { let close = control.close_connection(connection.connection.connection_id); } } }
The registry capacity is independent of the live connection ceiling and cannot
be resized or enabled retroactively. Zero and unrepresentable capacities are
rejected. Setting the live ceiling to None does not bypass registry capacity.
Registration follows the existing connection/peer/rate admission checks;
registry rejection can therefore consume an allowed connection-open rate slot.
Full storage and duplicate live custom IDs report ConnectionRegistry and
DuplicateConnectionId. No protocol or request work starts after rejection.
TCP, Unix, and their existing shared/local/serial TLS variants register before controlled setup. Setup, TLS detection/handshake, partial heads, queued input, admission, bodies, handlers, callbacks, and unflushed output are not idle. Only the driver establishes idle after the underlying writer has flushed and no accumulated input or work remains. New input and reclaim compete atomically: if reclaim wins, that input is not dispatched. Bytes not yet observed by Nacelle can still be discarded by idle reclaim.
Shared and worker-local HTTP/1 and Rustls HTTPS also register before setup.
Their snapshots expose idle_reclaim: false and graceful_retirement: true;
TCP/Unix expose the reverse. Hyper 1.10.1 has no public live-idle query covering
partial/pipelined input and pending output. Established HTTP connections remain
conservatively Active, even between requests. Request completion, response
body EOF, and application-permit release are not evidence of socket flush or
remote receipt. No second parser or per-request registry hooks infer idleness.
connection(id) distinguishes TrackingDisabled, Unknown, and Found.
Snapshots are owned, unordered observations, not live task handles or a stable
pagination mechanism. Unknown includes finished IDs and IDs outside a worker
handle's scope. Custom IDs must remain unique across the tracked group and
must not be reused while administrative callers can hold stale IDs.
close_connection(id) distinguishes disabled/unknown, Selected, and
AlreadyClosing. Forced close can cancel setup, active requests, response
delivery, and pending normal shutdown. Selection is not teardown confirmation.
TCP returns NacelleError::ConnectionTerminated(Forced) from direct serving,
does not invoke Protocol::error_response, and does not retry writes, flush,
or shutdown. Outstanding completion callbacks resolve as cancelled, not
delivered; already resolved callbacks are not repeated. Peers may have received
partial or complete output. Borrowed serial I/O remains with the caller, who
must not resume the cancelled protocol.
retire_connection(id, timeout) requests graceful HTTP/HTTPS retirement,
including during TLS setup. The absolute deadline starts at selection and covers
setup, response production, output, and shutdown. Hyper disables keep-alive and
continues polling accepted work; administration does not grant application
admission or trigger 100 Continue. Expiry forcibly drops remaining work and
I/O, not successful delivery. Existing shorter transport deadlines still apply.
Zero requests immediate expiry; an unrepresentable duration returns
DeadlineOutOfRange. Other outcomes are TrackingDisabled, Unknown,
Unsupported (including TCP/Unix), Selected, and AlreadyClosing.
Repeated retirement does not extend the deadline. close_connection can
escalate a retiring connection to immediate cancellation.
reclaim_idle(budget) selects at most budget new idle closes toward each
partition's current target. None has no gap. Existing closing reservations
are subtracted before selecting more, including across concurrent scans.
Reports include observed occupancy, target, already-closing count, new
selections, and the unfilled gap. Each partition also reports unsupported:
nonclosing entries that cannot prove safe idle eligibility, including HTTP.
Insufficient idle entries or budget leave a nonzero gap; HTTP connections may
continue blocking new admissions. Lowering a target alone never scans or
cancels work.
Connection capacity remains occupied until work/I/O teardown, then the entry
is removed. Setup failure, EOF, error, panic unwinding, cancellation, and task
abort use the same registration owner. Listener JoinSet supervision and
stop/drain/abort shutdown remain separate from administrative selection.
Listener shutdown does not automatically request per-connection HTTP retirement.
Worker accounting divides registry capacity at startup, including zero shares that reject rather than disabling tracking. All partitions share duplicate-ID detection but retain their own capacity and target gaps. Use the aggregate handle; spare capacity is not borrowed across workers.
Storage grows on registration, retains its bounded map high-water allocation, and holds only metadata/signals, not sockets, application state, or tasks. There is no registry allocation/lock or administrative waiter on tracking-off connections. Tracked TCP request activity uses atomics; HTTP adds no request activity hooks. Only a selected graceful retirement starts an administrative deadline. Snapshot/reclaim scans can inspect the entire allocated registry even with a small result/selection budget; registration and removal wait for that lock. Choose capacity and scan frequency together. See lifecycle measurements.
Application admission budgets
Use AdmissionConfig::new(timeout, max_pending) with one concrete application
policy. Both values must be positive; timeouts must be representable, and
capacity must be below usize::MAX. Configure TCP head-read limits before
enabling TCP admission. HTTP uses Hyper's parser bounds, not TCP's exact H/B
allowance; see HTTP hardening.
The framework acquires request capacity and then a finite waiter slot before
invoking the policy. Waiter accounting covers the policy invocation, including
an immediately ready result, and ends when admission resolves or is cancelled.
Server clones share this count. Independently constructed listeners and worker
factories have independent counts: size their combined waiting-head budget
explicitly. A process-wide backend budget belongs in shared application state,
for example an Arc<Semaphore> returning an owned permit.
The admission deadline begins on the first pending poll. On TCP it also covers flushing prior output. The handler deadline starts only after allowance; body read and response-write deadlines retain their transport responsibilities. A blocking policy cannot be preempted by an async timeout. Queue discipline belongs to the policy: Tokio semaphore FIFO is preserved by awaiting the same future, but Nacelle does not promise fairness across listeners or workers.
Application permits remain held through body resolution and response production. They do not extend runtime request metrics to remote delivery. The unlabelled runtime permit gauges belong to the independent runtime metric domain; changing request metric mode or application admission does not move or duplicate those gauge release boundaries. Silent TCP completion releases after body resolution; HTTP response bodies own their permits after the service future returns. EOF, response error, early drop, task cancellation, and suppressed HEAD/empty bodies release ownership. No application permit is retained just to flush queued output.
For admission-enabled TCP failures, the admission timeout supplies a finite fallback for error-response writes and closing flush/shutdown when those TCP timeouts were disabled, including malformed or oversized heads rejected before request dispatch. Explicit TCP timeouts take precedence. Normal admitted responses retain the selected transport deadlines. Cancellation during a prior-response flush abandons that delivery and closes without retrying partially written bytes or generating another error response.
Transport and body settings
Start from NacelleLimits::default() and tune shared resource budgets for the
deployment. Use NacelleTcpLimits for TCP socket timeouts and
NacelleHttpLimits for HTTP edge timeouts and keep-alive behavior. Active
connections, in-flight requests, streaming tasks, body sizes, handler timeouts,
and transport timeouts are bounded by default.
Optional deadlines can be disabled without direct field mutation. Use
NacelleLimits::without_handler_timeout(), the TCP
without_read_timeout(), without_write_timeout(),
without_shutdown_timeout(), and without_idle_timeout() builders, and the
corresponding HTTP without_*_timeout() or
without_max_connection_age() builders. Keep bounded defaults for public-edge
listeners unless another layer enforces an equivalent deadline.
TCP idle and read deadlines are independent. The default 120-second idle deadline bounds waiting for the first byte of a message with an empty input buffer. Once bytes are available, the 30-second read deadline bounds decoding that message without resetting on additional bytes. Request-body processing starts a separate absolute deadline using the same timeout, covering all remaining body reads and streaming channel waits. Body progress does not restart this deadline. Expiry cancels a still-running handler even when handler timeouts are disabled or the body channel is full. Idle time does not include active messages, bodies, handlers, or response delivery.
In 0.3.2, this replaces the earlier read-or-idle fallback: silent connections now
use the idle deadline rather than the read deadline. Set
with_idle_timeout(Duration::from_secs(30)) to retain a 30-second silent-connection
limit. without_idle_timeout() now permits indefinite waiting for the next
message while still bounding active reads. without_read_timeout() leaves idle
waiting bounded but makes active message and body reads unbounded; the idle
deadline no longer protects those reads.
Recommended presets:
- Internal service: keep defaults, set body limits to the largest expected payload, and run behind process supervision.
- Internet-facing behind proxy: cap connections and requests to the container budget, keep 30 second transport timeouts, and let the proxy own coarse traffic filtering or certificate automation when desired.
- Proxy-aware HTTP: trust only known proxy addresses and select the authoritative forwarding header; see HTTP hardening.
X-Forwarded-Foris the default;Forwardedrequires explicit selection. - Direct HTTPS listener: enable
http,rustls, load certificate/key material throughNacelleTlsConfig, configure an SNI allowlist withfrom_pem_with_allowed_server_namesorfrom_der_with_allowed_server_names, set a short TLS handshake timeout, configuremax_connections_per_peerandmax_connection_opens_per_peer_per_second, enable HTTP access logs, and attachNacelleHttpPolicywith Host, method, URI, header, security-header, and per-peer request-rate limits. - Direct TCP Rustls listener: enable
tcp,rustls, load certificate/key material throughNacelleTlsConfig, register it withNacelleApp::tcp_tls(...), and keep protocol-level authentication/authorization in the application protocol. - Direct TCP OpenSSL listener: enable
tcp,openssl, load certificate/key material throughNacelleOpenSslConfig, register it withNacelleApp::tcp_openssl(...), and configure theSslAcceptoryourself when you need OpenSSL-specific policy. - Local load-test/autodeploy HTTPS: enable
tls-self-signedand callNacelleTlsConfig::self_signed(...); do not treat generated certificates as a public trust or rotation strategy. - High concurrency: reduce TCP buffer capacities before raising
max_connections, and tuneNacelleTcpLimitsseparately from shared resource budgets.
Memory sizing:
This sizing formula requires a finite effective connection ceiling. Use the
finite cap from control.snapshot().max_connections. For None, substitute a
finite boundary enforced externally. A lower live cap does not reduce existing
occupancy immediately; size for retained connections as well as future
admissions. Zero pauses admission, not memory use by existing connections.
connection_budget =
effective_connection_ceiling * (read_buffer_capacity + response_buffer_capacity)
body_budget =
concurrent_buffered_or_streaming_bodies * max_request_body_bytes
total_budget =
connection_budget + body_budget + handler/backend/runtime headroom
Nacelle does not attempt to account for total process memory. Keep a process or container memory limit in place and use the sizing formula above when selecting connection, body, and concurrency limits.
TCP processes requests sequentially per connection.
request_body_channel_capacity controls the queued streaming chunks between
the socket reader and handler. HTTP uses Hyper's internal buffers plus Nacelle's
body queue, so leave extra headroom when enabling large request bodies.
For TCP protocols, NacelleLimits::max_request_body_bytes is the default body
limit. Override
Protocol::max_request_body_bytes(request, connection, state, default_limit) to
choose a per-request limit from the decoded head, immutable connection metadata,
and concrete connection state before body-specific allocation or additional
body reads. There is no dynamically typed connection extension.
With experimental-thread-per-core, server factories execute once per
configured worker. Nacelle's global or partitioned runtime counters do not
partition external client pools or backend resources automatically; pass
explicitly shared resources into worker factories when process-wide budgets
must remain global.
Cap Nacelle-owned worker threads after any worker-selection strategy with
ThreadPerCoreConfig::with_max_threads(...). The effective capped worker count
must also be used when constructing ThreadPerCoreLimits::worker(...). Shared
runtime threads belong to the caller's Tokio runtime and are configured there.
Dangerous configurations:
- unbounded connections with large per-connection buffers
- large body limits without a process/container memory limit
- disabled timeouts on internet-facing listeners
- direct internet-facing HTTP without Host/header/method/URI policy
- direct internet-facing TLS without an SNI allowlist
- direct internet-facing listeners without per-peer connection caps
- direct internet-facing listeners without per-peer connection-open rate caps
- direct internet-facing HTTP without per-peer request caps and access logs
- trusting forwarded peer headers without an explicit trusted proxy list
- generated self-signed certificates used as a long-lived public-edge certificate strategy
- high keep-alive connection counts without proxy-level idle limits
TLS certificate rotation:
#![allow(unused)] fn main() { let tls = NacelleTlsConfig::from_pem_files("cert.pem", "key.pem")?; tls.reload_from_pem_files("next-cert.pem", "next-key.pem")?; }
Reloads affect new TLS handshakes. Existing connections continue with the configuration negotiated when they connected.
Rustls certificate-only reloads serialize with other reloads/replacements and
preserve the current SNI allowlist. Invalid material leaves the prior snapshot
intact. Explicit replace_server_config* APIs install the supplied policy and
clear the stored allowlist for future certificate-only reloads.
NacelleOpenSslConfig::from_pem_files uses Mozilla's v5 intermediate profile
and requires TLS 1.2 or newer. TLS 1.3 is enabled when supported by the linked
OpenSSL-compatible library. Legacy protocol policy requires an explicitly
configured acceptor through from_acceptor.
Operations model
Deployment Shape
Recommended internet-facing shape:
client -> proxy/load balancer/TLS -> Nacelle service
The proxy should own TLS, coarse connection filtering, and external idle timeouts. Nacelle owns application limits, protocol handling, body limits, and graceful shutdown.
Startup
Use explicit limits and print the effective config for stress or benchmark services. For production services, record:
- process version and git SHA
- configured limits
- listener addresses
- feature flags
- allocator settings
Thread-per-core mode requires experimental-thread-per-core, is experimental,
and is Linux-only. Select workers explicitly, record logical CPU ids and
affinity settings, and treat any bind, affinity, or worker initialization
failure as a whole-runtime startup failure. TCP, HTTP, Rustls TCP/HTTPS,
required OpenSSL TCP, and optional plaintext/OpenSSL TCP have worker-local
stacks; optional OpenSSL detection additionally requires
experimental-openssl-detection. Performance qualification remains under
implementation. Use ThreadPerCoreConfig::with_max_threads(...) to cap any
selected worker set; configure the caller-owned Tokio builder separately for
shared-runtime thread limits.
Shutdown
Use NacelleApp::with_ctrl_c_shutdown() for the standard signal path, or pass a
shared NacelleShutdown through NacelleApp::with_shutdown(...). Configure the
drain deadline with with_shutdown_drain_timeout(...). Advanced manual hosts
can use nacelle::runtime::NacelleHost::shutdown_and_wait_timeout(...). Short
deadlines protect deploy velocity but can abort in-flight work.
Expected shutdown telemetry:
- shutdown requested
- listener stopped accepting
- drain started
- drain completed or timed out
- active connections aborted
Administrative connection management
Configure tracking at startup and retain the installed runtime_control().
Lowering a connection target only limits new admissions. Call reclaim_idle
explicitly to retire idle connections; repeat only after observing teardown,
not in a busy loop. Concurrent scans account for existing closing reservations,
but cannot guarantee the target when connections remain active. HTTP/HTTPS
report idle reclaim as unsupported rather than guessing from request counters.
Forced close_connection is cancellation, not graceful drain. It may discard
partial output and does not wait for TLS close_notify. Do not expose this
capability to untrusted callers or put connection IDs into metric labels.
The static forced-close reasons are administrative_close and idle_reclaim.
TCP setup that fails before its open event does not manufacture a close event.
After opening, TCP pairs that event with exactly one close outcome on normal
completion, cancellation, or task abort, including exempt connections and
connections with administrative tracking disabled.
HTTP emits its open event before setup, and pairs it with exactly one close
outcome through TLS failure, normal completion, cancellation, or task abort.
For HTTP/HTTPS, retire_connection(id, timeout) disables keep-alive and keeps
polling accepted work through response delivery. The deadline starts at selection,
including any remaining TLS setup; expiry cancels outstanding work and I/O.
Success reports administrative_retire; expiry reports
administrative_retire_timeout and timeout operation administrative_retire.
Neither result proves remote receipt. Repeating retirement does not extend its
deadline; forced close can escalate it. Existing request and byte metric
completion boundaries and metric labels are unchanged.
The runnable example demonstrates explicit forced retirement on Ctrl-C:
cargo run -p nacelle-examples --bin tcp_connection_control -- 127.0.0.1:8080
The HTTP example requests bounded graceful retirement on Ctrl-C:
cargo run -p nacelle-examples --no-default-features --features http --bin http_connection_control -- 127.0.0.1:8080
Both examples install one typed semaphore admission policy with a one-second
wait deadline and 64 framework-owned waiters, explicitly enable bounded
connection tracking, and retain the runtime control before run(). Ctrl-C
pauses new connections and then stops the listener. An admission already racing
the pause can complete after the snapshot; the listener's drain deadline remains
the final bound. Normal listener shutdown remains stop/drain/abort and does not
automatically administratively retire each HTTP connection.
See tracking outcomes and ownership
for selection versus teardown, borrowed I/O, and worker scope.
Metrics To Watch
server.runtime.workersserver.connection.activeserver.request.activeserver.streaming_task.activeserver.connection.acceptedserver.connection.closedserver.request.startedserver.request.completedserver.connection.rejectedserver.request.rejectedserver.request.timed_outserver.timeoutsserver.request.failedserver.request.body.sizeserver.response.body.size
Alerts should focus on sustained saturation, rising rejections, timeout spikes, and memory approaching the configured budget.
Runtime Topology
Nacelle parallelizes connection handling by spawning onto the ambient Tokio runtime, so a listener started on a current-thread runtime is confined to a single core regardless of how many cores the host has. The first listener to start — on any transport — reports the topology it observed:
INFO nacelle: listener started transport="http" runtime="multi_thread" workers=12
A single-worker topology additionally emits a warning, and the worker count is
published as the server.runtime.workers gauge. The gauge belongs to the
runtime metric domain, so with_metrics(false) or with_runtime_metrics(false)
suppresses it; the log lines are not metrics and are always emitted.
Thread-per-core hosts give each worker its own current-thread runtime, so the
ambient handle reports one worker per runtime. run_thread_per_core declares
the process-wide worker count before starting workers, so these deployments
report runtime="thread_per_core" with the real worker count rather than a
false single-core warning. Hosts that build their own per-worker runtimes
should call nacelle_core::runtime::declare_worker_topology to get the same
behavior.
Alert on server.runtime.workers == 1 where the process is expected to span
several cores; it is the clearest signal that the process is leaving throughput
on the table.
Benchmarking
Nacelle emits metrics through the metrics facade according to
NacelleTelemetryConfig. Connection, runtime, and error domains are on by
default. NacelleRequestMetrics::CountersAndBytes is the request default;
Counters keeps lifecycle counters without byte histograms and Off suppresses
both. Request duration, labelled request in-flight, and TCP phase timing are
independent fields in NacelleTelemetryDiagnostics and are off by default.
Use NacelleTelemetry::default().with_metrics(false) to suppress all Nacelle
metric domains while retaining any application recorder. This global gate does
not erase individual domain settings, and telemetry observers remain active.
Use with_connection_metrics, with_request_metrics, with_runtime_metrics,
with_error_metrics, and with_diagnostics for independent policy.
HTTP listeners skip connection metric context allocation when connection metrics
are disabled; connection observer events remain active.
A shared NacelleRuntimeState has one runtime-metric policy; configure servers
sharing that state consistently before serving traffic.
The stress server prints a console snapshot every 5 seconds. Its recorder
aggregates request/response body-size samples into constant-space byte totals
across labels, using fixed cache-line-isolated shards and off-path draining;
other metrics use the metrics-util debugging recorder. Snapshot window
boundaries are approximate; successive drains conserve non-saturating totals.
This stress-only aggregation does not change the library's histogram contract.
Production applications should install their chosen
recorder before constructing Nacelle runtime state, telemetry, or servers. If no
recorder is installed, facade handles are no-ops.
Request duration metrics remain opt-in through NacelleTelemetryDiagnostics.
With the default config, core/HTTP request paths avoid request timer work unless
HTTP access logging is enabled.
Compile and activate TCP phase timing only for a diagnostic build:
[dependencies]
nacelle = { version = "0.3.0", features = ["phase-timing"] }
#![allow(unused)] fn main() { let telemetry = NacelleTelemetry::default().with_diagnostics( NacelleTelemetryDiagnostics { tcp_phase_duration: true, ..NacelleTelemetryDiagnostics::default() }, ); }
The server.phase.duration_ms histogram uses a low-cardinality phase label:
| Phase | Boundary |
|---|---|
socket_read | One completed transport read, including asynchronous wait but excluding decode. |
decode | One protocol decoder invocation; a request may require more than one invocation. |
request_body_read | Request-body assembly or remaining streaming-body drain. May include socket_read operations. |
handler | The awaited application handler, including application body consumption and response construction. |
response_encode | One synchronous protocol response-frame encoder invocation. |
socket_write | One response write batch or explicit transport flush, including asynchronous wait. |
These are operation histograms, not a per-request trace. Do not add their
percentiles to infer round-trip latency: pipelining can decode several requests
from one read, streaming overlaps body reads with the handler, and response
coalescing can write several completed requests in one batch. Use
server.request.duration for server request processing and client-side
latency for actual round-trip time.
The server cannot measure TCP handshake duration because the kernel completes
it before accept() returns. Connection accepted, active, and closed metrics
remain available; TLS handshake timing is not currently emitted as a phase.
Canonical metric names are resource-first. Instrument type is documented here rather than embedded in the metric name:
| Metric | Type | Notes |
|---|---|---|
server.runtime.workers | Gauge | Worker threads serving the process, reported once by the first listener to start. A value of 1 means throughput is capped to one core. Thread-per-core hosts report their declared process-wide worker count. |
server.connection.active | Gauge | Current active connections. Listener-labeled series include `accounting="metered |
server.request.active | Gauge | Current active requests. Protocol-labeled series provide request-level detail; unlabeled series represent runtime permit usage. |
server.streaming_task.active | Gauge | Current runtime streaming body tasks. |
server.connection.accepted | Counter | Accepted connections, labeled by listener/transport/TLS and `accounting="metered |
server.connection.closed | Counter | Closed connections, labeled with accounting and close reason where available. |
server.connection.rejected | Counter | Connections rejected before acceptance. |
server.request.started | Counter | Requests started. |
server.request.completed | Counter | Requests completed, labeled by status where available. |
server.request.rejected | Counter | Requests rejected before handler execution. |
server.request.timed_out | Counter | Request failures caused by a timeout, labeled by operation. |
server.request.failed | Counter | Requests failed before normal completion. |
server.request.body.size | Histogram (By) | Request body size per completed request. |
server.response.body.size | Histogram (By) | Response body size per completed response. |
server.request.duration | Histogram (s) | Request duration, opt-in. |
server.phase.duration_ms | Histogram | TCP operation duration; requires compile-time and runtime opt-in. |
Run microbenchmarks before and after hot-path changes:
cargo bench -p nacelle-examples --features "bench tcp"
Performance model
nacelle's high-throughput TCP path is sensitive to small per-request costs. When comparing runs, keep these variables fixed:
- commit
- Linux kernel and CPU governor
- allocator configuration
- server threads
- connection count
- pipeline depth
- payload size
- TLS versus plain TCP
- stress client version
Use the performance how-to for repeatable command lines.
Do not use a repository-wide RPS number as a baseline. Compare commits on the same host with the same kernel, governor, allocator, features, transport/TLS mode, configuration, workload, and client revision.
Suggested local benchmark:
cargo bench -p nacelle-examples --features "bench tcp"
The runtime_limits benchmark group covers connection/request permit
acquire/drop overhead. Watch it closely after changes to NacelleRuntimeState.
Global connection rate limiting is disabled by default. Disabled admission reads
its atomic threshold but does not read a clock or lock a window. Enabling
set_global_connection_open_rate(...) adds a clock read and a synchronized
constant-size window on metered connection admission, not on each request.
Shared-state mode serializes those window updates across listeners and workers;
partitioned worker mode uses independent windows and fixed quota shares. Keep
both global and per-peer rate settings identical when comparing connection-churn
profiles. These costs are not a measured throughput comparison.
The default-off peer-limits feature compiles in per-peer concurrency and rate
tracking. Keep its selection fixed between revisions; leaving thresholds
disabled in a peer-enabled build is not the same build configuration as
compiling the tracking out. Add peer-limits to the benchmark feature list to
include peer admission and distinct-peer rate-table cases.
Concurrent requests without pipelining
Use pipeline depth 1 when evaluating request/response services. A connection then waits for each response before sending another request; additional connections provide concurrency without batching requests on one socket. Keep a pipelined case as a separate control, not as a substitute for this workload.
Measure server CPU per completed request alongside throughput and p50/p99 latency. Separate user CPU from kernel CPU: small loopback messages can spend most server CPU in socket I/O, hiding improvements in the Rust request path. Use disjoint physical cores for server and client and record their NUMA placement. Compare same-node and cross-node single-connection placement separately, keeping worker counts and CPU masks identical between binaries. A node-local process mask still permits worker migration and SMT sharing; it is not individual-core pinning. A client-bound run cannot establish server capacity.
For the one-connection case, use one persistent socket, pipeline depth 1, one
listener, and one client worker. Immediate delivery prevents batching from
confounding this measurement. The stress fixture's serial handler lends
connection state rather than cloning a shared context per request, and plaintext
serial I/O uses specialized borrowed TCP halves. An explicit one-worker
--worker-cpus list selects a dedicated current-thread listener; omitting it
uses the supervision runtime: current-thread for one unpinned immediate listener,
and one-worker multi-thread for coalescing or dedicated listeners. These are
distinct configurations, not interchangeable baselines.
The client normally uses a separate Tokio worker pool. Its opt-in
--current-thread mode places the same connection tasks and I/O on the main
thread. Measure client CPU/request, RSS, and thread count as well as server
CPU and end-to-end throughput. A client-runtime gain on an unchanged server
does not establish higher server capacity. Keep the multi-thread client
default for multi-core coalescing load and hold its runtime fixed in
server-only comparisons.
The stress client's opt-in --blocking-io profile assigns a blocking I/O worker
to each persistent pipeline-1 connection. This changes socket wait/scheduling
costs without adding requests in flight or changing the negotiated TLS
connection. It also adds threads and per-worker allocator/runtime memory.
Treat any improvement as an end-to-end driver profile result, not server-code
capacity evidence; keep this option off unless the measured trade-off fits
the workload.
For the sequential TLS target, keep exactly one request outstanding on each persistent connection. Compare TLS and plaintext using identical 256-byte requests, responses, and immediate delivery. Warm up those same connections, then report measured mean RTT and p50/p95/p99 with client/server CPU separately. Current stress-client RTT includes request preparation and TLS write; older after-write measurements omit that portion of the round trip.
Profile the complete lifecycle before changing buffering or synchronization. Socket-read wall time includes peer and scheduler waits; overlapping client and server phase durations cannot be added to reconstruct RTT. Allocation-counting and phase-timing stress-tool features are diagnostic-only and default off. Allocation counters observe Rust global-allocator calls, not native C internals. Do not infer TLS mutex contention from a generic split symbol alone, or propose a logging queue when formatting already runs outside request processing. See sequential TCP/TLS comparisons.
The request_permit_contended benchmark compares owned and transport-scoped
borrowed permits on one shared runtime state with 1, 4, and 8 worker threads.
Each worker acquires/releases 1,024 permits per iteration. Thread startup is
excluded; barrier synchronization is included. No metrics recorder is installed.
This isolates accounting contention, not socket throughput.
Successful-path ownership and dispatch
Connection tracking costs
Tracking is disabled by default. Enabling it adds connection-time registry allocation/locking and a cancellation waiter per connection. TCP uses atomic activity transitions at input/idle boundaries. HTTP also waits for graceful retirement but adds no request activity hooks; it cannot prove safe idle eligibility. Only a selected retirement creates an administrative timer. Tracking does not add per-request registry locks, timers, or metrics. Bounded registry map storage retains its high-water allocation; TLS metadata, snapshots retained by callers, sockets, and transport buffers must be budgeted separately.
Run the explicit lifecycle profiles:
cargo bench -p nacelle-examples --features bench,tcp --bench connection_lifecycle
registry_churn compares registration/drop with tracking off/on.
tracking_tcp compares one and 64 requests per direct-I/O connection, with
immediate delivery and metrics disabled. These are in-memory driver cases,
not network throughput. The 256-entry idle/reclaim profiles isolate registry
administration; the four-worker profile also includes channel dispatch/replies,
but excludes worker thread startup. Registry-only entries contain no TCP tasks.
On Linux, the same benchmark binary accepts
NACELLE_TRACKING_MEMORY_ENTRIES=100000. Run that mode in a fresh process.
It touches guard storage before observing RSS, registers plain metadata without
peer/TLS strings, then observes live and retired RSS. The difference estimates
registry/signal/allocator bytes per live entry, not total connection memory or
exact allocated bytes. Page rounding and allocator retention affect the result.
Keep allocator, entry count, toolchain, and platform fixed between comparisons.
Compare tracking-off network throughput with the retained baseline and frozen stress client as well; the absence of registry operations does not prove that future layout or code generation has no cost.
For HTTP, keep the unchanged critical_paths HTTP round-trip cases as the
tracking-off baseline and run the separate opt-in profiles:
cargo bench -p nacelle-examples --features bench,http --bench http_connection_lifecycle
NACELLE_HTTP_TRACKING=0 NACELLE_HTTP_MEMORY_CONNECTIONS=2048 cargo bench -p nacelle-examples --features bench,http --bench http_connection_lifecycle
NACELLE_HTTP_TRACKING=1 NACELLE_HTTP_MEMORY_CONNECTIONS=2048 cargo bench -p nacelle-examples --features bench,http --bench http_connection_lifecycle
NACELLE_HTTP_TRACKING=0 NACELLE_HTTP_LATENCY_REQUESTS=50000 cargo bench -p nacelle-examples --features bench,http --bench http_connection_lifecycle
NACELLE_HTTP_TRACKING=1 NACELLE_HTTP_LATENCY_REQUESTS=50000 cargo bench -p nacelle-examples --features bench,http --bench http_connection_lifecycle
http_tracking compares one and 64 sequential requests per loopback connection
using identical 32-byte fixed-length responses, a two-worker Tokio runtime, and
disabled metrics. It includes client parsing/allocation, network I/O, and
connection churn, not just registry work. http_retirement measures selection
through client-observed EOF and capacity release for established keep-alive
connections; setup and its warm-up request are excluded. Pending production,
flush, and deadline cancellation are deterministic tests, not latency claims.
The Linux memory mode holds warmed client/server pairs in one process. Its RSS delta includes both endpoints, runtime tasks, buffers, registry, and allocator retention, not isolated server allocations or kernel socket memory. Run each mode in a fresh process with the same live count. The latency mode reports client-observed p50/p99 on one warmed persistent connection; these distributions are separate from Criterion batch means. Alternate tracking-off/on repetitions without concurrent builds, keep CPU affinity and feature flags fixed, and do not generalize these plain HTTP profiles to HTTPS or worker-local topology.
Request ownership
The default successful TCP and HTTP pipelines use concrete protocol, handler, responder, body, and telemetry observer types. Nacelle does not box handler futures or dynamically dispatch those contracts.
Owned TCP admission handoff also keeps one controlled serving future pinned inline. Its runtime-identity check adds no boxed future or heap allocation; transport buffers and I/O adaptation retain their existing allocation behavior. Concrete serving-future sizes still depend on protocol connection state, handler types, features, compiler, and build profile. Use the future-size check to compare representative types without treating frame size as a throughput measurement.
Retained costs are scoped by ownership:
- TCP connection buffers and decoder state are created per connection and reused across requests. Oversized response frames and optional input-buffer rotation can replace those buffers deliberately.
- A non-empty HTTP request uses one bounded Tokio channel for the request-body bridge; an exact zero-length body skips the channel and producer work, while the small scoped future still completes immediately.
- HTTP response bodies remain concrete
StreamBodyvalues rather than boxed body trait objects. - Nacelle's handler, TCP I/O, and HTTP body-read timeout wrappers use concrete
futures. Ready operations do not construct a Tokio timer. Pending operations
retain the deadline computed
before their first poll, including partial I/O; cooperative budget exhaustion
cannot suppress the timeout. The HTTP response
write deadline retains a boxed
Sleeponly after connection-level backpressure because Hyper requires its I/O wrapper to remainUnpin. - Request and body-pump permits borrow the runtime state already owned by their connection or request future. This avoids shared reference-count updates per operation while retaining exact global limits, active counts, gauge updates, and release on cancellation. Public owned permits remain available for work that must outlive a borrow.
- The scoped HTTP request-body pump borrows runtime state and telemetry and moves received chunks into the body channel. HTTP response bodies retain the immutable response-byte limit rather than another runtime-state handle.
- Enabled per-peer request and connection-open rate limits use fixed-capacity, lock-free tables. Admission probes a bounded number of atomic slots and rejects a newly observed peer when the configured table is full; it does not take a per-request mutex or sweep every tracked peer.
- Type-erased protocol/handler errors are constructed only on error paths.
- TCP response coalescing is opt-in. It queues only complete bounded frames and restores socket backpressure at thresholds, streaming waits, and socket-read boundaries.
- App listener installers and worker thread closures erase startup-only closure types; they are not involved in request dispatch.
- Optional tracing, Hyper, Tokio, TLS providers, allocators, and metrics recorders retain their own external indirection.
TCP computes effective telemetry modes once per connection and constructs one
NacelleMetricsContext containing cached facade handles. Without an installed
recorder, metric writes through those handles are no-ops. Connection/request
permits update cached runtime gauges at their existing state transitions.
Diagnostic TCP phase timers are compiled only with
the non-default phase-timing feature and remain runtime-disabled until
explicitly enabled on NacelleTelemetry.
Enable the buffer-rotation feature for long-lived TCP connections that may
occasionally receive large requests. Once an oversized cumulative input buffer
is empty, Nacelle replaces it with a buffer sized to read_buffer_capacity.
Leave the feature disabled when retaining peak buffer capacity is preferable to
allocating again after traffic spikes.
The default-off compact-connections feature reduces response-buffer storage
for immediate TCP/Unix responses. Connections start without output storage,
allocate for their first encoded frame, and retain small buffers across
requests. After a buffer exceeds response_buffer_capacity, draining it
releases the allocation without eagerly replacing it. Coalescing policies keep
their configured initial and replacement capacity.
This profile leaves input buffers, request-future placement, limits, deadlines, backpressure, and TLS unchanged. It introduces no buffer pool or per-request boxing. It targets memory use, not a guaranteed CPU or single-connection throughput improvement. Compare warmed idle populations and active traffic separately; unused connections have not yet exercised lazy output allocation.
Suggested RPS comparison:
./examples/run-stress-test.sh --config examples/nacelle-stress-server/configs/tcp.toml --server-threads 48 --connections 256 --pipeline 8 --duration-secs 30 --payload-bytes 256
The stress server installs a console recorder backed by metrics-util and prints
a snapshot every 5 seconds. It aggregates request/response body-size samples
into fixed, cache-line-isolated byte-total shards across labels rather than
retaining raw byte samples. Cached histogram handles select one of 64 shards
at registration, so recording adds no thread-local lookup, mutex, or allocation.
Zero-byte contributions skip the atomic update. The console drains and sums
the shards off the connection path. Snapshots have approximate window boundaries;
successive drains conserve totals unless their u64 sum saturates.
Library histogram names and types are unchanged. Other histograms,
including opt-in phase diagnostics, retain the debugging recorder's sample
storage. Request metrics use the generic telemetry request_metrics mode; the
default counters-and-bytes mode preserves lifecycle counters and byte
histograms, while counters omits byte writes and off suppresses both.
Diagnostics remain independent and opt-in, which avoids request Instant work
on core/HTTP paths unless request duration metrics or HTTP access logs are
enabled. Use --request-metrics counters when comparing the cost of byte
accounting. Use the
telemetry_paths benchmark for a no-recorder facade baseline; the stress server
intentionally installs its console recorder in every feature set.
With multiple stress-server workers, each listener owns a current-thread Tokio
runtime. A separate one-worker Tokio runtime supervises listeners and exports
metrics; increasing --server-threads does not create another equally sized
supervisor pool. Process affinity alone does not pin each listener thread to a
specific physical core.
Its plaintext shared and serial handler paths use borrowed TCP socket halves
rather than the generic split allocation and mutex. TLS retains the generic I/O
path; compare handler and transport modes separately.
The fixture's shared 64-byte success template is read-only static storage, so
its Bytes clones/drops do not update a shared reference count. Custom sizes
and explicit worker-local templates retain owned Bytes. This optimization
preserves the fixed payload and does not apply to dynamically generated
application responses.
The stress fixture's optional --worker-local-response allocates one immutable
response template per listener. This separates the template's reference-count
traffic between workers; it does not remove per-response ownership updates or
make transport buffers worker-local. Runtime admission counters, limits, live
controls, and rate tables remain process-wide. Optional Linux --worker-cpus
pins each listener before its template initialization. Both options preserve
the default shared-template behavior when omitted. Compare affinity alone and
worker-local ownership independently, and budget template replication and
per-worker allocator retention; first-touch placement is not a NUMA guarantee.
See stress-test options for validation rules.
The checked-in root config.toml enables self-signed TCP TLS for local
stress runs. For the plain TCP throughput baseline, use
examples/nacelle-stress-server/configs/tcp.toml. Compare TLS and non-TLS runs
separately:
./examples/run-stress-test.sh --config examples/nacelle-stress-server/configs/tcp.toml
./examples/run-stress-test.sh --config examples/nacelle-stress-server/configs/tcp-tls.toml
The examples/run-stress-test.sh and examples/run-stress-test.ps1 helpers
apply root config.toml first, then the selected profile, and choose the
matching client mode automatically.
Guardrails:
- keep shutdown task tracking at the connection/listener boundary
- avoid per-request locks in the TCP hot path
- keep telemetry observers optional; default operation uses
NoopObserver - preserve single-chunk body fast paths
- tune TCP buffer sizes for the connection count instead of relying on large defaults
Configure production limits
Start from NacelleLimits::default() and tune shared resource budgets for the
deployment. Use NacelleTcpLimits for TCP socket timeouts and
NacelleHttpLimits for HTTP edge timeouts and keep-alive behavior. Active
connections, in-flight requests, streaming tasks, body sizes, handler timeouts,
and transport timeouts are bounded by default.
state.control().set_max_connections(None)? disables that state's connection
admission ceiling. Active connections are still counted for telemetry, and any
configured global rate or per-peer limits still apply. Use
this only when another layer enforces an appropriate connection and memory
boundary.
Set finite live thresholds with set_max_connections(Some(n)) for concurrent
connections, set_global_connection_open_rate(Some(n)) for global admission
attempts per second, and set_peer_connection_open_rate(Some(n)) for opens per peer
per second. Both rate controls default to disabled and can be used independently.
Enable the default-off peer-limits feature for per-peer concurrency,
connection-open rates, and HTTP request rates; global controls do not require it.
Global rates include Unix sockets; peer rates require an IP. Zero rejects new
admissions without evicting existing connections; None disables that control.
Obtain the app/host handle before serving and retain it
for updates; see runtime control
for startup configuration, update errors, and aggregate worker scope.
For explicit connection management, opt into
NacelleLimits::with_connection_tracking(NacelleConnectionTracking::new(n)?)
before installation. Set a registry capacity appropriate to the deployment,
retain the installed control, and prefer TCP/Unix reclaim_idle(budget) over
forced close when active work must be preserved. HTTP/HTTPS support
retire_connection(id, timeout) for deadline-bounded drain, not idle reclaim.
Expiry and forced close can truncate delivery. Tracking is off by default.
See tracking configuration and outcomes.
Recommended presets:
- Internal service: keep defaults, set body limits to the largest expected payload, and run behind process supervision.
- Internet-facing behind proxy: cap connections and requests to the container budget, keep 30 second transport timeouts, and let the proxy own coarse traffic filtering or certificate automation when desired.
- Proxy-aware HTTP: trust only known proxy addresses and select the authoritative forwarding header; see HTTP hardening.
X-Forwarded-Foris the default;Forwardedrequires explicit selection. - Direct HTTPS listener: enable
http,peer-limits,rustls, load certificate/key material throughNacelleTlsConfig, configure an SNI allowlist withfrom_pem_with_allowed_server_namesorfrom_der_with_allowed_server_names, set a short TLS handshake timeout, configuremax_connections_per_peerandmax_connection_opens_per_peer_per_second, enable HTTP access logs, and attachNacelleHttpPolicywith Host, method, URI, header, security-header, and per-peer request-rate limits. - Direct TCP Rustls listener: enable
tcp,rustls, load certificate/key material throughNacelleTlsConfig, register it withNacelleApp::tcp_tls(...), and keep protocol-level authentication/authorization in the application protocol. - Direct TCP OpenSSL listener: enable
tcp,openssl, load certificate/key material throughNacelleOpenSslConfig, register it withNacelleApp::tcp_openssl(...), and configure theSslAcceptoryourself when you need OpenSSL-specific policy. - Optional TCP OpenSSL listener: enable
experimental-openssl-detection(which impliestcp,openssl) and useserve_tcp_optional_openssl(...)or the matching host/app builder method when one listener must accept both plain and TLS clients; keepNacelleTlsDetectionOptions::timeoutshort enough to avoid tying up idle accepted connections. - IPv4 plus IPv6 TCP bind: use the
NacelleApp::*_dual_stack(...)helpers to register separate IPv4 and IPv6 listeners while forcing the IPv6 listener to v6-only mode. - Unix socket listener: enable
tcpon Unix and callNacelleApp::unix_socket(...); useNacelleUnixSocketOptionsonly when this process owns stale-path cleanup or socket-file permissions. - Local load-test/autodeploy HTTPS: enable
tls-self-signedand callNacelleTlsConfig::self_signed(...); do not treat generated certificates as a public trust or rotation strategy. - High concurrency: reduce TCP buffer capacities before raising
max_connections, and tuneNacelleTcpLimitsseparately from shared resource budgets.
Memory sizing:
This sizing formula requires a finite effective connection ceiling. Use the
finite cap from control.snapshot().max_connections; for None, substitute
an externally enforced finite boundary. Lowering a live cap does not evict
existing connections, so also budget for retained occupancy.
connection_budget =
effective_connection_ceiling * (read_buffer_capacity + response_buffer_capacity)
body_budget =
concurrent_buffered_or_streaming_bodies * max_request_body_bytes
total_budget =
connection_budget + body_budget + handler/backend/runtime headroom
Nacelle leaves memory governance to the application, runtime, process supervisor, or container. Use the calculated budget to select those external limits and to tune connection, body, and concurrency limits together.
TCP processes requests sequentially per connection. request_body_channel_capacity controls the queued streaming chunks between the socket reader and handler. HTTP uses Hyper's internal buffers plus Nacelle's body queue, so leave extra headroom when enabling large request bodies.
For TCP protocols, NacelleLimits::max_request_body_bytes is the default body
limit. Override
Protocol::max_request_body_bytes(request, connection, state, default_limit)
when the decoded request head, immutable connection metadata, or concrete
Protocol::ConnectionState should choose a stricter phase-specific cap. The
hook runs before body-specific allocation or additional body reads; normal
decoder read-ahead may already have placed bytes in the connection buffer.
Use NacelleTcpOptions for accepted TCP stream behavior. Defaults preserve the
existing behavior: TCP_NODELAY enabled and TCP keepalive disabled. Enable
keepalive deliberately per deployment target because OS defaults and supported
fields vary. NacelleTcpBindOptions adds listener bind controls such as
IPv6-only mode for APIs that need explicit family behavior.
NacelleTcpConfig::response_write_policy defaults to
ResponseWritePolicy::Immediate. Select CoalesceBuffered or
FlushAtBytes(n) only for measured workloads with already-buffered request
bursts. Coalescing preserves complete-frame order and flushes before waiting for
more socket input; streaming responses flush before awaiting the next body
chunk. Larger thresholds can delay earlier responses until a threshold or batch
boundary and apply the write timeout to the complete queued batch. Size the base
buffer near a measured batch size when using larger thresholds.
Use NacelleTcpLimits for TCP socket read, socket write, final writer shutdown,
and idle timeouts. idle_timeout (120 seconds by default) bounds waiting for the
first byte of a message when the input buffer is empty. Once input is available,
read_timeout (30 seconds by default) bounds completion of the decoded message;
request-body processing starts a separate absolute deadline using that timeout.
The body deadline covers all remaining reads and streaming channel waits.
Additional message or body bytes do not restart either deadline. Body expiry
cancels a still-running handler even with handler timeouts disabled or a full
body channel. These limits apply independently, including when one is disabled.
See body-timeout migration
when upgrading from per-read body timeouts.
Set shutdown_timeout independently when finalization
needs a shorter deadline than ordinary response delivery. Disable these only through
the corresponding without_*_timeout() builders when an explicitly unbounded
policy is required.
Use NacelleHttpLimits on HyperServer for HTTP header read, request body
read, response write, keep-alive, and max connection age behavior. Use its
without_*_timeout() and without_max_connection_age() builders to disable
optional deadlines, and NacelleLimits::without_handler_timeout() for handler
execution.
Keep the default NacelleRequestMetrics::CountersAndBytes mode when existing
dashboards require body-size histograms. Use Counters to retain request
lifecycle counters without byte writes, or Off to suppress both. Configure
request duration, labelled request in-flight, and TCP phase timing separately
through NacelleTelemetryDiagnostics; these diagnostics are off by default.
with_metrics(false) suppresses metrics but does not suppress telemetry
observers.
Dangerous configurations:
- unbounded connections with large per-connection buffers
- large body limits without a process/container memory limit
- disabled timeouts on internet-facing listeners
- direct internet-facing HTTP without Host/header/method/URI policy
- direct internet-facing TLS without an SNI allowlist
- direct internet-facing listeners without per-peer connection caps
- direct internet-facing listeners without per-peer connection-open rate caps
- direct internet-facing HTTP without per-peer request caps and access logs
- trusting forwarded peer headers without an explicit trusted proxy list
- generated self-signed certificates used as a long-lived public-edge certificate strategy
- high keep-alive connection counts without proxy-level idle limits
- long TLS detection timeouts on optional TLS listeners
- Unix stale-path cleanup for a socket path not exclusively owned by this process
TLS certificate rotation:
#![allow(unused)] fn main() { let tls = NacelleTlsConfig::from_pem_files("cert.pem", "key.pem")?; tls.reload_from_pem_files("next-cert.pem", "next-key.pem")?; }
Reloads affect new TLS handshakes. Existing connections continue with the configuration negotiated when they connected.
Run stress tests
Run the server:
cargo run --release --package nacelle-stress-server -- --config examples/nacelle-stress-server/configs/tcp.toml
Run a bounded client smoke test:
cargo run --release --package nacelle-stress-test -- --connections 32 --pipeline 16 --duration-secs 15
The examples/run-stress-test.sh and examples/run-stress-test.ps1 helpers
accept --config/-Config and pass --tls-insecure to the stress client only
when the effective tls_self_signed value is true.
The Bash helper builds both binaries before starting its listener-readiness wait. It rejects an occupied listen port, waits up to 10 seconds for its own server to listen, and stops only the server/client processes it launched. It does not terminate other stress servers by name.
The stress client enables its Rustls support by default so --tls-insecure
works with the local self-signed server. For a Rustls-free plain TCP build, run
both stress binaries with --no-default-features and use
examples/nacelle-stress-server/configs/tcp.toml.
Repeatable profiles:
examples/nacelle-stress-server/configs/tcp.toml: plain TCP baseline.examples/nacelle-stress-server/configs/tcp-tls.toml: TCP wrapped in self-signed TLS.
Server TOML separates initial live thresholds from startup-only limits:
[connection_limits]
max_connections = 16384
# max_connection_opens_per_peer_per_second = 100
[limits]
# Requires the peer-limits feature, as does the optional peer rate above.
# connection_rate_limit_table_capacity = 16384
Connection totals and rates no longer belong in [limits]; old fields are
rejected rather than ignored. Zero rejects new admissions. An overlay can use
unlimited_connections = true or disable_peer_connection_open_rate = true inside
[connection_limits] to clear an earlier finite value. A finite value and its
true clearing flag in the same file are an error; omitted or false flags leave
the prior value unchanged. These files configure startup thresholds, not a
remote administrative endpoint.
Peer keys are rejected unless the server is built with --features peer-limits.
This includes max_connections_per_peer, connection_rate_limit_table_capacity,
max_connection_opens_per_peer_per_second, and
disable_peer_connection_open_rate. The last key replaces the earlier
disable_connection_open_rate name.
To measure opt-in bounded head reads, add this table to a copy of the plain TCP profile; leave the baseline profile unchanged:
[head_read_limits]
max_head_bytes = 24
max_undecided_bytes = 4096
Both fields are required together, and invalid bounds reject the file before
applying its settings. Omitting the table preserves earlier configuration; code
defaults leave head-read limits disabled. The effective configuration prints the
selected limits. Report enabled-budget results separately from the default
baseline; B changes read-ahead and can change read counts. See
bounded head reads for the
plaintext scope and body/EOF contracts.
Linux example:
./examples/run-stress-test.sh --config examples/nacelle-stress-server/configs/tcp.toml --server-threads 48 --connections 256 --pipeline 8 --duration-secs 30 --payload-bytes 256
PowerShell example:
.\examples\run-stress-test.ps1 -Config examples/nacelle-stress-server/configs/tcp.toml -ServerThreads 48 -Connections 256 -Pipeline 8 -DurationSecs 30 -PayloadBytes 256
The stress server installs a console recorder backed by metrics-util and prints
a compact metrics snapshot every 5 seconds. Its [telemetry] table defaults to
request_metrics = "counters-and-bytes"; use "counters" to omit body-size
histograms or "off" to suppress request counters and byte histograms.
Request/response body-size histogram samples are aggregated into constant-space
byte totals across labels for this console; raw byte distributions are not
retained. Cached handles collect into 64 cache-line-isolated shards, and the
console drains them off the connection path. Window boundaries are approximate;
totals are conserved across successive snapshots unless they saturate.
This does not change the library's emitted metric names or types.
Use --request-metrics counters for a lower-overhead recorder run. Use
--no-default-features with the plain TCP config for a system-allocator,
Rustls-free diagnostic; metrics collection remains active. Add
--features mimalloc-allocator when the baseline must keep mimalloc while
disabling TLS.
On Linux, multiple server workers each own a current-thread Tokio runtime. One unpinned listener with immediate responses uses the main thread's current-thread runtime for I/O, metrics, and supervision. Coalescing and dedicated listener configurations retain a one-worker multi-thread supervision runtime. Process affinity does not assign individual listener threads to fixed cores. Plaintext shared and serial handlers use specialized borrowed TCP socket halves. TLS keeps generic I/O. Keep handler and transport modes fixed in comparisons.
The client defaults to a multi-thread Tokio runtime, sized by
TOKIO_WORKER_THREADS when set. Its explicit --current-thread option runs
the same connection tasks and I/O on the main thread without another worker
pool. It does not change connection count, pipeline depth, duration, or TLS
verification. Compare it separately for a one-connection workload; keep the
multi-thread default when generating load across multiple cores.
The explicit --blocking-io client mode requires --pipeline 1 and persistent
connections; it rejects connection churn. Each connection gets one blocking I/O
worker while the selected Tokio runtime coordinates the run. TCP/TLS setup is
unchanged, and each worker writes one request, flushes, then receives the complete
response before sending another. TLS uses the existing negotiated Rustls
connection and cipher; it does not reconnect or change verification.
This mode trades additional threads and allocator/runtime memory for different socket wakeup costs. It does not busy-wait. The blocking pool is sized to the explicit connection count so all workers can reach the phase barriers. Cancellation shuts down the shared socket and wakes phase waits. Keep the ordinary asynchronous mode as the default and compare CPU, RTT, RSS, and thread count before selecting blocking I/O for a workload.
Use --warmup-secs 5 to warm up the same established connections before
measuring. All warmup responses drain before the measured phase. The client
flushes measurement_start and measurement_end markers outside the request
loop; connect/handshake work, warmup, and final shutdown are excluded from its
request statistics. Server console windows include all served requests,
including warmup.
Mean RTT includes request frame preparation, write/flush, and receipt and validation of the complete response. p50, p95, and p99 use every completion in a bounded histogram with less than 0.4% upper-bound quantization error. The histogram uses approximately 114 KiB per connection, independent of run duration. Earlier client revisions timed from after the request write and sampled percentiles; keep the same client revision in comparisons.
For allocation diagnostics, build either stress tool with
--features allocation-counting. It wraps that tool's unchanged global
allocator and counts successful allocation, zeroed-allocation, and reallocation
calls, requested bytes, and frees. Client deltas exclude warmup and shutdown;
server deltas use its periodic/final console windows. Counts are process-wide,
include console work, and have non-atomic snapshot boundaries. Native C
allocations are not counted. Keep these instrumented results separate from
CPU/latency baselines; the feature adds atomic writes to allocation operations
and is disabled by default.
The client's separate phase-timing feature reports request preparation/
write/flush and response read/validation wall times. Read time includes peer
wait; these are diagnostic timings, not isolated TLS or socket CPU costs.
Rustls's synchronous stream can drive TLS I/O while servicing a caller operation,
so blocking-mode phase labels follow those operations rather than TLS internals.
Both extra timing and allocation collection compile out of ordinary builds.
The fixture's default 64-byte success payload uses read-only static Bytes.
This avoids template reference-count updates and payload allocation without
replicating templates. Other response sizes keep owned storage. This is specific
to the fixture's fixed 0x5A payload, not an optimization of application-generated
responses. Explicit worker-local mode keeps owned templates at every size.
For an explicit Linux listener-placement experiment, choose allowed logical CPU IDs, preferably one per physical core:
cargo run --release -p nacelle-stress-server -- \
--config examples/nacelle-stress-server/configs/tcp.toml \
--server-threads 2 --worker-cpus 0,2 --worker-local-response
Replace 0,2 with CPUs in the process's affinity mask. --worker-cpus requires
one unique CPU per effective listener worker. Invalid lists, unavailable CPUs,
and affinity failures reject startup; explicit affinity requires Linux.
The supervisor and metrics threads retain the process mask.
--worker-local-response is off by default. It builds one response template and
handler per listener instead of sharing them across workers; all listeners still
share one runtime state, admission limits, live controls, and rate history.
Template initialization happens after optional worker pinning. Allocator page
reuse means this is not a guarantee of NUMA-local memory. Template storage scales
with effective_workers * response_bytes, with overflow rejected at startup;
worker-local allocator retention can also increase RSS. Measure CPU, throughput,
and memory together. Use --worker-cpus without --worker-local-response to
isolate affinity from template ownership. Neither option changes the protocol
or response-write policy.
TCP phase timing is excluded from the default build. Compile and activate it only for a diagnostic run:
cargo run --release -p nacelle-stress-server --features phase-timing -- \
--config examples/nacelle-stress-server/configs/tcp.toml \
--tcp-phase-duration-metrics
The five-second metrics snapshot then prints count, mean, minimum, and maximum for each observed phase. Use an external metrics backend for percentiles and longer retention. The phase timers and histogram writes affect the measured hot path, so do not compare this run directly with a phase-timing-free throughput baseline.
The Tokio stress server default build includes tls-self-signed support. The
checked-in root config.toml enables tls_self_signed = true, so the local
stress client should use --tls-insecure with that default config. Use
--no-default-features with examples/nacelle-stress-server/configs/tcp.toml when
you need a Rustls-free plain TCP baseline.
CI-friendly scenarios should stay short and deterministic:
- baseline echo throughput
- max connection cap
- max request cap
- slow reader
- slow writer
- graceful shutdown under load
For plain-TCP connection churn, cap each connection at one request and use pipeline depth 1:
cargo run --release --package nacelle-stress-test -- \
--connections 64 \
--pipeline 1 \
--requests-per-connection 1 \
--duration-secs 30
The summary reports completed_connections and connection_rate. Churn mode
does not currently support TLS; use the persistent TLS profile for transport
throughput and latency evidence.
Heavy RPS and soak tests should run manually or nightly on dedicated Linux hosts.
For response-delivery comparisons, the stress server accepts
--response-write-mode immediate (the default) or
--response-write-mode coalesce-buffered. The same setting can be placed in a
server config as response_write_mode. Coalescing drains complete requests
already present in the socket read buffer and flushes before awaiting more
input, so it does not leave a single response waiting for a later request. It
is intended for measured pipelined workloads; keep immediate delivery for
latency-first or unmeasured workloads.
The Linux profiling helper records this setting and also exposes shared versus serial handler dispatch for controlled diagnostics:
./scripts/profile-linux.sh \
--tool baseline \
--handler-mode shared \
--response-write-mode coalesce-buffered \
--pipeline 8 \
--runs 3
Add --feature-set default for mimalloc. To measure the
self-signed Rustls config, also pass
--config examples/nacelle-stress-server/configs/tcp-tls.toml and
--tls-insecure. The latter disables certificate verification and is only for
the local generated certificate. The stress client flushes each populated
request window before reading responses so buffered TLS records cannot strand
deeply pipelined workers.
Compare performance profiles
Use separate profiles for each transport mode:
- plain TCP
- TCP with low-memory allocator behavior
- TCP with TLS
- HTTP
Do not compare TLS and non-TLS runs as if they measure the same path. Likewise, do not compare two runs if the stress client version changed.
Recommended plain TCP baseline config:
examples/nacelle-stress-server/configs/tcp.toml
Then run:
./examples/run-stress-test.sh --config examples/nacelle-stress-server/configs/tcp.toml --connections 256 --pipeline 8 --duration-secs 30 --payload-bytes 256
Record the tested commit, kernel, CPU model/topology, CPU governor, Rust toolchain, allocator, features, configuration, connection count, pipeline depth, payload, TLS provider, and client revision with every result. A throughput number without that context is not a comparable baseline.
Also record the metrics recorder and switches, warm-up, sample duration, repetitions, and any uncommitted harness changes. Repeat the unchanged baseline before choosing regression thresholds, then compare each candidate both with its parent and the pinned starting revision. Keep allocation-instrumented runs separate from throughput/latency samples. Shared-host measurements establish local variance, not a dedicated-host performance guarantee.
For Linux stress-worker experiments, record the process CPU mask and any
--worker-cpus list separately. Compare an unchanged default, affinity alone,
and --worker-local-response under the same worker count and effective CPU
placement. Worker-local templates can reduce shared reference-count traffic
while increasing RSS; record peak memory and single-connection controls rather
than assuming a multi-worker gain applies to them. Keep the
response-write policy identical unless batching is the
explicit variable under test.
The default shared 64-byte fixture template is static; use a custom response
size when isolating owned-template contention, and record --response-bytes.
Check serving future sizes
The compiler-pressure example reports unpolled future sizes for ordinary serving, owned-admission handoff, and surrounding runtime entry points. Serial handoff coverage includes the direct helper and a protocol with 6 KiB of inline connection state. Its regression test retains a 16 KiB ceiling for these representative types:
cargo run -p nacelle-examples --no-default-features --features bench,http,peer-limits,tcp,tls-self-signed --bin compiler-pressure
cargo test -p nacelle-examples --no-default-features --features bench,http,peer-limits,tcp,tls-self-signed --bin compiler-pressure -- --nocapture
Compare the same toolchain, target, feature set, compiler flags, and profile.
Start with the unoptimized dev/test builds used during development and Clippy;
repeat without peer-limits for the default-off configuration. These sizes
describe concrete future storage, not peak thread-stack use, heap allocation
counts, or throughput. A downstream protocol or handler can require a different
amount of inline state.
Two distinct TCP workloads
Build both stress tools before measuring. For one persistent connection with one request outstanding, use immediate responses, one listener, and one client worker. On Linux, pin the process to an allowed physical-core CPU; one unpinned listener shares the main thread's current-thread runtime:
taskset -c 0 target/release/nacelle-stress-server \
--config examples/nacelle-stress-server/configs/tcp.toml \
--bind 127.0.0.1:7879 --server-threads 1 \
--handler-mode serial --response-write-mode immediate
In another terminal:
TOKIO_WORKER_THREADS=1 taskset -c 12 target/release/nacelle-stress-test \
--addr 127.0.0.1:7879 --connections 1 --pipeline 1 \
--duration-secs 30 --payload-bytes 256
Replace 0 and 12 with allowed CPUs on separate physical cores. Serial
dispatch avoids per-request shared connection-context cloning; the fixture's
plaintext path also avoids generic split locking. Compare serial and shared
dispatch separately, then hold the selected mode and runtime topology fixed
between revisions. This is not connection churn: do not set
--requests-per-connection 1.
For a separate client-runtime comparison, add --current-thread to the client
command above while keeping the server binary and configuration fixed. This
removes the extra client worker thread; it is an end-to-end profile comparison,
not evidence of a server implementation improvement. Hold the client runtime
fixed when comparing server revisions.
An explicit --worker-cpus 0 instead adds a dedicated listener runtime and
thread, leaving supervision on the main thread. Measure that topology separately
rather than assuming it improves a one-request workload.
For the serial fixture's native I/O path, select --handler-mode serial with
--response-write-mode coalesce-buffered and use multiple requests in flight.
Measure a one-connection, pipeline-64 case separately from a many-connection,
pipeline-8 case. Keep listener count, affinity, handler mode,
and the same coalesced policy fixed at both revisions. A gain from switching
immediate delivery to coalescing is a configuration gain, not evidence that the
one-request path improved. Report server CPU per completed request and latency;
coalescing cannot combine responses that the client has not requested yet.
Sequential TCP and TLS round trips
Use one persistent connection, pipeline depth 1, and immediate responses when measuring a sequential driver. Receive and validate the complete response before sending the next request. Do not substitute a pipelined or batched workload. Keep the request payload at 256 bytes and the response behavior identical in plaintext and TLS comparisons.
For local self-signed TLS, use the same one-listener server command above with
examples/nacelle-stress-server/configs/tcp-tls.toml. Run the client with:
taskset -c 12 target/release/nacelle-stress-test \
--addr 127.0.0.1:7879 --connections 1 --pipeline 1 \
--payload-bytes 256 --current-thread --tls-insecure \
--warmup-secs 5 --duration-secs 30
The insecure trust option is only for this local self-signed fixture. Record the
printed negotiated TLS version and cipher. Omit --tls-insecure and select the
plaintext server config for the transport control; do not silently change
response size, timeouts, metrics, or allocator.
Warmup uses the same established connections and drains their responses before
the measured phase. measurement_start and measurement_end are flushed
outside the request loop. Initial connections, TLS handshakes, warmup, and final
shutdown are excluded from the client request statistics. Server console windows
still include warmup: use matching steady-state CPU snapshots or whole diagnostic
windows after warmup rather than dividing startup totals by measured requests.
Report RPS, mean RTT, p50/p95/p99, client and server user/kernel CPU per request, memory, thread count, and allocation/syscall evidence separately. Current RTT starts before request frame preparation and includes write/flush through complete response validation. Earlier client revisions started timing after the write; their latency values are not comparable. Current percentiles include every completion in a bounded histogram, whose bucket upper bounds overestimate by less than 0.4%. Repeat unchanged controls and interleave baseline/candidate runs before claiming a gain.
For a separate blocking-client experiment, add --blocking-io while keeping
the same binary, server, TLS cipher, payload, and pipeline depth 1. It creates
one additional blocking worker per connection; compare memory and thread count
as well as latency and CPU. It changes client I/O scheduling, not the server
implementation, and does not allow requests to overlap within a connection.
After the one-connection comparison, measure 2, 4, 8, 16, and 32 independent
connections with --pipeline 1. Record worker counts and CPU placement for each
case. Report aggregate throughput separately from single-connection throughput;
connections / RPS is not an independently measured latency distribution.
To compare the opt-in compact response-buffer profile, keep the builds separate:
cargo build --release -p nacelle-stress-server --target-dir target/perf-baseline
cargo build --release -p nacelle-stress-server --features nacelle/compact-connections --target-dir target/perf-compact
Run target/perf-baseline/release/nacelle-stress-server and
target/perf-compact/release/nacelle-stress-server with otherwise identical
commands and immediate responses.
Keep coalescing as a separate control; it retains its configured buffer
capacity in both builds. For idle-memory comparisons, complete and validate at
least one response on every connection before sampling settled RSS. Report the
verified socket count, startup RSS, incremental RSS per connection, allocator,
and response-buffer capacity. Stay below the configured connection cap and
within idle deadlines. Process RSS excludes kernel socket memory and does not
establish a deployment's maximum connection capacity.
Suggested local benchmark:
cargo bench -p nacelle-examples --features "bench tcp"
For the codec/TCP integration specifically, run both Criterion targets:
cargo bench -p nacelle-codec --bench framed_comparison --all-features
cargo bench -p nacelle-examples --bench critical_paths --features "bench tcp"
The same critical-path target has opt-in HTTP/1 loopback cases:
cargo bench -p nacelle-examples --bench critical_paths --features "bench tcp http" -- http_connection_round_trip --noplot
http_connection_round_trip/buffered_echo/0 and
http_connection_round_trip/buffered_echo/65536 measure one complete connection,
request, and chunked response. They use two Tokio workers, the system allocator,
default Nacelle telemetry switches without a recorder, and an application that
buffers the request before echoing it. Client connection, allocation, and read
costs are included. These are not persistent keep-alive, slow-reader, p99, or
HTTPS measurements. The comparison scripts' critical-paths suite uses the
TCP-only feature selection; run this HTTP selection separately with an
identical harness at both revisions.
For persistent HTTP/1 requests without pipelining:
cargo bench -p nacelle-examples --bench critical_paths --features "bench tcp http" -- http_keep_alive --noplot
These cases use 1 or 16 concurrent connections, 64 sequential requests per connection, and empty or 256-byte echoed bodies. They use the same two-worker runtime, system allocator, and no-recorder telemetry as the connection benchmark. Connection setup is included once per 64 requests. Client work is included; these cases do not measure server-only CPU, p99 latency, or HTTPS.
Compare shared permit contention separately:
cargo bench -p nacelle-examples --bench critical_paths --features "bench tcp" -- request_permit_contended --noplot
The owned and borrowed cases enforce the same runtime request limit. Borrowed permits are used internally by scoped transport operations; they do not disable accounting or replace public owned permits.
To isolate fragmented buffered bodies:
cargo bench -p nacelle-examples --bench critical_paths --features "bench tcp" -- tcp_body_read_128x256 --noplot
Each case processes 128 requests with 256-byte bodies over in-memory I/O capped at 32 or 4,096 bytes per read. The former forces the incomplete-body fallback; the latter is a buffered control. The fixture checks each complete body, uses a current-thread runtime, and installs no recorder. These are body-path timings, not a measurement of fragmentation frequency or network throughput. Fewer body allocations alone do not establish lower CPU cost.
The ready_timeout group in the same target isolates timeout-wrapper cost for
an immediately-ready future, comparing Tokio's wrapper with Nacelle's deferred
timer construction. It does not measure pending timers or network latency.
The telemetry group can be run independently:
cargo bench -p nacelle-examples --bench critical_paths --features "bench tcp" -- telemetry --noplot
The TCP crate also measures one complete connection plus one request through the metrics facade, separating disabled metrics, default switches, request timing, and TCP phase timing. All four cases use an in-memory duplex transport without a metrics recorder; the feature selection below does not make them TLS handshakes:
cargo bench -p nacelle-tcp --bench telemetry_paths --features "buffer-rotation phase-timing rustls tls-self-signed" -- --noplot
Response delivery policies have a separate end-to-end benchmark:
cargo bench -p nacelle-tcp --bench response_delivery -- --noplot
Measure optional application-admission overhead separately:
cargo bench -p nacelle-examples --bench admission --features "bench tcp http" -- --noplot
The TCP cases use four in-memory connections with 64 pipelined 32-byte requests each, comparing default and H=24/B=4096 bounded reads, ready allowance, and capacity-four/capacity-one semaphores under immediate and coalesced delivery. Handlers yield once in every case to exercise queued admission. HTTP uses four loopback connections per iteration, empty or 64 KiB requests, and empty or four-chunk responses. Both use default telemetry without a recorder. TCP uses one current-thread runtime; HTTP uses two Tokio workers. These are enabled-policy cost profiles, not substitutes for unchanged-harness parent/default comparisons, allocation measurements, or tail-latency and memory workloads.
Compare a tag or commit
The PowerShell comparison scripts keep data under
target/performance-comparisons, resolve tags to immutable commit hashes, and
use detached temporary worktrees so the current checkout is not modified. Each
revision receives an isolated Cargo target directory; only Criterion baseline
data is copied into the candidate target before comparison, preventing build
artifacts from being reused across worktrees.
Capture all Criterion suites for the current commit, a release tag, or another commit:
./scripts/capture-performance-baseline.ps1
./scripts/capture-performance-baseline.ps1 -Reference v0.3.0
./scripts/capture-performance-baseline.ps1 -Reference 00747f3
With no parameters, HEAD is captured in a detached worktree. Uncommitted
working-tree changes are intentionally excluded from that baseline.
Compare the current working tree with a captured baseline:
./scripts/compare-performance.ps1 -BaselineReference v0.3.0
Compare two committed revisions without checking either one out:
./scripts/compare-performance.ps1 `
-BaselineReference v0.3.0 `
-CandidateReference 0123456789abcdef
Use -Suite to limit both capture and comparison to one or more matching
suites: codec, critical-paths, telemetry, or response-delivery. For
example:
./scripts/capture-performance-baseline.ps1 `
-Reference v0.3.0 `
-Suite critical-paths,telemetry
./scripts/compare-performance.ps1 `
-BaselineReference v0.3.0 `
-Suite critical-paths,telemetry
The default capture runs every suite available at the selected commit. The
critical-paths suite follows its historical move from nacelle to
nacelle-examples. The telemetry and response-delivery suites are omitted for
commits that predate those benchmark targets. When comparison omits -Suite,
it uses exactly the suites recorded by the baseline, so newer-only targets do
not invalidate an older baseline. Within a shared suite, Criterion compares
matching benchmark IDs and measures newer IDs without a delta when no baseline
exists for them.
The scripts use explicit feature selections and do not restore removed features for historical revisions. A historical suite that requires a removed feature will fail to build; select a compatible revision or a different suite instead.
Each capture records the resolved commit, Rust toolchain, operating system,
architecture, CPU information, selected suites, and full benchmark log. Each
comparison records the same candidate metadata and Criterion's percentage and
confidence-interval output. Use -Force to replace an existing baseline for
the same resolved commit.
Run native host workloads
On a dedicated Linux host, the native workload harness detects physical cores, SMT siblings, sockets, NUMA nodes, memory, and CPU governors. It reserves one physical core per NUMA node for the operating system and uses one logical CPU per remaining physical core. Review the generated plan without building or running workloads:
./scripts/run-native-performance.ps1 -PlanOnly
Run the default capacity matrix with a warm-up before every measured sample:
./scripts/run-native-performance.ps1 `
-Runs 3 `
-WarmupSecs 15 `
-DurationSecs 30
The harness defaults to three 30-second measured runs per workload. The default capacity matrix uses 50 persistent connections, pipeline depth 1, worker counts of 1, 2, 4, 8, 16, 32, and 36, and response bodies of 0, 1, 10, and 100 KiB. Worker counts larger than the isolated server core set detected on the host are omitted. Requests use a zero-byte body while retaining the protocol's fixed frame overhead; sample banners report request and response body sizes separately.
Run plain TCP and TLS as separate result sets:
./scripts/run-native-performance.ps1 `
-Config examples/nacelle-stress-server/configs/tcp.toml `
-OutputDirectory target/native-performance/plain
./scripts/run-native-performance.ps1 `
-Config examples/nacelle-stress-server/configs/tcp-tls.toml `
-OutputDirectory target/native-performance/tls
The earlier diagnostic profiles remain available explicitly. For example:
./scripts/run-native-performance.ps1 -Profile min-rtt,pooled
Use -Profile all to run both the capacity matrix and the diagnostic
minimum-RTT, pooled, pool-saturation, and pipelined-throughput profiles. Override
the capacity dimensions with -CapacityWorkerCounts or
-CapacityResponseKiB.
The harness builds native release binaries once, starts a fresh server for each
sample, applies process and memory binding with numactl, and writes the host
snapshot, exact workload plan, raw server/client logs, per-run parsed results,
and median summary JSON under target/native-performance. It warns when it
detects virtualization or a non-performance CPU governor and refuses to reuse
an occupied bind address. Use -SkipBuild only when the release binaries
already match the current source.
The codec target measures length-delimited encoding, compares direct decoding
with MessageReader::decode_buffered, measures incomplete-header calls, and
separates the no-op buffer-rotation check from replacing an empty 256 KiB
buffer. The TCP target measures per-connection decoder construction and
compares direct reference-protocol decoding with the buffered 64-request
head/body drain used by the connection loop. Treat the rotation replacement
result as allocation cost, not per-request overhead.
The runtime_limits benchmark group covers connection/request permit
acquire/drop overhead. Watch it closely after changes to
NacelleRuntimeState.
connection_permit_contended/{bounded,unlimited} adds four persistent worker
threads sharing one state. Each timed round includes start/finish barriers and
1,024 acquire/drop operations; thread creation is outside the measurement.
Treat it as a contention comparison, not isolated single-permit latency. Keep
CPU affinity, worker count, metrics configuration, and the same benchmark
harness fixed on both revisions. The peer_rate_limit_distinct_peers group
measures the rate table directly, separately from runtime-state admission.
It and the per-peer runtime-limit cases require --features "bench tcp peer-limits".
Keep that feature selection identical for both revisions.
Profile Linux CPU and allocations
Use the Linux profiling helper for repeatable plain-TCP diagnostics:
./scripts/profile-linux.sh --tool baseline
./scripts/profile-linux.sh --tool perf
./scripts/profile-linux.sh --tool heaptrack
The helper builds the profiling Cargo profile with optimization, debug
information, and frame pointers. Its default --feature-set minimal uses
--no-default-features, which disables TLS and the server's mimalloc feature.
The stress client still uses mimalloc. The stress server's console recorder
remains active, but the helper keeps body-size recording off by default for
comparability with earlier profiles. Pass
--request-metrics counters-and-bytes to include the server's default byte
accounting. Its current console recorder stores bounded
sharded byte totals, not raw byte-size samples; compare the same recorder revision,
shard policy, and switches when attributing overhead. Shard selection occurs
when cached handles register; aggregation occurs during console snapshots.
The system allocator is required because
Heaptrack cannot intercept calls made directly to mimalloc. Treat this as a
diagnostic profile, not as a matched comparison with the default mimalloc
build.
Use --feature-set default to profile the default mimalloc and Rustls-capable
binaries. Self-signed Rustls workloads also require a TLS config
and the explicit local-test trust flag:
./scripts/profile-linux.sh \
--tool perf \
--feature-set default \
--config examples/nacelle-stress-server/configs/tcp-tls.toml \
--tls-insecure
For a return-to-idle profile, keep the default mimalloc build and enable its immediate page-purge configuration:
./scripts/profile-linux.sh \
--tool baseline \
--feature-set default \
--low-memory
The profile metadata records low_memory=true. This mode is rejected with
--feature-set minimal because that diagnostic build uses the system allocator.
The helper rejects Heaptrack with the default feature set because direct
mimalloc calls are invisible to Heaptrack. It also rejects --tls-insecure
with the minimal feature set because that client omits Rustls.
Pass disjoint CPU lists after reviewing the native harness plan:
pwsh -NoProfile -File ./scripts/run-native-performance.ps1 -PlanOnly
./scripts/profile-linux.sh \
--tool perf \
--server-cpus 2,4,6,8,10,12,14,16 \
--client-cpus 3,5,7,9,11,13,15,17,19,21,23
For user-space profiling of processes owned by the current user, Linux must
permit performance counters. A value of 2 keeps kernel profiling disabled:
sudo sysctl -w kernel.perf_event_paranoid=2
Each run writes metadata, raw logs, and text reports under
target/linux-profiles. The perf mode warms the server before attaching and
records cycles:u at 999 Hz with frame-pointer call graphs. Heaptrack launches
the server directly so allocator interception survives process startup, then
applies any requested CPU affinity to all server threads.
Client logs also include server user/kernel CPU seconds and
server_cpu_us_per_request, computed from process-wide /proc/PID/stat counters
around each client invocation. CPU totals include connection setup, teardown,
and the server's metrics-console work during that interval; they exclude client
CPU. The counters have clock-tick granularity, so use several-second samples.
server_average_cores divides that CPU total by the client's reported load
duration and is approximate because client startup lies outside that duration.
Start a non-pipelined comparison with the same explicit profile at both revisions:
./scripts/profile-linux.sh \
--tool baseline \
--config examples/nacelle-stress-server/configs/tcp.toml \
--server-threads 4 --connections 64 --pipeline 1 \
--payload-bytes 256 --warmup-secs 5 --duration-secs 15 --runs 3
Add disjoint physical CPU lists for the host, keep the client binary fixed, and alternate baseline/candidate order. Compare CPU per request, user/kernel split, throughput, and tail latency together. Repeat with pipeline depth 8 as a separate control. Do not treat a small throughput difference inside baseline variance as an improvement, or extrapolate a user-space microbenchmark to total socket CPU.
The helper can compare handler ownership and response delivery without changing their safe defaults:
./scripts/profile-linux.sh --tool perf --handler-mode serial
./scripts/profile-linux.sh \
--tool baseline \
--response-write-mode coalesce-buffered \
--pipeline 8 \
--runs 3
July 2026 Linux response-delivery diagnostic
The following results are local confidence checks from an Intel Xeon Silver 4214 host with 24 physical cores, Linux 6.8, and Rust 1.95.0. The profiling build used the system allocator, no TLS, and the former metrics configuration, eight pinned server workers, 256 persistent connections, 256-byte request bodies, 64-byte response bodies, and all timeout defaults enabled. Server and client CPU sets were disjoint. Each matrix cell used a five-second warm-up and three measured ten-second runs; pipeline depths 1 and 8 also received ABBA interleaved checks.
| Pipeline | Immediate median | Coalesced median | Local delta |
|---|---|---|---|
| 1 | 614,661 req/s | 624,258 req/s | inconclusive; ABBA was -1.0% |
| 8 | 763,646 req/s | 1,081,277 req/s | +41.6% |
| 32 | 724,094 req/s | 1,256,126 req/s | +73.5% |
All clients completed without reported failures. The pipeline-8 ABBA check
measured 764,854-774,894 req/s for immediate delivery and
1,072,662-1,075,516 req/s for coalesced delivery. Matched perf captures lost no
samples; coalescing reduced write_all_tracked_with_timeout self share from
4.33% to 1.39%, ResponseDelivery::write_pending from 4.14% to 1.68%, and TCP
write polling from 1.59% to 0.46%. The connection loop always flushes after it
drains the requests already decoded from the current read buffer and before it
awaits another socket read.
These loopback saturation results support coalescing as an explicit option for highly pipelined workloads, not as a universal default. Pipeline-1 performance showed no repeatable benefit, and target-network latency, response sizes, backpressure, TLS, and telemetry require separate measurements.
Default-feature plain TCP and Rustls diagnostic
A follow-up on the same host used the then-default stress-server feature set: mimalloc, the former OpenTelemetry recorder with byte metrics, and self-signed Rustls support. The workload, CPU sets, timeout defaults, warm-up, sample duration, and three-run cell size matched the preceding matrix. Plain TCP and Rustls were measured as separate transport profiles.
| Transport | Pipeline | Immediate median | Coalesced median | Local delta |
|---|---|---|---|---|
| Plain TCP | 1 | 537,566 req/s | 536,274 req/s | -0.2% |
| Plain TCP | 8 | 619,749 req/s | 1,168,411 req/s | +88.5% |
| Plain TCP | 32 | 608,519 req/s | 1,329,735 req/s | +118.5% |
| Rustls | 1 | 478,062 req/s | 471,512 req/s | -1.4% |
| Rustls | 8 | 524,887 req/s | 529,998 req/s | +1.0% |
| Rustls | 32 | 547,103 req/s | 546,342 req/s | -0.1% |
All 36 measured client runs completed without reported failures; all cells had
at most 1.1% min-to-max spread. At pipeline depth 8, matched perf captures lost
no samples. Plain coalescing reduced tracked write-loop self share from 2.10%
to 0.47%, pending-write self share from 1.78% to 0.42%, send from 0.62% to
0.12%, and TCP write polling from 0.53% to 0.09%. The equivalent Rustls pair
was throughput-neutral: tracked write-loop self share remained approximately
1.01%, while encryption, TLS buffering, and the former metrics aggregation remained
material costs.
Deep-pipeline Rustls testing also exposed two stress-path correctness gaps.
The client now flushes buffered TLS requests before reading responses, and the
TCP connection driver flushes the underlying transport before another request
read and performs a shutdown-timeout-bounded shutdown. This delivers terminal TLS
records promptly and emits close_notify. Final pipeline-32 Rustls samples all
completed in approximately 10.02 seconds instead of waiting for the 30-second
read timeout.
These results support coalescing for measured plain-TCP pipelined workloads on this host. They do not support enabling it for Rustls or pipeline-1 workloads.
Historical disabled-policy specialization
A matched local comparison used the telemetry_paths benchmark at checkpoint
0bce7f0 and after caching the effective TCP telemetry plan once per connection.
Both builds used the same WSL2 host/toolchain and all TCP features:
| Path | Before | After | Local delta |
|---|---|---|---|
| Metrics disabled | 5.72-5.76 us | 5.03-5.07 us | approximately 12% lower |
| Metrics enabled | 7.00-7.04 us | 7.02-7.08 us | no material change |
The optimized path did not construct NacelleMetricsContext or metric attribute
arrays when metrics are disabled, and request/phase mode checks are cached in a
copyable per-connection plan. Connection/request permits remain active because
they enforce runtime limits and expose operational state. Disabling telemetry
does not disable those safety policies.
On the same local WSL2 host, 64 already-buffered one-byte requests producing 32-byte responses measured. The first two rows use a 2 KiB base response buffer; the threshold rows use a 1 KiB base buffer:
| Policy | Time | Recorded writes |
|---|---|---|
| Immediate | 27.14-27.55 us | 64 |
| CoalesceBuffered | 20.18-20.40 us | 1 |
| FlushAtBytes(1024) | 20.22-20.45 us | 2 |
| FlushAtBytes(2048), grows from 1024 | 20.40-20.63 us | 1 |
This is a synthetic in-memory writer benchmark and demonstrates dispatch/write amortization plus one transactional buffer-growth case, not network throughput. Keep immediate delivery for latency-first workloads unless a matched workload shows a benefit.
Response coalescing depth and persistent-pool controls
The response_delivery benchmark also provides two policy-matched workload
families at pipeline depths 1, 8, and 32:
same_socket: one persistent in-memory connection and one request windowpool: eight persistent in-memory connections, each processing eight request windows; the next window becomes readable only after the previous response window is delivered
Both families compare Immediate with CoalesceBuffered on the same server,
decoder, handler, response shape, runtime, and transport. Every response is 32
bytes. The benchmark asserts total write count and largest write size on every
iteration. Response-buffer capacity is 2 KiB, so these cases remain inside the
base connection allocation and do not exercise overflow growth.
Run them with:
cargo bench -p nacelle-tcp --bench response_delivery --features "buffer-rotation phase-timing rustls tls-self-signed"
A local confidence run based on commit 9be59a0 with a modified worktree used
Rust 1.95.0 on Linux 6.6.87.2 WSL2 and an Intel Xeon Platinum 8370C virtualized
topology (one socket, eight visible cores, two threads per core). Times are
Criterion 95% confidence intervals from that one host.
| Same-socket depth | Policy | Time | Writes | Largest batch | Median delta |
|---|---|---|---|---|---|
| 1 | Immediate | 5.569-5.699 us | 1 | 32 B | baseline |
| 1 | CoalesceBuffered | 5.536-5.641 us | 1 | 32 B | 1.1% lower |
| 8 | Immediate | 8.497-8.577 us | 8 | 32 B | baseline |
| 8 | CoalesceBuffered | 7.593-7.758 us | 1 | 256 B | 10.2% lower |
| 32 | Immediate | 17.834-17.944 us | 32 | 32 B | baseline |
| 32 | CoalesceBuffered | 14.344-14.436 us | 1 | 1,024 B | 19.6% lower |
| Pool depth | Policy | Time | Total writes | Largest batch | Median delta |
|---|---|---|---|---|---|
| 1 | Immediate | 51.695-52.949 us | 64 | 32 B | baseline |
| 1 | CoalesceBuffered | 50.578-50.891 us | 64 | 32 B | 2.8% lower |
| 8 | Immediate | 229.82-230.90 us | 512 | 32 B | baseline |
| 8 | CoalesceBuffered | 176.78-177.72 us | 64 | 256 B | 23.1% lower |
| 32 | Immediate | 837.09-851.92 us | 2,048 | 32 B | baseline |
| 32 | CoalesceBuffered | 608.71-614.00 us | 64 | 1,024 B | 27.6% lower |
Depth 1 remains the latency control: both policies perform one write per window, and their intervals are close. At depths 8 and 32, coalescing reduces one response window to one write and lowers elapsed time in this synthetic adapter workload. These results demonstrate write-path amortization, not socket syscall cost, network throughput, allocator counts, or production latency.
Suggested RPS comparison:
./examples/run-stress-test.sh --config examples/nacelle-stress-server/configs/tcp.toml --server-threads 48 --connections 256 --pipeline 8 --duration-secs 30 --payload-bytes 256
The stress server installs a console recorder backed by metrics-util and prints
a compact metrics snapshot every 5 seconds. Request metrics use the generic
telemetry request_metrics mode; counters-and-bytes is the default,
counters omits body-size writes, and off suppresses both request counters and
byte histograms. Diagnostics remain opt-in, which avoids request Instant work
on core/HTTP paths unless duration metrics or HTTP access logs are enabled. Use
--request-metrics counters when comparing the cost of byte accounting. Use the
telemetry_paths Criterion target for a no-recorder facade baseline; every
stress-server feature set installs the console recorder.
The checked-in root config.toml enables self-signed TCP TLS for local
stress runs. For the plain TCP throughput baseline, use
examples/nacelle-stress-server/configs/tcp.toml. Compare TLS and non-TLS runs
separately:
./examples/run-stress-test.sh --config examples/nacelle-stress-server/configs/tcp.toml
./examples/run-stress-test.sh --config examples/nacelle-stress-server/configs/tcp-tls.toml
The examples/run-stress-test.sh and examples/run-stress-test.ps1 helpers
apply root config.toml first, then the selected profile, and choose the
matching client mode automatically.
Guardrails:
- keep shutdown task tracking at the connection/listener boundary
- avoid per-request locks in the TCP hot path
- keep telemetry observers optional; the default
NoopObservermust remain allocation-free - preserve single-chunk body fast paths
- tune TCP buffer sizes for the connection count instead of relying on large defaults
Harden HTTP listeners
Nacelle's HTTP transport is Hyper HTTP/1. Configure HTTP timeout and keep-alive behavior through NacelleHttpLimits, shared body-size budgets through NacelleLimits, and request-shape policy through NacelleHttpPolicy.
Defaults:
NacelleHttpLimits::header_read_timeout: 30 seconds, enforced with Hyper's HTTP/1 header timeout andTokioTimer.NacelleHttpLimits::request_body_read_timeout: 30 seconds, enforced while reading body frames.NacelleHttpLimits::response_write_timeout: 30 seconds, enforced at Hyper's I/O write boundary.NacelleHttpLimits::keep_alive: enabled.NacelleHttpLimits::max_connection_age: disabled by default.- request and response body size limits: 16 MiB each.
Configure parser bounds separately from post-parse header policy:
#![allow(unused)] fn main() { use nacelle::http::{HttpParserLimits, NacelleHttpLimits}; let limits = NacelleHttpLimits::default() .with_parser_limits(HttpParserLimits::new(16 * 1024, None)?); }
The minimum buffer setting is 8192 bytes. It controls Hyper's parser strategy,
not an exact read allowance: complete heads may include body read-ahead beyond
that threshold. None keeps the default 100-header parser. A configured count
selects Hyper's configurable-count path; in the resolved implementation, counts
through 100 remain inline and larger counts allocate the header arrays.
Use typed admission when requests must obtain application capacity before body
work. The HTTP admission example
shares an owned semaphore permit through AppState and accepts /work:
cargo run -p nacelle-examples --features http --bin http_admission -- 127.0.0.1:8080
curl -H 'Expect: 100-continue' --data 'work' http://127.0.0.1:8080/work
Install one policy with .with_admission(policy, AdmissionConfig::new(timeout, max_pending)?). Size waiter capacity across independently constructed workers
and listeners, and share the backend semaphore explicitly when its budget must
be process-wide. Pending admission does not poll the body or send 100 Continue.
Rejection/deadline with an unread body closes HTTP/1, even when a following
request is already buffered. See the status mapping and permit
lifetime.
NacelleHttpPolicy can reject requests before the handler runs:
- allowed Host headers
- allowed HTTP methods
- maximum URI length
- maximum header count
- maximum aggregate header bytes
- optional per-peer request rate limits through
with_max_requests_per_peer_per_second - bounded lock-free per-peer request-rate state through
with_peer_rate_limit_table_capacity(16,384 peers by default when enabled) - optional trusted proxy forwarded address handling through
with_trusted_proxy_ips - optional security headers through
with_security_header(...)orwith_default_security_headers() - optional per-peer connection caps through
NacelleLimits::with_max_connections_per_peer - optional live per-peer connection-open rate caps through
NacelleRuntimeControl::set_peer_connection_open_rate
Enable the default-off peer-limits Cargo feature for per-peer concurrency,
connection-open rates, or HTTP request rates. Without it, their settings and
tracking state are compiled out; trusted-proxy resolution and access logging
remain available. Global connection limits do not require this feature.
Rejected requests receive deterministic HTTP responses where the request parser has already accepted the request: 405, 414, 421, 429, or 431. Rejections emit low-cardinality telemetry reasons such as host, method_not_allowed, uri_too_long, header_count, header_bytes, peer_rate, and peer_rate_table_full.
Per-peer request and connection-open rate limiters use fixed-capacity,
lock-free tables. They retain active peer entries for 60 seconds and do not
allocate, lock, or scan every tracked peer during admission. Size the HTTP
table with NacelleHttpPolicy::with_peer_rate_limit_table_capacity(...) and
the TCP/connection table with
NacelleLimits::with_connection_rate_limit_table_capacity(...). If a table is
full or no inactive entry is found within its fixed probe budget, a newly
observed peer is rejected. Choose capacity from the deployment's expected
active-peer cardinality rather than silently accepting unbounded state.
Enable the rustls feature to terminate HTTP over TLS. NacelleTlsConfig loads PEM certificate/key pairs, accepts explicit Rustls ServerConfig values, supports reloads for future handshakes, and enforces a TLS handshake timeout. Enable tls-self-signed only when local load tests or auto-deploying applications need to generate a self-signed certificate immediately; it implies rustls.
For direct edge HTTPS, build TLS config with
NacelleTlsConfig::from_pem_with_allowed_server_names(...) or
NacelleTlsConfig::from_der_with_allowed_server_names(...). When an SNI
allowlist is configured, clients that omit SNI or send a name outside the list
fail during the TLS handshake. HTTP Host policy is enforced after the handshake,
so configure the SNI allowlist and NacelleHttpPolicy::with_allowed_hosts(...)
with the same service names unless you intentionally need a narrower Host
policy.
NacelleTlsConfig is the Rustls config shared with TCP TLS. HTTP TLS requires
the compile-time rustls feature. TCP can instead select openssl, but the two
backend features cannot be enabled together and cannot be swapped at runtime.
Enable HyperServer::with_access_log(true) when direct edge deployments need
structured request logs. Access events are emitted with target
nacelle::access and include transport, method, URI, status, request bytes,
elapsed microseconds, and rejection reason. Declared and streamed body-size
failures both use request_body_bytes; body-read deadlines use
http_body_read.
Forwarded peer identity is disabled by default. List only known proxy IPs with
with_trusted_proxy_ips(...) and choose the header your proxy controls:
#![allow(unused)] fn main() { use nacelle::http::{NacelleForwardedHeader, NacelleHttpPolicy}; let policy = NacelleHttpPolicy::new() .with_trusted_proxy_ips(["10.0.0.1".parse::<std::net::IpAddr>()?]) .with_forwarded_header(NacelleForwardedHeader::Forwarded); }
The default is X-Forwarded-For; Forwarded now requires explicit selection.
There is no fallback between header families. Every trusted proxy must sanitize
or append to the selected header, never pass it through unchanged. Nacelle uses
the rightmost untrusted IP across repeated header fields, or the leftmost IP
when all hops are trusted. Missing or malformed selected headers use the socket
peer identity. See the HTTP hardening reference
for parsing and migration details.
Internal handler errors return a generic 500 response. Construct a sanitized
HttpResponse explicitly for client-facing application errors. Protect
server-side diagnostics and avoid secrets in query strings logged by access logs.
Allow enough memory for handlers that aggregate entire bodies, and leave separate headroom for Hyper read-ahead and TLS/socket buffers. See runtime limits for sizing guidance.
For trusted administrative HTTP/HTTPS controls, enable a finite
NacelleConnectionTracking in startup limits before installing state, and
retain the installed runtime_control(). Use retire_connection(id, timeout)
for deadline-bounded graceful retirement; close_connection(id) cancels
immediately and can truncate output. HTTP idle reclaim is explicitly
unsupported, so lowering a connection target alone may leave keep-alive
connections occupying capacity. See the control example and
outcomes.
Do not expose these controls to untrusted callers.
For internet-facing deployments, a reverse proxy or load balancer can still own coarse traffic filtering and certificate automation. Nacelle now also enforces application-level body, request, connection, per-peer connection/request/connection-open-rate, timeout, TLS handshake, security header, and optional Host/header/method/URI limits in-process.
Slowloris-style clients are closed by NacelleHttpLimits::header_read_timeout.
The body timeout bounds each frame wait; keep the handler deadline or an upstream
total upload deadline to bound continuous trickle uploads. Slow response readers
are closed by NacelleHttpLimits::response_write_timeout when writes stall.
Run security scans
Run vulnerability and dependency checks before release:
cargo audit
cargo deny check
cargo tree -i serde_yaml
cargo tree -i unsafe-libyaml
deny.toml rejects known advisories, unapproved licenses and sources, wildcard
dependencies, and duplicate versions that do not have a dependency-owner
rationale. Review every exception when updating the lockfile; do not add a
blanket advisory, license, or duplicate-version exception.
serde_yaml and unsafe-libyaml should not appear in the dependency tree.
Safe TLS test diagnostics
Certificate and key parsing must be separate from failure reporting, including
in test code. Bind the result, then inspect it with an explicit match:
let parsed = nacelle_rustls::parse_pem_certificates(certificate_pem.as_bytes());
let certificates = match parsed {
Ok(certificates) => certificates,
Err(_) => panic!("test certificate should parse"),
};
The HTTP server tests and TCP runtime Rustls tests each provide a test-only
test_certificate helper using this pattern. Reuse the helper within its crate;
do not add test panic behavior to the public TLS API.
Avoid these patterns:
parse_pem_certificates(...).expect(...)or.unwrap(): a failure formats the parser error, which may contain input-derived details.parse_pem_certificates(...).unwrap_or_else(|_| panic!("fixed message")): although the message is constant, CodeQL has still reported this fluent form as a sensitive-data logging path. Use the separate result andmatchinstead.- Printing or debug-formatting PEM, parsed certificates/keys, parsing results,
or parser errors in logs, panics, or assertions (including
assert_eq!on sensitive values). Test-runner output and CI logs are persistent output too. - Returning an empty/default certificate after a parse error or suppressing the alert. Invalid fixtures must still fail explicitly.
Keep both valid-certificate handshake coverage and malformed/empty-input tests that check the exact constant panic payload. Rust tests verify behavior and diagnostics; only a new CodeQL scan can confirm that the alerts are cleared. Record advisory-specific fixes and verification in Dependency security resolutions.
Reference protocol
This document describes the LengthDelimitedProtocol fixture in the unpublished
examples/nacelle-reference-protocol workspace package. It is used by examples,
tests, benchmarks, and stress tools, but it is not part of Nacelle's published
library API. Applications can use it from a repository checkout or implement
Protocol with an associated Request type for TCP or Unix domain sockets.
Frame Layout
All integer fields are little-endian.
| Offset | Size | Field |
|---|---|---|
| 0 | 4 | frame_len |
| 4 | 8 | request_id |
| 12 | 8 | opcode |
| 20 | 4 | flags |
| 24 | frame_len - 20 | body bytes |
frame_len counts the fixed fields after itself plus the body. The minimum
valid value is 20.
Flags
| Flag | Value | Meaning |
|---|---|---|
FRAME_FLAG_START | 0b0001 | First response frame for a request |
FRAME_FLAG_END | 0b0010 | Last response frame for a request |
FRAME_FLAG_ERROR | 0b0100 | Response body contains an error message |
Request flags are decoded and preserved in FrameRequest, but the built-in
server does not currently interpret request flags.
Requests
Each request frame contains one complete request body. The server decodes only
the frame head before dispatch, then exposes the body to the handler as a
NacelleBody. Small bodies are served from the connection read buffer. Larger
bodies are streamed to the handler in configured chunks.
Custom protocols provide a per-connection MessageDecoder through
Protocol::decoder. Decoders follow the nacelle-codec progress contract:
returning a request consumes at least one head byte, while requesting more input
leaves the cumulative buffer unchanged.
A decoder may wait for a fixed header plus a small protocol prefix before
returning a DecodedRequest<Protocol::Request>. If the prefix is incomplete, return Ok(None) and
leave every byte untouched. Once classification is possible, consume only the
header/prefix and report the unconsumed body length in DecodedRequest. This
preserves early body-limit checks and streaming. The request head can carry an
opcode or flag that the handler uses to choose a response or silent completion.
opcode is request metadata. The application handler decides whether to use it
for routing, reject it, or ignore it. If the handler rejects an opcode after
draining the body and returns an error, the server encodes that error as a
response frame.
Handlers receive TcpRequestContext<P, AppState>, where application state
defaults to (). context.app_state() borrows the dependency root shared by
the app across listeners. Its request contains the associated
protocol head under request().head and the bounded body under
request_mut().body. Its connection context contains a stable connection id,
peer/local addresses, listener label, TLS metadata, and
Arc<P::ConnectionState>. The runtime constructs that state once with
Protocol::connection_state and shares it across requests on the connection.
State confined to the serial connection loop can use SerialTcpServer or
LocalSerialTcpServer. Their handlers implement SerialTcpHandler or
LocalSerialTcpHandler and receive SerialTcpRequestContext<'_, P>, which
lends exclusive mutable access to directly owned connection state. The loop
awaits completion before decoding the next message, so one connection cannot
overlap serial handler calls. The same serial context permits either a response
or explicit silent completion.
Serial server constructors adapt ordinary handlers automatically. For the free
connection::serve_serial_stream and connection::serve_serial_stream_with_admission
helpers, wrap an ordinary SerialTcpHandler with the public
Arc::new(SerialHandlerAdapter(handler)). Worker-local serial helpers accept
Rc::new(SerialHandlerAdapter(handler)) around a LocalSerialTcpHandler.
The adapter is re-exported through nacelle::tcp and nacelle_tcp.
TcpServer and SerialTcpServer accept owned or borrowed read/write halves
through serve_halves and serve_halves_with_connection_meta. For plaintext
TCP, TcpStream::split() supplies specialized borrowed halves without the
generic I/O split's allocation and mutex. Serial serving retains its exclusive,
ordered connection-state access. Capacity and tracking end when serving completes
or is cancelled. After cancelling borrowed serving, discard or finalize the
owner's stream rather than resuming its partially consumed protocol.
Admission before transport setup
Ordinary direct-serving methods reserve connection admission automatically.
Applications that own TLS or other transport setup can reserve first through
TcpServer::admit_connection(metadata) or
SerialTcpServer::admit_connection(metadata). Free serving helpers can use
TcpConnectionAdmission::new(&runtime, &telemetry, metadata) instead.
The opaque, non-cloneable token holds concurrent capacity and optional tracking
across setup and serving. It charges global and peer admission rates once and
never refunds rate budget. Its connection identity, peer, listener, and accounting
mode cannot change; with_tls(...) can attach negotiated TLS metadata.
For Rustls with a direct nacelle-rustls dependency:
#![allow(unused)] fn main() { let admission = server.admit_connection(connection)?; let (tls_stream, admission) = admission.setup(async move { tls_acceptor.accept(stream).await.map_err(NacelleError::from) }).await?; let tls_metadata = nacelle_rustls::connection_tls_meta(tls_stream.get_ref().1); let admission = admission.with_tls(tls_metadata); server.serve_io_with_admission(tls_stream, admission).await?; }
setup(...) owns the setup future. Failure, cancellation, or administrative close
drops owned setup work before releasing capacity and registry storage. Success
returns the setup output and the same token; tracking remains in Setup until
the serving driver establishes the connection. Applications still configure
their own setup/handshake deadlines. Setup does not emit serving-open events;
connection gauges and tracking already include the reservation.
serve_io_with_admission consumes the token without another permit or rate
charge. SerialTcpServer accepts borrowed &mut I/O in this method. The free
connection::serve_stream_with_admission and
connection::serve_serial_stream_with_admission helpers expose the same transfer.
The exact originating runtime state, or its clone, must serve the token;
another state or worker partition returns
NacelleConfigurationError::ConnectionAdmissionRuntime before protocol or I/O
work. This is ownership transfer, not an accounting exemption. Discard or
finalize borrowed I/O after cancellation rather than resuming the protocol.
Admission before body work
Implement nacelle::core::Admission<TcpAdmissionContext<'_, P, AppState>>
and return an owned associated Permit. Policies inspect head(),
connection(), and app_state() without copying the head. For serial
connection state use SerialTcpAdmissionContext; its exclusive internal borrow
allows Send but non-Sync state across an await. Worker-local policies may
implement LocalAdmission with !Send futures and permits.
Configure H/B with TcpHeadReadLimits, then call the shared builder's
.admission(policy, AdmissionConfig::new(timeout, max_pending)?)?.
Local, serial, and local-serial servers use .with_admission(...) after
.with_tcp_config(...). Missing bounded-head configuration fails before I/O.
Serial handlers that require typed application state can configure TCP limits
and install admission before the application or worker runtime binds that state.
An unconfigured server has no policy accounting or timer; explicit AllowAll
uses the configured admission bounds and returns ().
Cheap protocol body-size and runtime-capacity checks precede the policy. Pending admission neither constructs a body channel nor starts the handler or reads additional body bytes. It retains its queue position and first flushes prior output, including underlying writer buffers, under one admission deadline. Ready allowance/rejection does not add a pre-wait flush or timer.
Forbidden, RateLimited, and Unavailable are bounded application rejection
categories; TCP passes them through NacelleError::AdmissionRejected to
Protocol::error_response. Waiter exhaustion and deadline use
AdmissionWaiters and Admission. These terminal failures close the connection
without interpreting unread body bytes as another head.
The permit covers body resolution, handler work, and response encoding.
It is released before a completion callback's final flush, not after remote
receipt. A cancelled or failed prior-output flush closes without retrying the
write or encoding a replacement error. When the admission deadline cancels that
flush, TCP records one server.errors timeout under socket_write when error
metrics are enabled, not an admission rejection for the waiting request. See
admission budgets
for scope, deadlines, cancellation, and disabled-timeout fallbacks.
The runnable example shares a semaphore through typed application state, admits opcode 1, and rejects other heads:
cargo run -p nacelle-examples --bin tcp_admission -- 127.0.0.1:8080
The example's test also demonstrates timeout cleanup followed by a successful
request. Constructors now wrap serial handlers in a concrete dispatch adapter;
prefer inferred server types rather than naming the raw handler as the serial
server's handler parameter. Custom generic transport helpers use TcpService,
SerialTcpService, or their local counterparts; application handlers continue
implementing the existing handler traits.
Responses
Handlers call context.respond(P::Response).await or return
Ok(context.complete()) and return the resulting typed completion. A protocol can accept its own response type; the reference protocol
uses TcpResponse, whose body may be empty, one chunk, or streaming. Returning
an HTTP response from a TCP handler does not compile.
Every decoded message uses TcpRequestContext<P> and the same concrete handler.
TcpHandlerCompletion<P> wraps an optional response; explicit silent completion
does not call the encoder or emit any bytes. This differs from responding with
TcpResponse::empty(), which still produces protocol framing.
Silent completion is application policy, not a compile-time prohibition on
responses. Framework failures may still produce an error response. Protocols
requiring strict silence for a particular message must encode that policy in
their handler and error_response hook.
The TCP runtime encodes and writes each streaming response chunk before polling the next one, so socket backpressure bounds response production. It stages only one bounded frame at a time and writes an explicit end frame after a streaming body reaches EOF.
ResponseWritePolicy::Immediate writes each completed frame immediately.
CoalesceBuffered and FlushAtBytes may queue multiple completed frames from
already-decoded requests, preserving order and rolling back only the current
frame on encoder failure. The queue drains before another socket read and before
awaiting another streaming response chunk. At that boundary, the runtime also
flushes the underlying AsyncWrite, which is required for buffered transports
such as TLS. When the connection ends cleanly, the runtime performs a
shutdown_timeout-bounded writer shutdown so TLS transports can emit
close_notify. Terminal error paths make the same bounded shutdown attempt;
an earlier connection failure remains the returned error if shutdown also fails.
Request telemetry records encoded response bytes when a request completes; a
later batch write, transport flush, or shutdown failure is reported as a
connection operation error.
With connection tracking,
idle additionally requires no accumulated input or pending request/callback work.
An empty frame queue alone is insufficient. Idle reclaim competes with first
input before dispatch; partial heads and all subsequent request/response work
remain active. Explicit forced close can cancel that work, bypasses
error_response, and drops the driver without retrying partial writes or
pending flush/shutdown. Unresolved callbacks report Cancelled; already
resolved delivery outcomes are not changed.
The protocol guarantees:
- the first response frame has
FRAME_FLAG_START - the last response frame has
FRAME_FLAG_END - a handler that returns an empty body still emits a start/end response frame
- a handler error emits a start/end/error frame through the fixture's
error_responseimplementation
Responses are written in request-processing order for a single connection. The prototype does not yet provide concurrent per-connection response interleaving.
Error Handling
Protocol::error_response(context, error) returns either
Some(TcpCompletion::new(response, response_context)) or None. The default is
None, meaning no error response. A returned response passes through
apply_response, response_body, and the ordinary encode_response_* methods:
there is no separate error-frame encoder. The protocol chooses a peer-safe
payload and any response metadata or error flag. Avoid exposing arbitrary
internal error text to untrusted peers.
Malformed heads, oversized frames, framing-progress violations, incomplete-head
EOF, idle timeout, and message-read timeout are offered without a request error
context. Once a head is decoded, body-limit rejection, request/streaming
admission failures, body-read failures, handler errors, and handler timeouts are
offered with the context captured by error_context.
This includes failures while draining the body after a handler completes
silently or prepares a response. A streaming body-read failure cancels a still
running handler.
Responses retain the configured body limits, write policy, and write deadlines. They are best-effort: resource exhaustion can prevent delivery. Connection admission and TLS handshake failures occur before this hook is available. Initial socket read I/O failures and failures during response encoding, streaming, writing, flushing, or shutdown do not initiate a new error response. In particular, a partially delivered response is never followed by an automatic replacement response, and an error-response delivery failure never recursively invokes the hook.
The connection closes after a terminal failure, even if its custom response is successfully sent, so unread body bytes cannot become another request. The original error is returned unless response delivery fails; sending an error payload does not turn the request into success. Unknown opcode handling remains application policy.
Migrating from separate one-way handlers
- Return
DecodedRequest<Request>directly from the decoder, withoutDecodedMessage::RequestorDecodedMessage::OneWay. - Combine request head types into one
Protocol::Request(an enum is suitable when message shapes differ). RemoveOneWayRequest,one_way_wire_bytes, andmax_one_way_body_bytes; apply the ordinary request hooks to every head. - Move
.one_way_handler(...)logic into.handler(...)and returnOk(context.complete())for the silent branch. Use the ordinary serial or local handler for those execution modes. - Replace
encode_errorwitherror_responseand represent error-specific framing in the typed response or response context. TcpHandlerCompletionis now anOptionalCompletion; useinto_response()when inspecting it. Itsmap(...)helper transforms only actual responses, retaining delivery completion items without running on silent completions.- TCP server type parameters no longer include a separate one-way handler.
These are source-breaking TCP API changes. HTTP required-response contexts and the core required/no-response capability primitives are unchanged.
Limits
The server enforces NacelleTcpConfig::max_frame_len against frame_len.
Buffer sizes and request-body chunking are configured through
NacelleTcpConfig.
Runtime budgets, timeouts, and active counters are configured through
NacelleLimits / NacelleRuntimeState.
TCP protocols can apply phase-aware request body limits by overriding
Protocol::max_request_body_bytes(request, connection, state, default_limit).
The TCP
runtime calls this after decoding the request head and before buffering or
streaming the body. Implementations can use concrete protocol configuration,
the decoded head, immutable ConnectionInfo, and the same concrete
Protocol::ConnectionState exposed to handlers. Rejection occurs before
body-specific allocation or additional body reads, although decoder read-ahead
may already have buffered bytes.
Messages that the handler completes silently use these same hooks and
early-rejection boundary.
TCP request handling is sequential per connection. Pipelined frames can sit
in the socket/read buffer, but Nacelle does not run multiple handlers
concurrently for one TCP connection. Streaming request bodies use
request_body_channel_capacity for backpressure between socket reads and the
handler.
With TcpRequestBodyMode::Buffered, an incomplete body reserves storage for its
full declared length before consuming the buffered prefix. Reservation failure
returns NacelleError::ResourceLimit(RequestBodyBytes) through the ordinary
error-response and connection-close path. Additional reads stop at the declared
body length, even without head read limits, leaving following-request bytes in
the transport. Bodies already complete in the read buffer retain their existing
shared-storage path.
SharedProtocol marks protocols whose connection state is Send + Sync and is
required by the existing Arc-backed shared server. Shared serial servers
require state and handler futures to be Send, but not Sync, because each
connection owns its state. Worker-local serial servers may use !Send state and
futures.
Bounded head reads
Head read-ahead is opt-in. The default head_read_limits = None preserves
existing batching and fully buffered body delivery. For the reference protocol's
24-byte encoded head:
#![allow(unused)] fn main() { use nacelle::tcp::{NacelleTcpConfig, TcpHeadReadLimits}; let config = NacelleTcpConfig::default() .with_head_read_limits(TcpHeadReadLimits::new(24, 4096)?); }
H = max_head_bytes limits decoder-visible encoded head bytes.
B = max_undecided_bytes limits cumulative undecided plaintext, including the
head and any body or next-request prefix read with it. Construction requires
0 < H <= B <= isize::MAX. These values do not replace max_frame_len or
request-body limits: an admitted body can be much larger than either.
The first idle read and every incomplete-head continuation use only the remaining
B - buffered_bytes allowance. The decoder sees at most H bytes; following
bytes are split off and restored after decoding. This preserves shared storage
when the decoder retains its input allocation. A decoder that reallocates or
replaces input can force a copy when unread bytes are rejoined; keep input
storage intact when zero-copy reuse is required.
An ordinary complete head exactly at H or B succeeds. Needing more input at
H rejects the connection without another read. An EOF-delimited decoder needs
space below H to observe EOF; the runtime never treats a truncated head prefix
as EOF.
Reads stop once the head is available. The existing body-limit and runtime
admission checks run before further body reads. Buffered and streamed body reads
are limited to their remaining admitted body/chunk length, so they do not
prefetch new undecided bytes. Previously buffered next-request bytes remain
intact and count toward the next head's budget. One decoder and MessageReader
survive these transitions; zero-copy slices, cancellation, the absolute
first-byte-to-head timeout, and the separate idle timeout remain intact.
Rejections use NacelleError::InvalidFrame with the stable reasons
request head exceeds configured byte limit or
undecided input exceeds configured byte limit. They follow the ordinary
bounded error-response and connection-close path. The codec's corresponding
budget error is distinct from EOF; oversized caller-provided codec buffers are
rejected before decoding, never trimmed.
H and B do not bound allocation capacity, retained shared Bytes, decoder
allocations, TLS transport buffers, or kernel buffers. The plaintext read boundary
applies above TLS: record data already decrypted and buffered inside the TLS
implementation is outside B. Custom decoders must bound their own allocations
and consume only their head, leaving the declared body in the cumulative input.
Authentication and authorization remain application/protocol policy.
Codec primitives
nacelle-codec provides ordered byte/message I/O over AsyncRead and
AsyncWrite transports.
Components
| Component | Purpose |
|---|---|
MessageDecoder | Decodes messages from cumulative input |
MessageReader | Reads, decodes, validates progress, and handles EOF |
MessageEncoder | Appends encoded messages to an output buffer |
MessageWriter | Queues encoded bytes and writes them to a transport |
LengthDelimitedDecoder | Decodes four-byte length-prefixed payloads |
LengthDelimitedEncoder | Encodes four-byte length-prefixed payloads |
RotatingMessageReader | Reclaims empty large input buffers when enabled |
Decoder contract
Implement MessageDecoder for protocol parsing. decode receives the
cumulative BytesMut directly. Return a message only after consuming input,
and return Ok(None) without consuming bytes when more input is required.
MessageReader reports either progress-contract violation explicitly.
The built-in length-delimited decoder returns a split BytesMut without
copying. Callers can retain it, freeze it, copy it, pool it, or parse it into a
protocol-specific value.
Writer contract
Implement MessageEncoder<M> by appending directly to BytesMut.
MessageWriter checkpoints the buffer before each encoder call and rolls back
newly appended bytes when encoding fails.
feed only encodes. flush writes all queued bytes and flushes the transport.
send performs both operations.
Buffer behavior
MessageReader and MessageWriter each hold one cumulative BytesMut, because
framing partial reads and writes requires storage across transport operations.
Use with_buffer to supply storage and into_parts to reclaim it.
MessageReader::read_more() appends one transport read without decoding and
returns the byte count, or zero at EOF. Once EOF is observed, later calls return
zero without polling the transport. read_message() still handles final
decoding and incomplete-EOF errors. Cancelling a pending read_more() does not
consume bytes. This primitive supports separate first-byte and message-completion
deadlines without changing buffer ownership. Callers must decode between reads
to enforce input limits; repeated read_more() calls alone do not bound growth.
A decoded message may share its backing allocation with the reader's input
buffer. freeze() converts it to Bytes without copying. Use
Bytes::copy_from_slice or BytesMut::from when the decoded message needs an
independent allocation.
Bounded reads
read_message_bounded(B) decodes buffered input before attempting another read.
read_more_bounded(B) performs one read without decoding. Both cap the supplied
destination to B - buffer.len(), even when the allocation has much more spare
capacity. The allowance is cumulative, not renewed on each syscall. Following
message/body prefixes already buffered count toward B.
An initial buffer larger than B returns
MessageReadError::ReadBudgetExceeded { limit, buffered } before decoding or
polling, preserving its bytes. At exactly B, a complete message succeeds;
needing another read returns that error without polling a zero-length
destination. A zero budget cannot discover EOF. Exhaustion does not mark EOF:
the caller can resume with a larger budget or explicitly consume admitted bytes.
Normal decoding, progress checks, cancellation, and shared-slice ownership
remain unchanged. Once a transport read observes EOF, decode_eof runs as
usual, including incomplete-input errors. An EOF-delimited message that fills
the entire budget cannot discover EOF and needs spare allowance. Known EOF does
not poll the transport again.
The bound covers plaintext returned into the cumulative buffer. Allocation capacity, retained shared messages, decoder-owned allocations, TLS transport buffers (including decrypted record data), and kernel buffers have separate lifetimes and limits. Mixing bounded calls with unbounded reads or direct buffer mutation is the caller's responsibility; the next bounded call rejects an oversized buffer rather than trimming it.
Limits
The length-delimited codecs reject frames larger than their configured maximum.
Custom decoders are responsible for rejecting oversized input before the
cumulative MessageReader buffer grows indefinitely.
They must also bound their own allocations independently of reader budgets.
MessageWriter::feed queues encoded bytes. flush, send, and shutdown
write queued bytes to the transport.
Long-lived connections
The optional buffer-rotation feature provides
RotatingMessageReader. Configure a threshold and replacement capacity to
replace an empty input buffer after a large decoded message. The decoded
BytesMut remains zero-copy and retains its original allocation until it is
dropped. If coalesced input follows the large message, replacement waits until
that input has been consumed.
Stability
The 0.3 API is experimental.
HTTP hardening reference
Nacelle's HTTP transport is Hyper HTTP/1. Configure HTTP timeout and keep-alive behavior through NacelleHttpLimits, shared body-size budgets through NacelleLimits, and request-shape policy through NacelleHttpPolicy.
Defaults:
NacelleHttpLimits::header_read_timeout: 30 seconds, enforced with Hyper's HTTP/1 header timeout andTokioTimer.NacelleHttpLimits::request_body_read_timeout: 30 seconds, enforced while reading body frames.NacelleHttpLimits::response_write_timeout: 30 seconds, enforced at Hyper's I/O write boundary.NacelleHttpLimits::keep_alive: enabled.NacelleHttpLimits::max_connection_age: disabled by default.NacelleHttpLimits::parser: Hyper's default bounded parser buffer strategy and stack-backed 100-header parser.- request and response body size limits: 16 MiB each.
NacelleHttpPolicy can reject requests before the handler runs:
- allowed Host headers
- allowed HTTP methods
- maximum URI length
- maximum header count
- maximum aggregate header bytes
- optional per-peer request rate limits through
with_max_requests_per_peer_per_second - bounded lock-free per-peer request-rate state through
with_peer_rate_limit_table_capacity(16,384 peers by default when enabled) - optional trusted proxy forwarded address handling through
with_trusted_proxy_ips - optional security headers through
with_security_header(...)orwith_default_security_headers() - optional per-peer connection caps through
NacelleLimits::with_max_connections_per_peer - optional live global connection admission rates through
NacelleRuntimeControl::set_global_connection_open_rate - optional live per-peer connection-open rate caps through
NacelleRuntimeControl::set_peer_connection_open_rate
Per-peer concurrent connections, connection-open rates, and HTTP request rates
require the default-off peer-limits Cargo feature. Their settings and tracking
state are compiled out without it. Trusted-proxy address resolution, metadata,
access logging, and global connection controls remain available.
Global connection rates count attempts before concurrent and peer checks or TLS
setup, without refunds after a later rejection. Exhaustion closes the accepted
socket and emits connection_rate; it does not produce an HTTP 429. Both
connection rate controls are disabled by default and can be enabled independently.
See runtime limits.
Rejected requests receive deterministic HTTP responses where the request parser has already accepted the request: 405, 414, 421, 429, or 431. Rejections emit low-cardinality telemetry reasons such as host, method_not_allowed, uri_too_long, header_count, header_bytes, peer_rate, and peer_rate_table_full.
Parser and body boundaries
Host, method, URI, and header policies run after Hyper parses the request head, before Nacelle starts its body bridge or calls the handler. Header-policy limits therefore do not bound how many bytes Hyper has already read or allocated. A pending service future can retain body bytes read with the head even when no body chunks have been delivered to Nacelle.
In the resolved Hyper 1.10.1 dependency, the low-level HTTP/1 builder's
max_buf_size accepts a minimum of 8192 bytes. It controls parser buffering,
not a hard per-request plaintext read allowance: a complete head and read-ahead
can exceed that setting. Explicitly setting Hyper's max_headers selects its
configurable-count parser path.
Nacelle exposes these separately through validated
HttpParserLimits::new(max_buffer_bytes, max_headers) and
NacelleHttpLimits::with_parser_limits(...). None or Some(100) retains
the default parser path. In the resolved implementation, positive counts
through 100 use inline header arrays; larger counts allocate those arrays.
Buffer values below 8192 are rejected before serving. Keep post-parse byte/count
checks as a separate application policy.
For Expect: 100-continue, Hyper waits for the body consumer to request data
before sending 100 Continue. A head-policy rejection does not start that
consumer or send the interim response. Nacelle sets Connection: close on
rejections with an unread body, including a fully buffered body followed by a
pipelined request. It does not drain that body or dispatch the following request.
Rejections of requests whose bodies are already empty may retain keep-alive.
These observations concern plaintext reads and HTTP parsing. They do not bound TLS records, kernel socket buffers, or total process memory.
Application admission
Shared servers accept .with_admission(policy, AdmissionConfig) where the
policy implements Admission<HttpAdmissionContext<'_, State, AppState>>.
Local servers also accept LocalAdmission<LocalHttpAdmissionContext<...>>.
The borrowed HttpRequestHead contains method, URI, headers, HTTP version, and
effective peer IP. Headers are not cloned for admission. Typed application
state is the same root available to the handler.
Host/method/header policy, effective-peer resolution, rate checks, declared
body-size checks, and runtime request capacity precede custom admission.
A separate finite waiter slot is acquired before policy invocation. Only a
pending policy starts the admission timer; the original future remains pinned.
Before allowance Nacelle neither creates its body channel nor polls Incoming
or constructs the handler future. This also applies to chunked bodies.
| Admission outcome | HTTP status | Stable reason |
|---|---|---|
Forbidden | 403 | admission_forbidden |
RateLimited | 429 | admission_rate_limited |
Unavailable | 503 | admission_unavailable |
| Framework waiter exhaustion | 503 | admission_waiters |
| Admission deadline | 503 | admission |
Responses contain only bounded reasons, retain configured security headers and response-write deadlines, and close when a body remains unread. The admission deadline is separate from the handler/body deadlines. Server clones share waiter accounting; separate listeners/workers do not unless they share the same server. See runtime limits for process-wide capacity planning.
Body-producer failures now return directly to the driver, which cancels the
handler rather than awaiting an error send into a full channel. Streaming
request-size violations produce a sanitized 413 response; other body failures
use the generic 500 response. Do not depend on observing producer errors through
next_body_chunk() to construct a custom response.
On handler/body failure, Nacelle conservatively closes connections whose
requests initially had a nonempty body, since the pump may have been cancelled.
Completion and connection retirement
HTTP request-completion telemetry and the runtime request permit finish before the response body necessarily finishes production. Response-body byte telemetry is emitted separately when that body completes; cancellation does not record a partial successful body sample. Neither event acknowledges remote receipt.
An application admission permit has a longer lifetime than the runtime request gauge: it transfers into the concrete response body after request pumping ends or is cancelled. It releases on production EOF, response error, or body drop. Hyper's HEAD/empty/final-content-length paths can drop the body without another EOF poll; these release the permit as well. Cancellation and write failure drop that ownership. It is not retained for a later socket flush, and this adds no boxed callback or dynamically dispatched body.
Hyper's public graceful-shutdown operation disables keep-alive and still needs
the connection to be polled through response production and underlying I/O
flush. It does not expose a public live-idle query covering partial heads,
pipelined input, and pending output. Request counters alone cannot establish
that an HTTP connection is safe to reclaim as idle. Nacelle does not expose
HTTP idle reclamation: tracked snapshots advertise idle_reclaim: false, and
reclaim_idle counts nonclosing HTTP entries as unsupported.
Opt-in tracking registers shared/local HTTP and Rustls HTTPS before setup.
retire_connection(id, timeout) requests Hyper graceful shutdown under an
absolute deadline from selection, including TLS setup and pending output.
Expiry cancels remaining work; close_connection(id) can force cancellation
sooner. Neither operation grants pending application admission or polls an
unadmitted Expect: 100-continue body. Registration and connection capacity
remain owned until work and I/O teardown. See
tracked connections for
capacity, outcomes, and worker scope, and
operations
for static reasons and a runnable example.
Peer limits and deployment policy
Per-peer request and connection-open rate limiters use fixed-capacity,
lock-free tables. They retain active peer entries for 60 seconds and do not
allocate, lock, or scan every tracked peer during admission. Size the HTTP
table with NacelleHttpPolicy::with_peer_rate_limit_table_capacity(...) and
the TCP/connection table with
NacelleLimits::with_connection_rate_limit_table_capacity(...). If a table is
full or no inactive entry is found within its fixed probe budget, a newly
observed peer is rejected. Choose capacity from the deployment's expected
active-peer cardinality rather than silently accepting unbounded state.
Enable the rustls feature to terminate HTTP over TLS. NacelleTlsConfig loads PEM certificate/key pairs, accepts explicit Rustls ServerConfig values, supports reloads for future handshakes, and enforces a TLS handshake timeout. Enable tls-self-signed only when local load tests or auto-deploying applications need to generate a self-signed certificate immediately; it implies rustls.
For direct edge HTTPS, build TLS config with
NacelleTlsConfig::from_pem_with_allowed_server_names(...) or
NacelleTlsConfig::from_der_with_allowed_server_names(...). When an SNI
allowlist is configured, clients that omit SNI or send a name outside the list
fail during the TLS handshake. HTTP Host policy is enforced after the handshake,
so configure the SNI allowlist and NacelleHttpPolicy::with_allowed_hosts(...)
with the same service names unless you intentionally need a narrower Host
policy.
NacelleTlsConfig is the Rustls config shared with TCP TLS. HTTP TLS requires
the compile-time rustls feature. TCP can instead select openssl, but the two
backend features cannot be enabled together and cannot be swapped at runtime.
Enable HyperServer::with_access_log(true) when direct edge deployments need
structured request logs. Access events are emitted with target
nacelle::access and include transport, method, URI, status, request bytes,
elapsed microseconds, and rejection reason. Declared and streamed body-size
failures both use request_body_bytes; body-read deadlines use
http_body_read.
Forwarded peer identity is disabled by default. The immediate socket peer must
be listed in NacelleHttpPolicy::with_trusted_proxy_ips(...). When trusted,
Nacelle reads only X-Forwarded-For by default. Proxies using the standardized
header must explicitly select
with_forwarded_header(NacelleForwardedHeader::Forwarded). There is no fallback
between header families. This replaces the previous automatic preference for
Forwarded; update proxy-aware applications when upgrading.
Across all instances of the selected header, Nacelle selects the rightmost
untrusted IP, skipping trusted proxy hops to its right. If every address is
trusted, the leftmost address is used. Malformed or ambiguous elements are
ignored without discarding valid addresses elsewhere in the selected header.
If no valid address remains, resolution falls back to the socket peer. Numeric
IP addresses are required, and duplicate for parameters are invalid. Access
logs set peer_resolution_reason to forwarded_malformed whenever malformed
elements are skipped. Configure every trusted proxy to
sanitize or append to the selected header on every request. Never trust a proxy
that passes that header through unchanged. Request rate limits, request metadata,
and access logs all use this effective identity.
Handler failures produce a generic 500 body (internal server error), not
the wrapped error's diagnostic text. Return an explicit sanitized HttpResponse
for application errors intended for clients. Failure telemetry still receives
the original error; protect diagnostic logs and observers accordingly.
Leave headroom for Hyper's read-ahead, shared backing allocations, and TLS/socket buffers. Handlers aggregating a whole chunked body need enough process or container memory to retain that body.
Rustls certificate-only reloads preserve the configured SNI allowlist, including
concurrent reloads. Invalid replacement material leaves the previous snapshot
active. Explicit replace_server_config* calls instead install the supplied
configuration's policy and clear the stored allowlist for subsequent reloads.
For internet-facing deployments, a reverse proxy or load balancer can still own coarse traffic filtering and certificate automation. Nacelle now also enforces application-level body, request, connection, per-peer connection/request/connection-open-rate, timeout, TLS handshake, security header, and optional Host/header/method/URI limits in-process.
Slowloris-style clients are closed by NacelleHttpLimits::header_read_timeout.
The request-body timeout bounds each frame wait, not total upload duration;
keep the default handler deadline or enforce a total deadline upstream to bound
continuous trickle uploads. Slow response readers are closed by
NacelleHttpLimits::response_write_timeout when socket writes stop making progress.
Dependency security resolutions
This page records fixes for published dependency advisories. It is not an exhaustive advisory inventory or a substitute for running the security scans against the current lockfile. Dependency manifests and the lockfile remain authoritative for version requirements and resolved versions.
When addressing a dependency advisory, add or update its entry here with the affected dependency, advisory link, previous version, selected fixed version, remediation, and verification performed. Keep advisory-specific version notes out of general scanning instructions. Do not record an advisory as resolved merely because it has been ignored or suppressed.
RUSTSEC-2026-0386: Tokio AsyncFd I/O safety
- Advisory: RUSTSEC-2026-0386.
- Dependency:
tokio. - Previous locked version:
1.52.3. - Resolution: raised the workspace minimum and locked version to
1.53.3, which includes the advisory's upstream fix. - Scope: the advisory concerns I/O safety in Unix
AsyncFdconstructors. No application-level workaround or advisory suppression was added. - Verification at resolution:
cargo auditandcargo deny check advisoriesboth passed with the updated lockfile.
Rerun the scans when updating dependencies; this resolution record does not establish that later dependency sets are free of advisories.
Production configuration reference
Start from NacelleLimits::default() and tune shared resource budgets for the
deployment. Use NacelleTcpLimits for TCP socket timeouts and
NacelleHttpLimits for HTTP edge timeouts and keep-alive behavior. Active
connections, in-flight requests, streaming tasks, body sizes, handler timeouts,
and transport timeouts are bounded by default.
state.control().set_max_connections(None)? disables that state's connection
admission ceiling. Active connections are still counted for telemetry, and any
configured global rate or per-peer limits still apply. Use
this only when another layer enforces an appropriate connection and memory
boundary.
Connection thresholds are live: set_max_connections(Some(n)) sets the total,
set_global_connection_open_rate(Some(n)) sets global admission attempts per
second, and set_peer_connection_open_rate(Some(n)) sets opens per peer per second.
Zero rejects new admissions; None disables the respective ceiling.
Defaults remain 16,384 connections and both rate limits disabled. Global rates
also cover Unix sockets and count attempts rejected by later limits or setup;
per-peer rates do not cover Unix sockets. Startup-only
limits stay in NacelleLimits. See runtime control
for installed handles, retained rate history, update errors, and worker scope.
Per-peer concurrency, connection-open rates, and HTTP request rates require
the default-off peer-limits Cargo feature. Their settings and tracking state
are absent without it; global controls remain available.
NacelleLimits::with_connection_tracking(NacelleConnectionTracking::new(n)?)
enables fixed-capacity TCP/Unix and HTTP/HTTPS management. It is off by default,
independent of the live connection ceiling. HTTP supports deadline-bounded
retire_connection, but reports idle reclaim as unsupported. Budget for
registry metadata and high-water storage in addition to socket/body buffers.
See tracked connections
for rejection, selection, cancellation, and worker-capacity semantics.
Recommended presets:
- Internal service: keep defaults, set body limits to the largest expected payload, and run behind process supervision.
- Internet-facing behind proxy: cap connections and requests to the container budget, keep 30 second transport timeouts, and let the proxy own coarse traffic filtering or certificate automation when desired.
- Proxy-aware HTTP: trust only known proxy addresses and select the authoritative forwarding header; see HTTP hardening.
X-Forwarded-Foris the default;Forwardedrequires explicit selection. - Direct HTTPS listener: enable
http,peer-limits,rustls, load certificate/key material throughNacelleTlsConfig, configure an SNI allowlist withfrom_pem_with_allowed_server_namesorfrom_der_with_allowed_server_names, set a short TLS handshake timeout, configuremax_connections_per_peerandmax_connection_opens_per_peer_per_second, enable HTTP access logs, and attachNacelleHttpPolicywith Host, method, URI, header, security-header, and per-peer request-rate limits. - Direct TCP Rustls listener: enable
tcp,rustls, load certificate/key material throughNacelleTlsConfig, register it withNacelleApp::tcp_tls(...), and keep protocol-level authentication/authorization in the application protocol. - Direct TCP OpenSSL listener: enable
tcp,openssl, load certificate/key material throughNacelleOpenSslConfig, register it withNacelleApp::tcp_openssl(...), and configure theSslAcceptoryourself when you need OpenSSL-specific policy. - Optional TCP OpenSSL listener: enable
experimental-openssl-detection(which impliestcp,openssl), useserve_tcp_optional_opensslor the matching host/app builder method, and keepNacelleTlsDetectionOptions::timeoutshort enough for your accepted-connection budget. - IPv4 plus IPv6 TCP bind: use the
NacelleApp::*_dual_stack(...)helpers to register separate IPv4 and IPv6 listeners while forcing the IPv6 listener to v6-only mode. - Unix socket listener: enable
tcpon Unix and useNacelleUnixSocketOptionsonly when this process owns stale-path cleanup or socket-file permissions. - Local load-test/autodeploy HTTPS: enable
tls-self-signedand callNacelleTlsConfig::self_signed(...); do not treat generated certificates as a public trust or rotation strategy. - High concurrency: reduce TCP buffer capacities before raising
max_connections, and tuneNacelleTcpLimitsseparately from shared resource budgets.
The OpenSSL PEM helper uses Mozilla's v5 intermediate profile with a TLS 1.2 minimum. TLS 1.3 is enabled when supported by the linked OpenSSL-compatible library. Custom acceptors own their own protocol policy.
Memory sizing:
This sizing formula requires a finite effective connection ceiling. Use the
finite cap from control.snapshot().max_connections; for None, substitute
an externally enforced finite boundary. Lowering a live cap does not evict
existing connections, so also budget for retained occupancy.
connection_budget =
effective_connection_ceiling * (read_buffer_capacity + response_buffer_capacity)
body_budget =
concurrent_buffered_or_streaming_bodies * max_request_body_bytes
total_budget =
connection_budget + body_budget + handler/backend/runtime headroom
Nacelle leaves memory governance to the application, runtime, process supervisor, or container. Use the calculated budget to select those external limits and to tune connection, body, and concurrency limits together.
TCP processes requests sequentially per connection.
request_body_channel_capacity controls the queued streaming chunks between
the socket reader and handler. HTTP uses Hyper's internal buffers plus Nacelle's
body queue, so leave extra headroom when enabling large request bodies. See
runtime limits for memory sizing and TLS reload
semantics.
For TCP protocols, NacelleLimits::max_request_body_bytes is the default body
limit. Override
Protocol::max_request_body_bytes(request, connection, state, default_limit)
when the decoded request head, immutable connection metadata, or concrete
Protocol::ConnectionState should choose a stricter phase-specific cap. The
hook runs before body-specific allocation or additional body reads; normal
decoder read-ahead may already have placed bytes in the connection buffer.
Set NacelleTcpConfig::with_head_read_limits(TcpHeadReadLimits::new(H, B)?)
when that pre-check read-ahead must be bounded. H caps encoded head bytes and
B caps cumulative undecided plaintext, including inherited body/next-request
prefixes; require 0 < H <= B <= isize::MAX. The reference protocol uses H = 24.
The default is None, retaining existing batching. Choose B for the workload:
smaller values reduce plaintext prefetch but can require more reads.
This is not a process memory cap: buffer capacity, shared decoded allocations, decoder-owned memory, TLS transport buffers (including decrypted record data), and kernel buffers are excluded. Existing body/frame limits still govern admitted bodies. See bounded head reads for EOF behavior, stable rejection reasons, and the decoder allocation contract.
NacelleTcpOptions controls accepted TCP stream behavior. Defaults preserve the
existing behavior: TCP_NODELAY enabled and TCP keepalive disabled.
NacelleTcpBindOptions adds listener bind controls such as IPv6-only mode for
APIs that need explicit family behavior.
TCP response delivery defaults to ResponseWritePolicy::Immediate.
CoalesceBuffered uses response_buffer_capacity as its threshold, while the
configuration builder normalizes FlushAtBytes(0) to FlushAtBytes(1). Only
complete frames enter the pending batch; the runtime flushes before another
socket read, before awaiting another streaming body chunk, and when the
threshold is reached or crossed. Read-boundary flushes include the underlying
AsyncWrite, and clean connection teardown performs a writer shutdown bounded
by NacelleTcpLimits::shutdown_timeout; terminal error paths make the same
bounded attempt. This delivers buffered TLS records and permits a TLS
close_notify. Administrative cancellation instead drops owned work without
restarting flush or shutdown; it provides no delivery or TLS-close guarantee.
The default-off compact-connections feature starts immediate-response buffers
empty, retains small allocations across requests, and releases drained buffers
larger than response_buffer_capacity without eagerly replacing them.
Coalescing retains its configured initial and replacement capacity. The feature
does not change wire limits or timeouts, and lower retained storage is not a
process memory cap.
NacelleTcpLimits controls TCP socket read, socket write, final writer shutdown,
and idle timeouts. idle_timeout defaults to 120 seconds and bounds waiting for
the first byte of a message with an empty input buffer, including the first
message on a connection. read_timeout defaults to 30 seconds and bounds
completion of a decoded message once bytes are available. Buffered partial
messages enter the read phase immediately; additional bytes do not restart its
deadline. Request-body processing starts a separate absolute read_timeout
deadline covering all remaining body reads and streaming channel waits; body
progress does not restart it. Expiry cancels a still-running handler even with
handler timeouts disabled or a full body channel. Body failures reach the
request driver without waiting to enqueue an error into that channel.
idle_timeout never applies to body reads. Idle expiry reports
NacelleTimeoutReason::Idle; message and body read expiry report TcpRead and
RequestBodyRead, respectively.
Neither timeout is a fallback for the other. Idle time excludes handler execution
and response delivery. Shutdown uses its own deadline so finalization policy can
be tuned independently of ordinary response delivery. The corresponding
without_*_timeout() builders make an explicitly unbounded policy possible.
NacelleHttpLimits controls HTTP header read, request body read, response
write, keep-alive, and max connection age behavior on HyperServer. Its
without_*_timeout() and without_max_connection_age() builders disable those
optional deadlines; NacelleLimits::without_handler_timeout() disables the
core handler deadline.
Telemetry defaults preserve connection, runtime, error, request counter, and
request/response byte series. Select NacelleRequestMetrics::Counters to omit
byte histograms or Off to omit request counters and bytes; errors remain an
independent domain. Request duration, labelled request in-flight, and TCP phase
timing are separate opt-ins in NacelleTelemetryDiagnostics. The global
with_metrics(false) gate suppresses every metric domain without suppressing
observers or erasing the configured modes. Install the process recorder before
constructing telemetry or servers so cached handles bind to it.
Dangerous configurations:
- unbounded connections with large per-connection buffers
- large body limits without a process/container memory limit
- disabled timeouts on internet-facing listeners
- direct internet-facing HTTP without Host/header/method/URI policy
- direct internet-facing TLS without an SNI allowlist
- direct internet-facing listeners without per-peer connection caps
- direct internet-facing listeners without per-peer connection-open rate caps
- direct internet-facing HTTP without per-peer request caps and access logs
- trusting forwarded peer headers without an explicit trusted proxy list
- generated self-signed certificates used as a long-lived public-edge certificate strategy
- high keep-alive connection counts without proxy-level idle limits
- long TLS detection timeouts on optional TLS listeners
- Unix stale-path cleanup for a socket path not exclusively owned by this process
TLS certificate rotation:
#![allow(unused)] fn main() { let tls = NacelleTlsConfig::from_pem_files("cert.pem", "key.pem")?; tls.reload_from_pem_files("next-cert.pem", "next-key.pem")?; }
Reloads affect new TLS handshakes. Existing connections continue with the configuration negotiated when they connected.
OpenSSL builds need native OpenSSL development files. The openssl-vendored
feature can build OpenSSL from source, but that build requires Perl on Windows.
Versioning and support
Nacelle uses semantic versioning for published crates. This policy defines how new release lines are promoted, how patch releases are maintained, and which minor lines receive support.
Major and minor releases
Every new major or minor release line progresses through three stages:
- Publish one or more development versions, such as
0.4.0-dev.1and0.4.0-dev.2, while the release scope and public contracts stabilize. - Promote the development line to a release candidate, such as
0.4.0-rc.1, when it is ready for final compatibility and release validation. Publish another release candidate if the candidate requires changes. - Promote a validated release candidate to the release version, such as
0.4.0.
This promotion path applies to both major and minor releases. Development and release-candidate versions are prereleases for evaluation and stabilization; they do not add a supported minor line to the support window.
Patch releases
Patch releases do not repeat the development and release-candidate progression.
Apply a compatible patch directly to the applicable supported release branch
and to main when the fix is still relevant there, then publish the next patch
version. For example, a fix for 0.4.0 is released directly as 0.4.1.
A patch may differ on the release branch and main when later development has
changed the affected code, but both changes must preserve the fix's behavior.
Supported versions
Nacelle supports the current released minor line and the immediately preceding
released minor line. This is the N-1 support window. Support begins with
0.3.0; every version before 0.3.0 is unsupported.
The support window therefore develops as follows:
- When
0.3is current, only the0.3line is supported. - When
0.4is current, the0.4and0.3lines are supported. - When
0.5is current, the0.5and0.4lines are supported, and0.3is unsupported.
Support applies to minor lines, not every patch within them. Consumers should run the latest available patch release in a supported minor line. Once a minor line falls outside the N-1 window, it no longer receives fixes or releases.
API stability
Nacelle is pre-1.0, but the 0.3 line distinguishes supported opt-in APIs
from explicitly experimental features. See Versioning and support
for the release promotion process and supported minor-version window.
Stable enough for prototype integrations:
nacelle::core::pipelinetyped context, responder, and handler contractsnacelle::tcpandnacelle::httptransport-owned request/response contractsnacelle::core::NacelleBodynacelle::core::{NacelleLimits, NacelleRuntimeState}nacelle::NacelleApplistener registration andNacelleApp::run(...)nacelle::prelude::*for common application importsnacelle::core::{NacelleTelemetry, NacelleTelemetryConfig, NacelleRequestMetrics, NacelleTelemetryDiagnostics}nacelle::core::NacelleTelemetryObserverfor statically dispatched application telemetry- the
phase-timingfeature and its documented low-cardinality phase schema - the
error-hintsfeature andNacelleError::hint()method
Experimental:
- Linux thread-per-core execution behind
experimental-thread-per-core - plaintext/OpenSSL detection behind
experimental-openssl-detection - stress tooling config
TCP body-timeout migration
The 0.4 development line changes TCP request-body timeouts from a fresh
NacelleTcpLimits::read_timeout for each read to one absolute deadline for the
remaining body. Buffered and streaming bodies share this policy; streaming
channel waits count toward the deadline. The default remains 30 seconds.
Regular progress no longer extends body processing: a body taking more than
30 seconds can now fail with NacelleTimeoutReason::RequestBodyRead even if
every individual read takes less than 30 seconds.
Set with_read_timeout(...) to a budget that covers the complete body and
streaming backpressure for the expected workload. Use without_read_timeout()
only when an unbounded active-read policy is intentional. The body deadline
is independent of the handler and idle deadlines; disabling handler timeouts
does not disable body expiry.
Telemetry configuration migration
The 0.4 development line replaces NacelleRequestMetricsConfig and its five
per-series booleans with NacelleRequestMetrics::{Off, Counters, CountersAndBytes}. Request duration, labelled request in-flight, and TCP phase
timing move to NacelleTelemetryDiagnostics. Use with_request_metrics(...)
and with_diagnostics(...); the superseded per-switch builder methods are
removed rather than retained as aliases.
The stress server likewise replaces top-level byte_metrics and
phase_duration_metrics with a strict [telemetry] table. Its CLI uses
--request-metrics, --request-duration-metrics,
--request-in-flight-metrics, and --tcp-phase-duration-metrics. Removed TOML
keys and CLI flags fail as unknown configuration instead of silently falling
back.
Features prefixed with experimental- are default-off and use at your own
risk. They are not part of the supported 0.3 contract and may change or be
removed in a future minor release. NacelleError::hint() is supported, but its
returned text is advisory operator guidance: do not parse it or treat it as a
stable error identifier. Match NacelleError::ResourceLimit with
NacelleResourceLimitReason, or NacelleError::Timeout with
NacelleTimeoutReason, instead. Both reason enums are non-exhaustive; include a
wildcard arm. Their as_str() methods return stable low-cardinality telemetry
labels. Applications may use Other(&'static str) for their own static, bounded
reason vocabulary.
Application code should use the app-first path:
NacelleApp::new().tcp(...).http(...).run().await. The app owns shared runtime
state, telemetry, shutdown, and listener supervision. Concrete transport
servers retain transport-specific limits and policy. nacelle::runtime::NacelleHost
and lower-level server APIs remain available for advanced manual supervision.
Public exports marked #[doc(hidden)] are internal composition plumbing. They
exist so the facade can coordinate one process-wide drain deadline, runtime
state, telemetry instance, and application-state binding across concrete
transport crates. They are not part of the supported 0.3 API contract, even
though Rust visibility permits direct use. Applications should use the visible
app, host, server, or listener methods instead. Removing or changing a hidden
export does not require a 0.3 compatibility shim.
Use NacelleApp::with_state(...) when handlers need application dependencies.
The app shares one typed root internally through Arc, while handlers borrow
&AppState from RequestContext::app_state(). Mutable access, dynamic type
maps, and runtime replacement of the whole root are outside the contract.
Growth-prone connection metadata, ConnectionInfo, telemetry events and event
kinds, and TCP/Unix listener option types are
non-exhaustive. Consumers must include wildcard enum match arms and construct
supported option values through new, Default, conversions, and with_* or
without_* builders. NacelleTcpConfig and transport limit types follow the
same builder-first rule so settings introduced by later releases retain their
defaults.
The former detached NacelleRequest/NacelleResponse handler and Tower adapter
were removed. Transport pipelines now remain strongly typed through completion;
there is no compatibility adapter.
Before 1.0, minor releases may change defaults or builder methods when production safety requires it. After 1.0, public API changes should follow semver, with migration notes for config/default changes.
Peer limit migration
The peer-limits Cargo feature is default-off. Enable it to retain per-peer
concurrent connection limits, connection-open rates, and HTTP request rates.
Without it, the corresponding settings, APIs, and tracking state are not
compiled. Global connection controls remain available with no extra feature.
The earlier 0.4 RC setter set_connection_open_rate is renamed
set_peer_connection_open_rate. The setter still limits each IP independently.
Both peer and global rate validation use NacelleConfigurationError::ConnectionOpenRate;
global rates must be below usize::MAX, and peer rates must also fit u32.
Use set_global_connection_open_rate for a budget
across metered listeners sharing runtime state. See
runtime limits.
Experimental memory removal
The 0.4 development line removes experimental-memory and its runtime memory
accounting APIs. The formerly unconditional
NacelleResourceLimitReason::{MemoryBytes, MemoryLimitMismatch} and
NacelleTimeoutReason::MemoryAllocation variants are also removed, including
their exports through nacelle_core::error and the crate root. Applications
must stop matching those variants. Body, frame, connection, and request limits
and streaming backpressure remain available; they are not a process memory cap.
The release compatibility gate in .github/scripts/check-public-api.sh accepts
only these six variant removals in the two core provider comparisons against
its pinned baseline. It retains the complete diff artifacts, rejects other
core removals and changed items, and continues to deny removals and changes
for every other compared surface. An accepted experimental removal does not
authorize unrelated API breaks.
Unified TCP completion migration
TCP now uses one request type and handler for both responses and explicit silent
completion. The separate one-way handler API has been removed. Protocol error
replies are typed responses passed through the normal encoder rather than a
separate encode_error hook. These are source-breaking changes; follow the
TCP migration guide.
HTTP retains its required-response contract.
Reference protocol migration
The former reference_protocol feature and its facade/prelude exports have
moved to the unpublished examples/nacelle-reference-protocol workspace
package. Repository examples depend on that package directly. Application code
should implement nacelle::tcp::Protocol or maintain its protocol in a separate
application crate rather than depending on a protocol implementation from the
Nacelle facade.
Rust API reference
Generate the Rust API reference with:
cargo doc -p nacelle --no-default-features --features buffer-rotation,error-hints,experimental-thread-per-core,http,peer-limits,phase-timing,rustls,tcp,tls-self-signed --no-deps
cargo doc -p nacelle-openssl --all-features --no-deps
On Windows:
.\scripts\build-rustdoc.ps1
The facade documentation uses the Rustls backend. OpenSSL configuration is
documented separately from nacelle-openssl because both backend features
cannot be enabled in one build.
The generated index is:
target/doc/nacelle/index.html
Serving contract
The following contract applies to every supported app, host, direct TCP, TCP/Unix/TLS listener, and HTTP serving entry point. Overloads only select ownership of the listener, socket options, shutdown source, or drain timeout; they do not change request semantics.
- Purpose and ownership:
NacelleAppis the primary composition root and owns registered listener configurations untilrun.NacelleHoststarts manually registered listeners immediately and owns their tasks untilwaitorshutdown_and_wait. Lower-level listener functions consume anArc-backed server and own accepted connection tasks. Direct TCP methods borrow the server and own the supplied I/O value for the duration of the returned future. Dropping a serving future cancels that future; it does not provide a graceful drain guarantee. - Cancellation and shutdown: entry points without a shutdown argument run
until listener failure or external future cancellation. Token-aware entry
points stop accepting when the token changes, wait for active connections,
and abort tasks still active at the drain deadline.
NacelleApp::runalso requests process-wide shutdown when one listener fails. Configure Ctrl-C handling explicitly withwith_ctrl_c_shutdown(). - Errors: serving futures return
NacelleErrorfor bind, accept, socket, protocol, TLS, timeout, resource-limit, listener-task, and shutdown-drain failures. Match stable categories and reason enums rather than parsingDisplay. Connection-local failures, including HTTP connection-task panics, are observed through telemetry and do not normally stop the listener; listener setup/accept failure and top-level listener-task failure do. Runtime-state installation and hostenable_*calls are fallible;NacelleError::Configurationincludes invalid thresholds and attempts to replace state still shared by control handles or listeners. - Panics: shared-runtime serving methods do not intentionally panic for
runtime or peer input. They must be called while a Tokio runtime is entered;
Tokio may panic otherwise. Worker-local methods additionally require the
documented
LocalSet/thread-per-core context. Panics from application handlers are task failures and may trigger host/app supervision; panic-abort builds terminate instead of unwinding. - Limits:
NacelleRuntimeStatesupplies process-wide connection, per-peer, request, streaming-task, and body-size limits. TCP and HTTP server configurations add transport timeouts, frame/header policy, and edge limits. Listener and direct overloads do not implicitly bypass connection capacity or configured connection registration. The former publicwithout_connection_limithelpers are removed; useserve_stream,serve_local_stream,serve_serial_stream, orserve_local_serial_streamand do not acquire an additional caller-owned connection permit. Dedicated internal listeners can explicitly selectNacelleConnectionAccounting::Exempt; ordinary connections remain metered. Exempt connections remain visible in transport metrics but do not consume the runtime connection permit gauge or enter the administrative registry. Borrowed serial I/O returns to the caller on cancellation and must not resume the cancelled protocol. - Features: plain TCP and Unix serving require
tcp; HTTP/1 requireshttp; Rustls listeners requirerustls; required OpenSSL listeners requireopenssl.experimental-openssl-detectionandexperimental-thread-per-coreremain outside the supported0.3contract. Unix-domain listeners are available only on Unix targets.
Runnable examples exercise the same contracts:
cargo run -p nacelle-examples --bin echo
cargo run -p nacelle-examples --bin http_echo --no-default-features --features http
cargo run -p nacelle-examples --bin tls_echo --features tls-self-signed
cargo run -p nacelle-examples --bin tls_http_echo --no-default-features --features http,tls-self-signed
cargo run -p nacelle-examples --bin listener_tcp
cargo run -p nacelle-examples --bin unix_echo
cargo run -p nacelle-examples --bin tcp_connection_control
cargo run -p nacelle-examples --bin http_connection_control --no-default-features --features http
cargo run -p nacelle-examples --bin openssl_echo --no-default-features --features openssl -- cert.pem key.pem
See Runtime limits for default values and Operations model for the listener drain sequence.
Start with these public entry points:
nacelle::prelude::*for common application imports.nacelle::core,nacelle::codec,nacelle::tcp,nacelle::http,nacelle::openssl,nacelle::rustls, andnacelle::runtimefor capability-oriented imports.nacelle::openssl::NacelleOpenSslConfigandnacelle::rustls::NacelleTlsConfigfor concrete provider configuration.nacelle::advanced::runtimefor raw executor and transport listener helpers when app/host composition is not sufficient.nacelle::NacelleApplistener registration andNacelleApp::run(...)for the app-first serving path across TCP, Unix sockets, HTTP, and TLS.NacelleApp::with_state(...)orwith_state_and_telemetry(...)for one typed dependency root shared across listeners. Declare it inTcpRequestContext<P, AppState>orHttpRequestContext<ConnectionState, AppState>and borrow it throughRequestContext::app_state().nacelle::core::pipeline::Handlerfor typed shared-runtime handlers.nacelle::tcp::{NacelleTcpConfig, NacelleTcpLimits}for TCP buffering, framing, and timeout policy. These structs are non-exhaustive; construct them withDefaultand applywith_*builders so future fields retain their defaults.nacelle::runtime::{ThreadPerCoreConfig, WorkerSet}and therun_local_*_thread_per_core(...)functions for experimental Linux-only worker-local TCP, HTTP, Rustls, required OpenSSL, and optional OpenSSL execution. These APIs requireexperimental-thread-per-core; this mode does not silently fall back to the shared runtime.LocalTcpRuntimeConfig::with_state(...)andLocalHttpRuntimeConfig::with_state(...)to share the same typed dependency root across worker-local listeners.ThreadPerCoreConfig::with_max_threads(...)to cap the worker threads selected byWorkerSet::all(),WorkerSet::first(...), orWorkerSet::explicit(...)while preserving selection order. The shared runtime is caller-owned; configure its Tokio thread count on the runtime builder instead.nacelle::runtime::ThreadPerCoreLimits::global(state)for exact process-wide counters, orThreadPerCoreLimits::worker(startup_limits, count)?for partitioned worker-local counters. Pass the policy to a local runtime config constructor before obtaining itsruntime_control()handle. Worker mode controls aggregate process totals while retaining worker-local counters.nacelle::core::NacelleRuntimeControlfor live connection thresholds.NacelleRuntimeState::new_with_connection_limits(startup, thresholds)?applies initial thresholds through the same validated controls before installing the state.set_global_connection_open_rate(...)sets admission attempts per second across metered listeners sharing the state, including Unix sockets;set_peer_connection_open_rate(...)limits each IP and requirespeer-limits. Both rates default to disabled. The feature also gates per-peer concurrency and HTTP request-rate APIs; global controls need no extra feature.NacelleRuntimeState::startup_limits()contains only startup configuration;control.snapshot()observes live thresholds. Opt-in tracking adds bounded metadata snapshots and forced close for TCP/Unix and HTTP/HTTPS. Snapshot capabilities distinguish TCP/Unix idle reclaim from HTTP/HTTPS deadline-boundedretire_connection; HTTP idle reclaim is unsupported.nacelle::runtime::WorkerContext::offload_blocking(...)for explicit blocking work whose completion is awaited back on the originating local worker.nacelle::tcp::Protocolfor TCP wire-format adapters.nacelle::tcp::{TcpServer, LocalTcpServer}forArc-backed connection state, orSerialTcpServer/LocalSerialTcpServerfor exclusive mutable state lent to one serial handler at a time.NacelleAppandNacelleHostserial listener methods for plain TCP, required OpenSSL, optional OpenSSL, and Unix sockets. Optional plaintext/ OpenSSL methods requireexperimental-openssl-detection, which implies thetcpandopensslfeatures.nacelle::runtime::run_local_serial_tcp_thread_per_core(...)andrun_local_serial_tcp_openssl_thread_per_core(...)for worker-local serial plain TCP and required OpenSSL. Userun_local_serial_tcp_optional_openssl_thread_per_core(...)when plaintext and OpenSSL must share one worker-local listener; it requires both experimental features. Worker factories run once per worker, so externally bounded pools should be shared deliberately rather than constructed per worker.- Use
without_handler_timeout(), the fourNacelleTcpLimits::without_*_timeout()builders, and the HTTPwithout_*_timeout()/without_max_connection_age()builders when an explicitly unbounded policy is required. nacelle::core::{NacelleTelemetry, NacelleTelemetryConfig, NacelleRequestMetrics, NacelleTelemetryDiagnostics}for metrics and telemetry.nacelle::core::NacelleError::hint()with theerror-hintsfeature for optional operator guidance.NacelleError::Displayremains stable across feature combinations; applications append hints deliberately where suitable. Hint text is advisory and must not be parsed as a stable identifier.- Match
NacelleError::ResourceLimit(NacelleResourceLimitReason::...)andNacelleError::Timeout(NacelleTimeoutReason::...)for programmatic handling. The reason enums are non-exhaustive and theiras_str()methods expose stable low-cardinality labels. UseOther(&'static str)only for application-owned static reason vocabularies. nacelle::tcp::TcpServer,nacelle::http::HyperServer,nacelle::runtime::NacelleHost, andnacelle::advanced::runtimewhen a service needs lower-level listener control.
Connection metadata, ConnectionInfo, telemetry event types, and TCP/Unix
listener options are non-exhaustive. Observe them with
wildcard enum matches and construct option values through their documented
constructors, defaults, conversions, and builders.