Configuration August 23, 2026

Clash External Controller API: Advanced Node Failover Setup

Build a reliable Clash failover workflow that measures proxy latency, detects unhealthy nodes, and selects a working server through the external controller API. Includes practical scripts and secure deployment patterns.

Docker Proxy GitHub Acceleration Advanced Config YAML

1. Scope, design goals, and the External Controller model

This guide is for users who already run Clash Verge Rev, Mihomo, or another Clash-compatible client and want more than a manually selected proxy node. The goal is to build a practical failover workflow that measures latency, detects unhealthy servers, and switches a proxy group through the External Controller API when the current node becomes unreliable. A useful failover system should not simply choose the node with the smallest ping value. It should answer several questions at the same time: can the node complete a real HTTPS request, is the result recent, is the node already serving active traffic, and will switching create more disruption than waiting for a short recovery?

Clash separates traffic policy from node selection. Your rules decide that a request should use a group such as Auto or Proxy, while the group decides which concrete server is active. The external controller gives an automation script a control plane for reading that state and changing it without rewriting the entire YAML profile. In most Mihomo-compatible deployments, the controller listens on an address such as 127.0.0.1:9090 and exposes endpoints under /proxies.

This article focuses on reliability rather than bypassing access controls. Use only nodes and subscriptions that you are authorized to use, and do not route confidential company traffic through an unknown relay. A failover script can improve availability, but it cannot make an overloaded, dishonest, or poorly operated proxy trustworthy.

2. Secure the controller before writing automation

The most important setting is not the polling interval; it is the controller’s network exposure. A controller API can inspect proxy names, read connection metadata, and change the route used by every application on the machine. Exposing it to 0.0.0.0 without authentication is equivalent to handing remote users a network switch for your proxy client. For a local desktop workflow, bind the controller to loopback and protect it with a secret:

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

The exact field names can differ slightly between old Clash derivatives and current Mihomo builds, so confirm them in the configuration reference shipped with your client. In Clash Verge Rev, edit the active profile or its override layer rather than changing a generated subscription file that will be replaced during the next update. Restart or reload the profile, then verify that the controller is reachable locally:

curl -s \
  -H "Authorization: Bearer replace-with-a-long-random-token" \
  http://127.0.0.1:9090/version

Do not put the secret directly into a script committed to Git. On Linux and macOS, an environment variable or a file readable only by your user is a reasonable starting point. On Windows, store it in the user environment or a protected credential mechanism, and remember that command lines may be visible in process inspection tools. If you use a remote monitoring host, prefer an SSH tunnel or a private authenticated network path instead of binding the controller publicly.

There is also a difference between the API address and the proxy address. Your script may call 127.0.0.1:9090 directly, while the health-check URL must be fetched through the currently selected Clash group. A successful request to the controller proves only that the API is alive; it does not prove that the active relay can reach the public internet.

3. Inspect groups and node state through the API

Start with observation. Before changing a group, call GET /proxies and save a redacted response. The response normally contains a map of proxy names, their types, current selections, and available child nodes. Names may contain spaces, slashes, emoji, or characters from several languages, so always URL-encode a name instead of concatenating it into a path manually.

curl -s \
  -H "Authorization: Bearer $CLASH_SECRET" \
  http://127.0.0.1:9090/proxies | jq '.proxies.Auto'

A typical selector group exposes a field such as now and a list such as all. The precise JSON shape depends on whether the group is a Select, URLTest, Fallback, or another Mihomo-supported type. Do not assume that every item in all is a usable leaf node. A group can contain another group, a provider reference, or a special value such as DIRECT and REJECT.

The following small Python helper prints the active node and candidate list. It uses only the standard library, which makes it suitable for a cron job, Task Scheduler task, or a lightweight container:

import json
import os
import urllib.request

API = os.environ.get("CLASH_API", "http://127.0.0.1:9090")
SECRET = os.environ["CLASH_SECRET"]

def api_get(path):
    request = urllib.request.Request(
        API + path,
        headers={"Authorization": "Bearer " + SECRET}
    )
    with urllib.request.urlopen(request, timeout=5) as response:
        return json.load(response)

data = api_get("/proxies")
group = data["proxies"]["Auto"]
print("current:", group.get("now"))
print("candidates:", group.get("all", []))

Treat the response as a runtime inventory, not as a permanent configuration contract. A subscription update can rename a node, remove a server, or add a nested group. A robust script should fail closed when the target group disappears and should log the group name, observed candidates, and selected node without logging the controller secret.

4. Measure real health instead of trusting ICMP latency

A low TCP or ICMP latency does not guarantee a useful proxy. The relay might answer a port probe while failing TLS negotiation, DNS resolution, HTTP/2 streams, or larger responses. For that reason, use two layers of testing. The first layer is the controller’s delay endpoint, which is convenient for comparing candidates. The second layer is a real application-level request through Clash, which confirms that the selected path can complete the kind of transaction your users actually care about.

Mihomo-compatible controllers commonly provide a delay endpoint shaped like /proxies/{name}/delay, with query parameters such as url, timeout, and expected. Because names and query values require escaping, construct the URL with a proper encoder:

from urllib.parse import quote, urlencode

def node_delay(node, test_url="https://www.gstatic.com/generate_204",
               timeout_ms=5000, expected="204"):
    path = "/proxies/" + quote(node, safe="") + "/delay?" + urlencode({
        "url": test_url,
        "timeout": str(timeout_ms),
        "expected": expected,
    })
    return api_get(path)

The endpoint’s response often includes a delay value in milliseconds. Some versions return an error status or an error object when the request fails. Your code should treat timeouts, connection resets, invalid JSON, HTTP 4xx responses, and missing delay fields as unhealthy results. Do not convert every error to an artificially high but valid number without retaining the reason; the distinction between a timeout and an authentication failure is valuable during troubleshooting.

Choose a test URL that is stable, small, and permitted in your environment. A redirect-heavy homepage is a poor benchmark because CDN routing, cookies, and application scripts add noise. You can use more than one endpoint if your workload includes both ordinary HTTPS and long-lived streaming connections. For example, a lightweight status endpoint can measure basic reachability, while a second endpoint on the service your team uses can expose region-specific or TLS-specific failures.

One sample is not a health policy. A temporary queueing delay can make a healthy node look bad, while a node that is about to fail may pass once. Collect three measurements over a short window and use the median, or require two consecutive failures before marking a node unhealthy. Add a cooldown after switching so the script does not bounce between two nodes every few seconds.

5. Implement conservative selection and failover

A reliable selector should combine eligibility, freshness, latency, failure history, and stickiness. Begin by excluding values that must never be selected as ordinary relays. Then exclude nodes that failed recently, unless every candidate is unhealthy. Among the remaining nodes, choose the lowest median delay, not necessarily the lowest single measurement.

The controller normally changes a selector group with a request similar to PUT /proxies/{group} and a JSON body containing the desired node name:

import json
import urllib.request
from urllib.parse import quote

def select_node(group, node):
    payload = json.dumps({"name": node}).encode("utf-8")
    request = urllib.request.Request(
        API + "/proxies/" + quote(group, safe=""),
        data=payload,
        method="PUT",
        headers={
            "Authorization": "Bearer " + SECRET,
            "Content-Type": "application/json",
        },
    )
    with urllib.request.urlopen(request, timeout=5) as response:
        return response.status

Before switching, compare the proposed node with the group’s current now value. If they are identical, record a successful health observation and do nothing. If they differ, require a meaningful improvement, such as a 20 percent latency reduction, unless the current node has failed a real request. This prevents unnecessary changes caused by a five-millisecond difference that users will never notice.

A practical decision sequence looks like this:

  1. Read the target group and verify that it still exists.
  2. Resolve the current node and candidate list from the live API response.
  3. Remove nested groups, DIRECT, REJECT, and explicitly excluded nodes.
  4. Measure each candidate with a short timeout and record the result timestamp.
  5. Use the median of several samples and apply a failure threshold.
  6. Keep the current node when it is healthy and not materially slower.
  7. Switch only after the replacement passes its own health check.
  8. Verify the group’s new now value and write an audit log.

The last verification matters. A successful HTTP response from the controller means that the API accepted the request, not necessarily that the group now contains the expected value. A subscription refresh or another automation process may have changed the group at nearly the same time. Read the group again after a short delay and report a mismatch rather than silently claiming success.

6. Scheduling, observability, and recovery behavior

Run health checks at a frequency that matches the failure you are trying to solve. A desktop user may need a check every two or five minutes, while a shared gateway carrying long-lived connections may require a slower interval. Frequent checks consume bandwidth and can trigger provider rate limits; they also create false alarms when every candidate is measured during the same transient congestion period.

Use a state file or small local database to retain the following information: the last selected node, consecutive failures, last successful check, last switch time, and a cooldown deadline. Without state, a process restart forgets that it switched thirty seconds ago and may immediately switch again. A simple JSON file is enough for one workstation, but write it atomically by saving to a temporary file and renaming it so an interrupted process does not leave invalid data.

Log events in a format that can be searched later. Include the group, candidate, measured latency, test URL, HTTP status, reason for rejection, previous node, new node, and controller response status. Never log bearer tokens, subscription URLs containing credentials, or full proxy configuration objects. If logs leave the machine, treat node names and destination URLs as potentially sensitive metadata.

A useful recovery policy distinguishes three situations. If the active node fails but another candidate is healthy, switch once and enter cooldown. If all candidates fail, keep the current selection temporarily and retry with exponential backoff; switching among broken nodes only increases disruption. If the controller itself is unreachable, do not edit the profile automatically. Alert the user, because the failure may be a crashed Clash process, a locked port, or a malformed profile rather than a bad relay.

Test the workflow deliberately before trusting it. Stop the active node, introduce a blocked test URL, rotate the subscription, rename the target group, and restart the Clash client. Confirm that the script handles every case without exposing the controller or selecting DIRECT by accident. Also test long-lived WebSocket and streaming sessions if those are important to your workload; changing the selected node can interrupt existing connections even when new requests succeed immediately.

7. Common mistakes and a production checklist

The most common mistake is confusing an API health check with an end-to-end health check. GET /version can succeed while DNS, TLS, or the selected relay is broken. The second is using a public controller address for convenience. The third is relying on a single latency sample and switching whenever a different node is one millisecond faster. Another frequent error is hard-coding subscription node names; providers change names, and URL encoding bugs appear as soon as a name contains a slash or non-ASCII character.

Before enabling automatic switching, confirm that the controller binds only where intended, the secret is stored outside source control, and the API client has short timeouts. Confirm that the script discovers candidates dynamically, rejects special routes, applies consecutive-failure thresholds, and has a cooldown. Make sure the test endpoint is stable and legally appropriate for your environment. Finally, keep a manual recovery path: the Clash Verge Rev interface should still let you select a known-good node when automation behaves unexpectedly.

Compared with simple VPN toggles or clients that offer only a single global on/off switch, an External Controller workflow provides observable, policy-aware control: you can measure several nodes, preserve the current route when it is healthy, and switch only after a replacement passes a real check. That flexibility is especially useful when Windows, macOS, Linux, Android, and terminal applications share one Clash policy but generate different traffic patterns. If you want to build this setup on a maintained Mihomo-compatible client, the download page is the natural next step rather than copying an unverified controller script from a forum.

Download Clash clients →

Ready to get started?

Use a Mihomo-compatible Clash client to test API-based node monitoring and controlled failover across your devices.