# Replicas: one site on two nodes

URL: https://scalws.com/docs/guide/replicas/
Source: `docs/guide/replicas.md` in the ScalWS repository

A ScalPanel site can run on two nodes, a primary and a secondary. The ScalWS edge of each
node knows two upstreams for the site: its own container and the other node's edge,
reached over a private link with mutual TLS. In **failover** mode traffic leaves the node
only when the local container is unhealthy. In **weighted** mode it is shared, with sticky
sessions and with all writes sent to the primary. A node that lost the control plane is
**fenced** by switching its site to read-only.

Everything is built from the keys of [load balancing](https://scalws.com/docs/guide/load-balancing/) (pools,
`backends`, active health, `retry`, `write_backend`, `sticky`, `read_only`), plus a route
scope (`listeners`), a mutual-TLS listener and a JSON health view. There is no second
upstream model. Design record: [ADR-0055](https://scalws.com/docs/adr/0055-replica-failover-and-active-health/)
(on top of [ADR-0049](https://scalws.com/docs/adr/0049-upstream-pools-and-runtime-members/)). The generator
contract of the edge is in [ScalPanel edge](https://scalws.com/docs/guide/scalpanel-edge/).

Contents:

* [What ScalWS does and does not do](#what-scalws-does-and-does-not-do)
* [The two-node pattern](#the-two-node-pattern)
* [Pools, ids and failover](#pools-ids-and-failover)
* [Sticky sessions](#sticky-sessions)
* [Writes: `write_backend`](#writes-write_backend)
* [Fencing with `read_only`](#fencing-with-read_only)
* [Loop prevention](#loop-prevention)
* [The node link](#the-node-link)
* [`upstream_status`](#upstream_status)
* [The version line](#the-version-line)
* [Checking a node](#checking-a-node)

## What ScalWS does and does not do

ScalWS decides per request and per process; it shares nothing between nodes or instances
at run time. Each process probes the pools itself, and the shared sticky key file is what
lets two nodes agree on a cookie. Everything else belongs to ScalPanel: replicating files,
changing DNS, promoting the secondary, and deciding which node is primary and which is
fenced. ScalPanel should turn replicas on only when `scalwsd --version` lists
[the tokens it needs](#the-version-line).

## The two-node pattern

This is node 1 (the primary) of a site `example.com`; node 2 is the same file with the
node names, link addresses, certificate paths and `write_backend` swapped (shown after the
file). The container is at `192.0.2.4:8080`, the node's public address is `203.0.113.10`,
the node link is `198.51.100.0/24` (node 1 is `.1`, node 2 is `.2`).

```yaml
# fragment
server:
  listeners:
    - name: public                                 # the public address, not the link
      address: "203.0.113.10:80"
    - name: peer                                   # the node link, mutual TLS
      address: "198.51.100.1:8443"
      tls:
        certificates_file: /etc/scalpanel/node-link/certificates.yaml
        client_ca_file: /etc/scalpanel/node-link/ca.crt
        client_names: [node-2.link]
    - name: probe                                  # the agent's loopback listener
      address: "127.0.0.1:8098"
  trusted_proxies: ["198.51.100.2/32"]                # node 2 only: its X-Forwarded-For is believed
upstreams:
  r3_local:
    members: [{address: "192.0.2.4:8080"}]
    active_health: {path: /__scalpanel/health, host: example.com}
  r3_peer:
    scheme: https
    members: [{address: "198.51.100.2:8443"}]
    tls:
      ca_file: /etc/scalpanel/node-link/ca.crt
      server_name: node-2.link
      client_cert_file: /etc/scalpanel/node-link/node-1.crt
      client_key_file: /etc/scalpanel/node-link/node-1.key
    active_health:
      path: /__scalpanel/health
      host: example.com
      headers: {X-ScalPanel-Via: node-1}           # the peer answers from its own container
tenants:
  - name: scalpanel
    applications:
      - name: r3-0
        domains: [example.com]
        listeners: [public, peer]
        route_order: nginx
        routes:
          - path: /                                # requests forwarded by the other node
            listeners: [peer]
            headers: [{name: X-ScalPanel-Via, regex: "^node-[0-9]+$"}]
            runtime:
              type: proxy
              forwarded_for: client
              backends: [{pool: r3_local, id: node-1}]
              read_only: false
              read_only_response: {status: 503, body: "Read-only, try again shortly", retry_after: 30}
          - path: /                                # everything else
            request_headers: {set: {X-ScalPanel-Via: node-1}}
            runtime:
              type: proxy
              forwarded_for: client
              backends:
                - {pool: r3_local, id: node-1, weight: 1}
                - {pool: r3_peer, id: node-2, weight: 1}
              balance: failover
              retry: {on: [connect_error, timeout], max: 1, only_idempotent: true}
              write_backend: 0
              read_only: false
              read_only_response: {status: 503, body: "Read-only, try again shortly", retry_after: 30}
      - name: scalpanel-upstreams
        domains: ["*"]
        listeners: [probe]
        routes:
          - {path: /__scalpanel/upstreams, path_type: exact, runtime: {type: upstream_status}}
```

Node 2 differs in: `address` of `public` (its own public address) and of `peer`
(`198.51.100.2:8443`), `trusted_proxies: ["198.51.100.1/32"]`, `client_names: [node-1.link]`, the
peer pool's member (`198.51.100.1:8443`) and `server_name: node-1.link`, its own certificate
pair (`node-2.crt`, `node-2.key`), `X-ScalPanel-Via: node-2` in both places, backend ids
swapped (`r3_local` is `node-2`, `r3_peer` is `node-1`), `write_backend: 1` (writes go to
the peer, the primary), and `read_only: true` on the forwarded-request route (a write
forwarded to a node that is not the primary is refused: defence in depth). The same two
files are in `tests/integration/fixtures/scalpanel-replica/` (with private link addresses instead
of the documentation addresses used here, and the public listener on `0.0.0.0` with the
whole test link trusted, see below) and run in the test suite.

The peer route carries `forwarded_for: client` and `read_only_response` too: without the
first the container would see two `X-Forwarded-For` values, and without the second a
fenced write that came through the other node would get an empty answer.

## Pools, ids and failover

* One pool per upstream. A pool has one `scheme` and one `tls`, so a local `http` container
  and the peer's `https` edge cannot be members of one pool; use two pools and `backends`
  (`<site>_local`, `<site>_peer`). `backup: true` serves pools whose members share a
  scheme.
* `active_health` on both pools: the local container is probed directly, the peer is probed
  through its edge with the header `X-ScalPanel-Via`, so the peer's
  [loop-prevention route](#loop-prevention) answers from its own container and the probe
  measures the peer's container, never a path back to this node. A member counts as up
  until its first probe result, so a start or reload never blacks the site out
  ([active health](https://scalws.com/docs/guide/load-balancing/#active-health)).
* `balance: failover` sends every request to the first backend in list order that is
  healthy: the local pool first. `balance: weighted` shares requests by weight over the
  healthy backends. A backend is healthy while one of its members is neither ejected by
  passive health nor down by its probes. When no backend is healthy and a pool has
  `active_health`, the route answers `503`.
* `id` names a backend (`[a-z0-9-]{1,32}`, default the pool name). Give it the node name:
  on node 1 `node-1` is the local pool, on node 2 `node-1` is the peer pool, so a sticky
  cookie means the same node on both edges.
* `retry: {on: [connect_error, timeout], max: 1, only_idempotent: true}` moves a failed
  request to the other pool. 5xx retries (`status_5xx`) are left out on purpose, so a
  write is not done twice. A written `POST` or `PATCH` is never resent
  ([route retry](https://scalws.com/docs/guide/load-balancing/#route-retry)).

The keys `balance`, `retry`, `sticky`, `write_backend`, `read_only` and `read_only_response`
need `upstream: {pool: ...}` or `backends`.

## Sticky sessions

Sticky goes with `balance: weighted` only. With `failover` it is ignored with a warning.

```yaml
# fragment
runtime:
  type: proxy
  balance: weighted
  backends: [{pool: r3_local, id: node-1}, {pool: r3_peer, id: node-2}]
  sticky: {cookie: sp_node, ttl: 3600s, key_file: /etc/scalws/sticky.key}
```

The cookie `sp_node=<id>.<member>.<tag>` is signed with HMAC-SHA256 under the key file
([sticky backends](https://scalws.com/docs/guide/load-balancing/#sticky-backends)). Both nodes read the same key, so a
cookie set by one is honoured by the other.

**The key file.** Write the same 32 to 1024 bytes on both nodes (`head -c 32
/dev/urandom`). It must be a regular file (not a symbolic link) with no group or other permission bits (`0600` or `0400`) and be
owned by uid 0, by the user scalwsd runs as, or, when scalwsd runs as root, by the `scalws`
user. ScalPanel writes it `scalws:scalws 0600`. Anything else is refused at start, reload
and `scalwsctl check`; the error names the key and the reason, never the content. The key
is read when the configuration is loaded and again on every reload (a changed key rebuilds
what depends on it), never per request. The same file can serve `hash.key_file` of a pool.

Sticky costs about 6.7 microseconds per request without a cookie (a new choice and a
`Set-Cookie`), 1 CPU, measured in [the replica benchmark](https://scalws.com/docs/benchmarks/2026-11-22-replica/);
a request with a valid cookie costs one HMAC.

## Writes: `write_backend`

`write_backend: <index>` sends every write (any method but `GET`, `HEAD`, `OPTIONS` and
`TRACE`) and every WebSocket upgrade only to that backend: the primary. On the primary it
is the local pool, on the secondary the peer pool. When the primary has no healthy member,
the write gets `503`; there is no write on the secondary. See
[write backend](https://scalws.com/docs/guide/load-balancing/#write-backend) for retries (another member of the same
pool, only after a connect error) and the method rule.

## Fencing with `read_only`

A primary that lost the control plane is fenced by switching its site to read-only:
ScalPanel rewrites the configuration with `read_only: true` and reloads.

With `read_only: true`, every write and every WebSocket upgrade gets `read_only_response`
(default `503`, empty body, `Retry-After` when set) before its body is read and without
reaching any upstream; reads are served.

**What the fence covers.** The routing state is loaded per request on every stack
(hyper HTTP/1 and HTTP/2, the own HTTP/1 server including pipelined requests, and
HTTP/3). Once the reload that sets `read_only` has returned:

* every request that starts afterwards is fenced, on a new connection and on a keep-alive
  or HTTP/2 connection opened before. No GOAWAY or connection close is needed.
* every WebSocket tunnel the route's runtime opened before is closed before the reload
  returns (the client sees the connection end), and nothing sent on it reaches the
  upstream.
* requests that had already passed the check finish as they were: that is the whole window.

**Which reload to wait for.** Only a success answer from a call that waits means the fence
is in place:

| Call | Success means |
|---|---|
| `scalwsctl reload`, `POST /v1/reload` (admin socket) | the new configuration is in place in that scalwsd |
| `scalws-controller` `POST /reload` | `200` only once the new generation serves alone: old instances drained and gone (up to about 55 s per instance with the defaults, at most 180 s) |
| `SIGHUP` | nothing: no acknowledgement, not covered |

`409` (rolled back or replaced by a later reload), `504` (the roll did not finish within
180 s and goes on), a refused configuration, or a client timeout all mean **the node is not
fenced**: writes may still reach the upstreams. Wait longer than 180 s for the answer
(scalws-console's Apply waits 200 s), then retry the fencing reload or escalate. The
fencing window of ScalPanel is two minutes; a single scalwsd answers at once, a
multi-instance controller roll may take most of it.

The fence belongs to the route's runtime (application plus route). Set `read_only` on the
routes that serve the paths; a new route that takes paths over from another runtime does
not close that runtime's tunnels.

## Loop prevention

A request forwarded by the other node must be served by the local container and never sent
back. Three existing pieces do it:

1. **The header.** The main route sets `X-ScalPanel-Via: <node>` on requests it sends, so
   the peer knows the request was forwarded. `forwarded_for: client` sends one
   `X-Forwarded-For` value (the real client) and `X-Real-IP`.
2. **A route that lists only the local backend**, matching the header
   (`headers: [{name: X-ScalPanel-Via, regex: "^node-[0-9]+$"}]`), tried before the main
   route. A request with the header is served from the local container and never leaves
   the node.
3. **`listeners: [peer]` on that route.** The route applies only to requests that arrived on
   the peer (mutual-TLS) listener, so a public client that sends the header matches nothing
   special and gets the main route. A route with `listeners` is tried before one without
   it on the same path.

On a node that is not the primary, also set `read_only: true` on this route.

`server.trusted_proxies` lists the other node's link address alone (`198.51.100.2/32` on
node 1): the client address a forwarded request carries is believed only from it. The
access log of the node that serves it then names the real client.

That trust goes by the sender's address, on every listener, not only on `peer`: a request
from a trusted address to the public listener is believed too. So the example binds the
public listener to the public address, not `0.0.0.0`, and trusts only the other node, not
the whole link. A public listener on `0.0.0.0` (which also takes requests on the link
address) is safe only when nothing but the other edge can send from the link: no other
host on it, and no container whose traffic leaves with a node's link address (audit
replica R1). The test fixtures keep `0.0.0.0` on a private test link and trust the other node's `/32`.

## The node link

* The `peer` listener has `tls.client_ca_file` (the link CA) and optionally `client_names`
  (the other node's certificate name). A connection without a certificate from that CA, or
  with another name, fails in the handshake before any HTTP byte
  ([mutual TLS](https://scalws.com/docs/guide/tls/#client-certificates-mutual-tls)). HTTP/3 is not available on it.
  Name the peer: without `client_names`, any certificate the CA issued is accepted.
* The peer pool has `scheme: https`, `tls.ca_file` (the same CA), `tls.server_name` (the
  other node's link name) and `tls.client_cert_file` / `client_key_file` (this node's
  certificate and key). A reload rebuilds the pool when either file changed, so rotate by
  renaming new files over the old ones.
* Adding or removing `client_ca_file` needs a restart; a changed CA file or `client_names`
  applies on reload to new handshakes and to the next request of open connections (a
  revoked node gets `403`). The access log field `tls_client` names the peer.

## `upstream_status`

```yaml
# fragment
routes:
  - {path: /__scalpanel/upstreams, path_type: exact, runtime: {type: upstream_status}}
```

`GET` (and `HEAD`) answers a JSON array, one object per member of every pool the
application's proxy runtimes use, with `Cache-Control: no-store` and no request data:

```json
[{"app":"r3-0","pool":"r3_peer","member":"198.51.100.2:8443","healthy":false,
  "since":"2026-11-22T09:15:02Z","fails":4,"active":"down","ejected":false}]
```

* `active` is `up`, `down`, `unknown` (no probe result yet) or `off` (the pool has no
  `active_health`). `healthy` is false when ejected or down.
* `fails` counts consecutive failed probes when the pool has `active_health`, otherwise
  consecutive passive failures. `since` is the last change of `healthy` (member creation at
  first), RFC 3339 UTC.
* `app` is the application `name`. Other methods answer `405`.
* The view lists the pools of every application. It is for the agent on a loopback
  listener (`127.0.0.1:8098`); a route reachable from a non-loopback listener is a warning.

## The version line

ScalPanel should turn replicas on only when `scalwsd --version` lists what it needs:

| Token | Feature |
|---|---|
| `replica` | `active_health`, `backends[].id`, `balance`, `retry`, `write_backend`, route `listeners` |
| `sticky` | proxy `sticky` with the shared key file |
| `upstream_health` | `type: upstream_status` |
| `peer_tls` | listener `client_ca_file` and `client_names`, pool `client_cert_file` and `client_key_file` |
| `read_only` | `read_only` and `read_only_response` |

`backup_members`, `affinity_key`, `respond_file` and `pools` belong to the same release but
are separate features ([ScalPanel edge](https://scalws.com/docs/guide/scalpanel-edge/#the-version-line)).

## Checking a node

```sh
scalwsctl --config /etc/scalws/scalws.yaml check
scalwsctl upstreams
curl -s http://127.0.0.1:8098/__scalpanel/upstreams
```

`check` validates the configuration and reads the key files and certificates; `upstreams`
shows `HEALTHY` and `ACTIVE` per member ([reference](https://scalws.com/docs/reference/programs/scalwsctl/));
the metric `scalws_upstream_active_health{pool, member}` is 1 while a member is up. Under
`scalws-controller` every instance probes on its own, so the load of probes on a member is
multiplied by the instance count (spread by jitter, bounded by `interval`).
