Skip to content

fix(mux): fail over to another backend on connect timeout - #1806

Merged
FlorentinDUBOIS merged 11 commits into
mainfrom
fix/backend-connect-timeout-failover
Oct 2, 2026
Merged

FlorentinDUBOIS merged 11 commits into
mainfrom
fix/backend-connect-timeout-failover

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #1800

Summary

A backend that accepts no connection (blackholed: SYN dropped, accept queue full) 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 picking it.

  • Connect timeout counts as a connect failure. Mux::timeout_inner now flags a still-Connecting connection's readiness ERROR, the way the kernel flags a refused dial. Server::timeout then runs the ready pass that only it can trigger (new ProxySession::needs_ready_pass, default false). 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 through EndStreamAction::Reconnect. The request sent no byte, so it is safe to resend. A response timeout on an established connection still answers 504.

  • A WRITABLE event no longer marks a connecting socket connected. SO_ERROR (take_error) is read first, then getpeername(2). An error is a connect failure. ENOTCONN means 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: on main, a dial from an http2 = true cluster to a blackholed backend was marked connected and then hung until back_timeout.

  • A synchronous connect(2) failure is retried instead of being answered 503 at 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_attempts counts every attempt, the first included. It replaces the hard-coded CONN_RETRIES = 3, and the default is now 5. It can be set:

    • globally: TOML and ServerConfig field 29;
    • per cluster: Cluster field 23, TOML, sozu cluster add --max-connection-attempts, and sozu cluster connection-attempts set|unset (query, then re-send with the field changed, like cluster h2). A cluster table column shows the value;
    • at runtime on every worker: sozu connection-attempts set (Request.set_max_connection_attempts, field 62). Like connection-limit set, this is not saved.

    Allowed range is 1..=255. It is validated at config load, on AddCluster (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 for max_connection_attempts × connect_timeout. When the deadline expires during failover, the request gets the frontend timeout's existing answer: 504, with access-log message client_timeout_during_response. doc/configure.md recommends keeping connect_timeout well below front_timeout / max_connection_attempts, and explains how back-off grows.

  • Socket error logged. The socket error read by take_error() is logged at debug!, 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 answer 504. Requests that arrive during a back-off window can also fail fast with 503. Operators alerting on 504 rates should watch 503, backend.connections.error and backend.connect.retries_exhausted instead. 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: Request field 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_RETRIES is removed, and new fields are added to Cluster, ServerConfig, RequestType, FileConfig, FileClusterConfig, HttpClusterConfig, TcpClusterConfig, Stream and SessionManager. 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, and CHANGELOG.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_path and a_completed_backend_response_timeout_unlinks_through_end_stream_alone. Both describe a backend that has already sent response bytes, but their fixture left it Connecting. With this change, a Connecting connection is treated as a connect timeout. No assertion changed, and neither test encodes the old 504; they cover the response-timeout arms. An alternative would be to narrow the timeout branch to Connecting && 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, plus connect_outcome_tests, exclusion_tests, a_connect_timeout_flags_the_dial_dead_instead_of_answering_504, the max_connection_attempts config tests, and the state validation test.

What each test proves:

  • The connect-timeout e2e tests use 3 healthy and 3 blackholed backends with connect_timeout = 1. The blackhole is a backlog-0 listener with a full accept queue; test_blackholed_listener_times_out checks that it really times out. Every request must answer 200, and the cluster-level backend.connections.error must 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.
  • The refused-backend e2e tests use a refused/healthy alternation that drives the first request onto three refused backends in a row. The budget raise is what fixes them. The tried set itself is covered by exclusion_tests.

CI fix: leaked mock backend threads

CI on 9bd8bfa6 and 379b4a4e failed tests::h2_tests::test_h2_rapid_reset_triggers_goaway in every cell ("received 0 frames"). The cause was in this PR's test module, not in production code.

Cause: Backends in e2e/src/tests/backend_failover_tests.rs dropped its AsyncBackend handles 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 before h2_tests in 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 Backends now 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 --nocapture before and after the fix.

  • Before: about 24 threads were busy during the rapid-reset test (ps -L), and the 999 resets took 1.57 s instead of 0.1 s.
  • After: no busy leftover threads, and the 999 resets took 0.32 s.
  • The full e2e suite dropped from 3098 s to 1963 s.

CI fix: worker events read as answers

At dff0285e, test_connect_timeout_fails_over_h2 failed 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 reported BACKEND_DOWN on 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/main 320e86d6 (#1805; conflicts in command/src/config.rs and doc/health_checks.md resolved keeping both features):

Verified: cargo +nightly fmt --all -- --check -> exit 0
Verified: cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings -> exit 0
Verified: cargo test -p sozu-lib --lib --all-features -> test result: ok. 1586 passed; 0 failed
Verified: cargo test -p sozu-command-lib -p sozu --all-features --locked -> exit 0, all test 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 failed
Verified: 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 f8d4c18e had one timing failure under load: test_h1_chunked_encoding_edge_cases. That test passed 3 times out of 3 in isolation, and the full h1_security_tests module passed with --test-threads=4.)
Verified: python3 .github/scripts/check_doc_citations.py --root . --base origin/main -> exit 0

Red without the fix:

  • New e2e tests on main (dc25d2ff):
    • test_connect_timeout_fails_over_h1/_h2: [200, 504, 200, 504, …] (12×200, 12×504) and backend.connections.error: 0.
    • test_refused_backends_never_exhaust_attempts_h1/_h2: first request 503.
    • test_h2_backend_connect_failure_fails_over_h1/_h2: [200, 0, 200, 200, 0, …], where 0 is no answer within 10 s.
  • test_failover_is_bounded_by_front_timeout_h1/_h2 (6 blackholed backends, budget 20, connect_timeout 1 s, front_timeout 3 s):
    • in a scratch copy of this branch with the per-attempt re-arm restored: no answer within 10 s on both frontends;
    • with the fix: [504] after about 3.09 s on both.
  • try_connect_timeout_fails_over now asserts backend.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.
  • Budget and unit tests, in scratch copies of this branch with one part of the fix reverted at a time:
    • default set back to 3: test_default_connection_attempt_budget_is_five fails (503), and so does the config default test;
    • cluster override ignored: …overrides_global fails (503), and so do the runtime cluster update and the default test's per-cluster four;
    • runtime setter disabled: …changes_at_runtime fails (200 where 503 is expected);
    • exclusion, fallback or sticky filter removed: the matching exclusion_tests fail;
    • ENOTCONN treated as connected: a_dial_nobody_answers_is_pending and the H2-backend e2e tests fail;
    • Connecting early return removed: a_connect_timeout_flags_the_dial_dead_instead_of_answering_504 fails;
    • validation removed: the config and state range tests fail.

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]>
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]>
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]>
…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]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit e959838 into main Oct 2, 2026
28 checks passed
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(mux): a backend connect timeout answers 504 instead of failing over to a healthy backend

1 participant