Skip to content

feat(udp): first-class UDP load balancing alongside TCP/HTTP listeners — RFC + master plan #1273

Closed

Description

@FlorentinDUBOIS

Summary

Add a first-class UDP listener type to Sōzu, alongside the existing tcp/http/https listeners, so
Sōzu can load-balance datagram services (DNS, syslog, NTP, generic UDP) without a second load balancer in
front of it. The design preserves Sōzu's architecture — userland, single-threaded mio per worker,
hot-reconfig via protobuf IPC + SCM fd-passing, slab sessions, the e2e harness — and introduces a two-level
sans-io UDP core
(a pure flow state machine, I/O at the edges) for testability.

This is an RFC + master plan. Phase 1 is everything functional; Phase 2 is an optional performance pass;
heavier features are explicit non-goals.

Motivation

Datagram workloads (DNS first) are a large, growing class Sōzu cannot serve today; operators must run
IPVS/HAProxy/nginx-stream/Envoy alongside Sōzu purely for UDP. First-class UDP makes Sōzu the single
hot-reconfigurable edge for an operator's whole L4/L7 surface, reusing its control plane, metrics/logging,
and tests. A UDP LB is also security-sensitive (an amplification/DoS vector with no backpressure) — why we
want it inside Sōzu's conservative, no-panic-on-network-input model rather than bolted on.

Goals (phase 1)

  • udp listener type with full hot-reconfig + CLI parity.
  • Userland datapath in the existing single-threaded mio loop, with static per-listener worker
    ownership
    : each UDP listener is served by exactly one worker; scale by running multiple listeners.
  • Virtual 4-tuple flow sessions with a three-knob teardown (responses / idle timeout /
    requests); symmetric NAT return via a per-flow connected upstream socket.
  • Load balancing: round-robin (reuse) + source-hash affinity — both HRW/rendezvous (default) and
    Maglev selectable per cluster.
  • Sans-io core with a two-level split: a UdpManager (admission, flow-key extraction, LB request,
    timer-wheel scheduling with generation tokens) over per-flow UdpFlow machines —
    handle_input/handle_timeout/poll_transmit/poll_timeout, property-tested + cargo-fuzz'd.
  • PROXY protocol v2 to backend (first datagram, per-cluster) — Sōzu defines this; no reference ships it.
  • Active health checks bound to the endpoint: companion TCP-probe (primary) + app-level UDP
    probe (secondary), with rise/fall hysteresis and fail-open.
  • Metrics + access logs parity (new UDP/UDP-FLOW log tag, udp.* metrics).
  • Plaintext only.

Non-goals (not planned)

  • Single-listener multi-core by any means — no eBPF SK_REUSEPORT, no userland master-dispatcher,
    no SO_REUSEPORT-as-balancer (it skews few-and-fat sources to one worker and reshuffles live flows on
    hot-upgrade). Scale across cores by running multiple UDP listeners (one worker each).
  • UDP flow-state migration across hot-upgrade (flows reset on upgrade — see below).
  • DSR · io_uring / XDP · DTLS · QUIC / HTTP3 CID routing · UDP-over-HTTP tunneling ·
    inbound UDP PROXY-protocol decode · IP_TRANSPARENT/transparent return.

Proposed design

Two layers (per Google's Maglev): a per-worker flow table (4-tuple → backend, fast path) +
consistent hashing as the resilience fallback when a flow is cold/evicted or the backend set changes.

Two-level sans-io core (shape validated by quinn-proto / quiche / Firezone snownet / Sōzu's own kawa):

// UdpManager: admission, flow-key, LB request, timer wheel.  UdpFlow: per-flow teardown + forward/return.
enum ManagerInput<'a> { ClientDatagram{src,payload}, BackendDatagram{flow,payload}, Config(..), BackendResolved{..} }
enum Output           { SelectBackend{flow,cluster,hash}, SendToBackend(Transmit), SendToClient(Transmit),
                        OpenUpstream{flow,backend}, ArmTimer(Instant), Metric(..), CloseFlow(flow), Drop(reason) }
fn handle_input(&mut self, ManagerInput, now: Instant);
fn handle_timeout(&mut self, now: Instant);     // fire due flows; reap; check timer generations
fn poll_output(&mut self) -> Option<Output>;
fn poll_timeout(&self) -> Option<Instant>;      // MUST strictly advance — the #1 busy-loop bug

No socket / Instant::now / rand / Arc<Mutex> inside the core — time and the hash seed are injected;
idle timers use generation tokens so a reset timer can't close an active flow. The I/O shell owns
batched recvmmsg/sendmmsg, the flow table, per-flow connected upstream UdpSockets (the kernel
demuxes replies → NAT return; the socket fd is the return key), the timer wheel, bounded write queues, and
the buffer pool — the only place syscalls happen.

Three-knob teardown (responses/timeout/requests) parameterizes DNS (responses=1), syslog
(responses=0, fire-and-forget), NTP/RADIUS with no protocol-specific code.

DoS-first defaults (UDP has no backpressure): allocate nothing for unknown datagrams ("silence is a
virtue"), bound the flow table (max_flows auto-derived from RLIMIT_NOFILE = fd cap), shed new flows when
full (protect existing), per-source fairness, fail-open health.

Load balancing: reuse lib/src/load_balancing.rs + BackendMap (lib/src/backends.rs:498-564); the one
load-bearing change is threading a key: Option<u64> through next_available_backend. HRW/rendezvous
(default)
needs no precomputed table (no rebuild stall on hot-reconfig, minimal disruption; O(N) over a
small, bounded backend set); Maglev (opt-in) gives O(1) lookup + near-perfect balance for large N at
the cost of a (control-plane, ~ms) table rebuild on backend changes.

Health: companion-TCP-port probe is the industry-standard signal (IPVS/Keepalived, HAProxy check port,
Envoy health_check_config.port_value, nginx port=) because bare UDP has no reliable liveness signal;
plus an app-level UDP probe. Probes are timer-driven and non-blocking (no worker background threads);
rise/fall hysteresis; fail-open runs LB over the full configured set when all backends read unhealthy.

Worker model & hot-upgrade: one worker owns a UDP listener. On upgrade, SCM_RIGHTS hands off the
listener socket but not the flow table / per-flow upstream sockets — so in-flight flows reset
(old worker drains, new worker serves new flows). For DNS-class short flows this is near-invisible (a caught
flow loses at most a datagram; the client retries). This is a deliberate phase-1 limitation.

Prior art (how IPVS / HAProxy / nginx / Envoy / Pingora do UDP)

  • Envoy udp_proxy is the closest analogue: 4-tuple session, sticky from the first datagram, each
    session owns its upstream socket
    (the NAT-return key), idle_timeout, a max-session circuit breaker,
    ring-hash + Maglev LB, GRO batch reads. Its "decide the upstream before opening a socket" ordering
    maps cleanly onto a sans-io core.
  • IPVS/LVS (kernel): 4-tuple conns + OPS stateless mode; schedulers rr/wrr/lc/wlc, sh and mh
    (Maglev)
    ; health lives in Keepalived (the canonical companion-TCP-port signal). Clean
    datapath/control-plane split.
  • nginx stream: per-first-datagram session, one connected upstream socket per session,
    proxy_responses/proxy_timeout teardown, ketama consistent hash, active health is commercial-only;
    writes only PROXY v1 to backends (no PROXY-v2-over-UDP).
  • HAProxy (commercial UDP module): client-4-tuple flow, proxy-requests/proxy-responses teardown,
    consistent hash, check port <P> companion-port health, option udp-check = ICMP only (weak).
  • Pingora: no plain-UDP datapath — useful only for Rust LB ergonomics and SCM-fd graceful-upgrade
    validation; its tokio work-stealing / interwoven-async model is the opposite of Sōzu's constraints.

Takeaways: Envoy's per-worker shared-nothing flow table is the model; the three-knob teardown is
universal; the companion-TCP-port health probe is industry-standard by necessity (no reliable native UDP
health anywhere); and no system ships PROXY-v2-over-UDP — Sōzu would define it (the v2 DGRAM encoding is
the 14th header byte: 0x12=UDP/IPv4, 0x22=UDP/IPv6).

Security & protocol impact

  • New network-facing parser/datapath → no panic on input; invalid/truncated datagram ⇒ drop + metric + log.
  • Amplification/DoS surface → bounded allocation, shedding, per-source fairness, fail-open health.
  • New cargo-fuzz target (fuzz_udp_flow) + proptest state-machine tests; conservative review of flow-key
    extraction + PPv2 framing.
  • Gauge correctness (udp.active_flows must not underflow on error/shutdown).

Phasing

  1. Phase 1 (MVP — everything functional) — listener type + control-plane parity; static per-listener
    datapath; 4-tuple flows + three-knob teardown + NAT return; RR + HRW (default) + Maglev (opt-in);
    PPv2 (first-datagram); health (tcp/udp probe, hysteresis, fail-open); metrics + logs; two-level sans-io
    core + proptest/fuzz/e2e.
  2. Phase 2 (optional — performance) — recvmmsg/sendmmsg batching; UDP GSO/GRO on the connected
    upstream socket (Linux-version-gated). No functional change; sans-io core untouched.

Not planned: single-listener multi-core / eBPF / dispatcher · DSR · io_uring/XDP · DTLS · QUIC/HTTP3 ·
tunneling · flow-state migration on upgrade.

Control-plane impact

proto (ListenerType::UDP, UdpListenerConfig, oneof fields 56+, LB enum SOURCE_HASH/HRW/MAGLEV,
ListenersList/Count) → config (ListenerProtocol::Udp) → state (udp_listeners + diff/generate/activate
together) → lib (Protocol::{UDP,UDPListen}, new lib/src/protocol/udp/) → server wiring → SCM
(Listeners.udp, listener-fd hand-off across upgrade) → CLI (ListenerCmd::Udp). One load-bearing LB-trait
change: thread key: Option<u64> through next_available_backend. UDP needs a separate
listener-ingest/readiness path
— not the TCP accept()/create_session model (ProxyConfiguration::accept()
returns TcpStream). Every match ListenerType/Protocol gains a UDP arm (compiler-enforced). Riskiest:
state-replay symmetry, proto field-number allocation, SCM listener-fd hand-off.

Testing

proptest state-machine tests on the sans-io core (timeouts with generation tokens, eviction, three-knob
teardown, HRW & Maglev affinity stability, shedding, fail-open; injected clock) · fuzz_udp_flow · e2e
udp_tests.rs + mock UDP backend (RR, HRW & Maglev affinity, NAT return, teardown, truncation, PPv2, health
failover + fail-open + hysteresis, hot reconfig, listener-fd hand-off across upgrade) · state round-trip
test. DNS is the natural real-payload e2e.

Resolved decisions

  • Buffer pool: reuse the existing pool (no dedicated UDP class); max_rx_datagram_size capped at
    buffer_size (≥16393); larger datagrams truncate → drop + metric.
  • PPv2 v2: first-datagram-only by default, per-cluster opt-in for every-datagram.
  • UDP ingest: a separate UDP listener-ingest/readiness path, kept out of the TCP accept() abstraction.
  • Upstream socket: one connected socket per flow (the connected fd is the NAT-return demux key).
  • Flow cap: max_flows auto-derives from ~70% of the soft RLIMIT_NOFILE (overridable per listener);
    shed new flows on cap.
  • SCM listener-fd hand-off: verified fd-type-agnostic — a UdpSocket fd rides the same SCM_RIGHTS path as
    a TcpListener fd; only mio::net::UdpSocket::from_raw_fd is UDP-specific; locked by an upgrade e2e test.

Deliverables checklist (phase 1)

  • proto + regenerated bindings (incl. HRW/MAGLEV/SOURCE_HASH LB enum)
  • config parsing + validation
  • state model + replay symmetry + round-trip test
  • lib/src/protocol/udp/ two-level sans-io core + I/O shell (single-worker per listener)
  • server wiring + separate UDP listener-ingest path
  • SCM UDP listener-fd hand-off (verified across upgrade)
  • CLI parity
  • key: Option<u64> LB-trait change + HRW (default) + Maglev (opt-in)
  • health checks (tcp/udp probe, hysteresis, fail-open, endpoint-bound)
  • PROXY protocol v2 (first-datagram)
  • metrics + access logs + doc/configure.md + CHANGELOG
  • proptest + fuzz + e2e tests

Activity

  1. FlorentinDUBOIS commented on Jun 3, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Master plan — part 1/4 · motivation · goals · architecture & worker model.

    Master Plan — UDP Load Balancing in Sōzu

    Authoritative, self-contained design for the GitHub issue. Implementation happens in later sessions.
    Citations point only at real Sōzu source (file:line) and public papers/specs by name.

    1. Motivation & rationale

    Sōzu load-balances TCP, HTTP/1, HTTP/2 and TLS today, but has no UDP datapath. A large and growing
    class of services are datagram-based — DNS, syslog, NTP, generic UDP — and must currently be fronted by
    a second load balancer (IPVS, HAProxy, nginx stream, Envoy). First-class UDP lets Sōzu be the single
    hot-reconfigurable edge for an operator's whole L4/L7 surface, reusing its control plane (protobuf IPC,
    hot-reconfig, SCM fd-passing), metrics/logging, and e2e harness. A UDP LB is security-sensitive (an
    amplification/DoS vector with no backpressure), which is why we want it inside Sōzu's conservative
    no-panic-on-input model rather than bolted on.

    The work lands in one functional phase (generic UDP + DNS, plaintext, userland) with an optional
    perf follow-up
    ; everything heavier (DSR, io_uring/XDP, DTLS, QUIC, eBPF steering) is an explicit non-goal.

    2. Goals / non-goals

    Phase-1 goals:

    • A udp listener type, first-class alongside tcp/http/https, with full hot-reconfig + CLI parity.
    • Userland datapath in the existing single-threaded mio loop, with static per-listener worker
      ownership
      (§3): each UDP listener is served by exactly one worker; scale by running multiple listeners.
    • Virtual 4-tuple flow sessions with a three-knob teardown (responses / idle timeout /
      requests); symmetric NAT return via a per-flow connected upstream socket.
    • Load balancing: round-robin (reuse existing) + source-hash affinity — both HRW/rendezvous
      (default)
      and Maglev selectable per cluster.
    • A two-level sans-io core: a UdpManager (admission, flow-key, LB request, timer wheel) over per-flow
      UdpFlow machines — pure, property-tested + fuzzable.
    • PROXY protocol v2 to backend (first datagram, per-cluster) — Sōzu defines this; no reference ships it.
    • Active health checks bound to the endpoint: companion TCP-probe (primary) + app-level UDP
      probe (secondary), with rise/fall hysteresis and fail-open.
    • Metrics + access logs parity (UDP/UDP-FLOW log tag, udp.* metrics).
    • Plaintext only.

    Phase-2 (optional, performance only): recvmmsg/sendmmsg batching; UDP GSO/GRO on the connected
    upstream socket (Linux-version-gated).

    Non-goals (not planned — design must not preclude, but we are not building them):

    • Single-listener multi-core by any means — no eBPF SK_REUSEPORT, no userland master-dispatcher,
      no SO_REUSEPORT-as-balancer. Scale across cores by running multiple UDP listeners (one worker each).
    • UDP flow-state migration across hot-upgrade (flows reset on upgrade — §3.2).
    • Direct Server Return (DSR); io_uring / XDP / eBPF datapaths.
    • DTLS termination; QUIC / HTTP3 CID-aware routing; UDP-over-HTTP tunneling.
    • Inbound UDP PROXY-protocol decode (expect_proxy on a UDP listener);
      IP_TRANSPARENT/transparent-return (privileged, port-lossy, fights the connected-socket primitive).

    3. Architecture overview

            ┌──────── worker that OWNS this UDP listener (single-threaded mio loop) ───────┐
            │                                                                              │
    client ─UDP─▶ UdpListener (1 mio::UdpSocket; fd via SCM on upgrade — socket only)      │
            │       │  recvmmsg(MSG_WAITFORONE) until WouldBlock                            │
            │       ▼                                                                       │
            │  ┌──────────── I/O shell `UdpProxy` (all syscalls) ────────────┐             │
            │  │ flow table: FlowKey → flow (slab)    timer wheel (gen-token) │             │
            │  │ upstream_token → flow (NAT return)   buffer pool   hash seed │             │
            │  │ per-flow CONNECTED mio::UdpSocket  ──sendmmsg─▶ backend       │ bounded     │
            │  └───────────────┬──────────────────────────────────────────────┘ write q     │
            │                  │ handle_input(dgram→owned Buf, now) / drain poll_*           │
            │                  ▼                                                              │
            │   ┌──── sans-io `UdpManager` (admission, flow-key, LB req, timers) ────┐ reuses:│
            │   │      └─ per-flow `UdpFlow` machines (no socket/clock/rand/Arc)      │ Backend│
            │   └─────────────────────────────────────────────────────────────────────┘ Map…  │
            └──────────────────────────────────────────────────────────────────────────────────┘
    
    • I/O shell owns every syscall: batched recvmmsg/sendmmsg, the flow table, per-flow connected
      upstream sockets, the timer wheel, bounded write queues, the buffer pool, the hash seed, and the
      BackendMap/health/metrics edges.
    • Sans-io core owns admission + flow state + timeout bookkeeping; it is pure. This makes the datapath
      unit-testable/fuzzable and keeps the I/O policy swappable without touching logic.

    3.1 Why this preserves Sōzu's benefits

    • Single-threaded / no Arc<Mutex>: flow table + hash seed are per-worker, owned, not shared.
    • Edge-triggered epoll: shell loops recv to WouldBlock (one event = many datagrams = many flow
      transitions — relaxes lib/src/server.rs's one-event-one-session assumption); on a queued return it
      registers writable interest + calls signal_pending_write, and on WouldBlock from send it re-arms
      (a bounded write queue per flow/listener — signal_pending_write alone is necessary-but-insufficient).
    • Slab / hot-reconfig / SCM fd-passing / metrics / e2e: reused, not reinvented.

    3.2 Worker model & hot-upgrade semantics

    Sharing one UDP fd across workers breaks flow affinity (any worker may recv a flow's packet, but its
    connected upstream socket lives in one worker). Phase-1 model: static per-listener worker ownership —
    each UDP listener is bound/served by exactly one worker (assignable; may start with all UDP listeners on one
    designated worker and add per-listener round-robin assignment as a cheap follow-up). No shared UDP fd, no
    cross-worker flow state. Throughput per listener is one core; aggregate scale comes from running multiple
    listeners. Single-listener multi-core is a non-goal (see §3.3).

    Hot-upgrade: SCM_RIGHTS hands the listener socket to the new worker — but not the flow table or
    per-flow upstream sockets (those live in the old worker's heap). So in-flight UDP flows are not
    migrated
    : the old worker drains/closes its flows (bounded by idle timeout) while the new worker serves
    new flows on the handed-off listener. For short datagram flows (DNS = one request+reply, ms-lived) this is
    near-invisible; a caught-in-flight flow loses at most a datagram and the client retries. This is a
    deliberate phase-1 limitation, not "flows survive re-exec."

    3.3 Why static per-listener (and not the alternatives)

    For the record, since reviewers will ask "why not SO_REUSEPORT / eBPF?":

    • SO_REUSEPORT as a balancer is rejected. Its kernel 4-tuple hash pins few-and-fat sources (DNS
      resolvers, syslog relays) to one worker (skew), and socket(7) moves "the last socket into the closed
      socket's position", so a hot-upgrade re-exec reshuffles live flows.
    • eBPF SK_REUSEPORT and a userland master-dispatcher are out of scope. Both could give single-listener
      multi-core (eBPF in-kernel; the dispatcher portably, and especially well for long-lived flows via per-flow
      socket handoff) — but eBPF is unwanted (Linux-only, operationally heavy) and the dispatcher's sweet spot
      (media/QUIC long flows) is itself out of scope, leaving it a single-core bottleneck for DNS-class traffic.
    • Conclusion: scale across cores by running multiple listeners, each owned by one worker. Sōzu
      already binds listeners with SO_REUSEADDR + SO_REUSEPORT (lib/src/socket.rs:1015-1038) and SCM-passes
      fds to workers (command/src/scm_socket.rs:279), so the primitives exist if this is ever revisited.
  2. FlorentinDUBOIS commented on Jun 3, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Master plan — part 2/4 · sans-io core · datapath · load balancing · health · PROXY protocol v2.

    4. The sans-io UDP core (centerpiece) — two-level split

    A single per-flow machine cannot own admission ("allocate nothing for unknown datagrams") and select a
    backend before a flow exists. So the sans-io core is two levels (mirrors the H2 ConnectionH2/
    Context split in lib/src/protocol/mux/):

    • UdpManager (sans-io): owns the flow table keyed by FlowKey, admission + flow-table cap +
      shedding, pluggable flow-key extraction, the LB-selection request for new flows, and timer-wheel
      scheduling
      (one armed deadline for the whole manager).
    • UdpFlow (sans-io, per admitted flow): the three-knob teardown counters (responses/requests),
      idle/lifetime timers, PPv2-first-datagram bookkeeping, and the forward/return decisions.

    Shape validated by quinn-proto / quiche / Firezone snownet / Sōzu's own kawa. No socket, no
    Instant::now, no rand, no Arc<Mutex>
    inside either level; time and the hash seed are injected.
    Datagram payloads are copied into a pool-owned Buf at admission (one copy) so outputs may outlive the
    borrowed recv buffer; zero-copy IoSlice prefixing is a later optimization.

    // lib/src/protocol/udp/  (illustrative — names are Sōzu-domain; the input/poll split is load-bearing)
    
    enum ManagerInput<'a> {
        ClientDatagram  { src: SocketAddr, payload: &'a [u8] },   // admit → flow or Drop
        BackendDatagram { flow: FlowId, payload: &'a [u8] },      // return path (shell tags by upstream token)
        Config(ConfigEvent),                                      // add/remove backend, LB algo, timeouts, drain
        BackendResolved { flow: FlowId, backend: BackendId, addr: SocketAddr },
    }
    
    enum Output {
        SelectBackend { flow: FlowId, cluster: ClusterId, hash: u64 }, // shell consults BackendMap → BackendResolved
        SendToBackend(Transmit),     // payload (owned Buf) may carry a PROXY v2 prefix
        SendToClient(Transmit),      // symmetric NAT return
        OpenUpstream { flow: FlowId, backend: SocketAddr },
        ArmTimer(Instant),           // single manager-wide next deadline; shell owns the wheel
        Metric(MetricEvent),
        CloseFlow(FlowId),           // idle / responses-reached / requests-reached / drain
        Drop(DropReason),            // unknown/invalid/shed — allocate nothing
    }
    
    struct Transmit { dst: SocketAddr, segment_size: Option<usize>, payload: Buf } // segment_size reserves GSO room
    
    trait UdpManager {
        fn handle_input(&mut self, input: ManagerInput<'_>, now: Instant);
        fn handle_timeout(&mut self, now: Instant);          // fire due flows; reap; check timer generations
        fn poll_output(&mut self) -> Option<Output>;         // drain to None each tick
        fn poll_timeout(&self) -> Option<Instant>;           // MUST strictly advance (debug_assert)
    }
    • Timer correctness: idle timers are reset on every datagram, so the wheel needs generation tokens —
      each flow carries a timer_gen; an expiry only closes the flow if its generation matches. poll_timeout
      strict-advance alone is necessary-but-insufficient (the Allow to close connections for a given app in the TCP proxy #1 busy-loop bug in sans-io designs).
    • Three-knob teardown: responses (DNS=1, syslog=0 fire-and-forget), idle timeout, requests. Pure
      counts + a clock → DNS/syslog/NTP/RADIUS with no protocol-specific code.
    • "Silence is a virtue" (WireGuard's DoS posture): the manager drops unknown/invalid/over-cap
      datagrams before any flow/buffer/socket is allocated.
    • Two-tier selection (Google Maglev's pattern): tracked flow → reuse backend; new flow → SelectBackend
      (RR, HRW, or Maglev per cluster). Flow-table-full ⇒ Drop (shed) with zero per-packet allocation.
    • Flow-key extraction is a small trait (fn flow_key(datagram, cfg) -> FlowKey) — the 4-tuple is the
      only implementation in scope; the seam just keeps a fragmentation 2-tuple fallback (§5) clean. (QUIC-CID
      keying is a non-goal; the trait costs nothing and doesn't commit us to it.)
    • Testability: proptest state-machine testing (dropped datagrams, idle-timeout races, reconfig
      mid-flow, reaper drains to zero / no fd leak) with zero sockets; plus a cargo-fuzz target fuzz_udp_flow.

    5. Datapath details (the I/O shell)

    • Ingest: loop recvmmsg(MSG_WAITFORONE) per readable event until WouldBlock; copy each datagram into
      a pool Buf; handle_input. max_rx_datagram_size (default 1500) bounds the read; raise for large DNS.
    • Datagram size: a mio::UdpSocket delivers fully reassembled UDP datagrams (the kernel reassembles
      IP fragments before delivery to a UDP socket) — there is no non-first-fragment-without-ports problem at
      this layer
      . The real concerns: a datagram larger than the recv buffer is truncated (MSG_TRUNC) →
      drop + metric, never panic; size max_rx_datagram_size for EDNS0/large DNS; recommend operators keep
      responses within PMTU.
    • Return path (NAT): each flow owns a connected per-flow mio::UdpSocket to the chosen backend — a
      connected socket "only receives from the connected address", so its fd is the return demux key.
      upstream_token → FlowId; reply → client. connect() pins the return 4-tuple.
    • fd-pressure sizing model (Q-5 decision): one fd + one slab slot per flow. max_flows defaults to
      ~70% of the soft RLIMIT_NOFILE
      (overridable per listener), so the fd budget adapts to the host without
      hand-tuning; DNS-friendly idle timeout; close-on-responses-reached (a DNS flow closes after its
      single reply, not on idle); and on EMFILE/ENFILE or max_flows → shed new flow (drop +
      udp.flows.shed + log), protect existing, never panic. DNS flows can live milliseconds and churn at
      packet rate, so reaping must be O(1)-amortized via the timer wheel, not a per-flow scan.
    • Egress / backpressure: UDP send can return WouldBlock (socket buffer full). Queue into a bounded
      per-flow/per-listener write queue
      , register writable interest, rearm on the writable event; drop +
      metric when the queue is full. Batch with sendmmsg (phase 2).
    • Gauge correctness: udp.active_flows must never underflow on close/timeout/shed/error paths.
    • Buffer pool (Q-1 decision): reuse the existing buffer pool (lib/src/pool.rs) — no dedicated UDP
      class. Consequence: max_rx_datagram_size is capped at the configured buffer_size (≥16393); a
      datagram exceeding it is truncated (MSG_TRUNC) → drop + metric. DNS (incl. typical EDNS0) fits
      comfortably; document the cap for operators expecting very large datagrams.

    6. Load balancing & affinity

    • Reuse lib/src/load_balancing.rs RoundRobin/Random/LeastLoaded/PowerOfTwo + BackendMap
      (lib/src/backends.rs:498-564).
    • One load-bearing API change: the trait next_available_backend(&mut self, backends) takes no key
      and can't express a hash LB → thread a key: Option<u64> through it (None for the existing
      RR/Random/LeastLoaded/PoT).
    • Add two source-hash algorithms, both phase 1, selectable per cluster:
      • HRW / rendezvous (default): hash(key, backend), pick max. No precomputed table → no rebuild
        stall on hot-reconfig
        , provably-minimal disruption, exact weighting. O(N) per selection — fine
        because UDP cluster backend counts are small; validate/document a max-backends bound per cluster.
      • Maglev (opt-in): precomputed lookup table (prime size, default 65537), O(1) per-packet lookup,
        near-perfect balance — for large N / high pps. Costs: the table is rebuilt on backend-set change
        (~ms, in the control-plane reconcile step, not per-packet) and remaps ~2× more keys than HRW on churn.
    • Affinity key = real (pre-NAT) client src_ip by default (src_ip+src_port opt-in), from flow state.
      Hash seed injected once per worker at construction, persisted across reconfig (stable affinity).
    • Backend::try_connect is TCP-specific (lib/src/backends.rs:119-257) — reuse the selection, add UDP
      send in the shell.

    7. Health checks

    Layered, bound to the endpoint not the listener:

    • Primary: companion TCP-probe — non-blocking mio TCP connect to a configurable tcp_probe_port
      (default = data port). The industry-standard signal (IPVS/Keepalived, HAProxy check port, Envoy
      health_check_config.port_value, nginx port=), because bare UDP has no reliable liveness signal. It is
      a hint, not proof of UDP reachability — documented as such.
    • Secondary: app-level UDP probe — send a configured payload (DNS query / NTP), expect a response within
      a timeout; silence ⇒ unhealthy.
    • Mechanism: timer-driven non-blocking probes in the event loop (Sōzu has no worker background
      threads
      ); results feed a Config(UpdateBackend) input. Never block the loop.
    • rise/fall hysteresis: a flapping probe must not re-hash live flows; flows on a now-unhealthy backend
      stay pinned via the flow table until idle-timeout.
    • Fail-open with defined semantics: if all backends in a cluster read unhealthy, run the normal LB
      (HRW/Maglev/RR) over the full configured backend set, ignoring health (deterministic, testable),
      rather than black-holing. Configurable.

    8. PROXY protocol v2 — Sōzu defines this

    No reference ships PPv2-over-UDP (nginx writes only PROXY v1 to backends; Envoy closed its requests
    unimplemented; HAProxy punts to TPROXY). The v2 spec does have a DGRAM encoding: the 14th byte
    (offset 13) of the v2 header is family+transport — 0x12=UDP-over-IPv4, 0x22=UDP-over-IPv6 (offset 12 is
    version+command 0x21). Design:

    • A serialization concern in the pure core: the flow prepends the v2 header (real client SocketAddr
      from flow state) to the first upstream Transmit, reusing lib/src/protocol/proxy_protocol/. Since the
      payload is already a pool Buf (§4), the header is a cheap prefix.
    • First-datagram-only (recommended; stateful, matches the flow model) with per-datagram opt-in as a
      per-cluster knob (a flow re-created after idle eviction loses client context with first-only).
    • Backend PPv2-UDP parse support is not guaranteed (spec only mandates UNSPEC) — verify per backend.
    • Account for the prefix bytes in metrics/access logs.
  3. FlorentinDUBOIS commented on Jun 3, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Master plan — part 3/4 · metrics & logs · control-plane changes · config schema · testing.

    9. Metrics & access logs

    • New metrics (incr!/count!/gauge!/time! in lib/src/metrics/): udp.datagrams.{in,out},
      udp.bytes.{in,out}, udp.active_flows (gauge — no underflow), udp.flows.{created,evicted,shed},
      udp.datagrams.dropped (by reason: invalid/truncated/no-backend/shed/wq-full), udp.backend.health,
      udp.flow.duration (time!).
    • Per-flow access log on flow close via the canonical log_context! envelope; new module log tag
      UDP/UDP-FLOW
      (regression-guarded by lib/tests/log_layout.rs).
    • Update doc/configure.md for every public metric (docs-are-code).

    10. Control-plane changes

    Ordered: proto → config → state → lib → server wiring → SCM → CLI → tests → docs.

    • proto (command/src/command.proto): ListenerType::UDP=3; UdpListenerConfig +
      UpdateUdpListenerConfig; add_udp_listener/update_udp_listener oneof fields (numbers 56+);
      ListenersList.udp_listeners; ListenersCount.udp; LB enum SOURCE_HASH/HRW/MAGLEV. (Never hand-edit
      the generated command/src/proto/command.rs.)
    • config (command/src/config.rs): ListenerProtocol::Udp, FileUdpListenerConfig, push_udp_listener
      • validation (max-backends bound, max_flows, RLIMIT headroom warning).
    • state (command/src/state.rs): udp_listeners map; dispatch/activate/deactivate arms;
      add/remove/update methods; diff + generate_requests + generate_activate_requests updated
      together
      (replay symmetry — round-trip test mandatory, the top asymmetry risk); list_listeners.
    • lib (lib/src/lib.rs): Protocol::{UDP,UDPListen}; new lib/src/protocol/udp/ (manager + per-flow +
      shell).
    • server (lib/src/server.rs): udp proxy field + constructor; notify_add/update/activate/ deactivate_udp; ListenerType::Udp arms; a UDP listener-ingest/readiness path that is NOT routed
      through the TCP accept()/create_session model
      (UDP is one-socket-many-flows; prefer a separate
      listener-ingest trait over forcing ProxyConfiguration::accept() — which returns TcpStream — to carry
      UDP cases).
    • SCM (command/src/scm_socket.rs): Listeners.udp, get_udp, close logic. Verified (Q-6): the
      SCM_RIGHTS transport (send_listeners/receive_listeners/send_msg_and_fds) is fd-type-agnostic — a
      UdpSocket raw fd passes exactly like a TcpListener fd. The only UDP-specific step is re-wrapping with
      mio::net::UdpSocket::from_raw_fd in the UDP activation arm (TCP uses MioTcpListener::from_raw_fd,
      lib/src/server.rs:2104/2127/2153). O_NONBLOCK + SO_REUSE* are file-description flags preserved across
      SCM + exec. Locked by an upgrade e2e test. Flow state is not transferred (§3.2).
    • CLI (bin/src/cli.rs, bin/src/ctl/): ListenerCmd::Udp + UdpListenerCmd; request-builder methods.
    • ⚠ Exhaustive-match risk: every match ListenerType/Protocol needs a UDP arm (compiler-enforced).

    11. Configuration schema (illustrative)

    [[listeners]]
    protocol       = "udp"
    address        = "0.0.0.0:53"
    public_address = "203.0.113.10:53"
    front_timeout  = 30        # client flow idle timeout (s)
    back_timeout   = 30        # upstream idle timeout (s)
    max_rx_datagram_size = 1500   # capped at the global buffer_size (>=16393); larger datagrams truncate
    max_flows      = 0            # 0 = auto (~70% of soft RLIMIT_NOFILE); override per listener
    # NB: inbound UDP PROXY-protocol decode (expect_proxy) is NOT supported.
    
    [clusters.dns]
    load_balancing = "hrw"            # round_robin | hrw (default source-hash) | maglev
    affinity_key   = "source_ip"      # source_ip | source_ip_port
    responses      = 1                # expected replies per flow (DNS=1, syslog=0); closes flow when reached
    requests       = 0                # 0 = unlimited datagrams per flow
    send_proxy_protocol = true        # PROXY v2 to backend (first datagram)
    [clusters.dns.health]
    mode      = "tcp_probe"           # off | udp_probe | tcp_probe
    tcp_port  = 53                    # companion port (endpoint-level override; default = data port)
    rise = 2
    fall = 3
    fail_open = true                  # all-unhealthy ⇒ LB over full configured set

    12. Testing strategy

    • Unit / property: UdpManager+UdpFlow via proptest state-machine testing — timeouts (with timer
      generations), eviction, three-knob teardown, affinity stability across backend add/remove (HRW and
      Maglev disruption bounds), flow-table-full shedding, write-queue-full drop, fail-open selection, reaper
      drains to zero / no fd leak. Injected Instants; debug_assert poll_timeout strictly advances.
    • Fuzz: new fuzz/ target fuzz_udp_flow over flow-key extraction + PPv2 framing (H2-parity discipline).
    • E2E (e2e/): new udp_tests.rs + mock UDP backend + UDP client. RR distribution, HRW & Maglev
      affinity, NAT return, idle/responses/requests teardown, truncation handling, PPv2 to backend, health
      failover + fail-open + hysteresis, hot add/remove/activate UDP listener, listener fd hand-off across
      upgrade (flows reset, new flows served)
      . Ports via the e2e port registry; DNS is the natural real-payload
      test.
    • State round-trip: prove UDP listeners survive generate_requests→diff replay.
  4. FlorentinDUBOIS commented on Jun 3, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Master plan — part 4/4 · phasing · risks · resolved decisions.

    13. Phasing

    • Phase 1 (MVP — everything functional): listener type + control-plane parity; static per-listener
      userland datapath; 4-tuple flows + three-knob teardown + NAT return (per-flow connected socket);
      RR + HRW (default) + Maglev (opt-in); PPv2 (first-datagram); health (tcp/udp probe, hysteresis,
      fail-open); metrics + logs; two-level sans-io core + proptest/fuzz/e2e. Flows reset on hot-upgrade.
    • Phase 2 (optional — performance): recvmmsg/sendmmsg batching; UDP GSO/GRO on the connected upstream
      socket (Linux-version-gated). No functional change; the sans-io core is untouched.

    Explicit non-goals (not planned): single-listener multi-core / eBPF SK_REUSEPORT / userland
    master-dispatcher · DSR · io_uring / XDP · DTLS · QUIC / HTTP3 · UDP-over-HTTP tunneling · flow-state
    migration across upgrade · inbound UDP PROXY decode · transparent return.

    14. Risks & mitigations

    Risk Mitigation
    Hot-upgrade drops live UDP flows (state not migrated) Documented phase-1 limitation; short flows ≈ invisible; old worker drains; not planned to migrate (§3.2)
    UDP as amplification/DoS vector "Silence is a virtue", bounded max_flows, shed new flows, per-source fairness (per-IP rate-limit), fail-open
    FD exhaustion (per-flow upstream sockets) max_flows = fd cap; RLIMIT headroom; close-on-responses; idle reaping; EMFILE/ENFILE → shed, never panic
    Edge-triggered "stuck flow" / send WouldBlock signal_pending_write + writable rearm + bounded write queues; drain to WouldBlock; poll_timeout strict-advance assertion
    Stale timer closes active flow Timer generation tokens; expiry validates generation
    Maglev table-rebuild stall on reconfig Rebuild in the control-plane reconcile step (not the datapath); default to HRW (no table); document the trade
    State replay asymmetry drops UDP on reconfig diff/generate/activate updated together + round-trip test
    Gauge underflow on error/shutdown Correctness bug; tested on close/timeout/shed/wq-full
    Large datagram > buffer_size Reuse the H2 pool (no dedicated class); cap max_rx_datagram_size at buffer_size; over-size → truncate, drop + metric
    Health flap re-pins flows rise/fall hysteresis + pin now-unhealthy-backend flows until idle-timeout

    15. Resolved decisions (interview, 2026-06-03)

    All six former open questions are now decided:

    • Q-1 Buffer pool → reuse the existing pool (no dedicated UDP class); max_rx_datagram_size is capped at
      buffer_size (≥16393); larger datagrams truncate → drop + metric (§5).
    • Q-2 PPv2 framing → first-datagram-only by default, with a per-cluster opt-in for every-datagram (§8).
    • Q-3 UDP ingest → a separate UDP listener-ingest/readiness path, kept out of the TCP
      accept()/create_session abstraction (§10).
    • Q-4 Upstream socket → one connected socket per flow (the connected fd is the NAT-return demux key); no
      shared-socket/connection-table mode.
    • Q-5 Flow cap → max_flows auto-derives from ~70% of the soft RLIMIT_NOFILE (overridable per
      listener); shed new flows on cap (§5).
    • Q-6 SCM listener-fd hand-off → verified fd-type-agnostic; only mio::net::UdpSocket::from_raw_fd is
      UDP-specific; locked by an upgrade e2e test (§10).

    Earlier decisions: worker model = static per-listener ownership; LB = HRW default + Maglev opt-in (both
    phase 1); encryption = plaintext only; multi-core/eBPF/dispatcher/DSR/io_uring/DTLS/QUIC/tunneling = non-goals.

  5. FlorentinDUBOIS commented on Jun 5, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Implemented and merged via #1274 — the full RFC shipped: sans-io UDP core (lib/src/protocol/udp/), first-class protocol = "udp" listeners, HRW/Maglev flow-affine balancing, PROXY v2 to backends, UDP/TCP health probing, and operator docs (doc/configure.md, "UDP clusters" section).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions