relay: fuzz WebSocket 1012 restart-close timing on graceful drain (BUZZ_DRAIN_JITTER_MS)
Problem
On SIGTERM the relay sends every live WebSocket a 1012 Service Restart close frame via ConnectionManager::drain_all() — all in the same instant (main.rs shutdown task → state.rs::drain_all). On a pod holding thousands of sessions, that makes every client reconnect simultaneously: the thundering-herd reconnect behind the DB pool-timeout bursts observed on each rolling deploy. Client-side jitter can't fix this — the desktop client resets its backoff to base on a 1012 and reconnects with only ±25% jitter (relayClientSession.ts), so the spread has to come from the server.
Change
Add BUZZ_DRAIN_JITTER_MS (default 0 = unchanged behavior). The two paths are kept deliberately separate so the default is byte-for-byte the previously shipped shutdown:
- Jitter off (
0/unset, the default): the original synchronous, all-at-oncedrain_all()runs unchanged — queue the 1012 on each connection's control channel, cancel, return. No new machinery on the default path. - Jitter on (
> 0): a separate asyncdrain_all_jittered(jitter_ms)spreads each connection's restart close over an independent uniform delay in[1, jitter_ms]. Each delayed close travels a dedicatedRestartClosechannel; the writer flushes the 1012 frame and acknowledges the flush over a oneshot, so drain waits for confirmed delivery (up toRESTART_CLOSE_ACK_TIMEOUT= 5s) rather than assuming it, falling back to cancellation if the channel is full/closed or the ack times out. The drain future is owned and awaited by the shutdown task, and the 30s hard-drain backstop is aborted only after a clean drain — so a clean roll exits0.
The two methods can be unified and the old one dropped later once the jittered path is proven for all cases.
config.rs—drain_jitter_ms: non-negative parse, clamped toMAX_DRAIN_JITTER_MS= 20s (leaving 10s of the 30s budget for flush). Junk fails loudly at startup; empty/whitespace-only is treated as unset (jitter off) so aBUZZ_DRAIN_JITTER_MS=""kill switch does not crashloop the relay (matches the sibling env vars in this file).state.rs—drain_all()(unchanged synchronous default) +drain_all_jittered()(jittered + flush-ack). Both set the stickydrainingflag before the first await. A registration that lands mid-shutdown always self-signals via the immediate control-frame + cancel path — jitter smears already-established sockets, not late arrivals.main.rs— shutdown task dispatches:drain_jitter_ms == 0→drain_all(), elsedrain_all_jittered(...).await.
Safety
- Default off is the currently-committed path. With jitter unset/0 the shutdown runs the original synchronous
drain_all()— no restart channel, no ack wait. Safe to deploy dark and dial up. - Shutdown-boundary race preserved. Sticky flag set before any await; a late registration self-signals its close with no jitter.
- Owned + backstopped. The jittered drain future is awaited; the 30s hard-drain
process::exit(1)remains the ceiling.MAX_DRAIN_JITTER_MS(20s) +RESTART_CLOSE_ACK_TIMEOUT(5s) = 25s, inside the 30s budget; 5s pre-sleep + 25s = 30s againstterminationGracePeriodSeconds: 60.
Known behavior to note (not a blocker, flagged from review)
On a successful flush the jittered path deliberately does not cancel the connection token — teardown then depends on the client echoing our Close, or on process exit. Compliant clients echo; a silent client rides to the 30s hard exit. The default (jitter-off) path cancels deterministically as before.
Tests
config::tests::drain_jitter_defaults_off_and_rejects_junk— default off,20000, clamp60000→20000, explicit0, junk"soon"fails, empty""and whitespace-only treated as off.state::tests::drain_all_is_immediate— default path queues frame + cancels synchronously.state::tests::drain_all_sends_restart_close_and_cancels_every_conn,drain_all_full_control_buffer_still_cancels,register_after_drain_self_signals_restart_close_and_cancel.state::tests::drain_all_jittered_defers_close_until_within_jitter_window(paused time).state::tests::drain_all_jittered_waits_for_writer_acknowledgement_without_cancelling.state::tests::drain_all_jittered_cancels_when_restart_channel_is_full_or_closed.state::tests::drain_all_jittered_cancels_when_flush_ack_times_out(paused time — the 5s ack-timeout fallback).
Validation at 46c690940: cargo fmt -p buzz-relay --check, cargo clippy -p buzz-relay --all-targets -- -D warnings, and the drain/config unit suite all clean. Local live SIGTERM test with a real relay process + 200 NIP-42-authenticated sockets — see the PR comment for the before/after distribution and exit codes.
Rollout
Ship with default 0, then set BUZZ_DRAIN_JITTER_MS (e.g. 10000–20000) on bb-block first, watch the roll-window pool-timeout metric, then bb-public. "" is a safe kill switch. Complements the preStop sleep (stops routing before close).
Local live relay SIGTERM test — commit 46c690940
Ran a real buzz-relay process (not a unit harness) against local Postgres + Redis, opened 200 NIP-42-authenticated WebSocket sockets, signalled a real SIGTERM, and recorded the close code, reason, and per-connection close timing each client observed. Harness is an ephemeral drain_probe bin (not committed). All results below are at HEAD 46c690940.
Setup: DATABASE_URL + REDIS_URL local, BUZZ_BIND_ADDR=0.0.0.0:3030, host row seeded in communities. Timing offsets are measured from the moment all 200 clients finished authenticating; the drain path includes the fixed 5s readiness grace before draining, so the ~5s baseline offset is expected in every case.
Jitter off (default, BUZZ_DRAIN_JITTER_MS unset) — the currently-committed path
| run | 1012 clean | resets (no-close-handshake) | close spread | relay exit | drain wall |
|---|---|---|---|---|---|
| A | 187/200 | 13/200 | 12 ms | 0 | 5.04 s |
| B | 200/200 | 0/200 | 11 ms | 0 | 5.03 s |
All closes land in a ~11-12 ms window — this is the synchronized herd the jitter knob exists to spread. Note the reset count is intermittent on the synchronous path: run A saw 13/200 Connection reset without closing handshake (the 1006-equivalent) at the very tail of the burst as the process raced to exit; run B saw zero. Exit code is 0 (clean) either way.
Jitter on
| jitter | 1012 clean | resets | close spread | 1s-bucket occupancy | relay exit | drain wall |
|---|---|---|---|---|---|---|
5000 |
200/200 | 0 | 4854 ms | 44/29/48/41/38 | 0 | 10.03 s |
10000 |
200/200 | 0 | 9970 ms | 13/24/16/19/19/24/23/22/16/24 (max share 12%) | 0 | 15.03 s |
With jitter on, every socket received a clean 1012 "relay restarting", zero resets, and the closes were spread approximately uniformly across the full window (no t=0 spike, max 1s-bucket share 12% vs ideal 10%). The flush-acknowledgement path deterministically eliminates the tail resets seen intermittently on the synchronous path. Relay exited 0; drain wall = 5s grace + jitter window, well under the 30s hard-drain backstop. The "Signalled restart close to all connections" log line fires after the last delayed close, confirming the drain future is owned and awaited.
Config edge cases (real process boot)
BUZZ_DRAIN_JITTER_MS=60000→ clamped to20000(jitter_ms=20000, max_jitter_ms=20000in the drain log).BUZZ_DRAIN_JITTER_MS=soon→ hard startup error (must be a non-negative integer), refuses to start.BUZZ_DRAIN_JITTER_MS=""→ boots with jitter off (was a startup error before commit46c690940; now treated as unset, so a""kill switch no longer crashloops the relay).
Automated (same commit)
cargo fmt -p buzz-relay --check, cargo clippy -p buzz-relay --all-targets -- -D warnings, and the full drain/config unit set (16 tests incl. the new drain_all_jittered_cancels_when_flush_ack_times_out and the empty-string config cases) all green. Push hooks (branch-skew, rust-tests, desktop-tauri-checks) passed.
Not covered here
This did not run the Postgres-backed full cargo test -p buzz-relay integration suite, the reconnect-load A/B against a second relay (the "does the pool metric actually improve" proof), or a real Desktop/mobile client through a jittered restart. Those are the next tier from the reviewers' plans if we want the full herd-reduction proof before dial-up.