Skip to content

Design HTTP Client

Tuntii edited this page Dec 3, 2026 · 1 revision

Design: HTTP client (Phase 9)

Status: 9a done (cleartext upstreams) · Date: 2026-11-09 · User docs: HTTP Client

Why

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.

Goal

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.

Shape

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) takes http://host[:port] (no path). It resolves the host at startup and returns an Upstream, 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) sends method target with Host, and Content-Length when there is a body. After fetch and before the handler returns, c.fetch_body(data) sets a body and c.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, so target, data and 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 with after, the request is gone by then. Pass what cb needs in arg. cb may fetch again (a chain of calls) or call after.
  • c.fetched() is Fetched{err, status, body}. c.fetched_header(name) reads a reply header. Both are views into the upstream connection's read buffer, valid until cb returns.

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).

Engine

  • Peer. An upstream connection, a sibling of Conn on the same epoll set. The loop keeps peers []&Peer indexed by fd, beside conns. A file descriptor is in one table or the other, so on_event tries conns first, then peers. A Peer borrows its buffers from the worker's pools the same way a Conn does.
  • Pool. Each worker has one Pool per 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 below max_conns, or waits in the queue. The queue holds the request already written out as bytes, plus the waiter. Past max_queue, the fetch answers .busy at once.
  • Waiter. What the peer answers: (fd, gen, stream, serial). stream is the HTTP/2 stream id, 0 for HTTP/1.1. serial counts 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, so h2_resume already drops a stale one. The wait parks exactly like after: Conn.pending with c.waiting on HTTP/1.1, the stream's slot on HTTP/2. Its timer, due at timeout, is the timeout.
  • Reply. The peer frames the reply in its read buffer. On the last byte it sets the worker's fetched state (views into its buffer) and resumes the waiter directly (resume or h2_resume, as fire does), 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 cb with .timeout. The peer keeps its own deadline, the same timeout plus a second: sweep closes a peer past it, so a hung upstream cannot keep a connection forever.
  • Connect. A non-blocking connect, then EPOLLOUT, then SO_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: close and HTTP/1.0 ending reuse. The same limits as requests on header count and size.

Zero allocation

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.

Phases

  • 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 (or UpstreamOptions.ca_file). Handshakes use the same one-per-loop-turn queue as the server.

Not planned in Phase 9

  • 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 fetch for bodies under max_reply. A real proxy (streaming, hop-by-hop headers) is its own item.
  • Redirects, cookies, decompression (no Accept-Encoding is sent), HTTP/2 to the upstream, pipelining to the upstream.
  • Windows and macOS: the client is part of the epoll engine.

Clone this wiki locally