← Writing

Reaching a Self-Hosted Backend from Outside

7 min read#Networking#Tailscale#Deployment#Autarkia

The backend runs on a machine at home and the phone has to reach it from outside. Of four approaches I have used three and kept Tailscale. Includes measured latency and dropouts for Cloudflare Tunnel from mainland China.

Table of Contents

The Autarkia backend runs on a machine in my home, with web and Android clients I wrote myself. On the home LAN nothing is a problem. The trouble starts outside: home broadband has no public IPv4, and the phone cannot find the machine. When you build your own client, the code is the easy part. This is where the time goes.

There are four approaches below. I have used three of them over time and never used IPv6. I am in mainland China, so some conclusions only hold for networks there.

01Renting a server with a public IP

The most direct option. Either move the whole backend onto it, or keep the backend at home and use the server only as a relay. I started with the second: an FRP client at home, and Nginx on the server forwarding requests back. If your models need a GPU there is no real alternative, since cloud GPUs cost too much.

Where the server sits is the main trade-off. A mainland server has the lowest latency, but serving a domain from it requires ICP filing first. US and European servers need no filing, and the latency makes back-and-forth chat unpleasant. What is left as acceptable on both counts is essentially Hong Kong.

The other matter is security. A machine with a public IP gets its port 22 scanned and its passwords guessed within minutes of booting, and a guessed password turns it into someone else's bot. The minimum is:

  • SSH with keys only and password login off. If the provider creates the machine with key login by default, do not switch back to passwords for convenience.
  • A firewall that allows only the ports in use and closes everything else.
  • Something like fail2ban to ban addresses that keep failing.
ini
# /etc/ssh/sshd_config
PasswordAuthentication no
PermitRootLogin prohibit-password

02IPv6, if you would rather not pay

I have not used this one myself; it is put together from other people's write-ups. It is here because it costs nothing.

Home broadband lacks public IPv4, but most lines now have public IPv6, and so does almost all mobile data. In principle the phone can connect straight to the home machine over IPv6 with no server in between. Making that work takes a few steps:

  • The modem or router blocks inbound IPv6 by default, and the firewall has to allow it. Some ISP modems cannot be changed and need to be put in bridge mode with your own router dialing. This varies a lot by ISP and model.
  • Allow only the backend's port. Under IPv6 every device has a public address, and turning the firewall off entirely puts every device in the house on the internet.
  • The prefix changes, so set up DDNS to keep a domain's AAAA record current.
  • The network the phone is on needs IPv6 too. Mobile data usually has it; office and campus Wi-Fi often do not.

A backend exposed this way gets scanned just like the server in the previous section, so the API needs its own authentication and preferably TLS on top.

03Cloudflare Tunnel: slow and flaky from the mainland

After FRP I moved to Cloudflare Tunnel, attracted by not having a server to look after: cloudflared runs at home and dials out to Cloudflare's edge, the phone visits a domain, and traffic comes back around through the edge. I used it for a little over two months and then stopped.

First, slow. Over the tunnel, tapping send hung for two or three seconds before the message left; on the LAN there was nothing to notice. Timing the stages with curl -w: 0.4 s per request on a reused connection and 1.2 s on a new one; first byte at 0.95 s with a 1 KB body and 1.7 s with 100 KB.

Part of those seconds was my own doing: the client attached the last 200 messages of history to every send, 44 to 95 KB per request. Trimming history to what the backend actually uses and gzipping the body (about 4.6x on JSON) helped a lot. It also shows what a tunnel is like: on the LAN a few dozen KB is a few milliseconds and not worth a thought, and over the tunnel every KB counts.

Then, flaky. A conversation would suddenly return 530. Once I fired 20 health-check requests in a row and got 530 on all 20, while 20 direct local requests all returned 200; a little later, 12 more through the tunnel were all fine. Nothing was wrong with the backend. What dropped was the long-lived connection between cloudflared and the edge. Direct connections from the mainland to Cloudflare's edge jitter by seconds as a matter of course, and cloudflared retrying across IPs for 30 to 45 seconds before registering at startup is normal.

There was also a conflict with proxy software. cloudflared reaches the edge on port 7844. With a TUN-mode proxy running on the machine, that traffic was captured too, and the node I used did not pass 7844, which showed up as the connection closing right after the TLS handshake. cloudflared cannot be pointed at an upstream proxy, so I ended up adding direct routes for the two Cloudflare edge ranges to get around it.

If you are outside China, or just need a temporary entrance for someone now and then, it is still convenient. As a daily channel from the mainland, I do not recommend it.

04Tailscale: what I use now

Tailscale is a mesh network: install the client on the home machine and the phone, sign in to the same account, and they behave as if on one LAN, each with a 100.x.x.x address, connecting peer to peer when hole punching works and through a relay only when it does not. The backend is never exposed to the internet, so the scanning problems of the first two sections do not exist. When the direct path comes up, latency is about what a wire of your own would give.

Switching over needed one change on the backend. Mine rejects cross-origin requests by an Origin allowlist that held fixed domains. Opening the web client from a 100.x address or a *.ts.net hostname produces an Origin only known at runtime, which never matched, so everything got 403. I now treat loopback, private ranges and Tailscale's 100.64.0.0/10 as trusted origins and check the allowlist only for requests from the public internet.

If you write your own Android client, one more thing to know: with Tailscale on, the system default network is always that VPN, and when the underlying link moves from Wi-Fi to mobile data, the default-network callback does not fire. My client relied on that callback to decide the network had changed and the channel should be re-selected, so with Tailscale on it would not switch back to the LAN when I got home. To see the underlying networks you have to enumerate all networks, not just the default one.

Its biggest inconvenience is on the phone. Android allows one VPN at a time; Tailscale takes the slot and other proxy apps cannot run, and vice versa. The way out is to have the proxy app join the Tailscale network itself: mihomo, the core of Clash Meta, has an outbound of type tailscale. Configure it, route only 100.64.0.0/10 to it, and the phone needs just the proxy app running.

proxies:
  - name: ts
    type: tailscale
    hostname: phone-mihomo
    auth-key: tskey-auth-xxxx   # 不填的话首次启动会在日志里给一个登录链接

rules:
  - IP-CIDR,100.64.0.0/10,ts,no-resolve

According to the mihomo documentation, this outbound only connects to Tailscale when the first matching connection arrives, so a timeout on the very first request is expected and a retry works. A client shipping an older core will not have this type, so check first.

The Autarkia clients now pick among three channels automatically: LAN at home, Tailscale outside, and a slot for a public entrance that is left empty by default.