Why the Clash external-controller API matters for automatic failover

A proxy group that switches nodes manually is acceptable for a short browsing session, but it becomes fragile when Clash is serving a development workstation, a home gateway, or a small production server. A node can remain visible in the profile while its upstream route is already timing out, returning TLS errors, or losing packets only under sustained traffic. In that situation, clicking through the client interface is too slow and too subjective. A reliable workflow needs an observable signal, a controlled decision, and a repeatable recovery action.

The Clash external-controller API provides that control surface. Mihomo-compatible cores expose an HTTP API for reading runtime state, checking proxies, selecting a member of a proxy group, and inspecting traffic or configuration details. With the right authentication and network boundary, a local script can ask Clash to test candidate nodes, choose the fastest healthy option, and move a proxy group without rewriting the entire YAML profile. The core continues to handle connections, DNS, rules, and protocol details; the automation only makes a narrowly defined control decision.

This distinction is important. Automatic switching is not the same as blindly choosing the lowest ping. A node may answer an ICMP request quickly but fail HTTPS connections, suffer high packet loss, or become unstable after several minutes. Conversely, a node with slightly higher latency may provide a much better long-lived path. The goal is therefore a health-aware failover loop: measure the candidates using a meaningful URL, reject unusable results, avoid excessive switching, and preserve a known fallback when every test fails.

ℹ️
Scope: This guide assumes a Clash or Mihomo-compatible core with an enabled external controller. API paths and response fields can vary slightly between releases, so confirm the endpoint names exposed by your running core before deploying automation.

Enable the controller without turning it into an open relay

The controller is powerful because it can change live proxy state. Anyone who can reach an unauthenticated controller may be able to inspect groups, select nodes, alter settings, or use the client as an unintended network pivot. Treat the controller secret like a password and the listening address like an administrative service, not like an ordinary local web page.

A minimal configuration normally includes an address and a secret. Binding to 127.0.0.1 is the safest choice when the monitoring script runs on the same machine. If a separate server must manage Clash, bind to a private management interface or a Unix-domain mechanism supported by the deployment, then restrict access with a firewall or an authenticated reverse proxy. Avoid binding the controller to 0.0.0.0 merely because it makes testing convenient.

external-controller: 127.0.0.1:9090
secret: "replace-with-a-long-random-secret"

The API normally accepts the secret through an HTTP authorization header. A typical request looks like this:

curl -H "Authorization: Bearer replace-with-a-long-random-secret" \
  http://127.0.0.1:9090/proxies

Do not place the secret directly in a public repository, shell history, shared screenshot, or system-wide process list. For a Python service, load it from an environment variable or a file readable only by the service account. If you expose the controller through a reverse proxy, use TLS for traffic leaving the local host and apply an allowlist for source addresses. Authentication protects the endpoint, but it does not replace network segmentation.

Before writing failover logic, verify four basic conditions. First, the controller responds on the expected address. Second, a request without a secret is rejected. Third, the authorized request returns the active proxy inventory. Fourth, the API process can reach the controller after reboot, sleep, or a core restart. These checks prevent a common mistake: diagnosing every automation failure as a dead node when the script is actually pointed at the wrong port or missing its token.

⚠️
Security boundary: Never expose port 9090 directly to the public internet. The controller is an administrative API, not a public health-check service. Use localhost binding, firewall rules, and a secret even on a private network.

Understand proxy groups, health checks, and selection endpoints

The most useful endpoint for failover automation is usually GET /proxies. It returns the runtime proxy tree, including individual proxies and policy groups. A group such as PROXY, 🚀 Proxy, or Auto may contain selectable members, while a URL-test group may also expose its current selection and measured delay. Never assume the group is literally named Proxy; names are profile-dependent and may contain emoji, spaces, or localized text.

After locating the intended group, a selection request is generally sent to PUT /proxies/{group} with a JSON body containing the desired proxy name. Because group names and node names may include spaces or Unicode characters, construct the URL with a proper URL encoder rather than concatenating raw strings.

PUT /proxies/Auto
Authorization: Bearer your-secret
Content-Type: application/json

{"name":"Singapore-01"}

Latency testing is commonly exposed through an endpoint shaped like GET /proxies/{proxy} with query parameters such as url and timeout. A representative request is:

GET /proxies/Singapore-01/delay?url=https%3A%2F%2Fwww.gstatic.com%2Fgenerate_204&timeout=5000

The exact delay endpoint and query syntax depend on the core version. Some builds use a URL-encoded target, while others expect a different path or parameter spelling. Test it manually against one known node and inspect the JSON response before automating. A successful response often contains a numeric delay in milliseconds; an error response may indicate timeout, connection refusal, DNS failure, or an unsupported test operation.

Operation Typical API shape Automation purpose
Read runtime state GET /proxies Find groups, members, and the current selection
Measure a node GET /proxies/{name}/delay Reject slow or unreachable candidates
Select a node PUT /proxies/{group} Apply a live failover decision
Inspect errors HTTP status and JSON body Separate API, node, and policy failures

Do not test every object returned by /proxies. A policy group is not itself a remote endpoint, and special entries such as DIRECT, REJECT, or nested selectors may not support the same delay operation. Filter candidates by the group’s member list and exclude reserved actions unless your design explicitly treats DIRECT as a fallback. Also remember that a latency probe only measures the path to the selected test URL, not every destination your users will visit.

Build a conservative Python failover worker

A practical worker should have five responsibilities: load configuration, discover the group, measure eligible nodes, apply a decision, and record what happened. Keeping those responsibilities separate makes the script easier to test and prevents a temporary API error from immediately changing the active route.

The following example uses Python’s standard library so it can run on a small server without an additional dependency. It assumes that the running core accepts the common delay endpoint format. Adjust the endpoint if your release documents a different path.

import json
import logging
import os
import time
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError

CONTROLLER = os.getenv("CLASH_CONTROLLER", "http://127.0.0.1:9090")
SECRET = os.environ["CLASH_SECRET"]
GROUP = os.getenv("CLASH_GROUP", "Auto")
TEST_URL = os.getenv("CLASH_TEST_URL", "https://www.gstatic.com/generate_204")
TIMEOUT_MS = int(os.getenv("CLASH_TEST_TIMEOUT", "5000"))
MAX_DELAY_MS = int(os.getenv("CLASH_MAX_DELAY", "1800"))

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s"
)

def request_json(method, path, payload=None, timeout=8):
    body = None
    headers = {
        "Authorization": f"Bearer {SECRET}",
        "Accept": "application/json",
    }
    if payload is not None:
        body = json.dumps(payload).encode("utf-8")
        headers["Content-Type"] = "application/json"

    request = Request(
        CONTROLLER.rstrip("/") + path,
        data=body,
        headers=headers,
        method=method,
    )
    with urlopen(request, timeout=timeout) as response:
        raw = response.read().decode("utf-8")
        return json.loads(raw) if raw else {}

def read_group():
    data = request_json("GET", "/proxies")
    group = data["proxies"][GROUP]
    return group["now"], group.get("all", [])

def measure(name):
    query = urlencode({"url": TEST_URL, "timeout": str(TIMEOUT_MS)})
    path = f"/proxies/{quote(name, safe='')}/delay?{query}"
    result = request_json("GET", path, timeout=TIMEOUT_MS / 1000 + 2)
    return int(result["delay"])

def select(name):
    request_json("PUT", f"/proxies/{quote(GROUP, safe='')}", {"name": name})

def choose(candidates):
    results = []
    for name in candidates:
        try:
            delay = measure(name)
            if delay <= MAX_DELAY_MS:
                results.append((delay, name))
                logging.info("candidate=%s delay_ms=%s", name, delay)
            else:
                logging.warning("candidate=%s too_slow_ms=%s", name, delay)
        except (HTTPError, URLError, KeyError, ValueError, TimeoutError) as exc:
            logging.warning("candidate=%s failed=%s", name, exc)

    return min(results)[1] if results else None

def main():
    current, candidates = read_group()
    target = choose(candidates)
    if target is None:
        logging.error("no healthy candidate; keeping current=%s", current)
        return

    if target != current:
        select(target)
        logging.warning("switched group=%s from=%s to=%s", GROUP, current, target)
    else:
        logging.info("keeping group=%s current=%s", GROUP, current)

if __name__ == "__main__":
    main()

The example intentionally keeps the policy simple: select the lowest measured delay below a threshold and leave the current node untouched if every candidate fails. In production, add a minimum sample count, a cooldown period, and a preference order. A single unusually fast response should not defeat a stable node on every polling cycle. You can measure each candidate three times, discard the highest result, and compare the median of the remaining samples. This reduces the effect of one transient DNS or TCP spike.

Retry logic also needs boundaries. Retry a failed request two or three times with exponential backoff, such as one second, two seconds, and four seconds. Do not retry forever inside one execution because a hung controller can create overlapping workers. Set a total execution deadline and let the next scheduled run try again. For node measurements, a short timeout is appropriate; for the selection request, use a separate API timeout and verify the response status.

Prevent flapping with thresholds, logs, and deployment controls

The most damaging automation bug is flapping: the worker alternates between two nodes because their measurements are close. Flapping interrupts TCP sessions, invalidates WebSocket connections, and makes troubleshooting harder than a consistently slow route. Use hysteresis. For example, keep the current node unless a candidate is at least 250 milliseconds faster, or unless the current node fails two consecutive checks. A “three strikes” rule is often more useful than switching on the first timeout.

Separate the measurement interval from the failure threshold. Checking every ten minutes may be enough for a personal laptop, while a gateway serving several users might check every sixty seconds. More frequent checks increase API traffic and can produce noisy decisions. The interval should reflect how quickly a failure matters, not how quickly a script can run.

Choose a test URL that is stable, small, and representative of the traffic path you care about. A CDN-generated empty response is useful for basic HTTPS reachability, but it may not represent an API, streaming service, or regional application. If your users depend on several service classes, use a small set of targets and require a candidate to pass a majority. Avoid probing private business endpoints from a shared monitoring system unless the security and privacy implications are understood.

Logging should answer five questions without exposing secrets: when the check ran, which group was examined, which candidates passed, which node was selected, and why a switch occurred. Include elapsed time, HTTP status, and exception type where useful. Never log the full Authorization header, subscription URL, or sensitive destination query string. On Linux, send output to journald or a rotating file; on Windows, use Task Scheduler with a dedicated log directory and an account that has only the permissions it needs.

For a Linux workstation or server, a systemd timer is more reliable than leaving an interactive terminal open:

[Unit]
Description=Check Clash proxy health

[Service]
Type=oneshot
User=clash-monitor
EnvironmentFile=/etc/clash-monitor.env
ExecStart=/usr/local/bin/python3 /opt/clash-monitor/check.py
[Unit]
Description=Run Clash proxy health check periodically

[Timer]
OnBootSec=2min
OnUnitActiveSec=5min
Persistent=true

[Install]
WantedBy=timers.target

Use a lock or a systemd service policy to prevent a slow run from overlapping the next run. After the core restarts, the worker should discover the group again rather than assuming that its previous node list still exists. Profiles can be updated, providers can rename nodes, and users can change group names. Runtime discovery is safer than hard-coding a large list in the script.

⚠️
Fail-safe behavior: If the controller is unavailable, the API returns malformed data, or all candidates fail, keep the existing selection and raise an alert. Do not automatically rewrite the whole profile or switch to an unknown node merely because one check timed out.

Troubleshoot failures by layer

When the worker does not switch nodes, begin with the controller rather than the network provider. Run a local request to /proxies and verify the response code. A 401 or 403 points to the secret or authorization format. A connection refusal points to the bind address, port, core state, or firewall. A successful response with a missing group name means the profile uses a different selector name, not that every node is dead.

Next, test one candidate manually. If the delay endpoint returns a timeout but ordinary traffic through that node works, the test URL may be blocked or unsuitable. If every candidate reports the same error, inspect DNS, controller logs, and the core version before increasing timeouts. If only one candidate fails, remove it temporarily from the eligible set and investigate its protocol, certificate path, or upstream capacity.

A successful PUT request is not the same as a successful user session. Confirm that /proxies reports the expected now value after selection, then open a fresh connection through the client. Existing connections may remain attached to the old route until they close naturally. Long-lived WebSocket or download sessions may therefore appear unchanged even though new connections are using the new node.

Finally, compare API health with application health. A low delay proves that the controller completed a probe; it does not prove that authentication, large uploads, UDP, or a particular destination will work. Keep a small operational record of switch timestamps and user-visible incidents. Over several days, that history lets you tune thresholds based on real behavior instead of chasing every isolated millisecond spike.

Compared with manually rotating nodes in a basic GUI or using a generic ping script, this external-controller workflow is more deliberate: simple tools often test the wrong protocol, expose no authentication boundary, and switch too aggressively when latency jitters. ClashSky brings the controller, policy groups, logs, and profile management into a friendlier environment, making it easier to apply the same failover idea without assembling every operational detail from scratch. If you want a stable client for testing this setup, download ClashSky for free and try the workflow on your own machine.