# Running a cluster

> Several cairnflow nodes on one bucket, addressing rules, failover, and splitting and merging key ranges.

Source: https://cairnflow.dev/docs/self-hosting/cluster

A cluster is several `cairnflow` processes pointed at the same bucket and prefix. There is nothing
else to set up: nodes find each other through the bucket, each key range has one leader at a time,
and ranges move to another node when their leader stops.

Clusters need a store with compare-and-swap: an `s3://` store that passes the startup checks (see
[Object stores](/docs/self-hosting/storage)). `file://` runs one node only.

## Starting nodes

```sh
# on every node: same bucket and prefix, same --partitions, same keys
cairnflow --main-store s3://cairnflow/prod --partitions 8 \
          --node-id node-a --host 10.0.0.11 --port 8080   # internal port 8081
cairnflow --main-store s3://cairnflow/prod --partitions 8 \
          --node-id node-b --host 10.0.0.12 --port 8080
```

Every node needs:

- the same `--main-store` (and `--wal-store`, if you use one);
- the same `--partitions` value (see [Ranges](#ranges));
- the same authentication setup: the same `CAIRNFLOW_ADMIN_KEY` (or hashed variant), and keys
  created with `cairn keys create` are shared automatically through the bucket;
- the same cluster secret. Set `CAIRNFLOW_CLUSTER_SECRET` (32 bytes or more, identical on every
  node), or leave it unset and the first node creates one in the bucket. Setting it is safer: a
  secret stored in the bucket can be read, and used to sign internal requests, by anyone who can
  read the bucket.

Give each machine a stable `--node-id`. Without it, a node generates an id per process.

## Addresses

Each node has two ports: `--port` for clients and `--internal-port` (default `--port` + 1) for
peers. A node advertises both in its lease: peers send to the internal port, and clients are
pointed to the ingress port.

:::caution
**`--host` must be an address that peers can reach, not `0.0.0.0`.** Unless you set
`--advertise-host`, a node advertises exactly the address it is bound to. Bound to `0.0.0.0`, it
advertises `http://0.0.0.0:8080`, cross-range messages reach no one, and the failure is silent:
each node still looks healthy on its own.
:::

You can pass a hostname to `--host`; it is resolved to an IP when the node binds.

When a platform requires a node to listen on all interfaces while peers must reach it at a private
address, bind on all interfaces and advertise the private address:

```sh
cairnflow --main-store s3://bucket/prod --partitions 8 --node-id "$NODE_ID" \
          --host :: --advertise-host "$PRIVATE_IP" --port 8080
```

`--advertise-host` takes a hostname or an IP (IPv6 with or without brackets). It is not resolved at
startup, so names that only peers can resolve work. `0.0.0.0`, `::`, a scheme, a port or a path are
rejected. The advertised port is always the port actually bound.

**Firewall the internal port** so that only the other nodes reach it. Requests there must carry an
HMAC signature made with the cluster secret, but if you bind on all interfaces the signature is the
only thing standing between the internal API and the network.

## Requests that reach the wrong node

A request about a key whose range is led by another node gets `503` with a `leader` field: the
ingress address of the current leader. The `cairn` CLI and the TypeScript SDK client follow it
once, keeping the same `Idempotency-Key`. A client of your own should read `leader` from the body
and resend there.

Following `leader` requires clients to reach every node's advertised address. Behind a load
balancer that hides the nodes, send the header `x-cairn-forward: leader` instead. The node that
receives the request forwards it to the leader over the internal port (one hop, no retry) and
returns the leader's response with an `x-cairn-forwarded-by` header. If the request was sent but no
response came back, the node returns `504`: the operation **may** have run, so check its state (or
resend with the same `Idempotency-Key`) before repeating it. The web console always sends this
header.

A `503` without `leader` means the cluster is electing a leader or a range is being split or
merged: back off and retry.

## Failover

Leases expire after `--lease-ttl-ms` (default 10 000 ms). When a node dies, its ranges get a new
leader after about one lease TTL, plus up to a third of a TTL for peers to notice. By default, a new
cluster delegates lease renewal to one coordinating node to save requests; there, a dead node's ranges
move in under two TTLs, and in under three if the coordinator dies at the same time as another node.

A graceful stop is much faster. On `SIGTERM` or `SIGINT` a node seals each range, closes its
session and tells its peers, which take the ranges over almost immediately. The whole shutdown is
capped by `--shutdown-timeout-ms` (default 20 000 ms); past that, or on a second signal, the node
exits at once and peers take over after a TTL. Give your process manager a grace period longer
than the shutdown timeout.

Ranges balance themselves across live nodes. There is no rebalance command to run; `cairn cluster`
shows who leads what.

## Ranges

The key space is cut into **ranges**, each with its own leader. `--partitions N` sets the number of
ranges when the bucket is first initialised. The value is recorded in the bucket; while the range
table has never been split or merged, a node started with a different value refuses to start. After
the first split or merge, the table in the bucket is authoritative.

Start with more ranges than nodes; 8 to 64 is reasonable for a small cluster. You can change the
layout at runtime:

```sh
cairn ranges                    # range table: version, key bounds, generation, intent
cairn ranges split 3            # split range 3 at the middle of its key range
cairn ranges split 3 --at 8000000000000000   # split at a given key (16 hex digits)
cairn ranges merge 4 5          # merge two adjacent ranges into a new one
```

A split or merge must be sent to a node that leads the range (others answer `503` with `leader`),
pauses writes to the ranges involved for a short window, and returns the new table with a per-phase
timing report. If the node dies midway, the next leader of the source range rolls the change back.
While a split or merge is in progress, requests for those ranges may get `503` without `leader`;
the ingress itself waits up to two seconds for the table to settle before answering that way.

### Automatic splitting

Each leader measures load per range: the share of the node's turn capacity the range uses, and its
size. `--auto-split` chooses what happens:

| Mode | Behaviour |
|---|---|
| `suggest` (default) | Proposals only, at `GET /ranges/suggestions`. Nothing is split. |
| `on` | Hot or oversized ranges are split automatically. |
| `off` | Automatic splitting is disabled. |

A range is proposed for a split when it is busy (by default, at least half of the node's turn
capacity for 60 consecutive seconds) or larger than `--max-range-bytes` (default 8 GiB). The split
point balances measured work, not key count. When one key owner accounts for most of the load, no
split is proposed (`hot_owner`): a single owner cannot span two ranges, so use flow control instead
(see [Flow control](/docs/reference/flow-control)).

In `on` mode, only one split or merge runs in the whole cluster at a time, a range that was just
split cools down for 10 minutes, each node splits at most once a minute, and nothing is split while
the cluster is upgrading. Splits for load stop once the table holds `--auto-split-max-ranges` ranges
(default 128, `0` for no cap); the proposal then shows `blocked_by: max_ranges`.

Ranges are never merged automatically. In `suggest` and `on` modes, two adjacent ranges that have
both been cold for `--auto-split-merge-cold-ms` (default 6 hours, `0` turns this off), are together
under a quarter of `--max-range-bytes` and are not cooling down from a split are proposed for a
merge at `GET /ranges/suggestions`, with reason `merge`. Run the merge yourself with
`cairn ranges merge`.

Look at the proposals on real traffic before switching to `on`. `GET /ranges/stats` shows the load
per range.

### Storage after splits

A split or merge retires the parent range's data instead of deleting it. Retired data stays in the
bucket until you enable `--gc-retired-dbs`, which removes it (through the trash, see
[Backup and restore](/docs/self-hosting/backup-restore)) once no live range references it. It is
off by default because it deletes data; `--gc-retired-dbs=plan` only logs what it would remove.

A range keeps reading the sorted files of its ancestors after a split. When a range a node leads
still depends on files of two or more ancestor ranges (`--lineage-compact-depth`, default 2, `0`
turns this off), or on an ancestor retired for more than a day (`--lineage-compact-age-ms`), the
node runs one full compaction of that range so it stops depending on them and the retired data can
be collected. It compacts one range at a time and skips ranges that are being throttled. Automatic
splitting refuses a range that is already `--lineage-auto-split-max-depth` levels deep (default 3).

## Write-ahead log

Every node writes one shared write-ahead log for all the ranges it leads. The number of log writes
to the store therefore grows with the number of nodes, not with the number of ranges. Tuning flags
are listed in [Configuration](/docs/self-hosting/configuration).

## Readiness

`GET /health` answers `ok` as soon as the HTTP server is up; it says nothing about leadership. A
cluster is ready when every range in `GET /cluster` (or `cairn cluster`) has a `leader`. Wait for
that before stopping the next node during a rolling restart.
