Automate Clash Proxy Failover With the Controller API
Why automate Clash proxy failover instead of changing nodes by hand
A proxy node can be technically online and still be a poor route for the work you are doing. Latency may climb during peak hours, packet loss can interrupt a long-running development session, or a relay that worked minutes ago may stop responding altogether. If you rely on a browser speed test and then switch nodes manually, you are reacting to symptoms after an application has already stalled. A small, carefully bounded Clash API failover script can instead check eligible proxies, compare their response times, and move a selector group to a healthier option when the evidence supports a change.
The important word is bounded. Automatic failover should not mean “try every proxy every few seconds and select whichever number is smallest.” A single latency measurement says little about sustained throughput, jitter, or the route to a particular service. It can also be skewed by a temporary DNS delay or a test endpoint that is slow from your region. Treat the API as a control surface for a measured policy: decide which proxies are eligible, choose a repeatable test URL, set sensible timeouts, and make changes only when the new route is meaningfully better or the current one has failed.
Clash-compatible clients and Mihomo expose an external controller API for inspecting runtime state and changing supported proxy groups. This is distinct from editing the profile on disk. A profile defines the available proxies, rules, and groups; the controller lets an authorized local client inspect the active configuration and update a selector while the core is running. That makes the API useful for a workstation, a home server, or a controlled network lab, but it also means an exposed controller is a powerful interface that must be protected.
Before writing a script, check whether your profile already has a suitable fallback or url-test group. These group types can perform health checks within the core and may be the simpler solution when all you need is automatic selection. A script is justified when you need custom eligibility rules, scheduled checks, alerts, integration with another monitoring system, or a policy such as “change only if the alternative is at least 25 percent faster.” Do not add an external automation layer merely because the API exists; every extra loop is another place for credentials, stale state, and conflicting decisions to accumulate.
Keep the routing chain clear. Your application follows a rule to a policy group; the group selects a proxy; that proxy carries traffic through its upstream route. Changing a group does not repair an incorrect rule, a broken DNS path, or an unavailable local core. Likewise, a successful API response proves that the controller accepted a request, not that every application has immediately established a healthy connection through the new node. Failover is one part of a routing design, not a substitute for understanding it.
Prepare a safe controller endpoint and a predictable proxy group
First confirm that the running core supports the controller endpoints you intend to use. In Mihomo-based setups, the API is commonly enabled through a configuration entry such as external-controller: 127.0.0.1:9090. The exact place to edit that setting depends on the client: some expose it in settings, while others generate or manage the runtime configuration. Avoid editing a generated file that the client will overwrite. After changing controller settings, restart or reload the core as required by that client, then verify the active address from its runtime or logs.
Bind the API to loopback unless you have a specific, reviewed reason to make it reachable from another machine. Add a strong controller secret and send it as a bearer token in API requests. Do not put the secret in a script committed to a repository, a shared configuration file, a command-line argument that may be recorded in shell history, or a log message. An unattended task can read it from an environment variable or an operating-system secret store. If remote administration is unavoidable, restrict access with a firewall and a protected management network rather than publishing the controller port to the internet.
0.0.0.0 for convenience, and do not assume that a high port number or a home router makes an unauthenticated endpoint safe.Next, identify the group you want the automation to control. A selector group is usually a good fit because the script can choose a member while the profile continues to define which traffic uses that group. Give the group and its members stable, unambiguous names; subscription updates can rename proxies, so avoid relying on display names that change frequently. The script should target the group’s exact runtime name, not a similarly named rule group or a node label copied from an old profile.
Use the controller’s proxy inspection endpoint to read the group’s current selection and available members before attempting a change. A group response typically includes its current member and a list of options. Cross-check that list against the candidates you intend to test. This prevents a stale script from requesting a proxy that disappeared during a subscription update. If you use a group with nested selectors, decide explicitly whether the script should control the outer group or a specific inner selector; manipulating the wrong level can produce a valid API response without changing the route you expected.
Choose a health-check URL that is stable, reachable through the routes being compared, and appropriate for your environment. A small HTTPS response is generally more useful for a basic latency probe than downloading a large page. The measurement is a round-trip time to that specific endpoint, not a universal rating of the proxy. If your work depends on a particular service, supplement a generic probe with an application-level check rather than assuming one public endpoint represents every destination. Keep the timeout long enough for a slower but usable route to respond, and short enough that a dead node does not block the whole run.
Finally, define operational limits before testing: the candidate allowlist, a minimum improvement required to switch, the maximum acceptable probe time, how often the job may run, and what happens when all candidates fail. A conservative script should preserve the current selection when results are inconclusive. That single rule prevents a brief measurement wobble from turning into repeated group changes.
Build a small API workflow with latency checks and a switch threshold
The following Python example uses only the standard library. It reads the controller address and secret from environment variables, asks the API for the selector’s current state, probes a configured list of eligible members, and sends a selection request only when the best measured alternative improves on the current route by a configured margin. Replace the sample group and proxy names with names that actually appear in your active profile. Start with a manual run and inspect the output before scheduling it.
import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen
API = os.environ.get("CLASH_API", "http://127.0.0.1:9090").rstrip("/")
SECRET = os.environ.get("CLASH_SECRET", "")
GROUP = os.environ.get("CLASH_GROUP", "Auto")
CANDIDATES = [
item.strip()
for item in os.environ.get("CLASH_CANDIDATES", "Node A,Node B,Node C").split(",")
if item.strip()
]
TEST_URL = os.environ.get("CLASH_TEST_URL", "https://www.gstatic.com/generate_204")
TIMEOUT_MS = int(os.environ.get("CLASH_TIMEOUT_MS", "5000"))
IMPROVEMENT_MS = int(os.environ.get("CLASH_IMPROVEMENT_MS", "80"))
if not SECRET:
sys.exit("Set CLASH_SECRET before running this script.")
def api(method, path, payload=None):
body = None if payload is None else json.dumps(payload).encode("utf-8")
request = Request(
API + path,
data=body,
method=method,
headers={
"Authorization": "Bearer " + SECRET,
"Content-Type": "application/json",
},
)
with urlopen(request, timeout=8) as response:
raw = response.read()
return json.loads(raw.decode("utf-8")) if raw else {}
def encoded_name(name):
return quote(name, safe="")
try:
group = api("GET", "/proxies/" + encoded_name(GROUP))
current = group.get("now")
members = set(group.get("all", []))
allowed = [name for name in CANDIDATES if name in members]
if not allowed:
sys.exit("No configured candidates are members of the target group.")
results = {}
for name in allowed:
query = urlencode({"url": TEST_URL, "timeout": TIMEOUT_MS})
path = "/proxies/" + encoded_name(name) + "/delay?" + query
try:
result = api("GET", path)
delay = int(result["delay"])
if delay > 0:
results[name] = delay
except (HTTPError, URLError, TimeoutError, KeyError, ValueError):
print("Probe failed:", name)
if not results:
sys.exit("Every eligible proxy failed its latency check; selection unchanged.")
best = min(results, key=results.get)
current_delay = results.get(current)
print("Current:", current, "delay:", current_delay)
print("Best:", best, "delay:", results[best])
should_switch = current not in members or current_delay is None
if current_delay is not None:
should_switch = current_delay - results[best] >= IMPROVEMENT_MS
if best != current and should_switch:
api("PUT", "/proxies/" + encoded_name(GROUP), {"name": best})
print("Selected:", best)
else:
print("Keeping the current selection.")
except (HTTPError, URLError, TimeoutError, json.JSONDecodeError) as error:
sys.exit("Controller request failed: " + str(error))
The script intentionally does not discover every proxy and test it automatically. An allowlist makes the policy understandable and limits unnecessary requests to nodes that you do not want to use. Set its values in the environment for a manual test, for example by exporting CLASH_SECRET, CLASH_GROUP, and CLASH_CANDIDATES in a private shell session. Use the actual group member names returned by the controller; capitalization, punctuation, and spaces may matter. Do not paste a live secret into a public terminal transcript or a support screenshot.
The threshold is a simple form of hysteresis. If the current proxy measures 210 milliseconds and an alternative measures 195 milliseconds, an 80-millisecond threshold keeps the current route. That avoids switching for a difference smaller than ordinary measurement noise. If the current proxy cannot be measured but another eligible member can, the example permits a switch; if every candidate fails, it leaves the group unchanged and exits with a diagnostic. You may instead choose a separate emergency policy, but document it and test it deliberately rather than letting an empty result pick an arbitrary node.
This example makes one decision from one round of measurements. For a more dependable workflow, run multiple probes and compare a median or another robust statistic, add a cooldown after a successful switch, and retain a log of timestamp, group, previous selection, selected member, and measured delays. Keep logs free of the controller secret and avoid recording sensitive connection data. A scheduler should run no more frequently than your measurement and service needs justify; very short intervals can create noisy decisions, unnecessary traffic, and competing runs.
For environments where shell access is easier than Python deployment, the same workflow can be implemented with another HTTP client, but keep the same safeguards: URL-encode proxy names, authenticate every request, check HTTP failures, validate group membership, and avoid switching when the measurements do not justify it. Do not construct API URLs by concatenating unescaped node names. Names can contain spaces or punctuation, and malformed paths can turn a configuration issue into a misleading “not found” response.
Verify the result, diagnose failures, and keep failover calm
After a run, inspect both sides of the operation. Read the group again from the controller and confirm that its current member matches the script’s decision. Then test the applications that matter: load a page, make a request from the development tool, or check the service that originally exposed the slowdown. A low probe delay alone is not proof that a specific API, repository host, or streaming connection is healthy. Some applications maintain existing sockets and may not move until they reconnect; others use a different rule group and are unaffected by the selector you changed.
If the controller returns an authorization error, verify that the script is using the secret configured for the active core and that the request includes the bearer header. A connection refusal usually points to the wrong address or port, a controller that is disabled, or a core that has not been restarted after a settings change. A timeout may indicate that the address is reachable but the core is overloaded, the endpoint is filtered, or a request is waiting on an unreachable service. Check the client’s runtime status and core logs before widening network access.
A “not found” response often comes from a group or proxy name that does not exactly match the active runtime configuration. Fetch the group first and compare its member list instead of guessing names from a subscription page. If the script says no configured candidates are members, that is a useful safety stop: update the allowlist after confirming the subscription refresh, rather than removing validation and allowing the script to select an unintended route.
When every delay request fails, separate API failure from proxy failure. If the controller can return the group but delay probes fail for every member, check the test URL, DNS resolution, outbound policy, and timeout. If only one member fails, it may be offline or incompatible with the target. If the probe reports a healthy delay but real traffic still fails, test the destination through the selected group and inspect the client’s connection log. Rules, DNS mode, remote service restrictions, TLS behavior, or a destination-specific route can explain the difference.
Repeated switching is a sign that the policy needs tuning, not a reason to reduce the cooldown further. Increase the improvement threshold, require several consistent measurements, add a minimum time between changes, and avoid overlapping scheduler instances. Keep an explicit fallback behavior for maintenance windows and subscription updates. If a profile reload changes the group membership while a run is in progress, the next run should re-read the live group and safely reject stale candidates.
Finally, treat automation as part of configuration management. Record what the script controls, how credentials are supplied, where logs are stored, and how to disable the job. Run it as a user with only the permissions it needs, protect the script and its environment, and review behavior after changing client versions or profile structure. A short, observable script that fails closed is easier to trust than an elaborate daemon that hides decisions or silently retries forever.
Some all-in-one proxy clients and traditional VPN tools offer only a manual server list or a fixed reconnect action, leaving users to notice a slowdown, compare routes by hand, and repeat the process after every disconnect. Clash gives you a more inspectable workflow: proxy groups define the available choices, the controller API exposes live state, and an external script can apply explicit health checks and switching thresholds without rewriting the profile. That combination is useful for developer tools and services when it is configured carefully and kept under local control. If you want to set up a Clash client for this workflow, visit the download page to find a platform build. Compare the client’s core and controller options before enabling automation, then start with a manual test and a protected local API.
→ Download Clash for free and enjoy a better internet experience