# Upgrade Ledger

Source: https://docs.formance.com/v4.0/modules/ledger/operations/upgrade

Stack: v4.0

Start with the procedure published for the exact source and target releases. A one-member-at-a-time rollout is valid only when that procedure explicitly supports mixed binaries and the persisted state remains compatible. Treat the Stack release, Ledger server, Stack Operator, and `ledgerctl` as separate versioned artifacts.

The current Ledger 3.0 preview contains a persisted-state break for which its source requires a full wipe and replay from a trusted source; mixed-binary rolling upgrades are unsupported. The final Stack v4 source/target matrix and release procedure are blockers for this runbook. Do not approve a production upgrade from this page alone, and do not infer server compatibility from the `ledgerctl upgrade` command.

## Expect usage statistics to rebuild

Ledger v3 moves the counters returned by ledger statistics, together with Numscript template usage, into a local derived store on every member. The first v3 start resets the migrated counters and rebuilds them from the audit entries still available to that member.

This transition does not change transactions, balances, or account metadata. It can, however, make posting, revert, Numscript execution, reference, ephemeral-account, transient-account, volume, and template-usage figures start at zero and rise while the background rebuild runs.

Watch these three gauges on every member:

| Metric                                                | What it tells you                                             |
| ----------------------------------------------------- | ------------------------------------------------------------- |
| `formance.ledger.usage.builder.last_indexed_sequence` | Highest audit sequence already reflected in usage statistics. |
| `formance.ledger.usage.builder.audit_last_sequence`   | Highest audit sequence currently available to the builder.    |
| `formance.ledger.usage.builder.lag`                   | Number of available audit sequences still to process.         |

Wait for `formance.ledger.usage.builder.lag` to reach zero before accepting the rebuilt statistics. Do not use the figures for billing, limits, or an upgrade comparison while they are still moving.

Zero lag proves that the member processed the audit history it can still reach. It does not recover counter values from audit entries that were already archived or removed before the upgrade. In that case, the rebuilt values can remain below their historical totals. Ledger 3.0 does not provide a public full-rebuild command that can recover those missing values; record the limitation and reconcile critical figures against your own source of truth.

## Identify the four versions

Record these values before planning the change:

| Artifact                | Source of truth                                        | Why it matters                                                               |
| ----------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------- |
| Stack release           | The selected Stack version and its `Versions` resource | Resolves the component set intended to run together.                         |
| Formance Stack Operator | Installed controller and CRD versions                  | Determines which desired state and status fields are supported.              |
| Ledger server           | Image digest and Ledger version resolved by Stack      | Determines API behavior and persisted-format compatibility.                  |
| `ledgerctl`             | `ledgerctl version` or the packaged artifact           | Determines available administrative commands; it does not change the server. |

Pin image digests and released versions rather than mutable tags. The change record must contain both the source and target values.

## Precheck the upgrade

Do not start until every item has evidence:

1. The release matrix explicitly supports the source-to-target Stack, Operator, Ledger, and CLI path.
2. Release notes identify API, configuration, security, storage, and operational changes.
3. The previous server version can read state written by the target version if binary rollback is part of the plan.
4. The current cluster has a leader, the expected voters, and no member catching up.
5. The cluster can lose one voter and remain within its service objective during the rollout.
6. WAL, data, memory, and node-pool headroom cover restart and catch-up.
7. Required authentication, TLS trust, signing keys, and client versions support the mixed-version window.
8. A recent backup has restored successfully into an isolated cluster using the documented release path.
9. Dashboards, paging alerts, and the maintenance owner are active.
10. Clients send idempotency keys and honor retry guidance for transient `Unavailable` responses.

```bash
ledgerctl cluster status
ledgerctl cluster disk-usage --json
```

Repeat the disk check against every member endpoint. Capture a controlled write and current read as the pre-upgrade baseline.

## Choose the upgrade class

The published procedure for your source and target releases must name one of three upgrade classes. If it names none, stop and obtain a release decision rather than inferring the class from a successful single-node restart.

| Class               | When it applies                                                                                                                                    | What it requires                                                                                                                             |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| Rolling             | The target revision explicitly supports mixed binaries on the existing storage schema, and the cluster can lose one voter while traffic continues. | Restart members one at a time under load, as in _Roll the cluster only when the release permits it_ below.                                   |
| Coordinated restart | The persisted state is compatible, but two binaries can apply the same committed entry differently.                                                | Stop every member behind a maintenance barrier before any target binary starts, as in _Restart the cluster in one coordinated window_ below. |
| Rebuild or restore  | The persisted or backup format is incompatible.                                                                                                    | Follow the target revision's own reset, replay, or restore instructions. This is the current Ledger 3.0 preview case.                        |

Also use [maintenance mode](https://docs.formance.com/v4.0/modules/ledger/operations/maintenance-mode) within a rolling upgrade when the release notes require a stable write boundary, when a configuration or storage transition cannot accept concurrent mutations, or when the rollout owner cannot safely validate mixed members under load.

Maintenance mode does not make an unsupported downgrade safe.

## Roll the cluster only when the release permits it

This section applies only when the released compatibility matrix permits a mixed-version rolling change. For the coordinated-restart class, use the next section instead. For rebuild or restore, follow the target revision's own procedure.

Change only the supported Stack version declaration. The Stack Operator should resolve the target Ledger image and coordinate the member sequence; do not edit the Ledger workload or membership manually underneath it.

The rollout must follow this observable sequence:

1. Update one follower.
2. Wait for the process to become ready.
3. Wait for it to rejoin the same cluster and catch up to the committed position.
4. Confirm that it remains a voter and can serve the intended read path.
5. Send a controlled idempotent write and current read through the service.
6. Confirm that error rate, latency, queue, WAL, disk, and memory signals remain within the rollback thresholds.
7. Continue with the next follower.
8. Transfer leadership to an updated, caught-up voter when the workflow requires it.
9. Update the former leader last.

Watch Ledger membership independently from Kubernetes reconciliation:

```bash
ledgerctl cluster watch --interval 2s
```

Pause when a member cannot catch up, the cluster loses a leader, a second voter becomes unavailable, the resolved image differs from the target, or a safety threshold is crossed. A completed Kubernetes rollout is not proof that Ledger membership or state converged.

## Restart the cluster in one coordinated window

Use this section for the coordinated-restart class: the persisted state is compatible, but two binaries must never apply the same committed entry. Every member stops before any target binary starts, so there is no mixed-version window to validate.

Enable maintenance mode first, and confirm that the cluster state reports it and that writes are rejected:

```bash
ledgerctl cluster maintenance enable
ledgerctl cluster status --json
```

Read `raftStatus.commit` from the leader once maintenance mode is visible in that output. That index is the barrier; call it `C`. Then query every voter and require a normal `syncProgress.status` and a `raftStatus.lastPersistedIndex` at or above `C` before stopping it:

```bash
ledgerctl cluster status --node-id <node-id> --json
```

`lastPersistedIndex` is the storage-side cursor: it advances only after the member's write batch has committed to disk, so it, rather than `applied`, is what proves the member durably applied every entry through the barrier under the old binary.

Then complete the window in order:

1. Stop or finish any cluster-internal job that can still propose work, and repeat the per-voter barrier check if the leader's commit index advanced.
2. Stop every member. Do not start a target binary while any member still runs the old one.
3. Replace every server binary or image.
4. Start enough voters to form quorum, then start the remaining members.
5. Verify cluster health and run the documented integrity check.
6. Disable maintenance mode last, then resume traffic in controlled stages.

## Verify the upgraded cluster

After every member reports the target version:

1. Run `ledgerctl cluster status` and confirm the expected leader, voters, and applied positions.
2. Confirm that the Stack status and actual image digests match the target release.
3. Send a controlled write with a new idempotency key and read it back with current consistency.
4. Exercise the write through each externally reachable endpoint to detect follower-forwarding or trust failures.
5. Verify required indexes, prepared queries, event sinks, backup schedules, and `formance.ledger.usage.builder.lag` on every member.
6. Test allowed and denied authorization paths and any required request or response signatures.
7. Run the documented integrity check at the scope and time approved for the cluster.
8. Compare request latency, error rate, queue, WAL, compaction, disk, and memory against the baseline.
9. Keep the change window open for at least one representative compaction and background-work cycle.

If maintenance mode was enabled, complete these checks before reopening, then resume traffic in controlled stages.

## Roll back safely

Stop the rollout first. Keep the healthy existing voters running and preserve every volume and node identity.

Reapply the previous Stack release only when the published compatibility matrix confirms that:

- the previous Operator understands the current CRDs or the downgrade sequence handles CRDs explicitly;
- the previous Ledger binary can read all persisted state written by the target version;
- no irreversible configuration or data transition has completed;
- authentication and TLS still support the mixed window.

Roll members back one at a time with the same quorum and catch-up checks. If any condition is not confirmed, do not attempt a binary downgrade. Keep writes stopped when required, preserve evidence, and follow the target release's forward-recovery or restore procedure.

A backup is a disaster-recovery input, not proof that a runtime downgrade is safe. Restoring it replaces cluster state and requires the separate restore runbook and business approval.

## Update `ledgerctl` separately

`ledgerctl upgrade` replaces the local CLI binary. It does not upgrade Ledger servers or the Stack.

Check the latest stable CLI release without installing it:

```bash
ledgerctl upgrade --channel stable --dry-run
```

Install the latest stable CLI only when that version is approved by the Stack compatibility matrix:

```bash
ledgerctl upgrade --channel stable
```

The command verifies the downloaded archive checksum before replacing the binary. Its default channel is `nightly`, so always name `stable` in a production procedure. When the change requires an exact CLI version rather than the latest stable one, install the pinned release artifact through your normal package or image workflow instead.

After changing the CLI, verify its version, connection profile, TLS trust, authentication, request signing, and response verification before using an administrative mutation.
