phoenix_wtransport
WebTransport (HTTP/3 over QUIC) transport for Phoenix sockets and LiveView,
with one QUIC stream per LiveView component, shortest-message-first
scheduling, Phoenix WebSocket coexistence without upstream patches, and
automatic browser fallback (WebTransport -> WebSocket -> LongPoll).
Built purely in Erlang/Elixir on top of
erlang_quic (:quic ~> 3.3.2)
with zero native C/Rust build dependencies.
Why
A LiveView pushes every diff down one WebSocket (a single ordered TCP stream). A 50-byte counter or flash update queued behind a 300 KB table diff waits for every byte of the table, and a single lost packet stalls everything behind it.
QUIC provides independent ordered streams over one connection, and
WebTransport exposes those streams to the browser. Because LiveView diffs
already separate per-component updates, phoenix_wtransport places independent
component deltas on separate unidirectional QUIC streams and prioritizes small
frames ahead of large ones. The browser transport reassembles frames back into
the standard phoenix.js socket contract, without patching phoenix,
phoenix_live_view, or phoenix.js.
Features
- Per-component QUIC lanes (
PhoenixWebTransport.LaneSerializer): splits component deltas (without staticss) onto dedicated lanes while keeping control frames, root diffs, new/reset components, replies, joins, and heartbeats on lane0. - 3-tier lane isolation & shortest-first scheduling (
PhoenixWebTransport.LaneScheduler): isolates control (0), small interactive components (< 4 KiBEMA), and bulk components across bounded stream slots with O(1):queuebuffering, RFC 9218 stream urgency, congestion-aware watermark pacing, per-lane/session/listener memory bounds (PhoenixWebTransport.MemoryBudget), and lightweight causal barriers for mixedpush_event/ teardown diffs. - Zero-patch Phoenix coexistence (
PhoenixWebTransport.Supervisor&Router): runs beside Bandit or Cowboy, auto-discoversEndpoint.__sockets__/0(plus explicit:socketsoverrides), and mirrorsPhoenix.Socket.Transportcheck_origin,connect_info,3/4/5-tuple :stopclose codes, and graceful shutdown draining (PhoenixWebTransport.Drainer). - Cookie-less authentication bridging (
PhoenixWebTransport.Token&Plug): browsers send WebTransportCONNECTwithout cookies (credentials: "omit").phoenix_wtransportforwardsphoenix.jsauthTokenin a pre-join:authframe and providesPhoenixWebTransport.Plug(Alt-Svc+POST /_wt/token) to mint short-lived signedPhoenix.Tokencredentials from Plug sessions. - Automatic 3-tier fallback (
WebTransportTransport): silently falls back from WebTransport to WebSocket (with asessionStoragecooldown circuit breaker on UDP-blocked networks), then delegateslongPollFallbackMstophoenix.js. Routes large binary pushes onto a secondary bidirectional stream so file uploads do not stall heartbeats. - Opt-in RFC 9297 Datagrams & runtime controls:
PhoenixWebTransport.send_datagram/3,session_info/1,path_stats/1,set_congestion_control/2(:bbr | :cubic | :newreno), andset_stream_deadline/4. - Pure-OTP dev certificates (
PhoenixWebTransport.Cert): generates 13-day ECDSA P-256 certificates and SHA-256 hashes for ChromiumserverCertificateHashesusing Erlang:public_keywith no externalopensslbinary required.
Installation
Add phoenix_wtransport to your dependencies in mix.exs:
def deps do
[
{:phoenix_wtransport, "~> 0.1.0"}
]
end
Requires Elixir ~> 1.18 and OTP 27+ (required by erlang_quic;
socket_backend: :socket for OTP socket NIF GRO/GSO requires Linux + OTP 27+,
while :gen_udp is the cross-platform default).
Usage
1. Start the WebTransport supervisor
Add PhoenixWebTransport.Supervisor (or PhoenixWebTransport) after your
Phoenix Endpoint in lib/my_app/application.ex:
children = [
MyAppWeb.Endpoint,
{PhoenixWebTransport.Supervisor,
endpoint: MyAppWeb.Endpoint,
port: 4433,
# In dev, omit certfile/keyfile to auto-generate a 13-day ECDSA P-256 cert in priv/cert
certfile: "/etc/letsencrypt/live/quic.myapp.example.com/fullchain.pem",
keyfile: "/etc/letsencrypt/live/quic.myapp.example.com/privkey.pem",
url: "https://quic.myapp.example.com:4433/live"}
]
By default, PhoenixWebTransport.Router inspects MyAppWeb.Endpoint.__sockets__/0
(for example /live and /socket) and inherits check_origin, connect_info,
and auth_token settings.
2. Optional Endpoint Plug (Alt-Svc & /_wt/token)
In lib/my_app_web/endpoint.ex (after Plug.Session, before your router):
plug PhoenixWebTransport.Plug,
token_path: "/_wt/token",
alt_svc: true
3. Expose URL & dev cert hash in root layout
In root.html.heex:
<meta name="wt-url" content={PhoenixWebTransport.url()} />
<!-- Dev only (when using self-signed 13-day ECDSA certs): -->
<meta name="wt-cert-hash" content={PhoenixWebTransport.cert_hash()} />
4. Configure the browser transport (app.js)
Ensure your bundler (esbuild, Vite, or Bun) resolves deps (Phoenix's default
esbuild config includes NODE_PATH=../deps):
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
import WebTransportTransport from "phoenix_wtransport"
const csrfToken = document.querySelector("meta[name='csrf-token']")?.getAttribute("content")
const wtUrl = document.querySelector("meta[name='wt-url']")?.getAttribute("content")
const certHash = document.querySelector("meta[name='wt-cert-hash']")?.getAttribute("content")
const transport = WebTransportTransport.configure({
wtUrl,
certHash,
handshakeTimeoutMs: 1800
})
const liveSocket = new LiveSocket("/live", Socket, {
transport,
longPollFallbackMs: 5000,
params: {_csrf_token: csrfToken}
})
liveSocket.connect()
How it works
browser server
|-- CONNECT :protocol=webtransport ---------> Quic.Listener -> Quic.Session -> SessionEngine
|-- bidi stream (control / upload) --------> Phoenix.Socket.Transport (connect/init/handle_in)
|<-- uni stream, lane 0 -------------------- control: join reply, root diffs, events, replies
|<-- uni stream, lane 1 -------------------- component 1 deltas
|<-- uni stream, lane N -------------------- component N deltas
Each server unidirectional stream starts with a 4-byte lane header (<<lane::32>>),
followed by bounded length-prefixed frames (<<len::32, type::8, payload>>).
Control and structural diffs stay on lane 0; independent component deltas are
isolated across lanes by LaneScheduler and dispatched in the browser directly
into phoenix.js.
Hosting & network notes
- WebTransport requires a direct UDP path to the BEAM (e.g., UDP
443or4433on a VPS or QUIC-capable edge) with a valid TLS certificate in production. - Standard HTTP reverse proxies and Cloudflare Tunnel do not proxy origin
WebTransport sessions; clients behind UDP-blocking networks automatically fall
back to WebSocket / LongPoll via
WebTransportTransport. - On Linux OTP 27+, pass
socket_backend: :socketto opt intoerlang_quic's OTPsocketNIF UDP GRO/GSO path (other platforms safely fall back to:gen_udp).
Repository layout
lib/
phoenix_wtransport.ex Public facade & runtime control APIs
phoenix_wtransport/
backend.ex Backend behaviour (:quic)
cert.ex Pure-OTP 13-day ECDSA P-256 cert & hash
connect_info.ex Phoenix.Socket.Transport connect_info parity
drainer.ex Graceful batched session shutdown drainer
frame.ex Bounded stream frame codec (:text, :binary, :auth)
lanes.ex Lane routing, causal barrier & datagram helpers
lane_scheduler.ex 3-tier O(1) :queue scheduler & shortest-first drain
lane_serializer.ex Phoenix.Socket.Serializer component splitter
memory_budget.ex Shared :atomics outbound parked-byte ceiling
origin.ex Phoenix check_origin parity
plug.ex Optional Alt-Svc & /_wt/token endpoint plug
router.ex Endpoint.__sockets__/0 introspection & routing
session_engine.ex Shared Phoenix.Socket.Transport protocol core
supervisor.ex Registry, DynamicSupervisor, Listener & Drainer
token.ex Signed short-lived Phoenix.Token helper
quic/
listener.ex erlang_quic HTTP/3 listener
session.ex erlang_quic session & watermark pacing
assets/js/phoenix_wtransport.js Browser transport (WT -> WS -> LongPoll)
test/ Unit, erlang_quic integration & Node JS tests
demo/ Side-by-side WebSocket vs WebTransport Phoenix app
docs/ Architecture decision records & protocol spec
scripts/impair.sh macOS dummynet traffic shaping for benchmarks
Demo & verification
Run the library verification suite from the repository root:
mix precommit
node --test test/js/phoenix_wtransport.test.mjs
Run the side-by-side comparison demo app:
cd demo && mix setup && mix phx.server
Then open http://localhost:4000.
Credits & prior art
benoitc/erlang_quic— pure-Erlang QUIC & HTTP/3 stack powering the transport layer.bugnano/wtransport-elixir— Rustler/wtransport prior art for WebTransport in Elixir.- Original prototype architecture and protocol spec documented in
docs/SPEC.md.
License
Apache License 2.0 LICENSE.