HTTP listeners
Add axiom-http and call app.listen(8080). This starts the application, freezes
routes, and binds 127.0.0.1. Use listen(new InetSocketAddress(host, port)) to
choose an interface, or port zero for an allocated port. Server.localAddress()
reports the actual address. Netty is an implementation dependency; application
and transport-provider contracts expose only JDK and Axiom types.
Ownership and shutdown
An application owns every listener it creates. Multiple listeners can share its routes. Closing one listener leaves the application and other listeners running. Closing the application permanently rejects requests and closes all its listeners. Both close operations are idempotent and nonblocking, including from a handler.
Listener shutdown is graceful. It stops accepting connections at once and closes
idle keep-alive connections and connections still receiving a request. It also
stops admission: requests waiting for execution capacity are answered 503 and
their connections close without invoking the handler. A connection with a
running handler keeps it running; its response is sent with Connection: close
and queued pipelined requests on it are dropped unanswered. This holds for every
response sent after close() is called, so it is already in force when a waiting
request receives its 503. The connection then
lingers for at most 500 milliseconds by default (see wire behavior) before it
closes; connections already lingering when the listener closes stop within the same
bound, so they do not hold up shutdown.
After the shutdown grace period (five seconds by default, see
listener options), remaining connections close and their
handlers are interrupted; then execution and I/O threads stop. Await
server.termination() to join resource shutdown. Handlers must cooperate with
interruption; termination cannot complete while a handler refuses to stop.
Direct in-memory app.handle calls remain the caller’s responsibility.
Shutdown on SIGTERM
Nothing closes an application by itself: Axiom never installs a JVM shutdown hook unless asked, so
a library or test that embeds it is not surprised. Closing on SIGTERM is opt-in. A service
run by a container runtime or Kubernetes, which stops it with SIGTERM, calls
app.closeOnJvmShutdown() once at startup:
var app = Axiom.create().closeOnJvmShutdown();
app.get("/", ctx -> "ok");
var server = app.listen(new InetSocketAddress("0.0.0.0", 8080));
server.termination().toCompletableFuture().join(); // keeps main alive until the drain is done
When the JVM begins to shut down (SIGTERM, SIGINT, System.exit or the end of the last
non-daemon thread) the hook closes the application and waits for every listener to terminate. The
drain is the graceful shutdown described above, within each listener’s shutdownGrace: running
requests finish and are answered with Connection: close, waiting requests get 503, and what is
left is interrupted after the grace period. The wait is bounded by the longest shutdownGrace of
the application’s listeners plus five seconds, so a handler that ignores interruption cannot keep the
JVM from exiting. Closing makes the application not RUNNING, so a Health readiness probe
reports DOWN from then on. If a load balancer needs time to notice, use
closeOnJvmShutdown(Duration drainDelay): the hook first runs the drain actions (a Health registers
beginDrain() itself, so readiness turns DOWN), waits the delay, and only then closes (see
observability). The grace
period must fit inside the platform’s own kill timeout (Kubernetes
terminationGracePeriodSeconds, 30 seconds by default). Calling it twice registers one hook,
an explicit app.close() unregisters it, and it throws IllegalStateException on a closed
application or when the JVM is already shutting down. Hooks of different libraries run concurrently
and in no defined order.
Open streams keep the grace period too, and are told that shutdown began
(BodyWriter.shutdownRequested(), onShutdown) so that a body can end normally with a final chunk;
a body still running when the period ends is cut with SHUTDOWN, and its connection closes without
a final chunk, so the client sees the body cut off rather than completed.
A failed bind releases its resources before reporting IOException. The
application remains running, so binding another address is safe. Missing or
multiple transport providers fail before startup. Closed applications cannot bind.
Management listener
Diagnostics can be moved off the application port. This is opt-in and off by default:
an application that never calls Application.management(ManagementOptions) binds a
single listener. When configured, the first listen call also binds a second,
application-owned listener for health probes and a metrics scrape:
var app = Axiom.create()
.management(ManagementOptions.builder().host("127.0.0.1").port(9090).build());
var health = Health.builder(app).readiness("database", () -> pool.isValid(1)).build();
var api = app.listen(new InetSocketAddress("0.0.0.0", 8080));
var management = app.managementServer().orElseThrow();
The management port serves only /health/startup, /health/live (and
/health/liveness), /health/ready (and /health/readiness) and /metrics. Health
probes come from Health instances built for the application; /metrics calls
Metrics.prometheusText(). No application route, global middleware, authentication
middleware or user handler is registered there, and the answers are small and opaque.
Binding is loopback by default: a wildcard address is refused unless
allowWildcardBind(true) is set, and a non-private address is logged as a warning.
Because there is no authentication on this port, keep it on a loopback or private
network; tls(true) reuses the first application listener’s TLS material and requires
that listener to have TLS configured. For a different certificate, management ACL or
client-authentication policy, pass TlsOptions to tls(...): that material is used
instead of the application’s, and a plain application listener is then allowed. Request
bodies and response text are bounded (64 KiB by default), and the listener uses fixed, small
transport limits. See
observability for the probe and scrape contract.
The scrape is the Metrics.prometheusText() text of the installed implementation; the
OTel and Micrometer adapters leave exposition to the application’s own exporter, as
described in the observability guide.
The management listener follows the application’s lifecycle, not the application
listener’s: closing the listener returned by listen leaves it serving, and closing
the application closes both. managementServer() exposes its bound address, which is
needed when the configured port is zero. If the management bind fails, the application
listener bound by the same listen call is closed too, so no socket or thread is left
behind; a later listen call can retry. TestClient has no management port because it
opens no socket; use a real-socket test for this listener.
Wire behavior
The listener accepts HTTP/1.1 origin-form requests with exactly one valid Host,
and HTTP/1.0 requests, whose Host is optional but validated when present. The
asterisk-form target is accepted only as OPTIONS * (see
OPTIONS *); * with any other method receives 400. An
absolute-form target such as http://host/path is accepted when its scheme is http or
https and its authority equals the Host header; see
absolute-form targets.
Responses always use HTTP/1.1. An HTTP/1.0 connection closes after each response
unless the request sends Connection: keep-alive, which the response echoes.
A method that is not an RFC 9110 token receives 400; methods are case-sensitive, and
method-override headers such as X-HTTP-Method-Override are ignored. The
method table lists the answer for every method, including
OPTIONS, TRACE, CONNECT and extension methods. Paths that Request rejects (empty or dot segments, backslashes, malformed or
encoded separators; see routing rules) receive 400. Accepted raw paths
retain their encoding. Query strings are excluded from routing, retained on the
request and validated as described in routing rules;
a malformed or oversized query also receives 400. Request headers are available to handlers, the
connection’s peer is ctx.request().remoteAddress() (forwarding headers are never applied
to it; see trusted proxies), and
request bodies are read up to the application’s limit, either buffered or incrementally on a
streaming route; see request bodies. Responses support UTF-8 strings, byte arrays, empty
bodies, values encoded by an installed codec and streams. Unencodable body objects and
handler exceptions other than AxiomException produce a generic 500 and close the
connection; exception details are not sent to clients. The in-memory API still
propagates those exceptions.
The transport controls Content-Length, Transfer-Encoding, connection headers and
Date, which every response carries as an IMF-fixdate with one-second precision.
A streamed response is sent with Transfer-Encoding: chunked on HTTP/1.1,
and unframed until the connection closes on HTTP/1.0; HEAD gets its head only.
Hop-by-hop headers, including names nominated by Connection, are removed. HEAD
uses an explicit HEAD route or falls back to GET and sends no body bytes. OPTIONS
for a routed path without an OPTIONS route is answered 204 with Allow and no
handler runs (see automatic OPTIONS). TRACE is never
echoed: it is answered 405 or 404 (see TRACE). A successful
HEAD response (2xx other than 204 and 205) carries the Content-Length the GET
representation would have, its encoded body length, replacing any value the
application set; a representation the transport could not send is a 500 for HEAD as
for GET. Error responses to HEAD keep their own framing: no body and no Content-Length,
including errors the listener produces before routing (400, 413, 417, 501 and the
others below).
Statuses 204 and 304 omit Content-Length; 205 uses zero, because RFC 9112 section 6.3 does not treat it as
bodiless and the client needs explicit framing to read the next response. The
interim 100 Continue carries no header fields. Keep-alive and pipelining are supported, with
one active handler per connection and responses in request order.
Every error response, whether produced by the listener or the application, is an
application/problem+json body holding only status, code and request ID; see
errors for the full status table. CONNECT (see
CONNECT), upgrades and unsupported transfer codings return 501; an overlong request line 414; an oversized header
section 431; an
Expect other than 100-continue 417; other HTTP versions 505; malformed requests
- These close the connection.
Transfer-Encoding follows a fixed contract (details in request bodies).
Only chunked is supported, except on a listener that opted into
compression: there a single gzip or deflate coding before chunked
(gzip, chunked) is decoded and the request succeeds. Without that opt-in, one field line
whose last coding is chunked but that applies another coding first (gzip, chunked) is
answered 501: its framing is unambiguous and the coding is merely unsupported, which
is the case RFC 9112 section 6.1 says a server should answer with 501. On a compression
listener, an unknown coding still gets 501, while more than one content coding or a
repeated one gets 400, because at most one coding is decoded. A list whose last coding
is not chunked is 400, as RFC 9112 section 6.3 requires, because the body length
cannot be determined. More than one Transfer-Encoding field line is 400 even when the
combined list would be acceptable: the RFC allows combining the lines, but intermediaries
disagree about how, which is a classic request-smuggling vector, so the listener refuses
rather than picks a reading. All of these close the connection and nothing sent after the
rejected head is parsed or executed, whether the request arrives alone or pipelined behind
others.
Closing right after a response could destroy it: if the client is still sending
(the rest of a rejected body, or further pipelined requests), unread input makes the
operating system reset the connection, which can discard response bytes not yet
delivered, and a client may report the reset instead of the response. So whenever
the listener ends a connection after a response, for any reason (a listener error,
Connection: close from the client or the handler, HTTP/1.0 without keep-alive, or
listener shutdown), it shuts down its output, so the client reads the whole response
and end of stream, and keeps reading and discarding input without buffering it. The
connection closes when the client closes its side, once no input has arrived for 500
milliseconds, after two seconds in total, after 16 MiB of discarded input, or on
inactivity, whichever comes first. Each arriving byte restarts the 500-millisecond
quiet period but never extends the two-second total.
Lingering exists for a client that is still sending, so a client that has gone quiet
is taken to have finished: one that reads the response and keeps its socket open is
closed after the quiet period, and closing a connection with no unread input sends no
reset. The quiet period is longer than a typical TCP retransmission timeout, so a
single lost segment does not end it. The trade-off is a client that is still sending
but pauses for longer (a very lossy link, or a client that stalls between writes): its
next bytes arrive at a closed connection, the operating system answers with a reset,
and response bytes the client has not read yet may be lost. The quiet period is the
lingerQuietTimeout listener option (see listener options): raise it
for clients known to upload slowly or over lossy links, up to the lingerTimeout total, which
is the hard bound either way. The cost of a longer period is that a client which reads the
response and then idles keeps its lingering connection (and its socket) for that long, which
the lingering pool and its bound limit (see resource limits). Once the listener is
closing, lingering lasts at most 500 milliseconds in total by default, so lingering connections
barely delay shutdown. A lingering connection holds no request data and no longer
counts against the connection limit (see resource limits).
Connections closed without a response (an idle
connection at shutdown, a connection still receiving a request at shutdown,
inactivity, a transport failure or a disconnect) close at once.
Errors on pipelined requests
A listener error never overtakes an earlier response and never aborts earlier work. When a pipelined request is rejected (any of the errors above, 408 for a head or body that arrives too slowly, 413, or 503 for exceeding the pipeline bounds below) while earlier requests on the connection are running or queued:
- The rejected request and everything after it are never executed. The listener stops parsing input: bytes after an error are read and discarded unparsed, since after a framing error (a malformed chunk, conflicting Content-Length and Transfer-Encoding, an unparseable head) their boundaries cannot be trusted. Requests already parsed from the same read are dropped too.
- The running request and every request received completely before the error run normally, in order, and each gets its usual response. The running handler is not interrupted.
- The error response follows them, with
Connection: close, and the connection closes.
Responses arrive in request order, so the client can match each one to its request;
the rejected request and those after it, which receive no response of their own,
were not executed. Input keeps being read and discarded, never buffered, so a client
disconnect still cancels and interrupts the running handler. A client that sends
more than 16 MiB after the error is treated as abusive: the connection closes at
once, the running handler is cancelled and interrupted, and no further responses are
sent. If an earlier response itself closes the connection (a listener 5xx, a
handler’s Connection: close, or listener shutdown, which sends the running response
with Connection: close), that response is the last one and the pending error is
not sent. The 30-second inactivity timeout does not interrupt the running handler,
but still closes the connection if a response write stalls, and each response must
be written within the response bound (see resource limits).
Conditional and range requests
Conditional and range evaluation is opt-in and lives in axiom-core: the
framework never invents validators, so the application attaches ETag and
Last-Modified to the response it wants to be conditional. Register the
middleware globally or on a route with app.use(...):
app.use(HttpPreconditions.conditional());
app.use(HttpPreconditions.preconditionRequired()); // optional: answer 428 for unsafe methods
app.get("/report", ctx -> ctx.encode("application/json", report)
.withHeader("ETag", "\"report-v3\"")
.withHeader("Last-Modified", "Wed, 21 Oct 2015 07:28:00 GMT"));
HttpPreconditions.conditional() calls the rest of the chain and evaluates the
request against the response. Precedence follows RFC 9110 section 13.2.2, and
the first failing condition determines the answer:
| Field | Rule | Answer |
|---|---|---|
If-Match |
strong comparison; * matches any current representation |
412 |
If-Unmodified-Since |
evaluated only when If-Match is absent; ignored when its date is invalid or the response has no Last-Modified |
412 when modified since the date |
If-None-Match |
weak comparison, including *; for GET and HEAD |
304 on a match; 412 for other methods |
If-Modified-Since |
GET or HEAD only, ignored whenever If-None-Match is present or its date is unusable |
304 when not modified since the date |
If-Range |
strong ETag or exact Last-Modified; only with Range on GET |
ignores Range when the validator does not match |
A Range: bytes=... field is parsed strictly: only the bytes unit, ASCII
digits, optional whitespace around commas, at most eight specifications, and
both prefix (2-5, 7-) and suffix (-4) forms, whose end is clamped to the
representation. Numbers too large for a long become unsatisfiable instead of
overflowing. A single satisfiable range produces 206 with
Content-Range: bytes first-last/length; several produce a
multipart/byteranges body with the fixed boundary
HttpPreconditions.BOUNDARY and a Content-Range on each part. A malformed,
over-large or unsatisfiable range produces 416 with
Content-Range: bytes */length. Both 206 and 416 carry Accept-Ranges: bytes.
The 304, 412 and 416 responses are bodiless and keep only the original cache
validators (Content-Location, ETag, Expires, Vary, Cache-Control,
Last-Modified).
Evaluation applies to buffered responses after encoding: byte arrays, and
strings read as UTF-8 bytes. It also applies to a stream whose response declares
a total representation length and a slice writer, such as the files served by
StaticFiles: ranges are written from those slices, so
206 and 416 need no buffer. An ordinary stream is deliberately left
unchanged. A stream without a declared length has no total against which a
byte range or a 416 with bytes */length can be defined; an application that
needs ranges over such a body must slice the data itself before streaming it. A
multipart body over a buffered response also counts toward the
1 MiB buffered response limit, so a request for many overlapping
ranges can exceed it; cap the ranges or slice the data in the application for
large bodies.
HttpPreconditions.preconditionRequired() answers 428 with code
precondition_required when an unsafe method (anything other than GET, HEAD,
OPTIONS or TRACE) carries none of If-Match, If-None-Match or
If-Unmodified-Since. Registering either middleware has no effect on requests
that carry no conditional fields, and both are immutable and thread-safe.
Serving static files
StaticFiles in axiom-core is an opt-in handler for files from a directory or
a classpath location. There is no new dependency, no transport hook and no
server mode: register it on a route with a terminal wildcard and, when
conditional and range answers are wanted, register the middleware above.
app.use(HttpPreconditions.conditional()); // optional: 304, 412, 206 and 416 for files
app.get("/assets/*path", StaticFiles.directory(Path.of("public")).build());
app.get("/ui/*path", StaticFiles.classpath("web/ui")
.maxFileSize(8L * 1024 * 1024)
.cacheControl("public, max-age=3600")
.build());
The wildcard capture (named path by default, change it with capture(name))
is the file path. It passes the raw-path policy
before any file system access: empty and dot segments, backslashes, controls and
NUL, malformed escapes and encoded dot, slash, backslash or NUL answer 400.
Remaining escapes are decoded once as strict UTF-8, then normalized and checked
for containment; symbolic links are followed only while their target stays under
the root. Missing files, directories and targets outside the root answer 404,
and files above maxFileSize (64 MiB by default) answer 413. All three are
problem responses with fixed codes and no path or file system detail.
Every file response carries Content-Type from a bounded built-in extension
table (override individual extensions with contentType(extension, value)),
Cache-Control, Accept-Ranges: bytes, a strong SHA-256 ETag and, when the
source supplies a time, Last-Modified. GET streams the file in bounded pieces
through the normal response stream path, so a 64 MiB file does
not become a 64 MiB heap array; the stream is cancelled with the request. HEAD
sends no body and advertises the representation’s Content-Length. The handler
is immutable and thread-safe; one instance can serve any number of routes.
A file replaced between hashing and streaming can produce an ETag for one
version and bytes from another, so publish immutable files when that matters;
JAR entries that carry no usable timestamp are served without Last-Modified.
Resource limits
Each listener owns one acceptor thread and one I/O thread per available processor
(at least two). Execution belongs to the application:
all listeners and test clients share one dispatcher and its deadline scheduler,
which defaults to 36 active virtual-thread tasks with no waiting queue across
the whole application.
Aggregate and route limits are configurable through app.executionBudget(...)
(or the app.admissionPolicy(...) views of the same budget); see
admission and bounded queues. User handlers never execute on I/O
threads. Full execution capacity with no free queue slot, or an expired queue
wait, produces 503 and closes that connection. So does any other failure to start
a request, including a pipelined request reached after the application has
closed. Connections are limited to 128 by default; additional connections close immediately
without a response and without consuming a slot. A connection that only lingers after its last response
(see wire behavior) gives its slot back, because it holds no request
data and its remaining life is bounded by the linger caps. At most 32 connections per
listener linger this way by default; beyond that a lingering connection keeps its slot until it
closes, so a listener never has more than 160 open sockets by default (the connection cap plus
the lingering pool). The gauge axiom.http.connections (tag state = open or lingering)
reports both pools, see observability. The listening socket requests a 1024-entry accept
backlog and sets SO_REUSEADDR so a restart can rebind while old connections
linger in TIME_WAIT. Connections use TCP_NODELAY and a 32/128 KiB write-buffer
water mark. A connection holds at most eight outstanding requests, including the
running one. A further request is refused when its head arrives: it is never
executed, and after the eight earlier responses it is answered 503 and the
connection closes (see errors on pipelined requests).
Reads continue while a handler runs, so a client disconnect (including a
half-close after sending the request) cancels and interrupts the active handler
and drops queued requests. Pipelined requests are buffered only up to the
eight-request bound above; the next queued handler starts after the previous
write completes. The decoder limits request lines to 4 KiB (414 beyond) and headers to 8 KiB (431
beyond). Request bodies are limited by app.maxRequestBody (1 MiB by default, at
most 64 MiB): an oversized Content-Length gets 413 before the body is read, and a
chunked body gets 413 as soon as its running total exceeds the limit. Per connection the listener holds at most the running request’s body (L) plus
the bodies of waiting pipelined requests and the body being received (2 × L
together; a request that would exceed that share is answered 503 after the earlier
responses and the connection closes), so 3 × L with
L = maxRequestBody. Across all of a listener’s connections, request bodies are further
limited by maxInFlightBodyBytes (64 MiB by default): a request whose body does not fit in what
remains is answered 503 and its connection closes, instead of the listener holding up to
128 × 3 × L; see request bodies. A streaming route holds only
the bytes its reader has not consumed, pauses channel reads at 64 KiB and resumes below 16 KiB,
and charges those queued bytes to the same budget. Body bytes are copied out of network buffers as
they arrive, so no Netty buffer is retained across reads. With
compression enabled, both wire and decoded bytes are checked against these
limits and the decoded bytes are what the listener reserves and the handler receives.
Response bodies are limited to 1 MiB of encoded bytes (a String counts its UTF-8
bytes) and response headers to 8 KiB, counted as name, value and four characters
per field; header values must be Latin-1. Other responses produce 500. The listener
and TestClient apply these rules from one shared definition. Application allocations before
returning a response are outside these limits. Connections close after 30 seconds
without network read/write activity, including idle keep-alive connections and a
response write stalled by a client that stopped reading. A request waiting for
admission or a running handler is not interrupted by inactivity; its queue wait
and execution deadline bound it instead. Writing one response must also finish
within 30 seconds of handing it to the socket: a client that keeps reading a few
bytes at a time never looks inactive, so without this bound it could hold a
connection indefinitely. When the bound passes, the connection closes and the
client receives a truncated response; at the 1 MiB response limit this needs a
client reading slower than about 35 KB/s. The same bound applies to the write of the interim
100 Continue, tracked separately from the final response because the client may send its body
while that write is pending: a client that never reads loses the connection after
responseTimeout instead of after the inactivity timeout. A stream is not a response of at
most 1 MiB: its body is limited by its own byte cap (64 MiB by default), by the request
deadline, and by the same 30 seconds for a client that takes no data, applied to each wait for
the channel to become writable rather than to the whole stream. The inactivity timeout does not
interrupt a running stream either; a handler that is writing nothing is bounded by the request
deadline.
A request head must arrive within ten seconds of its first byte; otherwise the
listener answers 408 Request Timeout and closes (after any earlier pipelined
responses). Trickling bytes does not extend the bound. The
bound also starts when the head’s first bytes arrive together with the end of the
previous request or its body; empty lines before a request line, which are ignored,
do not start it.
A request body must arrive before the request deadline, which starts when the head
is parsed; otherwise the listener answers 408 and closes. A connection receiving
body bytes is not idle, but one that stops sending mid-body for 30 seconds is.
The default execution deadline is ten seconds, configurable before startup through
app.requestTimeout(Duration). Responses include a generated X-Request-ID, a correlation value
that is predictable within one process and must not be used as a secret or credential.
See execution and deadlines for timing, cancellation and capacity ownership.
A listener serves HTTPS when its options carry TLS. HTTP/2 is opt-in; WebSocket is registered per path on the HTTP/1.1 listener. Conditional and range requests, streaming request bodies and multipart parsing are available. Observability adapters ship as opt-in modules (observability).
HTTP/2
ListenerOptions.builder().http2(true) opts one listener into HTTP/2. The default is false, so
a listener without it is byte-for-byte the HTTP/1.x listener described above. This is a transport
choice only: no application or core API changes, and no third-party dependency enters
axiom-core. Both wire protocols call the same dispatcher, handlers, error mapping, codecs and
response serialization, with the same timeouts, admission, body budgets and shutdown.
With TLS, ALPN offers h2 followed by http/1.1. A client that negotiates h2 gets
HTTP/2; a client that negotiates http/1.1 or offers no ALPN gets HTTP/1.1 on the same port. TLS
1.2 remains the minimum (HTTP/2 requires at least 1.2), and cipher policy, the handshake timeout
and certificate reload are unchanged. On a cleartext listener the first bytes choose the protocol:
the HTTP/2 client preface selects h2c prior knowledge, and anything else selects HTTP/1.x. An
HTTP/1.1 Upgrade: h2c request is not supported and is answered 501 as before.
var options = ListenerOptions.builder().http2(true).build();
var server = app.listen(new InetSocketAddress("0.0.0.0", 8080), options);
HTTP/2 pseudo-headers become ordinary request headers; Request still has no protocol version.
Request trailers on a buffered body are merged into ctx.request().headers() before the handler
runs; a streaming handler starts before the trailers arrive and does not see them. A response may
send trailers by naming them in a Trailer header and setting each as an ordinary header: the
listener moves the named fields into the HTTP/2 trailing HEADERS frame and omits them from the
initial headers. Hop-by-hop and Connection-nominated headers are removed as on HTTP/1.1, and
every response still carries X-Request-ID and Date.
maxPipelinedRequests is advertised as SETTINGS_MAX_CONCURRENT_STREAMS and maxHeaderBytes as
SETTINGS_MAX_HEADER_LIST_SIZE, so concurrent streams and header sections obey the same per-listener
limits. A streamed response writes DATA frames in bounded pieces and pauses while the stream’s
flow-control window is closed; buffered bytes still count against maxInFlightBodyBytes. Cancellation,
deadlines and the stream admission lane behave as on HTTP/1.1. Closing a listener sends GOAWAY, lets
running streams finish, and closes the connection when the last one ends, within shutdownGrace.
TestClient stays in memory and HTTP/1-shaped; it does not simulate h2c or ALPN. Use a real
listener for wire-level HTTP/2 tests.
Compression
var options = ListenerOptions.builder().compression(true).compressionLevel(1).build();
var server = app.listen(new InetSocketAddress("0.0.0.0", 8080), options);
Compression is off by default and is a transport choice only. With compression(true),
a listener decodes one gzip or deflate request coding and may compress a response. No new
dependency enters axiom-core, no public transport type is added, and an in-memory
TestClient stays uncompressed and HTTP/1-shaped regardless of the option.
Requests. Content-Encoding: gzip or deflate is decoded before the handler runs; the
handler sees decoded bytes and no Content-Encoding. A single gzip or deflate transfer
coding before chunked is decoded as well, and the handler sees plain Transfer-Encoding:
chunked. Other codings receive 415, several codings (including duplicates, or a coding
both in Content-Encoding and Transfer-Encoding) receive 415 for content codings and
400 for transfer codings, and an unknown transfer coding keeps the previous 501.
At most one coding is ever decoded. Malformed or truncated compressed bodies receive 400.
Responses. Accept-Encoding is parsed with q-values; an explicit entry wins over * and
a higher q-value wins over the listener’s gzip-then-deflate preference. A coding with q=0
is not used. No header, no acceptable coding, or a body below 512 bytes leaves the response
uncompressed; a compressed result that is not smaller than the original is also sent
verbatim. Compressed responses carry Content-Encoding, Vary: Accept-Encoding and a
Content-Length for the bytes actually on the wire. Vary is appended to any value the
application set, unless it is *. A response that already has a Content-Encoding, an
already-compressed media type (gzip/zip/font formats, image/, audio/, video/), a
Content-Range, or status 204, 304, 206 or 416 is never compressed. HEAD responses,
streamed responses of unknown length, and WebSocket upgrade responses are never compressed.
A streamed response whose total representation length is known is compressed too, provided its
status is 200 and the request is not HEAD or HTTP/1.0. Content-Encoding and Vary are sent
with the head; the body stays chunked because the compressed length is not known in advance.
Compression is flushed with each write, so it adds no latency beyond the existing backpressure,
and the byte cap, deadline and cancellation still apply to the bytes the handler writes, not to
the compressed bytes on the wire. Static files served through StaticFiles are the built-in
example of such a stream. An application that needs a different policy can compress in a
handler and set Content-Encoding itself; the listener will not compress that response again.
Bounds and security. Both the wire length and the decoded length of a request body are
checked against app.maxRequestBody and the listener’s maxInFlightBodyBytes; a body that
expands past either limit receives 413 as soon as the limit is reached, before a large
decoded array is allocated. Decoding uses a fixed 8 KiB scratch buffer and a gzip header
bounded to 64 KiB, and adds only the decoded bytes to the listener’s reservation. A gzip
member’s CRC and length are verified. A compressed request therefore cannot turn a small
upload into a large allocation, and a peer that sends a truncated or trailing-coded stream
gets an opaque problem response.
Cost and tuning. Compression is CPU work on the channel’s I/O threads. It stays there
deliberately: the work is bounded by the body limit, uses one copy-free buffer and needs no
queue or extra copies, whereas an offloaded pool would add both and hurt tail latency on the
very connections that benefit from compression. compressionLevel (1 to 9, default 6) trades
CPU for bytes on responses; it has no effect on decompression, whose level the sender chose.
The axiom.http.compression.bytes, axiom.http.compression.responses and
axiom.http.compression.time metrics report wire bytes, representation bytes, outcomes and
time in both directions, so the level can be chosen from evidence rather than guesswork.
Enable compression where the bandwidth saving is worth that cost, and keep the response body
limit in mind when compressing highly compressible data.
Listener options
Transport limits and timeouts are set per listener with an immutable ListenerOptions,
passed to app.listen(address, options). app.listen(address) and app.listen(port) use
ListenerOptions.defaults(), which keeps the values described in this document. Each
builder method validates its value when called and throws IllegalArgumentException naming
the setting and its range; build() cannot fail. The options apply to that listener only, so
listeners of one application may differ. Application-level limits (request body size,
execution deadline, the shared admission budget and the stream bound) stay on the
application.
var options = ListenerOptions.builder()
.shutdownGrace(Duration.ofSeconds(30))
.maxConnections(512)
.build();
var server = app.listen(new InetSocketAddress("0.0.0.0", 8080), options);
| Setting | Default | Valid range | Governs |
|---|---|---|---|
shutdownGrace |
5 s | 0 to 1 day | Time close() lets running exchanges finish before connections close and handlers are interrupted; zero interrupts at once |
idleTimeout |
30 s | 1 ms to 1 day | Network inactivity after which a connection closes |
headTimeout |
10 s | 1 ms to 1 day | Time from a request’s first byte until its head is complete (408) |
responseTimeout |
30 s | 1 ms to 1 day | Time to write one response to the socket, including an interim 100 Continue |
lingerTimeout |
2 s | 1 ms to 1 day | Total linger after the last response |
lingerQuietTimeout |
500 ms | 1 ms to 1 day | Silence that ends lingering |
shutdownLingerTimeout |
500 ms | 1 ms to 1 day | Total linger once the listener is closing (the smaller of this and lingerTimeout applies) |
handshakeTimeout |
10 s | 1 ms to 1 day | Time a new connection may take to finish its TLS handshake; applies only with tls |
tls |
none (plain HTTP) | a TlsOptions |
Serves HTTPS with the given certificate, protocols and client-authentication settings; validated at startup, see TLS |
http2 |
false |
true or false |
Accepts HTTP/2 in addition to HTTP/1.x: h2 through ALPN with TLS, h2c prior knowledge in cleartext; see HTTP/2 |
compression |
false |
true or false |
Decodes one gzip/deflate request coding and compresses eligible responses; bounded by the body limits; see compression |
compressionLevel |
6 | 1 to 9 | Deflater level for compressed responses; 1 spends less CPU and 9 produces smaller bodies; see compression |
maxDiscardedInput |
16 MiB | 0 to 1 GiB | Bytes discarded unread after an error or last response before the connection closes |
maxConnections |
128 | 1 to 1,000,000 | Open connections per listener |
maxLingeringConnections |
32 | 0 to 1,000,000 | Lingering connections that stop counting against maxConnections; zero keeps them on their regular slots |
maxPipelinedRequests |
8 | 1 to 1024 | Outstanding requests per connection, including the running one |
maxInFlightBodyBytes |
64 MiB | 1 byte to 1 TiB | Request body bytes the listener holds at once, across connections (503 beyond); must be at least the application’s maxRequestBody |
maxRequestLine |
4096 | 256 to 65,536 | Longest request line in bytes (414 beyond) |
maxHeaderBytes |
8192 | 256 to 1 MiB | Largest header section in bytes (431 beyond) |
ioThreads |
processors, at least 2 | 1 to 1024 | I/O threads of the listener; handlers never run on them |
transport |
AUTO |
AUTO, NIO, EPOLL, KQUEUE, IO_URING |
I/O mechanism; AUTO uses epoll, io_uring or kqueue when their native library is on the class path and usable, NIO otherwise; see native transports |
rejectionObserver |
none | a RejectionObserver |
Called with status, problem code and request ID for each error response the listener generates itself; see observing rejections |
name |
default |
lowercase letters, digits, _; at most 32 |
The listener tag of the listener’s metrics |
Choosing values:
- File descriptors and load balancers. A listener can hold
maxConnections + maxLingeringConnectionssockets (160 by default) plus its listening socket, its event-loop selectors and wakeup pipes, and the files and outbound connections the application itself opens. Raise the process descriptor limit (ulimit -n, container or systemdLimitNOFILE) above the sum over all listeners with headroom, and size any connection limit on a load balancer or proxy in front of the listener to the same sum, not tomaxConnections. The lingering pool is only used briefly, but a burst of connections that all end at once can fill it. - Total open sockets are at most
maxConnections + maxLingeringConnections. The memory held for request bodies is capped bymaxInFlightBodyByteshowever many connections are open (see request bodies); lower it to bound heap use under many slow uploaders, and raise it together withmaxRequestBodywhen large bodies must upload concurrently. - The connection cap and admission are independent limits. A connection over the cap is closed
at once without a response, so the client sees a closed connection, never a 503; admission 503s
are only produced for requests on accepted connections. A cap below the application’s aggregate
admission capacity (active plus queued requests across all of its listeners and test clients)
leaves part of that capacity unreachable, because clients are turned away before admission could
queue or answer them. Set
maxConnectionsat or above the capacity one listener should be able to reach, plus headroom for idle keep-alive connections; see admission and bounded queues. - A short
shutdownGraceinterrupts handlers sooner; a long one delaystermination()for as long as a handler keeps running. Handlers must still cooperate with interruption. lingerQuietTimeoutlonger thanlingerTimeouthas no effect beyond the total bound, and a very smalllingerQuietTimeoutraises the chance that a client still sending gets a reset (see wire behavior).responseTimeoutis also the stall bound of streamed responses. The byte cap of a stream is not a listener option: each response sets its own (Response.DEFAULT_STREAM_LIMITby default); see streaming.- On a TLS listener,
handshakeTimeoutbounds the handshake and a connection holds its slot while it handshakes; see handshake limits. headTimeoutandidleTimeoutare the main defense against slow clients; raising them or the connection cap widens the exposure to slowloris-style clients.
Native transports
A listener runs on the JDK’s NIO selector by default. Linux (epoll and io_uring) and macOS or
BSD (kqueue) have native Netty transports that axiom-http can use instead. They change how
the event loops wait for sockets and nothing else: request handling, limits, timeouts,
lingering, draining on close() and write backpressure are the same code on every transport,
and the HTTP and TLS tests run on them (see below).
var options = ListenerOptions.builder().transport(TransportKind.AUTO).build(); // the default
TransportKind |
Meaning |
|---|---|
AUTO (default) |
epoll if usable, then io_uring if usable, then kqueue if usable, else NIO. Never fails for lack of a native library |
NIO |
The JDK selector. Always available; never replaced by a native transport |
EPOLL |
Linux epoll. Startup fails with IllegalStateException if the library is missing or does not load |
KQUEUE |
kqueue. Same rule |
IO_URING |
Linux io_uring. Same rule; also needs a kernel that supports io_uring and permission to use it |
IO_URING is opt-in and Linux-only. Netty needs a recent kernel (5.10 or newer) with io_uring
enabled, and the process must be allowed to call it: container seccomp profiles commonly deny
io_uring, and in that case Netty reports the transport as unavailable. AUTO selects io_uring
only when its library is present, it is usable on the host, and no earlier native kind was
selected, so applications that add nothing keep NIO and applications that add several native
artifacts keep the mature epoll default.
An explicit native kind fails before any socket or thread exists, naming the artifact to add and
carrying Netty’s reason (for example a platform without epoll, or a container blocking io_uring)
as the cause. AUTO falls back silently, so the same build runs on a developer’s laptop and in a
container.
Adding a native transport
The native libraries are optional runtime dependencies. axiom-http compiles against Netty’s
epoll, kqueue and io_uring classes but does not depend on them, they are not in its POM, and an
application that adds nothing runs on NIO exactly as before. To opt in, add the artifact with the
classifier of the platform the application runs on, at the same Netty version as axiom-http
(the Netty BOM io.netty:netty-bom keeps them aligned):
dependencies {
runtimeOnly("io.netty:netty-transport-native-epoll::linux-x86_64") // or linux-aarch_64
// runtimeOnly("io.netty:netty-transport-native-io_uring::linux-x86_64") // Linux only
// runtimeOnly("io.netty:netty-transport-native-kqueue::osx-aarch_64") // or osx-x86_64
}
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport-native-io_uring</artifactId>
<classifier>linux-x86_64</classifier>
<scope>runtime</scope>
</dependency>
Add the classifier that matches the production host, not the build host, or use several
(the extra jars are inert where they do not load). Netty loads the library from the jar at
startup, which needs a writable temporary directory that is not mounted noexec. Applications that
check dependency checksums need the new artifacts and POMs in their verification metadata; this
repository’s own gradle/verification-metadata.xml carries them for linux-x86_64, linux-aarch_64,
linux-riscv64 (io_uring), osx-x86_64 and osx-aarch_64.
How it is tested
./gradlew check runs the integration tests of axiom-http three times. integrationTest has no
native library on its class path, so AUTO is NIO. integrationTestNative adds the native library
of the build platform (epoll on Linux x86_64 and aarch64, kqueue on macOS) and, on Linux, the
io_uring library, so AUTO must select the first native transport and every real-socket test (plain
HTTP, TLS, lingering, shutdown and connection draining, write backpressure, body budgets) runs on
it unchanged. integrationTestIoUring adds only io_uring, so AUTO must select IO_URING on a
Linux host where it is usable. TransportSelectionTest additionally names each transport
explicitly and checks selection, HTTP, HTTPS and shutdown on it; a unit test pins that an explicit
IO_URING kind fails resolution and startup before a socket exists when its classes are absent.
On a platform without the matching Netty native library, or where the library cannot load, the
native cases skip cleanly. -Daxiom.requireNativeTransport=true turns that skip into a failure for
the transport the build provides (axiom.expectedTransport): an io_uring-only run does not also
require epoll or kqueue, whose classes are absent from that class path. CI runs a dedicated
native-io-uring job on ubuntu-latest with that flag: ./gradlew
:axiom-http:integrationTestIoUring -Daxiom.requireNativeTransport=true --rerun-tasks
--no-build-cache. It then parses TransportSelectionTest’s XML and requires at least one
testcase, failures="0" and errors="0" for the suite, and no skip for
autoPicksTheNativeTransportExactlyWhenTheBuildProvidesIt. The XML is uploaded as evidence and the
job is part of check, so CI requires and verifies a real io_uring listener on Linux rather than
accepting a silent skip.
Decision: the default and io_uring
The default is AUTO because applications choose the native transport by adding its artifact: with
the artifact present they get it, without it nothing changes. No measurement is published and none
is claimed; the choice rests on epoll and kqueue being Netty’s mature, widely deployed transports
with the same semantics as NIO for the features Axiom uses, and on the whole HTTP suite passing on
both. Anyone who wants numbers can compare the transports with the
benchmarks on their own hardware.
Netty’s io_uring transport (netty-transport-native-io_uring) is supported as an opt-in
TransportKind.IO_URING on Linux. It uses the same listener code as every other kind, but it needs
a recent kernel and permission to use io_uring, which many container seccomp profiles deny; where
it cannot be used, AUTO falls back and an explicit request fails before binding. Because it is
less mature than epoll, AUTO prefers epoll when both libraries are present, and applications
that need io_uring name it or add it as the only native artifact. The transport boundary is
ListenerOptions.transport, so choosing it never changes how listeners are used.