Skip to content

Design Streaming

Tuntii edited this page Dec 3, 2026 · 2 revisions

Design: streaming responses and SSE on the 1.x core

Status: implemented, on HTTP/1.1 (Phase 7a) and HTTP/2 (7b). User guide: Streaming and SSE.

Goal

A response body written over time, after the handler returns, without holding the worker and without allocating per write. Two ways for bytes to arrive:

  • push: timers on the stream, and sends or publishes from any thread (live events, tokens);
  • pull: on_drain, called when everything written so far is out (a large generated body that must follow the client's pace).

Server-Sent Events are a stream with text/event-stream framing helpers on top; nothing in the engine is SSE-specific except the heartbeat.

Shape

It follows WebSocket, which already solved "a connection owned by callbacks after the handler returns":

WebSocket Stream
c.ws_upgrade(h) writes the 101; finish sees x.ws and calls ws_open c.stream/c.sse write the head; finish sees x.st and calls st_open
one http1.Ws per worker, lent per callback (ws_lend / ws_take) one http1.Stream per worker (st_lend / st_take)
Conn.ws, ws_data, subs Conn.st, st_data, the same subs
hub posts with op text/binary hub posts with op = stream_data, plus the target stream

The Stream a callback holds has out set to the connection's write buffer. A write appends to it, framed as one chunk on HTTP/1.1 and raw on HTTP/1.0, so nothing is copied twice and nothing is allocated. st_take takes the buffer back. It then carries out what the callback queued (subscriptions, publishes, timers) and finishes the stream if it ended.

Timers

Stream.after(ms, cb, arg) queues a StreamTimer. st_take pushes it on the worker's existing timer heap, the one deferred responses use. The entry is the usual (fd, generation) plus the connection's stream serial and cb/arg. The serial counts streams per connection: after one stream ends on a keep-alive connection and another starts, a timer left from the first does not reach the second. Loop.fire tells a tick from a deferred response by tick != 0.

tick is the callback's address kept as a u64. With a pointer field, every Timer in scope (the one pop returns, the one fire holds) became a V -prod GC scope pin, which gcpin_check refuses. A function is code; the GC never needs to see it.

Pull: on_drain

Loop.flush writes wbuf, then a file being sent, then held HTTP/2 output. Last, if the connection streams, it calls on_drain; if that wrote anything, it goes round again. After 256 KiB from on_drain in one flush, the connection arms EPOLLOUT and yields, so a client on a fast link cannot hold the worker. EPOLLOUT fires on the next turn of the loop, and the generator continues there.

Push from elsewhere

http1.stream_post / sse_post build a WsPost with op = stream_data and the target StreamId. The StreamId is {worker, fd, gen, stream}, a WsId plus the stream serial. Hub.post routes it unchanged. Worker.deliver checks kinds: a stream post goes to st_push only when the connection still streams with that serial; on a topic, only streams take stream posts and only WebSockets take WebSocket posts. The topic table is shared, since names are names.

A slow client is bounded as for WebSocket: past four times max_pending unread, the connection closes.

Lifecycle

  • Open. st_open saves close_after (from Connection: close, or HTTP/1.0's close-delimited body) into st_close, clears it so the head does not close the connection, and runs on_open.
  • End. end() writes the last chunk. st_take sees ended, runs st_end (on_close with writes dropped; publishes still go out, topics left) and restores the close. On a keep-alive connection, requests pipelined behind the stream are served next, from wherever the end happened (a timer, on_drain, on_open).
  • Client gone. Loop.close calls st_end.
  • Timeouts. sweep skips streaming connections unless output is blocked (EPOLLOUT armed, under the write timeout). It sends due heartbeats on SSE streams.
  • Input. process parses nothing while c.st is set. Input piling up to the read cap closes the connection, as behind a deferred response.
  • handle_raw and tests. process_waiting runs a stream in place: on_drain while it writes, else its next timer, slept out. A stream with neither can never end and is closed.

HTTP/2 (7b)

The same API, a stream per HTTP/2 stream rather than per connection, so a browser can hold many SSE streams on one connection. That is the main reason to have SSE over HTTP/2: browsers allow six HTTP/1.1 connections per origin. The code is in engine/h2_stream.v.

  • State. The stream lives in its H2Stream slot (st, st_data, st_sse, st_last, subs) from its HEADERS until it ends. Slots count against the 128 concurrent streams, so streams cannot outgrow them.
  • Writes. h2_st_lend lends the slot's own out as Stream.out, unchunked; h2_st_take counts what was added as held output, the same held output a response bigger than its window leaves. h2_pump sends it as DATA within the windows, a frame per stream in turn. Nothing is copied twice: the callback writes into the slot, the pump frames it into wbuf.
  • End. end() runs on_close at once (as on HTTP/1.1) and clears st. With nothing held, an empty DATA with END_STREAM goes now and the slot is freed; else the last frame h2_pump sends carries END_STREAM, as for any held response. While st is set, a pump that empties the slot keeps it.
  • Pull. Loop.flush calls h2_drain once the socket took wbuf and the pump has nothing more to move: it runs on_drain on each stream whose slot holds nothing, one call each per pass. A stream whose window is shut holds what it wrote, so on_drain waits for the client's WINDOW_UPDATE. The 256 KiB per flush cap applies.
  • Ids. StreamId.stream is the HTTP/2 stream id. Ids are never reused on a connection, so a timer or a send for a stream that ended finds no slot with its id and is dropped, as the serial does on HTTP/1.1. Timers go on the same heap; st_tick tells the two by c.h2.
  • Topics. A Topic holds (conn, id) pairs, id 0 for a WebSocket or an HTTP/1.1 stream, which is the connection itself. A publish skips only the stream it came from, not its neighbours on the connection. deliver walks a topic from the end, because a stream reset while being written to leaves it on the spot.
  • Cancel. RST_STREAM from the client, our own reset, and the connection closing all run h2_st_end before the slot is released: on_close, topics left.
  • Slow streams. Output a stream's window holds back past four times max_pending resets that stream (CANCEL). Flow control is per stream, so one stalled stream does not close the connection. New streams are refused while the held output of all of them passes max_pending, as for responses.
  • Timeouts. h2_waits covers streams as it does deferred responses: a connection that has nothing coming in part and nothing held back is not idle-timed out. Held output falls under the write timeout through h2_held_deadline. sweep sends due heartbeats on SSE streams.

Not done

  • Request-body streaming (reading an upload as it arrives). The body is still whole when the handler runs.
  • Compression of streams. gzip leaves them alone.
  • Trailers after the last chunk.

Clone this wiki locally