# ADR-0055: Replica failover, active health and the node link

URL: https://scalws.com/docs/adr/0055-replica-failover-and-active-health/
Source: `docs/adr/0055-replica-failover-and-active-health.md` in the ScalWS repository

Status: accepted, 2026-11-22 (design: `docs/design/2026-11-19-1.2-replica-design.md`,
plan: `docs/design/2026-11-19-1.1.1-replica-plan.md`; ships as 1.1.1)

## Context

ScalPanel (its ADR-0231) runs a site on two nodes. The edge of each node must send to its
own container and, when that is unhealthy, to the other node's edge over a private link
with mutual TLS; in a balanced mode it must share traffic with sticky sessions and send
writes to the primary; and a primary that lost the control plane must be fenced into
read-only. ScalWS had pools with passive health (ADR-0049) but no active checks, no
ordered failover, no route retry policy, no cookie signed by a shared key, no fencing and
no client certificates on listeners or pools. The old 1.1 item "active health checks" was
moved here, so plain load balancing and the Kubernetes ingress gain it too.

ScalPanel proposed an upstream list inside the route (`runtime.upstreams`). The owner chose
to build on pools instead (2026-11-19); the generator writes two pools and `backends`.

## Decision

Everything builds on ADR-0049 pools and `backends`. There is no second upstream model.

* **Active health.** `upstreams.<pool>.active_health` (`path`, `host`, `headers`,
  `interval`, `timeout`, `fails`, `passes`, `status`): one tokio task per member and
  process, with its own connection. A member is **healthy** when passive health has not
  ejected it and its probes have not marked it down. State is atomics next to the passive
  state (`balance::Health`), read without a lock per request. A probe carries no client
  data (`GET`, the path, `Host`, fixed headers, `user-agent: scalws-health/<version>`).
  A member whose probes come back up leaves a running passive ejection at once.
* **Backends and failover.** `backends[].id` names a backend (default the pool name);
  `balance: weighted | failover`. Failover takes the first backend in list order that has a
  healthy member. Backends with no healthy member are skipped. The choice lives in
  `route_select.rs`, built only when a replica key or an `active_health` pool is present.
* **Retry.** `retry: {on, max, only_idempotent}` replaces the pools' `retries` for the
  route and may move to another backend. A request already written is retried only for the
  idempotent set; a written POST or PATCH is never resent.
* **Sticky.** `sticky: {cookie, ttl, key_file}`: a cookie naming the backend `id` and a
  keyed hash of the member, signed with HMAC-SHA256 (16-byte tag) under a key file the
  nodes share. Pools' `hash: {by: cookie, key_file}` can use the same kind of file.
* **Writes and fencing.** `write_backend` pins writes and WebSocket upgrades to one
  backend. `read_only` and `read_only_response` answer writes without reaching an upstream.
* **Node link.** `server.listeners[].tls.client_ca_file` and `client_names` require and
  limit client certificates; pools gain `tls.client_cert_file` and `client_key_file`.
* **Route scope.** A route key `listeners: [name]` applies a route only to requests that
  arrived on those listeners; the loop-prevention route for forwarded requests uses it.
* **View.** `type: upstream_status` answers the health of every pool member as JSON for the
  ScalPanel agent.
* **Tokens.** `scalwsd --version` lists the edge features `peer_tls read_only replica
  sticky upstream_health` (and, from the same release, `affinity_key backup_members
  pools respond_file`), each added by the task that finished its feature.

### Decisions after the builder check

1. **Sticky identity across nodes.** The cookie names the backend `id` plus the member, so
   with `id` set to the node name the same cookie leads to the same node from either edge.
2. **Probe of the peer.** `active_health.headers` carries `X-ScalPanel-Via`, so the peer
   answers a probe from its own container and a probe measures the peer's container, never
   a path back.
3. **Route listener scope.** `listeners: [peer]` scopes the forwarded-request route to the
   mutual-TLS listener; a public client sending the header matches nothing special. On a
   node that is not the primary the route is also `read_only`.
4. **What counts as down.** A member is unhealthy when its active check is down or passive
   health ejected it. The `503` for "no healthy backend" applies only when at least one
   backend of the route has `active_health`; otherwise ADR-0049's fallback (the member
   ejected longest ago) stays, so passive health alone never refuses traffic.
5. **Retry safety.** A request whose connection failed before it was written is retried
   for any method (GET, HEAD and OPTIONS with `only_idempotent`). A written request is
   retried only for GET, HEAD, OPTIONS, PUT and DELETE (GET, HEAD and OPTIONS with
   `only_idempotent`). A write to `write_backend` goes only to another member of its pool
   and only after a connect error. Writes pinned by `write_backend` are never resent after
   a stale kept-alive connection either.
6. **Read-only boundary (corrected from the design draft).** The design draft said an old
   connection serves at most the request it is in and then closes, with GOAWAY for HTTP/2.
   The code is stronger: the routing state is loaded per request on every stack (hyper
   HTTP/1 and HTTP/2, the own HTTP/1 server including pipelined requests, HTTP/3), so a
   reloaded `read_only` applies to the next request of an already open connection, and no
   GOAWAY is needed. WebSocket tunnels carry bytes after the check, so a reload that makes
   a runtime `read_only` closes every tunnel opened through that runtime before the reload
   returns (a fence per runtime, spanning handler generations). Only requests already past
   the check finish. The guarantee holds only for a reload that was acknowledged:
   `scalwsctl reload` and `POST /v1/reload` answer when the configuration is in place;
   `scalws-controller` `POST /reload` answers `200` only once the new generation serves
   alone, `409` when it was rolled back or replaced and `504` after 180 s; `SIGHUP` has no
   acknowledgement. `409`, `504` and a client timeout mean the node is not fenced.
7. **Kubernetes.** Data plane only. Ingress annotations and Gateway API health policy
   belong to the 1.2 Kubernetes project.
8. **Peer identity.** `client_names` limits accepted certificates to exact SAN DNS names.

### Rulings (spec ambiguities)

* **R1. Key file owner.** The packaged `scalwsd` runs as `scalws` and cannot read a
  root-only file. A key file is a regular file (no link), owned by uid 0, by the effective
  uid, or, when scalwsd runs as root, by the `scalws` user; `mode & 0o077 == 0`; 32 to 1024
  bytes; read whole. ScalPanel writes `scalws:scalws 0600`.
* **R2. Start-up.** A new member is up with zero counters; from its first probe on `fails`
  and `passes` decide. The first probe runs after a jitter of at most `min(interval / 2,
  1s)`, later ones every `interval` plus or minus 10 %.
* **R3. Ids.** `[a-z0-9-]{1,32}` when written, default the pool name; not on `status`
  backends, which are never sticky targets.
* **R4. Skipping.** Backends whose members are all unhealthy are skipped when the route
  sets `balance` or a pool has `active_health`; a plain `backends` route keeps 1.1.0's
  choice, so existing configurations do not change.
* **R5. Retry.** A connection broken after the request was written and before a response
  head counts as `timeout`; `only_idempotent` defaults to `false`, `max` to 1.
* **R6. Keys need pools.** The replica route keys need `upstream: {pool}` or `backends`.
  `sticky` with `balance: failover` is ignored with a warning; a route with `sticky` does
  not set its pools' `hash` cookie (warning).
* **R7. `upstream_status` values.** `active` is `up`, `down`, `unknown` or `off`; `fails`
  counts probe failures with `active_health`, else passive ones; `since` is the last change
  of `healthy`, RFC 3339 UTC.
* **R8. mTLS reload.** Adding or removing `client_ca_file` needs a restart; a changed CA
  file or `client_names` applies on reload to new handshakes, and open connections are
  checked again on their next request (`403` when revoked; audit replica R3). mTLS
  listeners send no TLS 1.3 tickets and keep no session cache. The access log field
  `tls_client` holds the first matched `client_names` entry, else the first SAN DNS name,
  else `-`.
* **R9. Pool client certificates.** A pool whose `client_cert_file` or `client_key_file`
  changed (device, inode, size, mtime) is rebuilt on reload.
* **R10. Fixtures.** The replica fixture is written by ScalWS from ScalPanel's key list and
  is replaced byte for byte when ScalPanel supplies generator output.
* **R11.** ADR number 0055.

Smaller rulings made while building: a probe down-to-up transition ends a passive ejection
(up to up does not, so it cannot flap); a retry never goes to a `status` backend; a member
tag mismatch renews the sticky cookie only when the pool has more than one member (two
edges reach a member by different addresses); a key file is compared by content on reload,
so an in-place rewrite is noticed; a fence per runtime key survives generations.

## Consequences

* A configuration without the new keys behaves and allocates as in 1.1.0 (the
  `pipeline_cost` rows are unchanged). Cost when on: see
  [the replica benchmark](https://scalws.com/docs/benchmarks/2026-11-22-replica/). Sticky costs about 6.7
  microseconds per request without a cookie.
* Under scalws-controller every instance probes, so probes multiply by the instance count
  (spread by jitter, bounded by `interval`). Nothing is shared between instances or nodes:
  each process probes, balances and decides on its own; only the sticky and affinity keys
  are shared (files), so cookies agree. After a failover the passive state of the other
  node is not known.
* A fenced node needs an acknowledged reload; on a multi-instance controller that answer
  takes the roll time (at most 180 s). Faster drain acknowledgement is left to 1.2.
* The peer probe and the loop-prevention route depend on the header `X-ScalPanel-Via` and
  on `listeners` scoping; a generator that omits them loses loop safety.
* A probe-only outage shorter than `fails` probes runs the passive cooldown as before.
* `upstream_status` lists the pools of every application; it belongs on a loopback
  listener.
* Left open: Kubernetes health policy (1.2), shared health between nodes (not planned),
  a no-follow `O_PATH` connect for runtime sockets (1.2).

## Related

* ADR-0049 (pools, amended), ADR-0050 (route matching), ADR-0054 (edge features).
* Guides: [replicas](https://scalws.com/docs/guide/replicas/), [load balancing](https://scalws.com/docs/guide/load-balancing/),
  [mutual TLS](https://scalws.com/docs/guide/tls/#client-certificates-mutual-tls).
