This guide shows how to use Xray’s local gRPC API to observe traffic counters and support node-health automation. It covers the API inbound, StatsService, HandlerService, active probes, and the limits of changing outbounds at runtime. The key distinction is that traffic statistics are not health checks, and adding or removing an outbound does not by itself change how routing selects a node. Keep the API bound to loopback, test changes against a backup, and make failover decisions with explicit recovery criteria.
What the API can—and cannot—tell you
Xray’s gRPC API is a control and observation interface for a running Xray process. Its StatsService exposes counters such as traffic sent or received by an outbound. Its HandlerService can manage inbound and outbound handlers. These capabilities are useful to an external monitor or controller, but neither service is a complete node-health system on its own.
A traffic counter is cumulative: it increases as Xray handles traffic and is not a direct measurement of reachability, latency, or packet loss. A counter that stays at zero may simply mean no request has used that outbound during the observation window. Conversely, a counter that continues increasing does not prove that a particular destination is reachable or that response quality is acceptable. Use counters as evidence about usage, not as the sole trigger for a failover.
For a meaningful health signal, run a probe through the route you intend to assess. Xray’s observatory features can test selected outbounds against a configured probe URL and provide observations that a routing balancer can use. The probe target should be stable and reachable from the node’s network. A failed probe can also mean the target is temporarily unavailable, DNS resolution failed, or the probe is blocked—not necessarily that the proxy process has stopped.
Think of the API as one part of a control loop: the monitor collects signals, applies a policy, and then takes an action. Define what counts as unhealthy, how many failures are required, how recovery is confirmed, and what happens if the controller itself is unavailable. Without these rules, a short network interruption can cause repeated switching, while an overly permissive check can leave traffic on a dead route.
Enable a loopback-only API inbound
In a JSON configuration, declare the API service and create a local dokodemo-door inbound dedicated to API requests. Then add a routing rule that sends requests received on that inbound to the API outbound. The example below is a focused fragment, not a complete Xray configuration: merge it with your existing inbounds, outbounds, and routing arrays rather than replacing them.
{
"api": {
"tag": "api",
"services": [
"StatsService",
"HandlerService"
]
},
"inbounds": [
{
"tag": "api-in",
"listen": "127.0.0.1",
"port": 10085,
"protocol": "dokodemo-door",
"settings": {
"address": "127.0.0.1"
}
}
],
"routing": {
"rules": [
{
"type": "field",
"inboundTag": ["api-in"],
"outboundTag": "api"
}
]
}
}
Port 10085 is a common local API port, not a required value. If another service already uses it, choose a free port and use that same port in your monitoring client. Keep listen set to 127.0.0.1 when the controller runs on the same host. Binding the API to 0.0.0.0 or a public interface can expose powerful management methods to remote clients; do not treat a hard-to-guess port as access control.
Local API listener
- Protocol
- dokodemo-door
- Listen address
- 127.0.0.1
- Example port
- 10085
- Routing target
- api
Use a dedicated inbound tag and route only that tag to the API outbound.
Service selection
- Traffic counters
- StatsService
- Handler changes
- HandlerService
- Client endpoint
- 127.0.0.1:10085
- Remote exposure
- Not recommended
Enable only the API services the controller needs; do not expose the listener publicly.
Before restarting the service, save a copy of the current configuration and check the edited JSON for syntax errors. Start Xray and confirm that it remains running, then connect a gRPC client to the loopback endpoint. If the API inbound is missing from routing, the listener may exist but API requests will not reach the API outbound. If the controller runs in a separate container, remember that its 127.0.0.1 refers to that container, not the Xray host; use a protected private network arrangement rather than making the API publicly reachable.
Read counters and run real health probes
When querying StatsService, request counters by name or query a set of matching statistics, depending on the client you use. Outbound traffic counters commonly follow names such as outbound>>>edge-a>>>traffic>>>uplink and outbound>>>edge-a>>>traffic>>>downlink, where edge-a must match the outbound tag in the configuration. Confirm the returned names against your running Xray build; a misspelled tag or a counter that has not been created can produce an empty result.
To calculate a rate, store two counter readings and divide the byte difference by the elapsed time. For example, if an uplink counter rises by 2,400,000 bytes over 60 seconds, the observed average is 40,000 bytes per second. Handle resets and restarts: if the second value is lower than the first, do not report a negative rate. Mark the interval as reset or unknown and establish a new baseline.
| Signal | What it indicates | What it does not prove | Useful response |
|---|---|---|---|
| Outbound byte counters increase | Traffic has used that outbound during the interval | That every destination is reachable or responsive | Compare rates with the same time window and expected workload |
| Probe succeeds repeatedly | The selected probe target was reachable through the tested route | That all applications or destinations will work | Keep the route eligible, subject to your routing policy |
| Probe fails once | The probe did not complete successfully on that attempt | That the node is permanently down | Retry and check target reachability, DNS, and local logs |
| No counter is returned | The requested statistic may not exist or match the query | That the outbound is necessarily unhealthy | Check the outbound tag, policy, and exact returned names |
For node health, configure observatory checks for the outbounds you want to evaluate, then connect those observations to a routing balancer that selects from the corresponding outbound tags. The probe URL, interval, and selected nodes should be chosen for your environment; they are policy values, not universal defaults. A probe should exercise the route you care about, and the URL should return a response that the probe mechanism can recognize. Test it manually from the Xray host before using it to make automatic decisions.
Use more than one signal when the consequences of a false switch are significant. A practical policy might require several consecutive probe failures before marking an outbound unavailable, followed by multiple successful probes before declaring it recovered. Add a cooldown so the controller does not switch back and forth on every interval. Record the timestamp, outbound tag, probe outcome, and action for each decision. These records make it possible to distinguish an actual outage from a bad probe target or an incorrect threshold.
Automate failover with a controlled workflow
For routine traffic selection, prefer a configuration designed around Xray’s observatory and routing balancer instead of building a controller that repeatedly rewrites the running configuration. A balancer can select among configured outbound tags using available observations. Keep the primary and backup outbounds defined, and route the relevant traffic through the balancer. This provides a clearer separation between health evaluation and traffic selection than adding and removing handlers after every probe result.
HandlerService is useful when a controller genuinely needs to add or remove an inbound or outbound from a running instance. However, handler operations are not the same as editing arbitrary routing rules. Adding an outbound does not automatically make existing traffic use it; removing an outbound while a routing rule or balancer still refers to its tag can leave an invalid or ineffective configuration. Confirm the behavior supported by the Xray version you deploy, and validate the complete route after every management operation.
-
Define candidates
Give every outbound a stable, unique tag, such as
edge-aandedge-b. Keep the backup route configured and verify it manually before enabling automatic switching. -
Set probe policy
Choose a probe URL and interval that suit the service. Set a failure threshold, recovery threshold, and cooldown; do not treat one timeout as a confirmed outage.
-
Collect evidence
Read observatory results and relevant StatsService counters. Store timestamps and results, and distinguish “no traffic observed” from “probe failed.”
-
Apply the route
Let the configured balancer select an eligible outbound, or use a controlled management action only if your routing design explicitly requires it. Verify traffic on the intended path afterward.
-
Test recovery
Restore the primary route only after the recovery condition is met. Confirm the controller can keep the backup active if the primary becomes unhealthy again.
Decision: keep detection separate from switching
Use probes to assess reachability, counters to understand actual usage, and routing policy to select a path. Keeping those roles separate makes a false positive easier to diagnose and prevents a statistics query from being mistaken for a failover command.
Run the controller with a least-privilege account and restrict access to the local gRPC endpoint. Do not expose port 10085 to the public internet or log credentials and sensitive subscription data alongside health results. If remote management is unavoidable, place it behind a carefully restricted private network and firewall policy. Also define safe behavior for controller restarts: re-read the current Xray state before making changes instead of assuming the last requested action succeeded.
Troubleshoot API and failover errors
When a query or switch fails, check the API listener, routing, tags, and controller assumptions in that order. A successful TCP connection to the local port is not proof that the intended gRPC service is available. Likewise, a successful StatsService response does not prove that HandlerService operations or routing selection are configured correctly.
Error: connection refused to 127.0.0.1:10085
Cause and fix: Xray may not be running, may be listening on a different port or address, or may not have loaded the API inbound. Check the startup log and confirm the configured listener before testing again.
Error: gRPC method unavailable
Cause and fix: The requested service may not be listed under api.services, or the client may target an incompatible API definition. Enable the required service, check the deployed Xray build, and retry against the local endpoint.
Error: no statistics returned for outbound tag
Cause and fix: The tag may not match, traffic may not have used that outbound, or the relevant statistics may not be enabled by policy. Check the exact counter names returned by the server and generate a controlled test request before concluding the node is down.
Error: outbound added but traffic stays on the old route
Cause and fix: HandlerService manages the outbound handler; it does not necessarily update the routing rule or balancer that selects it. Check the active route design and ensure the backup tag is an eligible member of the configured selection policy.
Keep a known-good configuration and a rollback method before enabling automatic actions. Test the API with a harmless statistics query first, then test failover in a maintenance window or a controlled environment. Confirm that the primary-to-backup transition, recovery transition, application traffic, and Xray restart behavior all match your expectations. Treat API errors as controller failures—not as evidence that a proxy node is unhealthy—and avoid destructive retries until the current process state is known.
Can a zero traffic counter trigger failover?
Not by itself. First check whether any test traffic used that outbound during the interval, then use an active probe to assess reachability.
Does HandlerService switch the routing rule?
No. It manages handlers such as inbounds and outbounds; verify the balancer or routing configuration that determines which outbound carries traffic.
Should the gRPC port be reachable remotely?
Usually not. Bind to 127.0.0.1 when the controller is local, and use a restricted private management path only when remote access is necessary.