# Operations

> Health checks, metrics, logs, graceful shutdown, upgrades and the SST disk cache for a self-hosted cairnflow.

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

## Health and readiness

| Check | Meaning |
|---|---|
| `GET /health` | Returns `ok` once the HTTP server is up. No key needed. Use it as a liveness probe. |
| `GET /cluster` (`cairn cluster`) | The range table and who leads each range. Every range with a `leader` means the cluster is ready. The answer is the same on every node. |
| `GET /cluster/nodes` | Nodes, the ranges they lead, the health of their writes to the store, disk cache usage. |

`/health` does not tell you whether a node leads anything. During rolling restarts, wait until
every range in `/cluster` has a leader before stopping the next node.

## Metrics

`GET /metrics` serves Prometheus text on the client port of every node. It accepts the metrics
token (`CAIRNFLOW_METRICS_KEY`) or a `cluster-admin` key. Give Prometheus the metrics token: if the
scrape configuration leaks, only metrics leak.

```yaml title="prometheus.yml"
scrape_configs:
  - job_name: cairnflow
    metrics_path: /metrics
    authorization:
      type: Bearer
      credentials_file: /etc/prometheus/cairnflow-metrics-key
    static_configs:
      - targets: ["node-a:8080", "node-b:8080", "node-c:8080"]
```

Each node is a target; the `instance` label tells nodes apart. Metrics describe what that node
sees, so aggregate across instances.

Useful series to start with:

| Metric | Watch for |
|---|---|
| `cairnflow_commit_wait_seconds` | Time to make a commit durable in the store (histogram). |
| `cairnflow_drive_seconds` | Duration of one run of an invocation (histogram). |
| `cairnflow_timer_lateness_seconds` | How late timers fire (histogram). |
| `cairnflow_partitions`, `cairnflow_partitions_with_leader` | A difference that lasts means ranges without a leader. |
| `cairnflow_range_l0_views{range}`, `cairnflow_range_l0_reject_ratio{range}` | Compaction falling behind; new work is being refused with `429 range_overloaded`. |
| `cairnflow_invoke_throttled_total`, `cairnflow_flow_blocked_total{resource}` | Flow-control limits being hit. |
| `cairnflow_failstop_total{cause}` | A node stopping itself to stay safe; repeated stops need attention. |
| `cairnflow_slow_score` | A node much slower than its peers at writing to the store. |
| `cairnflow_registry_stale` | A node that cannot confirm its key book is fresh and refuses stored keys. |
| `cairnflow_scrub_findings` | The background consistency check found something. |
| `cairnflow_nodewal_floor_age_seconds` | The shared write-ahead log cannot be trimmed. |
| `cairnflow_disk_cache_hits_total`, `cairnflow_disk_cache_misses_total` | Disk cache effectiveness. |

Labels never carry user-chosen values such as scope names, so cardinality stays bounded. Per-scope
and per-handler detail lives in the API (`/limits`, `/vqueues`, `/stats/handlers`) and in SQL (see
[Query](/docs/query)).

The source repository includes a Grafana dashboard (`deploy/grafana/cairnflow.json`) and a set of
Prometheus alerting rules (`deploy/prometheus/alerts.yml`) built on these metrics.

## Logs

Logs go to stderr. `RUST_LOG` filters them (default `info`); `CAIRNFLOW_LOG=json` switches to one
JSON object per line for log collectors.

Runs longer than `--slow-log-ms` (default 5000 ms) leave one `warn` line with target
`cairnflow::slow_log`. It breaks the time down: waiting for your service, waiting for durable
writes, waiting for a concurrency slot, and so on. At most 10 lines per second per node are printed.
A tenant can have its own threshold (`PUT /admin/tenants/{tenant}` with `{"slowMs": n}`). The last
1 000 slow runs of each node are also available at `GET /stats/slow-runs` until the node restarts.

## Traces

A binary built with OpenTelemetry support exports traces over OTLP/HTTP when
`CAIRNFLOW_OTEL_ENDPOINT` (or `OTEL_EXPORTER_OTLP_ENDPOINT`) is set: one trace per invocation,
spans for each run and each turn, plus the spans and logs your handlers record.
`--no-user-otlp` exports only the system spans. Handler logs and spans are always readable through
the API (`/invocations/{id}/logs`, `/invocations/{id}/spans`) and the console.

## Stopping a node

Send `SIGTERM` or `SIGINT`. The node stops accepting connections, seals each range, closes its
session and tells its peers, which take the ranges over almost immediately. The shutdown is capped
by `--shutdown-timeout-ms` (default 20 s). Past the cap, or on a second signal, the node exits at
once and peers wait one lease TTL before taking over. Set your orchestrator's grace period above
the cap.

## Upgrades

### Data format and migrations

The bucket carries a data format number, which is frozen, and a **cluster version** that advances
through ordered migration steps. Each binary knows how many steps it can apply; `--version` prints
both (`data=`, `knows=`). Releases are designed to open existing buckets and migrate them
automatically:

- cluster-wide objects are migrated by the **first** upgraded node to start, under a lock in the
  bucket;
- each range's own data is migrated lazily by its leader, the first time the range opens on an
  upgraded node.

While the migration lock is held, split and merge answer `503` and the collection of retired range
data skips its turn.

### Rolling upgrade

1. **Back up the bucket** (see [Backup and restore](/docs/self-hosting/backup-restore)). There are
   no reverse migrations.
2. Record the state: `GET /admin/cluster-version` (`cluster-admin`) shows `version`,
   `requiresKnows`, the migration lock (`upgrading`) and the `knows` of every node.
3. Upgrade **one node at a time**: `SIGTERM`, replace the binary, start it.
4. Wait until every range has a leader in `/cluster` before stopping the next node.
5. After the last node, `GET /admin/cluster-version` must show `upgrading: null`, `version` equal
   to `binary.knows`, and the same `knows` for every node.

Only two consecutive releases can run side by side. After the cluster version moves past what an
old binary knows, that binary keeps serving the ranges it already leads but cannot open new ones,
and stops rather than overwrite an object it does not understand. Finish an upgrade instead of
leaving the cluster mixed.

**Rolling back** is possible only before the cluster version moves past what the old binary knows
(`requiresKnows` still at or below the old binary's `knows`). After that, the old binary refuses to
start and the way back is the backup taken in step 1; invocations written after it are lost.

### One-way feature gates

Features that older binaries would mishandle are switched on by one-way gates once every node runs
a binary that knows them, with commands such as `cairn-ctl cluster enable-key-roles --apply`.
`cairn-ctl cluster status` shows the gates and the `knows` of every session. A cluster created by a
binary that already knows a gate starts with it enabled.

### Upgrading your services

An invocation stays bound to the deployment it started on, so registering a new version of your
service does not move in-flight invocations to new code. New invocations use the new revision. To
move existing ones on purpose, test with `POST /deployments/{id}/replay-check`, then use
`POST /invocations/{id}/migrate` (which requires a matching replay) or `restart`. See the
[HTTP API](/docs/reference/http-api#deployments-and-services).

## SST disk cache

By default a node uses no disk: after a restart or a leadership change, the first reads of a range
go to the store. `--disk-cache-dir DIR` keeps copies of sorted files (SSTs) of every range on local
disk, up to `--disk-cache-bytes` (default 16 GiB) for the whole node, with LRU eviction. Newly
written SSTs enter the cache immediately, and when a node takes over a range it warms the cache with
that range's recent files in the background. The cache survives restarts.

The cache can only make reads faster, never wrong: only immutable SSTs go in it, never the
write-ahead log, manifests or leases. A damaged entry is read again from the store, and a full or
broken disk falls back to the store. Deleting the directory while the node is stopped is always
safe.

Size it to the hot SSTs of the ranges a node leads; 10 to 20 percent of the data per node is a
reasonable start. Watch `cairnflow_disk_cache_evictions_total` and the hit ratio, also visible with
`SELECT node, disk_cache_bytes, disk_cache_hit_ratio FROM sys_node` through `POST /query`.

:::caution
The cache holds customer data: journals, state and outputs.

- Put `DIR` on an encrypted volume.
- Purging an invocation does not remove copies already in the cache. They disappear when evicted or
  when the directory is deleted, with no time bound.
- When a node leaves the cluster, delete its cache directory. Ephemeral volumes do this for you.
- Do not copy a cache directory between nodes.
:::

## Bucket growth

- **Retention.** Finished invocations are purged after `--retention-ms` (default 24 hours). With
  `0` they are kept forever and the bucket grows with history, not with load.
- **Archive.** Before purging, cairnflow writes a compressed copy of the journal and final state
  under `archive/<tenant>/<date>/`. Archives never expire on their own: set a lifecycle rule on the
  `archive/` prefix, or run with `--no-archive`.
- **Splits and merges** leave retired range data behind until `--gc-retired-dbs` is enabled (see
  [Running a cluster](/docs/self-hosting/cluster)).
- **Trash.** Cairnflow's own deletions are kept for `--trash-keep-s` (default 7 days) before they
  are removed for good.

## Background consistency check

Every `--scrub-every-s` seconds (default 600), one node runs a read-only check of the bucket's
invariants, the same family of checks as `cairn-ctl verify`. Its store requests are capped by
`--scrub-requests-per-hour`: a round that costs more requests is followed by a longer pause, so on
a cluster with many ranges the interval stretches while every round stays complete. It never
changes anything; findings appear in `cairnflow_scrub_findings`, in the log and at
`GET /admin/scrub`. A finding that persists over two rounds deserves a look with `cairn-ctl verify`
(see [Backup and restore](/docs/self-hosting/backup-restore)).

The background check does not look for missing individual sorted files. Run
`cairn-ctl verify --deep` periodically for that, so a file deleted from outside cairnflow is found
before a read needs it.
