Repository navigation
fix(mux): fail over to another backend on connect timeout - #1806
Merged
Merged
Conversation
A backend that accepted no connection hit `connect_timeout` and the request was answered 504. The timeout path marked the connection `Disconnecting`, so the dead-backend branch of `Mux::ready_inner`, the only place a connect failure is counted, never saw it: the backend's retry policy was never armed and the load balancer kept choosing it. A connect timeout is now a backend connect failure like a refused dial. `Mux::timeout_inner` flags the connecting connection's readiness ERROR and `Server::timeout` runs the `ready` pass only it can trigger (`ProxySession::needs_ready_pass`); the dead-backend branch counts the failure, closes the connection and re-links the request, which sent no byte, through `EndStreamAction::Reconnect`. 504 stays the answer to a response timeout on an established connection. On the same path: - a WRITABLE event on a connecting socket reads `SO_ERROR` and `getpeername(2)` before the connection is marked established: an error is a connect failure, a dial still in flight (a WRITABLE sozu raised itself, as for an HTTP/2 backend's preface) waits for the kernel edge; - a synchronous `connect(2)` failure is retried instead of answered 503; - each retry skips the backends that already failed for the request, under every load-balancing policy, falling back to the plain selection when every selectable backend was tried; - the retry budget replaces the hard-coded `CONN_RETRIES = 3` with `max_connection_attempts`: global (default 5) and per cluster, in TOML, the protocol and the CLI, changeable at runtime with `sozu connection-attempts set` and `sozu cluster connection-attempts`. Fixes #1800 Signed-off-by: Florentin Dubois <[email protected]>
…imeout-failover Signed-off-by: Florentin Dubois <[email protected]>
The pending-links loop re-armed the frontend timer to the full `front_timeout` on every link, so a request failing over between dead backends could run for `max_connection_attempts` times `connect_timeout` with no answer. The nominal frontend timeout is now set only on a request's first link: the deadline armed then bounds the whole failover, and when it expires the request is answered 504 (`client_timeout_during_response`), as any request still waiting on a backend is. The socket error read on a failed dial is logged at the level of the synchronous refusal. The documentation and changelog state the status change for an unreachable backend (503, was 504 on a connect timeout), the fail-fast 503 during back-off, the relation between `max_connection_attempts`, `connect_timeout` and `front_timeout`, the back-off growth, and the replay bound the new default implies. Refs #1800 Signed-off-by: Florentin Dubois <[email protected]>
…imeout-failover Signed-off-by: Florentin Dubois <[email protected]>
… next one Signed-off-by: Florentin Dubois <[email protected]>
…imeout-failover Signed-off-by: Florentin Dubois <[email protected]>
…c link Signed-off-by: Florentin Dubois <[email protected]>
The failover tests dropped their `AsyncBackend` handles without stopping them. That backend's thread polls a non-blocking listener in a loop only a stop message ends, so each dropped handle left a thread spinning for the rest of the test process: about two dozen, all started before `h2_tests` in name order. On a small CI runner they starved the worker of `test_h2_rapid_reset_triggers_goaway`, which then read no frame in its 2.5 s window. `Backends` now stops them on drop. Signed-off-by: Florentin Dubois <[email protected]>
…imeout-failover Signed-off-by: Florentin Dubois <[email protected]>
…tests A worker writes the events it emits to the command channel too. The failover tests make backends fail on purpose, and once a backend's retry policy gives up on it the worker reports BACKEND_DOWN: in CI that event arrived just before the answer to the metrics query, which the test then read as the answer and failed on (crypto-openssl cell, every status 200). The tests now skip events while waiting for an answer. Signed-off-by: Florentin Dubois <[email protected]>
…imeout-failover Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Oct 3, 2026
…1809) Audit of the docs, `bin/config.toml` and `os-build/config.toml` against everything merged on `main` from 2026-10-01 to 2026-10-03 (43 commits, #1724 through #1808). Most of the new keys were already documented by their own PRs (`max_connection_attempts`, `h2_stream_refusal_percent`, health check `mode`/`accepted_statuses`, the raised flood defaults, the 16 MiB connection window). This PR fixes what was still stale. | Area | Where | Was | Now | |---|---|---|---| | #1806 | `bin/config.toml`, `os-build/config.toml` answer comments | 503 only for "no backend available"; "504 means the backend timed out" | 503 also when every attempt failed; 504 = connected backend silent or frontend timeout while waiting; connect timeout fails over | | #1806 | `bin/config.toml` `max_connection_attempts` | connect timeout always fails over | a TCP session whose connect times out is closed | | #1806 | `doc/debugging_strategies.md` | 503 after a circuit breaker of 3 failed connections; ERROR log lines, one that no longer exists | `max_connection_attempts` (default 5), `backend.connect.retries_exhausted`, real TCP log levels and text | | #1806 | `doc/configure.md` `front_timeout` / `connect_timeout` rows | "inactivity for a request to connect" | time to establish a backend connection; HTTP fails over, TCP closes; H1 failover bound by `front_timeout` | | #1806 | `doc/configure.md` `client_timeout_during_response`, `backend_timeout`, `http.503.errors` | "connection-level slowness", "circuit breaker" | failover case included; established connection only; attempt budget | | #1806 | `LIFECYCLE.md` backend timer | 504 for any linked stream | established connection only | | #1806 | `cli.rs` help, `doc/configure_cli.md` | "answered 503" | "or a TCP session is closed" | | #1756 | `doc/configure.md` flood metrics | RST lifetime rows described as absolute ceilings; no `window_update_stream0_window` row | floor-and-ratio semantics; row added | | #1756/#1798 | `doc/architecture.md`, `doc/h2_mux_internals.md` | 6 / 13 `H2FloodConfig` thresholds | 14, with `h2_stream_refusal_percent` | | #1756 | `doc/configure_admin_ops.md` | "halve" example 50/25 (old defaults); H2 knobs HTTPS only | 1000/500; HTTP and HTTPS; `h2.flood.stream_refused` | | #1752 | `doc/configure.md` glitch tuning | "1 MiB window ... about 64" frames | 64 KiB stream window, about four | | #1805 | `doc/health_checks.md` | `remove` resets backends to healthy; DOWN logs an error; `load_balancing.rs::BackendList::healthy` | backends keep their last state (see note); warning; `BackendList::select_tiers` in `backends.rs` | | #1805 | `doc/metrics.md` | health-check counters "per cluster" | unlabelled | | #1805 | `doc/configure_cli.md` | no health-check section | short section, `--mode`, `--probe-timeout` vs global `--timeout` | | #1746 | `cli.rs` `--load-balancing-policy`, `bin/config.toml`, proto comment | HRW/MAGLEV key = UDP flow key | UDP affinity key (source IP, or IP and port) | | UDP | `doc/configure.md` | hot upgrade drains flows bounded by idle timeout; `udp.flows.evicted` reasons | soft-stop closes flows at once; listener removal/soft-stop/abort added | | #1770 | `doc/udp_simulation.md` | no per-source limits | in reconfig storms and the invariant list | | #1743 | `doc/lifetime_of_a_session.md` | keep-alive backend always reused | unless its backend was removed | | older | `command.proto` update messages | `h2_stream_shrink_ratio >= 1` | `>= 2`, as validated in `state.rs` | | #1806 | e2e shuffle-sharding doc comment | "three connection attempts" | `max_connection_attempts` (5 by default) | Reported here, not changed in this PR: - `sozu cluster health-check remove` does not reset backends a probe marked DOWN (`remove_health_check_state` skips the reset that `set_health_check_config(None)` does), so they stay out of rotation until the cluster is added again. The doc now describes this. It looks like a code bug. - `sozu top`'s H2 pane reads `h2.flood.violation.{rapid_reset,made_you_reset,ping,settings,priority,continuation}`, which the detector never emits (it emits `rst_stream_pre_response_lifetime`, `ping_window`, ...). Only `glitch_window` matches, and `h2.flood.stream_refused` is not shown. - `h2_flood_detector.rs` comments still refer to a 1 MiB connection window, and the `h2_stream_idle_timeout_seconds` proto comment says "Default: 30" where the value inherits `back_timeout`. - `connections.rejected_per_cluster_ip` is documented as also counting TCP rejections; only the HTTP 429 path increments it. Validation: - `sozu config check` passes on `bin/config.toml`, on a copy with every commented key under review uncommented (global and cluster `max_connection_attempts`, the H2 block, the health check block), and on `os-build/config.toml` with local state/socket paths. Negative controls (`max_connection_attempts = 0`; `expected_status = 200` next to `accepted_statuses`) are rejected. - `cargo +1.93.1 test -p sozu-command-lib --all-features --locked`: 235 passed. - `cargo +1.93.1 test -p sozu --bin sozu --locked`: 124 passed (including the `--load-balancing-policy` help tests). - `cargo +nightly fmt --all --check` and `python3 .github/scripts/check_doc_citations.py --root . --base origin/main` are clean. Signed-off-by: Florentin Dubois <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1800
Summary
A backend that accepts no connection (blackholed: SYN dropped, accept queue full) hit
connect_timeoutand the request was answered504. The timeout path marked the connectionDisconnecting, so the dead-backend branch ofMux::ready_inner, the only place a connect failure is counted, never saw it. The backend's retry policy was never armed and the load balancer kept picking it.Connect timeout counts as a connect failure.
Mux::timeout_innernow flags a still-Connectingconnection's readinessERROR, the way the kernel flags a refused dial.Server::timeoutthen runs thereadypass that only it can trigger (newProxySession::needs_ready_pass, defaultfalse). That pass reuses the existing dead-backend branch: it counts the failure (failures,retry_policy,backend.connections.error,backend.down), closes the connection, and re-links the request throughEndStreamAction::Reconnect. The request sent no byte, so it is safe to resend. A response timeout on an established connection still answers504.A WRITABLE event no longer marks a connecting socket connected.
SO_ERROR(take_error) is read first, thengetpeername(2). An error is a connect failure.ENOTCONNmeans the WRITABLE was raised by Sōzu itself, not by the kernel, so the connection waits for the kernel's completion edge. This fixes a separate defect you can observe on its own: onmain, a dial from anhttp2 = truecluster to a blackholed backend was marked connected and then hung untilback_timeout.A synchronous
connect(2)failure is retried instead of being answered503at once.Each retry skips the backends that already failed for this request (
Stream::tried_backends), for every load-balancing policy. The exclusion narrows the candidate set (BackendList::select_with_key_excluding). If every selectable backend was already tried, selection falls back to the plain behaviour, fail-open included, so the request retries one of them instead of being refused. A sticky cookie that names a tried backend is not followed.The retry budget is configurable.
max_connection_attemptscounts every attempt, the first included. It replaces the hard-codedCONN_RETRIES = 3, and the default is now 5. It can be set:ServerConfigfield 29;Clusterfield 23, TOML,sozu cluster add --max-connection-attempts, andsozu cluster connection-attempts set|unset(query, then re-send with the field changed, likecluster h2). A cluster table column shows the value;sozu connection-attempts set(Request.set_max_connection_attempts, field 62). Likeconnection-limit set, this is not saved.Allowed range is
1..=255. It is validated at config load, onAddCluster(main and worker), and on the runtime set. A cluster value wins over the global one, for both HTTP and TCP clusters.Failover is bounded by
front_timeout. The frontend's nominal timeout is set only on a request's first link, not on every re-link. The deadline armed then therefore bounds the whole failover, so a request can no longer run formax_connection_attempts × connect_timeout. When the deadline expires during failover, the request gets the frontend timeout's existing answer:504, with access-log messageclient_timeout_during_response.doc/configure.mdrecommends keepingconnect_timeoutwell belowfront_timeout / max_connection_attempts, and explains how back-off grows.Socket error logged. The socket error read by
take_error()is logged atdebug!, the same level as the synchronous-refusal path.Status change for alerting: when every attempted backend is unreachable (connect timeout or refused), the answer is now
503. A connect timeout used to answer504. Requests that arrive during a back-off window can also fail fast with503. Operators alerting on504rates should watch503,backend.connections.errorandbackend.connect.retries_exhaustedinstead. With the default budget at 5, an idempotent request on a stale keep-alive connection can be replayed to up to 4 backends (n - 1), against 2 before.Coordination:
Requestfield 62 is also used by the open PR #1300. That PR already needs renumbering, so this one keeps 62.Library API break:
sozu_lib::server::CONN_RETRIESis removed, and new fields are added toCluster,ServerConfig,RequestType,FileConfig,FileClusterConfig,HttpClusterConfig,TcpClusterConfig,StreamandSessionManager. Upgrade the main process, the workers and the CLI together before setting a per-cluster budget: an older CLI that patches clusters by read-modify-write drops the field.Docs:
doc/configure.md(new "Backend connection failover" section, global key, metrics, shard and replay budget text),doc/configure_cli.md,doc/health_checks.md,doc/lifetime_of_a_session.md,doc/rate-limit-design.md,lib/src/protocol/mux/LIFECYCLE.md§7.3,bin/config.toml, andCHANGELOG.md.Existing tests touched
Two existing tests now call
mark_connected(h1)in their fixtures:a_backend_timeout_leaves_no_linked_stream_behind_on_the_close_pathanda_completed_backend_response_timeout_unlinks_through_end_stream_alone. Both describe a backend that has already sent response bytes, but their fixture left itConnecting. With this change, aConnectingconnection is treated as a connect timeout. No assertion changed, and neither test encodes the old504; they cover the response-timeout arms. An alternative would be to narrow the timeout branch toConnecting && no linked stream has back.consumed. I kept the fixture fix instead, because that extra condition cannot be reached in production.Tests
New:
e2e/src/tests/backend_failover_tests.rs, plusconnect_outcome_tests,exclusion_tests,a_connect_timeout_flags_the_dial_dead_instead_of_answering_504, themax_connection_attemptsconfig tests, and the state validation test.What each test proves:
connect_timeout = 1. The blackhole is a backlog-0 listener with a full accept queue;test_blackholed_listener_times_outchecks that it really times out. Every request must answer 200, and the cluster-levelbackend.connections.errormust be greater than 0. That counter shows the timeouts are now counted against the backend, which arms its retry policy. It does not measure a drop in how often dead backends are picked.exclusion_tests.CI fix: leaked mock backend threads
CI on
9bd8bfa6and379b4a4efailedtests::h2_tests::test_h2_rapid_reset_triggers_goawayin every cell ("received 0 frames"). The cause was in this PR's test module, not in production code.Cause:
Backendsine2e/src/tests/backend_failover_tests.rsdropped itsAsyncBackendhandles without stopping them. That backend's thread (e2e/src/mock/async_backend.rs, the spawn loop) only exits on a stop message, so every dropped handle left a thread spinning for the rest of the test process. That was about two dozen threads, all started beforeh2_testsin name order. On a small CI runner they starved the rapid-reset worker: CI logged its 999 resets over 12 s, in batches of about 17 every 110 ms. Main's CI run took 0.16 s for the same resets, with identical per-stream timings.Fix:
impl Drop for Backendsnow stops those backends. The rapid-reset test is unchanged.Evidence: I ran
taskset -c 0 cargo test -p sozu-e2e --locked -- backend_failover tests::h2_tests::test_h2_rapid_reset_triggers_goaway --test-threads=4 --nocapturebefore and after the fix.ps -L), and the 999 resets took 1.57 s instead of 0.1 s.CI fix: worker events read as answers
At
dff0285e,test_connect_timeout_fails_over_h2failed in the crypto-openssl cell even though every request got its 200. The test's metrics query read a worker event (content_type: Some("event")) in place of its answer. The failover tests make backends fail on purpose, and a backend whose retry policy gives up on it is reportedBACKEND_DOWNon the same command channel. Reads in these tests now skip events (read_answer).That event's arrival depends on randomized back-off, so I did not reproduce the race locally. After the fix, both connect-timeout tests passed 20 runs out of 20 under
taskset -c 0, and 20 out of 20 on 2 CPUs loaded with 6 busy processes.Validation at head
6c7dd668, after merging origin/main320e86d6(#1805; conflicts incommand/src/config.rsanddoc/health_checks.mdresolved keeping both features):Verified:
cargo +nightly fmt --all -- --check-> exit 0Verified:
cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings-> exit 0Verified:
cargo test -p sozu-lib --lib --all-features->test result: ok. 1586 passed; 0 failedVerified:
cargo test -p sozu-command-lib -p sozu --all-features --locked-> exit 0, alltest result: ok(227 command-lib unit tests)Verified:
cargo test -p sozu-e2e --features opentelemetry,splice,simd -- --test-threads=4->test result: ok. 621 passed; 0 failedVerified:
RUSTDOCFLAGS="-D warnings" cargo +1.93.1 doc --no-deps --locked -p sozu-lib -p sozu-command-lib -p sozu-> exit 0(An earlier run at
f8d4c18ehad one timing failure under load:test_h1_chunked_encoding_edge_cases. That test passed 3 times out of 3 in isolation, and the fullh1_security_testsmodule passed with--test-threads=4.)Verified:
python3 .github/scripts/check_doc_citations.py --root . --base origin/main-> exit 0Red without the fix:
main(dc25d2ff):test_connect_timeout_fails_over_h1/_h2:[200, 504, 200, 504, …](12×200, 12×504) andbackend.connections.error: 0.test_refused_backends_never_exhaust_attempts_h1/_h2: first request503.test_h2_backend_connect_failure_fails_over_h1/_h2:[200, 0, 200, 200, 0, …], where0is no answer within 10 s.test_failover_is_bounded_by_front_timeout_h1/_h2(6 blackholed backends, budget 20,connect_timeout1 s,front_timeout3 s):[504]after about 3.09 s on both.try_connect_timeout_fails_overnow assertsbackend.connections.error >= 3, one failure per blackholed backend. Round robin hits each of the six backends in the first six requests, so this is deterministic.test_default_connection_attempt_budget_is_fivefails (503), and so does the config default test;…overrides_globalfails (503), and so do the runtime cluster update and the default test's per-clusterfour;…changes_at_runtimefails (200where503is expected);exclusion_testsfail;ENOTCONNtreated as connected:a_dial_nobody_answers_is_pendingand the H2-backend e2e tests fail;Connectingearly return removed:a_connect_timeout_flags_the_dial_dead_instead_of_answering_504fails;