Repository navigation
Design HTTP Client
Status: 9a done (cleartext upstreams) · Date: 2026-11-09 · User docs: HTTP Client
A handler that needs another service (an upstream API, a data source, the next hop of a proxy) has no way to ask it without blocking its worker, and a blocked worker stops every connection it owns. The 0.x line had a minimal blocking client; the 1.x engine has none. This keeps viltrum out of every app that calls another service, out of reverse proxying, and out of Sharkbench, whose requests each fetch JSON from a local data source over HTTP.
A handler asks an upstream over HTTP/1.1 and answers when the reply comes in, on the same worker, without holding it, with keep-alive connections pooled per worker and no allocation per request once the pool is warm.
It follows Ctx.after, which already answers a request later: the handler returns at once, the request's
connection (or HTTP/2 stream) waits, and a callback on the same worker writes the response. The only difference
is what ends the wait. For after it is a timer; for a fetch it is the upstream's reply, with a timer kept as
the timeout.
mut app := viltrum.new()
// at startup: resolves the host once (blocking is fine here) and sets up a pool on every worker
data := app.upstream('http://127.0.0.1:9000', viltrum.UpstreamOptions{})!
app.get('/user/:id', fn [data] (mut c viltrum.Ctx) {
c.fetch(data, .get, c.path(), on_user, 0)
})
fn on_user(mut c viltrum.Ctx, arg u64) {
r := c.fetched()
if r.err != .none {
c.text(502, 'upstream failed')
return
}
c.bytes(r.status, c.fetched_header('content-type') or { 'application/octet-stream' }, r.body)
}-
app.upstream(url, opts)takeshttp://host[:port](no path). It resolves the host at startup and returns anUpstream, a small value naming the pool. Hosts are not looked up again while serving: no DNS on the hot path and no resolver thread. -
c.fetch(up, method, target, cb, arg)sendsmethod targetwithHost, andContent-Lengthwhen there is a body. Afterfetchand before the handler returns,c.fetch_body(data)sets a body andc.fetch_header(name, value)adds a header (at most 8). The request is copied into the upstream connection's write buffer when the handler returns, sotarget,dataand header values can be views of the incoming request (c.path(),c.body(),c.header(...)). -
cb(mut c, arg)runs once: with the reply, or with an error. As withafter, the request is gone by then. Pass whatcbneeds inarg.cbmay fetch again (a chain of calls) or callafter. -
c.fetched()isFetched{err, status, body}.c.fetched_header(name)reads a reply header. Both are views into the upstream connection's read buffer, valid untilcbreturns.
Errors (FetchError): .none, .connect (refused or unreachable), .timeout (no whole reply within
timeout), .closed (the upstream closed before the reply was whole), .protocol (not a valid HTTP/1.1
reply), .too_big (reply past max_reply), .busy (pool and queue full).
UpstreamOptions: max_conns per worker (default 64), max_queue per worker (default 1024), timeout from
the fetch to the whole reply (default 10 s), idle_timeout for pooled connections (default 30 s), max_reply
(default 1 MiB).
-
Peer. An upstream connection, a sibling of
Connon the same epoll set. The loop keepspeers []&Peerindexed by fd, besideconns. A file descriptor is in one table or the other, soon_eventtriesconnsfirst, thenpeers. APeerborrows its buffers from the worker's pools the same way aConndoes. -
Pool. Each worker has one
Poolper upstream: idle peers (a stack, most recently used first), the busy count, and a FIFO queue. A fetch takes an idle peer, or connects a new one belowmax_conns, or waits in the queue. The queue holds the request already written out as bytes, plus the waiter. Pastmax_queue, the fetch answers.busyat once. -
Waiter. What the peer answers:
(fd, gen, stream, serial).streamis the HTTP/2 stream id, 0 for HTTP/1.1.serialcounts waits on a connection, so a reply cannot answer a later request that reused the connection after this one timed out. HTTP/2 stream ids are never reused, soh2_resumealready drops a stale one. The wait parks exactly likeafter:Conn.pendingwithc.waitingon HTTP/1.1, the stream's slot on HTTP/2. Its timer, due attimeout, is the timeout. -
Reply. The peer frames the reply in its read buffer. On the last byte it sets the worker's
fetchedstate (views into its buffer) and resumes the waiter directly (resumeorh2_resume, asfiredoes), then flushes that connection and serves what was pipelined behind. It then takes the next queued request, or goes back to the idle stack. A reply whose waiter is gone (timed out, client closed) is read to its end and dropped, and the peer is reused. -
Timeout. The waiter's timer fires
cbwith.timeout. The peer keeps its own deadline, the same timeout plus a second:sweepcloses a peer past it, so a hung upstream cannot keep a connection forever. -
Connect. A non-blocking
connect, thenEPOLLOUT, thenSO_ERROR. The request bytes are already in the write buffer and go out when the connection is up. -
Stale keep-alive. An idle peer that becomes readable (the upstream closed it, or sent something it should
not have) is closed. A request whose peer closes before any byte of the reply arrives is retried once on a
new connection if its method is idempotent (GET, HEAD, PUT, DELETE, OPTIONS). Otherwise it answers
.closed. -
Reply framing (
http1/reply.v, portable, unit-tested and fuzzed): status line, header fields,Content-Length, chunked (decoded in place, as request bodies are), close-delimited bodies, no body for HEAD/204/304, 1xx skipped,Connection: closeand HTTP/1.0 ending reuse. The same limits as requests on header count and size.
Peers, pools and queues grow on the cold path, up to the most ever busy at once, then they are reused. Writing
the request and framing the reply happen in buffers the peer borrows. The gate gets a fetch scenario: the same
allocated_bytes diff the process tests use, around a batch of warm fetches.
- 9a: cleartext HTTP/1.1 upstreams, over HTTP/1.1 and HTTP/2 front connections. Everything above.
-
9b: TLS upstreams (
https://): mbedtls in client mode, SNI from the host, certificates checked against the system CA bundle (orUpstreamOptions.ca_file). Handshakes use the same one-per-loop-turn queue as the server.
- URLs chosen per request, or DNS while serving. Upstreams are declared at startup.
- Fetching from outside a handler (background threads). The client lives on the workers.
- Several fetches in parallel from one request. Chaining them one after another works.
- Streaming reply bodies, request-body streaming, and a reverse-proxy middleware. A proxy can be written on top
of
fetchfor bodies undermax_reply. A real proxy (streaming, hop-by-hop headers) is its own item. - Redirects, cookies, decompression (no
Accept-Encodingis sent), HTTP/2 to the upstream, pipelining to the upstream. - Windows and macOS: the client is part of the epoll engine.