On this page

0281. HTTP server v2: one poll loop, keep-alive, streaming and SSE

Context

v1 (ADR-0165) serves one connection at a time, Connection: close, with a 30 s total deadline per connection (ADR-0163). One slow client (slow-loris headers, a stalled reader) blocks every other client for up to 30 s, each request pays a TCP handshake, and nothing can stream: agent UIs cannot push model tokens to a browser. http.wire rejects Transfer-Encoding (501). Threads are a poor fit: par workers reject non-Fs capabilities (ADR-0103), arenas are per thread (ADR-0102), and the runner is single-threaded (ADR-0107). The outbound side already has a pull-based http.transport (start/poll/cancel, ADR-0247) and a chunk-safe SSE parser (ADR-0108). TLS stays at a reverse proxy (Caddy) on the box, per PLAN-http; WebSockets are later.

Decision

  1. Concurrency: one thread, one poll(2) loop, non-blocking sockets. No worker pool, no process per connection in v2. A slow client never blocks others; a slow handler still does, and handlers must bound their work (as today). A par handler pool is a later ADR, only if Measurement S2 shows handler CPU dominates. Multi-core = run N processes later (SO_REUSEPORT), not threads.
  2. One new native set on cli (as ADR-0165 foresaw): Net.wait(listener, reads: vec<Conn>, writes: vec<Conn>, ms) -> result<Waited, CliError> with Waited { now_ms, events } and NetEvent = Accepted(Conn) | Data(Conn, bytes) | Writable(Conn) | Closed(Conn) | Term; Conn.write_some(bytes) -> result<i64, CliError> (bytes taken, non-blocking) and Conn.key() -> i64. Events are ordered listener first, then by key, so both backends agree. C: poll(2) plus a SIGTERM/SIGINT self-pipe (Term). Interpreter: set_nonblocking scan with 1 ms backoff (std only, no crate, no unsafe). Wait-accepted conns have no total deadline; the server's timers replace it. CliError.Io keeps its fixed message set.
  3. Pure core, thin driver (http.server). step(Server, Waited) -> Stepped { server, out: vec<Out> } with Out = Write(key, bytes) | Close(key) | Dispatch(id, Request) holds per-connection parser state, timers and buffers as plain values (map set-reuse, ADR-0053). It is unit-testable with fake events; the driver only calls Net.wait/write_some.
  4. Two APIs, no closures needed. Plain: serve(listener, handler, cfg) keeps Handler.handle(Request) -> Response unchanged. Pull (for agent apps, mirrors ADR-0247): poll(server, ms) -> Polled { server, events }, then respond(server, id, Response), open(server, id, status, headers), send(server, id, bytes) -> Sent, finish(server, id). The app's loop polls its model Transport and the server side by side; no callback crosses C. Once ADR-0275 closures land, serve_fn(listener, cfg, { req -> ... }) and middleware become plugin sugar over the same core.
  5. Keep-alive and limits (Config, defaults): max_conns 256 (at the cap, stop polling the listener; the kernel backlog pushes back), head_ms 10 000 for a complete request head, idle_ms 5 000 between requests, write_stall_ms 30 000, max_requests 1 000 per connection, out_cap 1 MiB buffered per connection, plus wire.Limits (8 KiB line, 16 KiB / 100 headers, 1 MiB body). One request in flight per connection; pipelined bytes wait in the input buffer under the same caps. Connection: close and HTTP/1.0 are honoured.
  6. Streaming. Chunked request bodies are decoded under the body cap (501 goes away). open responses use chunked framing on HTTP/1.1 and close-delimited on 1.0. Fixed responses keep Content-Length.
  7. Backpressure. send returns Sent.Queued | Sent.Full; Writable(id) fires below half of out_cap. A stream above out_cap for write_stall_ms is closed, so one stalled SSE reader cannot grow memory.
  8. SSE (http.sse): event(name: option<str>, id: option<str>, data: str) -> bytes splits data on LF into data: lines and rejects CR/LF in name/id; comment(str); start(headers) sets text/event-stream, Cache-Control: no-cache. The server sends a : heartbeat every 15 s on idle streams. Last-Event-ID reaches the app as a header. Encoder output must parse back unchanged under ADR-0108's rules (CR/LF/CRLF, joined data lines).
  9. Graceful shutdown. On Term: stop polling the listener, close idle connections, send Connection: close on in-flight responses, emit Term to pull apps (to end streams), and exit after drain_ms (10 000).
  10. Arenas. Each step/poll call is one transition (ADR-0107 shape): request parsing and handler scratch die with it; only Server state carries over.

Prior art

Alternatives considered

Consequences

UX: one slow browser or stalled tab no longer freezes the app; tokens stream live. DX: same Handler, keep-alive by default, a documented knob set mirroring Go's. AX: one loop, one native, pure step testable with fake events; the pull API reuses the ADR-0247 shape agents already know. Harder: the per-connection state machine is new code (~600 lines Tenon); slow handlers still block (documented). LANGUAGE.md: 0 lines; plugins/http/DOCS.md (1 500 budget, near full) moves transport detail to a linked section. No new compile-time diagnostics. Frozen files (slice 4 only, needs the maintainer's OK): plugins/cli/platform.toml, plugins/cli/native/trt_net.h, plugins/cli/DOCS.md, crates/tenon/src/interp_net.rs, crates/tenon/src/interp.rs (native dispatch). Coordinate with Forge P7/P8, which also serve HTTP.

Measurement plan

Baseline v1 before any code, in new bench/http/ (opt-in, not the gate). Load client: a stdlib-only Python asyncio client (bench/http/load.py); oha/wrk used when on PATH. C backend for timing; the interpreter only for byte-identical responses. Record req/s, p50/p99 latency, peak RSS, open fds; 5 runs, median.

ID Scenario v2 acceptance
S1 1 / 16 / 256 keep-alive clients, 200 B GET 1 client within 10% of v1; 16 ≥ 3× v1; 256 no errors, RSS ≤ 64 MiB, fds ≤ 272
S2 1 slow-loris (1 byte/s head) + 16 fast clients fast p99 ≤ no-loris p99 + 5 ms (v1: ~30 s)
S3 1 reader that stops reading a 10 MiB stream + 16 fast same as S2; RSS growth ≤ out_cap
S4 SSE fan-out: 100 clients, 10 events/s × 200 B, 60 s all events in order; p99 event latency ≤ 50 ms; RSS flat (≤ 10% after warm-up)
S5 static files 4 KiB and 1 MiB via http.files ≥ Python ThreadingHTTPServer req/s
S6 SIGTERM with 50 in-flight requests all complete; exit ≤ drain_ms

Implementation slices

  1. bench/http baseline of v1 — S1–S6 runner, RESULTS.md. Files: bench/http/. Frozen: no. Agent: Claude Sonnet.
  2. Wire: chunked codec, keep-alive framing, http.sse encoder — test blocks (ADR-0269). Files: plugins/http/{wire,sse}.tn, DOCS.md. Frozen: no. Agent: Claude Sonnet.
  3. Pure http.server core (step, Config, timers, backpressure, pull API) with fake Waited events. Files: plugins/http/server.tn. Frozen: no. Agent: Claude Opus.
  4. Net.wait / write_some / key natives in both backends + Term self-pipe. Files: plugins/cli/platform.toml, plugins/cli/native/trt_net.h, plugins/cli/DOCS.md, crates/tenon/src/interp_net.rs, crates/tenon/src/interp.rs. Frozen: yes. Agent: Claude Opus (or OpenCode build-deep).
  5. Driver serve, examples (examples/tools/http-demo/ SSE token stream), v2 bench run vs thresholds, retire v1 serve loop. Files: plugins/http/{serve,server}.tn, examples/, bench/http/RESULTS.md. Frozen: no. Agent: Claude Sonnet.

Open questions (resolved)

Resolved by maintainer on 2026-11-22: every question takes its stated default.

  1. Approve slice 4's frozen-file touches before M14 ends? Default: yes, after slices 1–3 land.
  2. Default max_conns: 256 or 1 024? Default: 256 (fits default ulimit -n).
  3. Keep v1 serve as an alias of v2 or remove it? Default: alias for one release, then remove.
  4. Handler worker pool: decide now or only if S2/S5 show need? Default: only after measurement.
  5. WebSockets: a separate later ADR on the same loop? Default: yes, after R4 web toolkit ships.