# Performance

Per-packet CPU and allocation costs from Go benchmarks, plus end-to-end capacity measurements on a small relay VM. On an established route, the relay forwards a datagram with a map lookup, a pooled buffer copy, and a channel send: zero allocations and no cryptography.

## Benchmark environment

Run with `go test -run='^$' -bench=. -benchmem -count=10` in `pkg/relay`, `pkg/connector`, `pkg/connector/protocol`, `pkg/noise`, and `pkg/session` (`make bench` runs them once), using Go 1.27.4 on `linux/amd64` (AMD Ryzen 5 5600X, 6 cores / 12 threads).

Because the host was shared during measurement, the tables below report the fastest of 10 runs (closest to code-only cost; medians ran up to 2× slower). Treat these as orders of magnitude and compare changes on your own hardware with `benchstat`.

## Relay microbenchmarks

### Established route

After the Initial flight, packets are short-header QUIC datagrams from a known client `IP:port` (measured with 1,280-byte packets):

| Benchmark | Time / packet | Allocs | What it measures |
| --- | --- | --- | --- |
| `SelectRouteActive` | 45 ns | 0 | Route lookup for a known client address |
| `ForwardActive` | 150 ns | 0 | Lookup, copy into pooled buffer, and enqueue for connector |
| `RouterActiveParallel` | 32 ns | 0 | Concurrent forward/return lookups across 64 routes on 12 threads (wall time per op) |
| `LongHeaderIDs` | 27 ns | 0 | Parse connection IDs from a QUIC long header |

At 150 ns per packet, one core can route ~6.5 million packets/s (~8 GB/s of 1,280-byte packets) before NIC and kernel UDP overhead, which dominate in practice.

### New connection

For a client's first packet, the relay removes public header protection, decrypts the QUIC Initial payload, parses SNI, and binds the route:

| Benchmark | Time | Allocs | What it measures |
| --- | --- | --- | --- |
| `InitialPayloadDecrypt/v1` | 2.0 µs | 3 | Decrypt a QUIC v1 Initial payload |
| `InitialPayloadDecrypt/v2` | 2.1 µs | 3 | Decrypt a QUIC v2 Initial payload |
| `SelectRouteNewSinglePacket` | 4.8 µs | 5 | Parse a single-packet `ClientHello` and select a route |
| `SelectRouteNewMultiPacket` | 10.6 µs | 12 | Reassemble a multi-packet `ClientHello` (e.g., post-quantum key shares) and select a route |
| `AdmissionServeHTTP` | 1.5 µs | 14 | Issue a browser admission ticket over HTTP (excluding TLS) |

Initial decryption runs once per connection; every subsequent packet skips it.

## Connector and control link

Measured over loopback with 1,200-byte inner packets between relay and connector:

| Benchmark | Time / packet | Allocs | What it measures |
| --- | --- | --- | --- |
| `WriteReadRecord` | 68 ns | 0 | Frame and unframe one packet in `stream` mode |
| `LinkSendReceive/stream` | 15.5 µs | 7 | Relay to connector over a `stream` control link (~77 MB/s) |
| `LinkSendReceive/datagram` | 21.9 µs | 9 | Relay to connector over a `datagram` control link (~55 MB/s) |
| `ForwardUDP/stream` | 102 µs | 10 | Synchronous round trip: relay → connector → UDP echo → back (`stream`) |
| `ForwardUDP/datagram` | 139 µs | 24 | Synchronous round trip (`datagram`) |

The control link accounts for most of the CPU cost because packets are QUIC-encrypted twice (end-to-end client↔service and connector↔relay). One control link sustains tens of megabytes per second on a single core. `ForwardUDP` waits for each reply before sending the next packet, measuring round-trip latency rather than throughput.

## WebSocket fallback sessions

Over WebSocket fallback, the relay copies raw bytes between a browser WebSocket and a control-link QUIC stream while client and service encrypt frames with ChaCha20-Poly1305:

| Benchmark | Time | Allocs | What it measures |
| --- | --- | --- | --- |
| `SessionCarry` (`pkg/relay`) | 430 µs / 32 KiB RTT | 138 | WebSocket ↔ connector stream round trip over loopback TLS and QUIC (~76 MB/s) |
| `TransportSealOpen/1200B` (`pkg/noise`) | 1.2 µs | 0 | Seal and open one 1,200-byte Noise message |
| `TransportSealOpen/16384B` (`pkg/noise`) | 14 µs | 0 | Seal and open one 16 KiB Noise message (~1.2 GB/s) |
| `SessionStreamThroughput` (`pkg/session`) | 24 µs / 16 KiB | 0 | Stream framing and flow control over an in-memory pipe (~680 MB/s) |
| `SessionStreamEcho` (`pkg/session`) | 6.5 µs | 0 | 1 KiB echo round trip on one stream |
| `SessionHandshake` (`pkg/session`) | ~630-800 µs | ~117 KiB | Hybrid ML-KEM session handshake pair (ML-KEM-1024 wire overhead: 1,632 B hello and 1,632 B reply) |

After the one-time handshake, steady-state per-record ChaCha20-Poly1305 and stream costs are unchanged by hybrid post-quantum key exchange (a TLS 1.3 handshake with `X25519MLKEM768` is ~3,194 B and ~0.66 ms vs 922 B and ~0.42 ms classical). The relay pools its copy buffers so active transfers allocate only inside the underlying WebSocket and QUIC libraries.

## Practical limits

Forwarding is small and allocation-free, so NIC bandwidth, kernel UDP processing, and cloud transfer allowances usually bind before relay CPU. Fixed caps on connectors, routes, pending Initials, and sessions (alongside `GOMEMLIMIT` load shedding) keep memory bounded on small VMs. Junk UDP datagrams failing the size or header check are dropped immediately, while valid QUIC Initials cost ~2 µs to decrypt, so public relays should still apply UDP rate limits at the network edge.

## Load testing a relay VM

`cmd/vagus-stress` measures a deployed relay end to end (CPU, NIC, kernel buffers, and provider limits). It attaches connectors, opens WebSocket sessions and QUIC routes, ramps load in steps, and prints one summary line per step (or JSON with `-json`).

Run it against a dedicated test relay started with browser admission, no Turnstile secret, and `-disable-per-source-limits` (so the load generator does not trip per-IP caps):

```sh
vagus relay -public 0.0.0.0:443 -control 0.0.0.0:19451 -domain stress.example.com \
  -cert cert.pem -key key.pem -https :443 -allow-origins https://stress.example \
  -disable-per-source-limits
```

Run `vagus-stress` from a second VM in the same region with at least twice the relay's cores (the load generator runs both ends of every connection). `-ssh` samples relay CPU, memory, open files, network counters, and UDP receive errors once per second:

```sh
go build -o vagus-stress ./cmd/vagus-stress
common="-https stress.example.com -origin https://stress.example -ssh admin@stress.example.com"
./vagus-stress throughput $common   # MB/s across 1 to 1,024 active sessions
./vagus-stress idle $common         # 250 to 4,000 concurrent idle sessions
./vagus-stress open $common         # 10 to 800 new sessions per second
./vagus-stress quic $common         # ticket rate, Initial burst, and packets/s on 1,000 QUIC routes
```

| Subcommand | Step variable (`-steps`) | Reported metrics |
| --- | --- | --- |
| `throughput` | Concurrent sessions echoing at full speed | MB/s each way and probe session 1 KiB RTT |
| `idle` | Concurrent idle sessions | Sessions still alive after `-measure`, open latency, and probe RTT |
| `open` | New sessions/s (ticket + WebSocket + handshake + 1-byte echo) | Completed sessions/s and handshake latency |
| `quic` | Packets/s across 1,000 QUIC routes (after ticket + Initial setup) | Delivered packets/s, loss rate, and echoed share with `-echo` |

Each step warms up for `-warmup` (3s) and measures for `-measure` (20s), stopping once failures or packet loss exceed `-max-failure` (5%).

Every output line prints `load box cpu`. If it approaches 100%, or `quic` cannot sustain its target send rate, you are measuring the load generator rather than the relay; use a larger load VM or run multiple generators in parallel.

Default relay-wide caps still apply during stress runs (see [Built-in limits](https://vagus.neuroplast.io/docs/operations#built-in-limits)). `vagus-stress` attaches enough connectors for its largest step, respecting the connector's 16-concurrent-handshake limit.

In `quic`, Initial packets are real `quic-go` Initials decrypted and routed by SNI, while follow-up packets are random short-header datagrams forwarded unread. Wait 2 minutes between `quic` runs so the 1,024-route table clears.

### Example results: 2-vCPU, 512 MB VM

Measured on an AWS Lightsail `nano_3_0` instance (2 burstable vCPUs, 512 MB RAM, ~410 MB usable, no swap, ~180 MB free after OS services) running Ubuntu 24.04 with 7.5 MB kernel UDP buffers (`net.core.rmem_max` / `wmem_max`) and an 8-vCPU load VM in the same zone over private IPs (load VM stayed under 40% CPU, tested without the 80% `GOMEMLIMIT` overload backstop):

| Test | Highest clean step | Breaking point | Bottleneck |
| --- | --- | --- | --- |
| `throughput` (`GOMEMLIMIT=250MiB`) | 4 sessions: 123 MB/s each way (~2 Gbit/s NIC) | 109 MB/s at 64 sessions, 80 MB/s at 512, 66 MB/s at 1,024 (143 MB RSS) | CPU |
| `idle` (`GOMEMLIMIT=250MiB`) | 2,500 sessions (154 MB RSS) | OOM-killed between 2,500 and 3,000 | Memory (~60 KB RSS/session incl. GC headroom) |
| `idle` (`GOMEMLIMIT=160MiB`) | 3,000 sessions (153 MB RSS) | GC saturates a core at 3,500; killed before 4,000 | Memory |
| `open` | 1,200 new sessions/s (p99 37 ms) | 1,600/s completes 1,323/s | CPU |
| `quic` | 1,000 routes at 18,000/s; 50,000 pkt/s (60 MB/s), 0% loss | 100,000 pkt/s delivers 68,500/s (32% loss) | CPU |

Each idle WebSocket session uses roughly 45 KB of Go live heap and goroutine stacks (`memory_bytes` in `relay load`), or ~60 KB RSS with GC headroom, because copy buffers are pooled and acquired only while transferring data. Setting `GOMEMLIMIT` to the RAM actually free for the relay (160 MiB here, not 250 MiB) lets GC and the 80% overload backstop act before the OOM killer (see [Memory and capacity](https://vagus.neuroplast.io/docs/operations#memory-and-capacity)).

High-throughput runs tripped Lightsail's `bw_in_allowance_exceeded` counter (`ethtool -S`), slowing handshakes in the following test until the allowance recovered, so run `throughput` last or pause afterward. With Linux's default 208 KiB UDP socket buffer, a burst of 1,000 simultaneous QUIC Initials overflows the kernel queue and drops most connections; raising `rmem_max` and `wmem_max` to 7.5 MB lets all 1,000 routes open cleanly.

## Run the benchmarks locally

```sh
mise exec -- make bench
# Compare before and after a change:
go test -run='^$' -bench=. -benchmem -count=10 ./pkg/relay > old.txt
# ...make changes...
go test -run='^$' -bench=. -benchmem -count=10 ./pkg/relay > new.txt
benchstat old.txt new.txt
```
