[GH-ISSUE #6778] Proposal: reachability-aware balancer control (auto override) on top of RoutingService #4516

Open
opened 2026-10-31 20:40:12 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @AliKarami on GitHub (Oct 9, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6778

Problem

Xray's balancer strategies choose on weak signals:

  • Probes: every strategy ranks by the RTT of one tiny generate_204 probe. The body is never read and any HTTP response counts as "alive". Nothing measures loss, throughput, or failures of real traffic.
  • burstObservatory: a node stays "alive" while any probe in the last 10-minute window succeeded, and its delay averages only the successful probes. So leastPing prefers fast-but-flaky nodes.
  • leastLoad: it ranks by delay spread rather than mean, and tolerance defaults to off.
  • No fallbackTag: an empty pick falls through to the default outbound, which is direct in our template, so relay setups leak traffic from the server's own IP.

Upstream has frozen the balancer and observatory code apart from bug fixes. XTLS/Xray-core#6179 was closed "not planned", and in XTLS/Xray-core#5483 / #6495 maintainers said to write a controller on the routing API. XKeen recently shipped one (jameszeroX/XKeen#105) that pins the fastest node with xray api bo.

Why not port XKeen's controller

  • OverrideBalancerTarget bypasses the strategy, the alive filter and fallbackTag. A pinned node that dies keeps receiving traffic until the next cron tick (15 min by default). A pinned tag that no longer exists makes the core close the connection.
  • Its speed test downloads 10 MB per node every 15 min, about 29 GB/month per outbound. A periodic bulk download through a circumvention tunnel is also a fingerprint.
  • It was built for one household on a router. On a multi-user server, pinning everyone to the "fastest" exit loads that exit, so its measured speed drops and the controller flaps.

Proposed phases

Phase 0: overrides that stay put. PR #6779. The panel records the overrides it sets for the running core and re-applies them after its own routing reloads (every Xray-settings save, node tests through an outbound). It validates targets against the running config and clears an override whose outbound is removed. A restart still clears overrides, as documented.

  • Open question: should manual overrides survive an Xray restart or crash (stored in settings)? My recommendation is no for manual pins. Phase 1 re-derives its own pin after a restart anyway.

Phase 1: per-balancer "Auto" mode (reachability). Opt-in, one controller per panel. Each node manages its own core, the way balancers already work.

  • Health: reuse the observatory scrape we already collect (xray_metrics.go, debounced outbound.down/up), optionally plus probes of real services that validate the HTTP status.
  • Decision: a margin in both ms and percent, the median of the last k samples, a minimum dwell time, and a rule to fail fast and recover slowly.
  • Safety: when the pinned node fails, clear the override at once, handing traffic back to Xray's strategy and fallbackTag. Don't wait for the next ranking tick.
  • Probing path: run probes through the live core, using a static loopback SOCKS inbound with one user per outbound and rules placed first (the per-user bridge pattern amneziawgnet uses). Don't use the outbound tester: it holds the UI test lock and tests the template, not the live handler.
  • Lazy: probe only while the balancer carries traffic.

Phase 2: optional throughput tie-breaker. Off by default.

  • A bounded GET (256 KB–1 MB) that requires a 2xx response, using the median of several samples and a daily byte budget.
  • It never ejects a node that latency considers healthy. This is the design of the open SagerNet/sing-box#4398.

Related: #6387, #6624, #5681.

Does this direction fit the project? I'm happy to send Phase 1 once the shape is agreed.

Originally created by @AliKarami on GitHub (Oct 9, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6778 ### Problem Xray's balancer strategies choose on weak signals: - **Probes:** every strategy ranks by the RTT of one tiny `generate_204` probe. The body is never read and any HTTP response counts as "alive". Nothing measures loss, throughput, or failures of real traffic. - **burstObservatory:** a node stays "alive" while any probe in the last 10-minute window succeeded, and its delay averages only the successful probes. So `leastPing` prefers fast-but-flaky nodes. - **leastLoad:** it ranks by delay spread rather than mean, and `tolerance` defaults to off. - **No `fallbackTag`:** an empty pick falls through to the default outbound, which is `direct` in our template, so relay setups leak traffic from the server's own IP. Upstream has frozen the balancer and observatory code apart from bug fixes. XTLS/Xray-core#6179 was closed "not planned", and in XTLS/Xray-core#5483 / #6495 maintainers said to write a controller on the routing API. XKeen recently shipped one (jameszeroX/XKeen#105) that pins the fastest node with `xray api bo`. ### Why not port XKeen's controller - `OverrideBalancerTarget` bypasses the strategy, the alive filter and `fallbackTag`. A pinned node that dies keeps receiving traffic until the next cron tick (15 min by default). A pinned tag that no longer exists makes the core close the connection. - Its speed test downloads 10 MB per node every 15 min, about 29 GB/month per outbound. A periodic bulk download through a circumvention tunnel is also a fingerprint. - It was built for one household on a router. On a multi-user server, pinning everyone to the "fastest" exit loads that exit, so its measured speed drops and the controller flaps. ### Proposed phases **Phase 0: overrides that stay put.** PR #6779. The panel records the overrides it sets for the running core and re-applies them after its own routing reloads (every Xray-settings save, node tests through an outbound). It validates targets against the running config and clears an override whose outbound is removed. A restart still clears overrides, as documented. - **Open question:** should manual overrides survive an Xray restart or crash (stored in settings)? My recommendation is no for manual pins. Phase 1 re-derives its own pin after a restart anyway. **Phase 1: per-balancer "Auto" mode (reachability).** Opt-in, one controller per panel. Each node manages its own core, the way balancers already work. - **Health:** reuse the observatory scrape we already collect (`xray_metrics.go`, debounced `outbound.down/up`), optionally plus probes of real services that validate the HTTP status. - **Decision:** a margin in both ms and percent, the median of the last k samples, a minimum dwell time, and a rule to fail fast and recover slowly. - **Safety:** when the pinned node fails, clear the override at once, handing traffic back to Xray's strategy and `fallbackTag`. Don't wait for the next ranking tick. - **Probing path:** run probes through the live core, using a static loopback SOCKS inbound with one user per outbound and rules placed first (the per-user bridge pattern `amneziawgnet` uses). Don't use the outbound tester: it holds the UI test lock and tests the template, not the live handler. - **Lazy:** probe only while the balancer carries traffic. **Phase 2: optional throughput tie-breaker.** Off by default. - A bounded GET (256 KB–1 MB) that requires a 2xx response, using the median of several samples and a daily byte budget. - It never ejects a node that latency considers healthy. This is the design of the open SagerNet/sing-box#4398. Related: #6387, #6624, #5681. Does this direction fit the project? I'm happy to send Phase 1 once the shape is agreed.
Author
Owner

@github-actions[bot] commented on GitHub (Oct 9, 2026):

This is a feature proposal, not a defect report, and the repository source backs up its premises. The panel can already set a manual override through the core's RoutingService, but it keeps no record of that override. Nothing in the code re-applies it after the panel reloads routing. Whether the direction fits the project is the maintainer's decision, so I've labelled it enhancement and left it open.

What the current code does (relevant to Phase 0)

  • The manual override is a straight pass-through to the core. XrayService.OverrideBalancer in internal/web/service/xray.go:1341-1360 resolves a balancer-loopback target and then calls return s.xrayAPI.SetBalancerTarget(tag, target). It persists nothing and keeps no in-memory record. The core API call is OverrideBalancerTarget in internal/xray/api.go:330-338.
  • No validation against the running config. The controller balancerOverride (internal/web/controller/xray_setting.go:391-403) checks only that tag is non-empty. resolveOverrideTarget (xray.go:1365) reads the saved template from GetXrayConfigTemplate(), not the running config, and it only maps balancer names to loopback tags. It never checks that a plain outbound tag exists. So the "validates targets against the running config" part of Phase 0 would be new behaviour.
  • Routing reloads replace the whole routing section. When an Xray-settings save changes only rules or balancers, tryHotApply (xray.go:1492) applies it through diffRouting (internal/xray/hot_diff.go:461). That pushes the full RouterConfig via AddRule with ShouldAppend: false (internal/xray/api.go:283-284). Any other change goes through process.Stop() and a fresh process (xray.go:1454-1464). Inference, not checked against xray-core source here: a full routing replacement rebuilds the balancers, which would drop an override set earlier. That matches the problem your Phase 0 describes.
  • The default outbound really is direct. The template's first outbound is "protocol": "freedom" … "tag": "direct" (internal/web/service/config.json:31-39). An empty balancer pick without a fallbackTag therefore exits from the server's own IP. The balancer form already exposes fallbackTag (frontend/src/pages/xray/balancers/BalancerFormModal.tsx:258), so filling it in is the workaround available today.
  • A debounced health signal already exists. outboundHealth in internal/web/service/xray_metrics.go:53-63 requires a configurable streak of consecutive failed observatory probes before publishing outbound.down, and publishes outbound.up only after a down was notified. The events are EventOutboundDown/EventOutboundUp in internal/eventbus/events.go:10-11. Phase 1 could reuse these instead of building new health logic.

Points the maintainer will likely want settled before a Phase 1 PR

  1. Multi-node. CLAUDE.md requires every state-changing operation to go through runtime.Runtime. Any controller that runs on its own schedule would also be a new cron job under internal/web/job/. The proposal says "each node manages its own core", so the design should say whether the master drives node overrides through runtime.Remote or each node runs its controller locally. It should also say how the setting syncs to nodes.
  2. Persistence (your open question). Overrides currently live only in the running core, and nothing stores them. Storing manual pins in settings would need a DB migration in internal/database/db.go and a user-visible behaviour change, so that is the maintainer's call.
  3. Probe path. A loopback SOCKS inbound with one user per outbound changes the generated config for everyone who turns Auto mode on. It also has to coexist with the existing balancer-loopback rules; ordering bugs there have bitten before (#5960).

Related, not duplicates: #6387 (priority/preferential outbounds in balancers) and #6624 (per-balancer observatory settings) touch the same area with different mechanisms. #5681 is closed. I found no existing issue or PR proposing an override controller.

Verdict: Feature request

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:6085476607 --> @github-actions[bot] commented on GitHub (Oct 9, 2026): This is a feature proposal, not a defect report, and the repository source backs up its premises. The panel can already set a manual override through the core's `RoutingService`, but it keeps no record of that override. Nothing in the code re-applies it after the panel reloads routing. Whether the direction fits the project is the maintainer's decision, so I've labelled it `enhancement` and left it open. **What the current code does (relevant to Phase 0)** - The manual override is a straight pass-through to the core. `XrayService.OverrideBalancer` in `internal/web/service/xray.go:1341-1360` resolves a balancer-loopback target and then calls `return s.xrayAPI.SetBalancerTarget(tag, target)`. It persists nothing and keeps no in-memory record. The core API call is `OverrideBalancerTarget` in `internal/xray/api.go:330-338`. - No validation against the running config. The controller `balancerOverride` (`internal/web/controller/xray_setting.go:391-403`) checks only that `tag` is non-empty. `resolveOverrideTarget` (`xray.go:1365`) reads the saved template from `GetXrayConfigTemplate()`, not the running config, and it only maps balancer names to loopback tags. It never checks that a plain outbound tag exists. So the "validates targets against the running config" part of Phase 0 would be new behaviour. - Routing reloads replace the whole routing section. When an Xray-settings save changes only rules or balancers, `tryHotApply` (`xray.go:1492`) applies it through `diffRouting` (`internal/xray/hot_diff.go:461`). That pushes the full `RouterConfig` via `AddRule` with `ShouldAppend: false` (`internal/xray/api.go:283-284`). Any other change goes through `process.Stop()` and a fresh process (`xray.go:1454-1464`). *Inference, not checked against xray-core source here:* a full routing replacement rebuilds the balancers, which would drop an override set earlier. That matches the problem your Phase 0 describes. - The default outbound really is `direct`. The template's first outbound is `"protocol": "freedom"` … `"tag": "direct"` (`internal/web/service/config.json:31-39`). An empty balancer pick without a `fallbackTag` therefore exits from the server's own IP. The balancer form already exposes `fallbackTag` (`frontend/src/pages/xray/balancers/BalancerFormModal.tsx:258`), so filling it in is the workaround available today. - A debounced health signal already exists. `outboundHealth` in `internal/web/service/xray_metrics.go:53-63` requires a configurable streak of consecutive failed observatory probes before publishing `outbound.down`, and publishes `outbound.up` only after a down was notified. The events are `EventOutboundDown`/`EventOutboundUp` in `internal/eventbus/events.go:10-11`. Phase 1 could reuse these instead of building new health logic. **Points the maintainer will likely want settled before a Phase 1 PR** 1. **Multi-node.** `CLAUDE.md` requires every state-changing operation to go through `runtime.Runtime`. Any controller that runs on its own schedule would also be a new cron job under `internal/web/job/`. The proposal says "each node manages its own core", so the design should say whether the master drives node overrides through `runtime.Remote` or each node runs its controller locally. It should also say how the setting syncs to nodes. 2. **Persistence (your open question).** Overrides currently live only in the running core, and nothing stores them. Storing manual pins in settings would need a DB migration in `internal/database/db.go` and a user-visible behaviour change, so that is the maintainer's call. 3. **Probe path.** A loopback SOCKS inbound with one user per outbound changes the generated config for everyone who turns Auto mode on. It also has to coexist with the existing balancer-loopback rules; ordering bugs there have bitten before (#5960). **Related, not duplicates:** #6387 (priority/preferential outbounds in balancers) and #6624 (per-balancer observatory settings) touch the same area with different mechanisms. #5681 is closed. I found no existing issue or PR proposing an override controller. Verdict: Feature request *This reply was generated automatically; a maintainer may follow up.* <!-- claude-issue:analyst -->
Author
Owner

@AliKarami commented on GitHub (Oct 14, 2026):

@MHSanaei thanks for merging #6779. That PR was the first step of a larger plan in this issue. Here is the full picture in one place, so you can decide whether the rest is worth doing.

The problem

Many operators put several relay outbounds behind one Xray balancer and expect it to send users to a node that works and is fast. In practice it often doesn't:

  • Dead nodes keep getting traffic. With burstObservatory, an outbound counts as alive if any probe in the sampling window succeeded. A node that fails most probes keeps receiving users.
  • The pick is noisy. leastPing and leastLoad rank outbounds by the round-trip time of one tiny generate_204 request, with no hysteresis by default. The choice jumps between nodes on jitter, and it says nothing about real throughput.
  • Failures can leak. When no outbound passes and no fallbackTag is set, traffic falls through to the default outbound, which is direct in our template. A relay setup then exits from the server's own IP.

Xray won't change its balancer: the balancer and observatory code is frozen apart from bug fixes, and XTLS/Xray-core#6179 was closed as not planned. Its maintainers suggest writing an external controller that drives RoutingService. People now do that outside the panel, for example XKeen's cron script (jameszeroX/XKeen#105). It speed-tests each node with a 10 MB download and pins the winner with xray api bo. That approach has its own problems:

  • The pin is blind between runs, so a dead pinned node keeps all the traffic until the next tick (15 minutes by default).
  • The downloads cost about 29 GB per outbound per month.
  • On a multi-user server, pinning everyone to the "fastest" node slows it down, so the pick flaps.

The panel already has what a better controller needs: the observatory data, the live core API and the balancer UI. So I'd like to build it into the panel, in three steps.

The plan

Phase 0: make manual overrides reliable. Done in #6779.
The panel's existing Override button was the only way to pin a balancer, but the pin silently disappeared on any routing save or node test. The panel also accepted target tags the core didn't have, which made the core close every connection through that balancer. Phase 1 builds on this.

Phase 1: an "Auto" mode per balancer, based on reachability. This is the main step.

  • Off by default. It is enabled per balancer.
  • Health. It reuses the observatory results the panel already collects. Optionally it also probes a real target through the live core and checks the HTTP status.
  • Stable choice. It pins the best reachable outbound and switches only when another one is clearly better: by a fixed and a relative margin, on the median of recent samples, after a minimum time on the current pick.
  • Fails safe. When the pinned outbound fails, it removes the pin at once and hands traffic back to Xray's own strategy and fallbackTag. It never pins a tag the running config doesn't have.
  • Lazy. It probes only while the balancer carries traffic.
  • Shape of the PR. One PR: the backend controller with tests, a toggle in the balancer UI, and translations for all 13 locales. Each node panel runs its own controller for its own core, the same way balancers work today.

Phase 2 (optional, later): a throughput tie-breaker.
A small, bounded download test (well under 1 MB, with a daily byte budget) that only breaks ties between outbounds Phase 1 already considers healthy. It would be off by default, and I'd only propose it once Phase 1 has been in use for a while.

Questions for you

  1. Are you aligned with Phase 1 being part of 3x-ui? If yes, I'll start on it. If you'd rather keep the panel out of active balancing, I'll stop here, and Phase 0 still stands on its own.
  2. Should a manual override survive an Xray restart? Today a restart clears it, as the API docs say. I'd keep it that way, because Auto mode re-picks after a restart anyway, and a manual pin that silently comes back after a crash could surprise people. If you prefer them persisted, that's a small separate PR.
<!-- gh-comment-id:6165255181 --> @AliKarami commented on GitHub (Oct 14, 2026): @MHSanaei thanks for merging #6779. That PR was the first step of a larger plan in this issue. Here is the full picture in one place, so you can decide whether the rest is worth doing. ### The problem Many operators put several relay outbounds behind one Xray balancer and expect it to send users to a node that works and is fast. In practice it often doesn't: - **Dead nodes keep getting traffic.** With `burstObservatory`, an outbound counts as alive if any probe in the sampling window succeeded. A node that fails most probes keeps receiving users. - **The pick is noisy.** `leastPing` and `leastLoad` rank outbounds by the round-trip time of one tiny `generate_204` request, with no hysteresis by default. The choice jumps between nodes on jitter, and it says nothing about real throughput. - **Failures can leak.** When no outbound passes and no `fallbackTag` is set, traffic falls through to the default outbound, which is `direct` in our template. A relay setup then exits from the server's own IP. Xray won't change its balancer: the balancer and observatory code is frozen apart from bug fixes, and XTLS/Xray-core#6179 was closed as not planned. Its maintainers suggest writing an external controller that drives `RoutingService`. People now do that outside the panel, for example XKeen's cron script (jameszeroX/XKeen#105). It speed-tests each node with a 10 MB download and pins the winner with `xray api bo`. That approach has its own problems: - The pin is blind between runs, so a dead pinned node keeps all the traffic until the next tick (15 minutes by default). - The downloads cost about 29 GB per outbound per month. - On a multi-user server, pinning everyone to the "fastest" node slows it down, so the pick flaps. The panel already has what a better controller needs: the observatory data, the live core API and the balancer UI. So I'd like to build it into the panel, in three steps. ### The plan **Phase 0: make manual overrides reliable. Done in #6779.** The panel's existing Override button was the only way to pin a balancer, but the pin silently disappeared on any routing save or node test. The panel also accepted target tags the core didn't have, which made the core close every connection through that balancer. Phase 1 builds on this. **Phase 1: an "Auto" mode per balancer, based on reachability.** This is the main step. - **Off by default.** It is enabled per balancer. - **Health.** It reuses the observatory results the panel already collects. Optionally it also probes a real target through the live core and checks the HTTP status. - **Stable choice.** It pins the best reachable outbound and switches only when another one is clearly better: by a fixed and a relative margin, on the median of recent samples, after a minimum time on the current pick. - **Fails safe.** When the pinned outbound fails, it removes the pin at once and hands traffic back to Xray's own strategy and `fallbackTag`. It never pins a tag the running config doesn't have. - **Lazy.** It probes only while the balancer carries traffic. - **Shape of the PR.** One PR: the backend controller with tests, a toggle in the balancer UI, and translations for all 13 locales. Each node panel runs its own controller for its own core, the same way balancers work today. **Phase 2 (optional, later): a throughput tie-breaker.** A small, bounded download test (well under 1 MB, with a daily byte budget) that only breaks ties between outbounds Phase 1 already considers healthy. It would be off by default, and I'd only propose it once Phase 1 has been in use for a while. ### Questions for you 1. **Are you aligned with Phase 1 being part of 3x-ui?** If yes, I'll start on it. If you'd rather keep the panel out of active balancing, I'll stop here, and Phase 0 still stands on its own. 2. **Should a manual override survive an Xray restart?** Today a restart clears it, as the API docs say. I'd keep it that way, because Auto mode re-picks after a restart anyway, and a manual pin that silently comes back after a crash could surprise people. If you prefer them persisted, that's a small separate PR.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#4516
No description provided.