# Prepare a Ledger Deployment

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

Stack: v4.0

Deploy Ledger through Stack v4 and the Formance Stack Operator. A production deployment needs more than running pods: it needs a voting topology, durable node identities, enough storage and memory, protected network paths, and telemetry that proves the cluster can commit writes.

The Stack v4 production resource schema is not available in this preview. Use the direct-server workflow below only for evaluation. Wait for the release-specific Stack Operator reference before applying a production Ledger resource.

## Evaluate Ledger with a direct server

This workflow starts one Ledger process directly for evaluation and integration development. It does not provide production scheduling, failure-domain placement, secret distribution, rolling convergence, or automated recovery. Use Stack v4 and its released Operator workflow for production.

The direct server opens three listeners by default:

| Port   | Surface                                 | Exposure for this evaluation                                                                                                                                                      |
| ------ | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `7777` | Raft transport and cluster join         | `--bind-addr` defaults to `0.0.0.0:7777`. Pass `--bind-addr 127.0.0.1:7777` as the examples below do, and do not expose the port to application clients.                          |
| `8888` | Public gRPC service used by `ledgerctl` | The direct server listens on the configured port on all interfaces. Keep the host firewalled and connect through `localhost` with `--insecure` only in this plaintext evaluation. |
| `9000` | HTTP API and health probes              | The direct server listens on the configured port on all interfaces. Keep the host firewalled and use `localhost` for the Quick Start.                                             |

### Bootstrap the first start once

Create distinct paths for the Raft WAL and Ledger data:

```bash
mkdir -p .ledger-evaluation/node-1/wal .ledger-evaluation/node-1/data
```

Start the first node in a terminal:

```bash
ledger run \
  --node-id 1 \
  --cluster-id local-evaluation \
  --bind-addr 127.0.0.1:7777 \
  --grpc-port 8888 \
  --http-port 9000 \
  --wal-dir ./.ledger-evaluation/node-1/wal \
  --data-dir ./.ledger-evaluation/node-1/data \
  --bootstrap
```

`--bootstrap` creates a new single-voter cluster. Use it only for this node's first start. A fresh node that has neither `--bootstrap` nor `--join` stops with `first start requires --bootstrap or --join`.

### Wait for the process and the cluster

Run the checks from another terminal:

```bash
curl --fail --silent --show-error http://localhost:9000/livez
curl --fail --silent --show-error http://localhost:9000/readyz

until curl --fail --silent --show-error http://localhost:9000/clusterz; do
  sleep 1
done

ledgerctl \
  --server localhost:8888 \
  --insecure \
  cluster status
```

Each HTTP probe returns:

```json
{"data":{"status":"ok"}}
```

The probes answer different questions:

| Probe       | Meaning                                                                                                                                                 |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/livez`    | The HTTP process is running.                                                                                                                            |
| `/readyz`   | The local Raft loop started. It can return `200` before the cluster elects a leader, so use it for process orchestration rather than traffic admission. |
| `/clusterz` | The local node is connected to a healthy Raft state and sees an elected leader. Wait for this before a client sends cluster-dependent traffic.          |

Disk and clock protection can still reject writes after `/clusterz` succeeds. Monitor those gates separately. `cluster status` must show node `1` as a voter and the current leader in this single-node evaluation.

### Restart without bootstrap

Stop the process cleanly, then restart it with the same identity and storage paths and without `--bootstrap`:

```bash
ledger run \
  --node-id 1 \
  --cluster-id local-evaluation \
  --bind-addr 127.0.0.1:7777 \
  --grpc-port 8888 \
  --http-port 9000 \
  --wal-dir ./.ledger-evaluation/node-1/wal \
  --data-dir ./.ledger-evaluation/node-1/data
```

Wait for `/clusterz` again, then run `ledgerctl cluster status`. The same node must return as voter and leader. Ledger persists the node ID and cluster ID with its data and keeps the consensus identity and history in the WAL directory. Changing either identity or attaching another node's directory causes startup validation to fail; do not delete either path to work around that failure.

### Understand the direct multi-node boundary

A fresh additional process joins through the Raft address of an existing member with `--join <host:7777>`. Give every member a unique non-zero node ID, advertised endpoint, WAL directory, and data directory. Processes sharing one host also need distinct Raft, gRPC, and HTTP ports. Use `--join` only for that member's first start. After the cluster accepts it, restart the same member with its original paths and without `--join` or `--bootstrap`.

Direct multi-node operation also requires TLS and one shared cluster secret before the Raft or gRPC listeners cross a trusted loopback boundary. It remains an advanced development path, not a substitute for the Stack v4 production workflow. Follow [Plan Topology and Manage Cluster Lifecycle](https://docs.formance.com/v4.0/modules/ledger/operations/cluster-lifecycle) for membership checks and stop conditions.

## Before you deploy

Confirm these prerequisites with the platform and application owners:

| Area          | Required decision                                                                                                                                                                          |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Release       | Pin one Stack v4 release whose version manifest resolves Ledger to `3.0.0` and identifies compatible Operator and CLI versions.                                                            |
| Topology      | Use three voting replicas as the normal production starting point. Choose five only when the additional failure tolerance justifies the consensus and operating cost.                      |
| Placement     | Spread voters across independent Kubernetes nodes and, where available, failure zones. Prevent routine disruption from removing quorum.                                                    |
| Storage       | Give every member its own retained persistent storage for the Raft WAL and Ledger data. Confirm expansion support, IOPS, encryption, and the retention policy before creating the cluster. |
| Capacity      | Size every voter for the complete dataset and workload, including compaction, index builds, backup staging, and catch-up.                                                                  |
| Security      | Prepare client authentication, internal TLS, network policy, and secrets without placing credentials in the Stack resource or Git.                                                         |
| Observability | Route metrics, traces, and logs to an owned backend. Preserve cluster and node labels so operators can distinguish a cluster-wide failure from one slow replica.                           |
| Recovery      | Define RPO and RTO, choose object storage, and schedule an isolated restore test.                                                                                                          |

Review [Plan Capacity and Tune Performance](https://docs.formance.com/v4.0/modules/ledger/operations/capacity-and-performance) before choosing resource requests or volume sizes. Review [Plan Topology and Manage Cluster Lifecycle](https://docs.formance.com/v4.0/modules/ledger/operations/cluster-lifecycle) before choosing replica count and disruption settings.

## Verify Stack v4 supports your deployment

Before production, confirm that the Stack Operator reference shipped with your selected release explains how to declare and observe all of the following:

- the Stack v4 version selection and the resolved Ledger image;
- voting replicas, failure-domain placement, and disruption controls;
- distinct WAL and data persistence, storage classes, sizes, and retention;
- CPU, memory, `GOMEMLIMIT`, and supported Ledger tuning settings;
- public HTTP and gRPC exposure, internal peer traffic, and TLS;
- authentication and secret references;
- OpenTelemetry export and stable cluster/node resource attributes;
- backup credentials and schedules when managed by the Operator;
- reconciliation conditions for bootstrap, learner catch-up, voter promotion, readiness, and failure;
- the supported pause, rollback, and deletion behavior.

If the released reference omits one of these controls, resolve it before production rather than guessing a resource field.

## Deploy the cluster

### 1. Run the precheck

1. Install the Operator and its CRDs using the [self-hosted Operator setup](https://docs.formance.com/v4.0/deploy/self-hosted/installation/operator-setup).
2. Confirm that the installed CRD and controller versions match the selected Stack v4 release.
3. Confirm that all target failure zones can provision the selected persistent volumes.
4. Confirm that the node pool can schedule all voters at their requested CPU and memory at the same time.
5. Test access from the Ledger namespace to the telemetry, identity, and backup services it will use.
6. Record the expected Stack, Ledger, and Operator versions in the change request.

Do not continue while an existing resource uses the intended cluster identity or while retained volumes from another member could be attached to the new cluster.

### 2. Apply the supported Stack v4 resources

Use the exact resource shape from the Stack Operator reference shipped with the selected release. Keep the declaration in version control, keep secrets in the configured secret manager, and review the rendered diff before applying it.

The first member bootstraps the cluster. Additional members must join as learners, catch up, and become voters. Do not open application traffic while reconciliation still reports a learner, a restoring member, or an unresolved version.

### 3. Observe reconciliation

Follow the Stack and Ledger status until:

- the Operator reports the selected Ledger version on every member;
- the expected members exist with distinct identities and persistent volumes;
- one member is the leader;
- every intended replica is a voter rather than a learner;
- no member is still restoring, synchronizing, or restarting;
- the HTTP and gRPC services expose only the intended network paths;
- telemetry contains one series of cluster-level signals and distinct node labels.

Operator readiness is necessary, but it does not replace the Ledger checks below.

## Verify the deployment

Configure `ledgerctl` with the production endpoint and credentials, then inspect the cluster:

```bash
ledgerctl cluster status
ledgerctl ledgers list --json
```

`cluster status` must show a leader, the expected member count, the expected voter roles, and no unexplained gap between the committed and applied positions. Query a specific member when the cluster view suggests that one replica is behind:

```bash
set -euo pipefail

ledgerctl cluster status --json > cluster-status.json
MEMBER_ID="$(
  jq -er '
    . as $cluster
    | [
        .nodes[]
        | select(
            .id != $cluster.leader
            and (
              .progress.match != $cluster.raftStatus.commit
              or .progress.recentActive != true
              or ((.syncProgress.status // "normal") != "normal")
            )
          )
      ]
    | sort_by(.id)
    | .[0].id
  ' cluster-status.json
)"

ledgerctl cluster status --node-id "$MEMBER_ID"
```

The extraction selects the lowest-ID follower whose replication position, activity, or sync state needs investigation. It exits without choosing an arbitrary member when the cluster view contains no such follower. Review `cluster-status.json` first when several members are affected.

Complete these independent checks before opening traffic:

1. Send a controlled, idempotent write to a non-production verification ledger and read it back with current-read consistency.
2. Repeat the read and write path through every externally reachable endpoint so a follower-forwarding or trust error cannot hide behind the leader.
3. Confirm that an unauthorized read or write returns the expected `401` or `403` result.
4. Confirm that the no-leader, disk, queue, process-memory, and write-stall alerts are loaded and routed to an owner.
5. Build every index required by the launch workload and wait for readiness on every replica.
6. Produce a backup, restore it into an isolated cluster, and run the integrity and business checks.

The deployment result is a cluster that can commit a controlled write, serve the corresponding current read, lose one voter within its designed tolerance, and produce actionable telemetry.

## Roll back or stop safely

Before application traffic or production data exists, revert the Stack declaration through the Operator and follow the documented persistent-volume retention policy.

After production data exists:

- stop the rollout when a member cannot catch up or the cluster loses its expected failure tolerance;
- do not delete persistent volumes, change node identities, or bootstrap another member over existing state;
- do not downgrade the Ledger image unless the release compatibility matrix confirms that the previous binary can read the current persisted format;
- preserve the cluster state and follow [Upgrade Ledger](https://docs.formance.com/v4.0/modules/ledger/operations/upgrade) or the relevant recovery runbook.

If deployment validation fails, keep traffic closed. Capture the Stack conditions, resolved versions, `ledgerctl cluster status`, affected node logs, and volume state, then start with [Troubleshoot Ledger](https://docs.formance.com/v4.0/modules/ledger/operations/troubleshooting).
