Why API-driven node failover is more reliable than a static proxy group
A Clash profile can already test proxy health with groups such as url-test, fallback, and load-balance. Those features are useful, but they are not a complete operations strategy when Clash supports a developer workstation, a build server, a home gateway, or an always-on service. A static group may measure only one URL, use a fixed interval, or react to latency without understanding packet loss, HTTP status codes, DNS failures, or the difference between a temporarily slow node and a genuinely unusable one.
This is where the Clash external controller API becomes valuable. A small health-check script can ask several nodes to reach an endpoint, record latency and failure reasons, select the best currently available proxy, and update a policy group without requiring you to open the GUI. The same mechanism can be used by a cron job, a systemd timer, a CI runner, or a lightweight monitoring service. Instead of hoping that an automatic group makes the right choice, you can define exactly what “healthy” means for your environment.
The workflow in this guide is designed for Mihomo-compatible clients, including Clash Verge Rev and other clients that expose the controller API. You will build the process in layers: establish a safe controller connection, inspect available proxies, run repeatable checks, rank candidates, switch the selected proxy, and add safeguards against flapping or accidental lockout. The examples use shell and Python-style requests conceptually, but the same API calls can be implemented in Go, Node.js, PowerShell, or any language available on your host.
Secure the external controller before writing automation
The controller is powerful because it can inspect runtime state and change active proxy selections. Treat it like an administrative interface, not like an ordinary local web page. A script that can reach the controller may be able to switch groups, read configuration details, or alter runtime behavior. Exposing the controller on a public interface without authentication is therefore an avoidable security mistake.
Choose a private listener and a strong secret
For a single workstation, bind the controller to the loopback address whenever possible. A typical configuration uses an address such as 127.0.0.1:9090 and a long secret token. The exact YAML key is commonly named external-controller, while the secret is commonly configured with secret. Do not assume that changing the port is security; a nonstandard port only reduces casual discovery and does not replace authentication.
external-controller: 127.0.0.1:9090
secret: replace-with-a-long-random-token
If the controller must be reached from another machine, prefer a private VPN, an SSH tunnel, or a firewall-restricted management network. Binding to 0.0.0.0 can be appropriate in a carefully isolated server environment, but it should be accompanied by firewall rules, a strong token, and a clear understanding of which interfaces are reachable. Never place the controller directly on the public internet merely because a monitoring script needs remote access.
Keep the token outside source control. An environment variable, a root-readable file, or a secrets manager is safer than embedding it in a repository. Also consider the process permissions of the script: the health checker usually needs to send GET and PUT requests, but it does not need permission to rewrite the entire Clash configuration file. Limiting credentials and filesystem access reduces the impact of a compromised automation host.
Understand the API calls your script will use
Most failover scripts need only a small set of controller endpoints. The exact route names should be checked against the API exposed by your core, but the common pattern is easy to recognize:
- Controller status: request the version or general runtime endpoint first. This confirms that the address, port, and authentication token work before the script performs any change.
- Proxy inventory: request the proxies endpoint to discover node names, proxy types, and available groups.
- Group state: request the selected policy group to see its current proxy and its members.
- Health measurement: use the proxy delay endpoint with a target URL and timeout, or perform an independent request through a local Clash port when you need richer checks.
- Group selection: send a PUT request to the group endpoint with the chosen proxy name.
Use an explicit HTTP header such as Authorization: Bearer your-secret when the controller expects a secret token. Store response bodies and status codes in logs, but redact the token and avoid recording subscription URLs or private node credentials. A useful log line contains the group name, candidate, test target, measured delay, result, and final decision; it does not contain secrets.
Build health checks that measure service quality, not only ping speed
Latency is an important signal, but it is not the same as usability. A node may respond quickly to a lightweight test while failing TLS negotiation, returning an unexpected status, losing packets during a larger transfer, or resolving a required hostname incorrectly. Your checker should therefore combine several signals and use targets that resemble the traffic you actually care about.
Select targets and define pass criteria
Choose at least one small HTTPS endpoint that should return a predictable response. A lightweight endpoint is suitable for frequent checks because it consumes little bandwidth. For developer workflows, add a target that represents the service category you use regularly, such as a package registry, source-control API, or build artifact host. Avoid relying on only one popular website: a CDN outage or regional routing change could make every node appear broken.
Each test should have a finite timeout and a clear success rule. A reasonable baseline might require a successful TCP and TLS connection, an HTTP status in an accepted range, and a total delay below a limit. If you need to validate response content, check a short expected marker rather than downloading an entire page. The objective is to measure path health consistently, not to create a browsing session for every node.
Use delay results carefully
The controller’s delay endpoint is convenient because it asks the core to test a specific proxy against a URL. A successful response usually gives you a delay value, while a timeout or error identifies a failed attempt. Do not compare values from tests with different URLs, different timeout limits, or different geographic destinations. A node that is fastest to one endpoint may be slower to another because of peering, congestion, or destination-side routing.
Run more than one sample when stability matters. The minimum value can hide intermittent loss, while the maximum can exaggerate a single transient queue. A median or trimmed average is often more useful, and a failure count should be included in the score. For example, you might reject a node after two consecutive failures, prefer nodes with a median below 800 milliseconds, and add a penalty for every recent timeout. The numbers are examples, not universal guarantees; tune them against your own connection.
For long-lived WebSocket, SSH-over-proxy, or API streaming workloads, add a persistence check. A node can pass short requests yet reset connections after several minutes. A separate scheduled test can open a controlled long-lived connection, transfer a small amount of data, and record whether it survives the expected duration. Keep this test less frequent than the basic delay probe so it does not create unnecessary load.
Rank candidates and switch the Clash group safely
Start with a single policy group rather than changing every group in the profile. Suppose your profile contains a group named Auto with several selectable nodes. The script should first retrieve the group members, filter out unsupported entries such as DIRECT or REJECT when they are not valid failover targets, and preserve the current selection for comparison.
Next, test candidates in a controlled manner. Sequential testing is simple and puts less pressure on the local machine, while limited concurrency reduces the time required when a node has a long timeout. If you use concurrency, cap the worker count and ensure that one slow request cannot hold the entire scheduler indefinitely. Do not start an unlimited request for every node whenever the timer fires.
for candidate in group_members:
result = measure(candidate, target, timeout)
if result.success:
score = result.median_delay + result.failure_penalty
healthy.append((score, candidate))
if healthy:
selected = min(healthy)
if should_switch(selected, current):
put_group_selection(group_name, selected.name)
The score should reflect your actual priorities. A simple score can combine median latency, recent failures, and a stability penalty. If your workflow values reliability more than speed, make failures expensive and require a meaningful improvement before switching. If your application is latency-sensitive but tolerant of occasional reconnects, give delay more weight. Document the formula so that a future operator understands why the script chose a node that was not the absolute fastest single sample.
Add hysteresis to prevent node flapping
The most common mistake in automatic switching is changing nodes whenever another candidate is a few milliseconds faster. This creates churn: existing connections are interrupted, DNS behavior may change, and the supposedly better node can disappear before the next request. Add a switching margin and a minimum hold time. For example, require the new candidate to be substantially better than the current node, or require the current node to fail twice before leaving it.
Persist a small state file containing the current candidate, the last switch time, consecutive failures, and recent scores. A memory-only script loses this context whenever the timer restarts and may immediately switch back and forth. You can also use a cooldown after every change, during which the scheduler continues observing but does not select another node unless the active one becomes completely unusable.
Handle the case where every node fails
When all candidates fail, do not blindly select the first item in the list. Keep the current selection if it has not been proven unusable, or fall back to a deliberately chosen emergency node. Some environments should switch to DIRECT for domestic services, while others must fail closed to avoid leaking traffic. That decision belongs in your policy design, not in an accidental default inside a script.
Return a nonzero exit code when the scheduler cannot find an acceptable candidate, and emit an alert only after a short confirmation window. A single failed run may be caused by a local Wi-Fi interruption or a temporary test endpoint problem. Repeated failures across independent targets are stronger evidence. Include the group, number of candidates tested, failure categories, and last known good node in the alert so the operator can act without guessing.
Schedule, observe, and test the automation like production code
A health checker should be boring to operate. Run it under a dedicated service account, set a working directory explicitly, use absolute paths, and define a predictable environment for the controller address and secret. A systemd timer is suitable for Linux servers, while Task Scheduler can run the same logic on Windows. On a workstation, a longer interval is usually enough because the user can manually intervene through the Clash GUI when necessary.
Separate measurement from decision-making in your logs. Record the raw result for each candidate, then record the policy decision and the API response from the group update. This makes it possible to distinguish “the node was slow” from “the script selected a node but the controller rejected the update.” Rotate logs and avoid writing full URLs if they contain query tokens. If you send metrics to a monitoring system, use stable labels such as group name and node alias rather than exposing subscription metadata.
Test the script with a disposable group before attaching it to your main traffic policy. Simulate a timeout, an HTTP error, a DNS failure, a rejected authentication token, an unavailable controller, and a group containing no valid candidates. Confirm that an interrupted PUT request does not leave the scheduler believing a switch succeeded. Also test a core restart: the controller may be temporarily unavailable, and the script should retry with backoff rather than launching a rapid request storm.
Finally, remember that automated failover cannot repair a bad profile. Incorrect DNS mode, conflicting rules, an overloaded local port, or a rule that routes the target through DIRECT can make every node appear broken. Verify the selected traffic path with Clash connection logs and inspect which rule matched the request. A successful API switch is only evidence that the group changed; it is not proof that the application used that group.
Compared with many generic proxy managers that offer only a coarse auto-select toggle, ClashSky gives this workflow a clearer operational surface: you can inspect active groups, combine Mihomo health checks with your own scoring logic, and keep manual control when an automated decision is inappropriate. Some competing tools hide node diagnostics behind limited screens or make server-side scheduling difficult, while ClashSky’s compatible controller workflow is easier to integrate with shell scripts, timers, and developer services. If dependable node failover matters to your setup, download ClashSky and try the process with a small test group first.
Download ClashSky and start configuring reliable proxy failover.