# Plan Capacity and Tune Performance

Source: https://docs.formance.com/v4.0/modules/ledger/operations/capacity-and-performance

Stack: v4.0

Plan capacity from the workload and recovery objective, not from a universal transactions-per-second number. Every voter stores the cluster state, applies every committed write, and needs enough headroom to compact, build indexes, create [checkpoints](https://docs.formance.com/v4.0/modules/ledger/querying/consistency-and-checkpoints), and catch up after an interruption.

## Build the workload profile

Measure or estimate these inputs before choosing resources:

| Input                                                     | Why it changes capacity                                                                       |
| --------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| Peak and sustained write rate                             | Sets the CPU, WAL, consensus, and compaction load.                                            |
| Postings and accounts per transaction                     | Increases validation, state updates, serialized size, and cache lookups.                      |
| Numscript programs and variables                          | Unique script text consumes parse and cache work; account fan-out increases preload work.     |
| Bulk request size and concurrency                         | Trades network and consensus overhead for request memory, latency, and retry blast radius.    |
| Active accounts and metadata                              | Determines hot-cache working set and point-read pressure.                                     |
| Retention requirements                                    | Determines long-term data volume; history is permanent, so see the growth note below.         |
| Required indexes and query rate                           | Consumes read-index disk, memory, I/O, and background build work.                             |
| Event delivery, backup, restore, and usage reconstruction | Adds source reads, serialization, network transfer, background writes, and temporary storage. |
| Recovery objective                                        | Determines how quickly a voter or full cluster must catch up or restore.                      |

Include normal peak traffic and a recovery scenario in the same test. A cluster that meets latency targets only when every voter is current has not proved its catch-up capacity.

## Size storage per voter

Every voting member needs space for:

- the latency-sensitive Raft WAL and its spool;
- Ledger data and retained history;
- derived read indexes;
- compaction overlap and temporary files;
- checkpoints and backup staging;
- the local usage projection at `<data-dir>/usage/usagedb`;
- catch-up or restore work;
- growth during the time needed to approve and complete a volume expansion.

Use fast persistent storage for the WAL. Separate WAL and data I/O when the platform and Stack Operator support it, then monitor both volumes independently.

History is permanent

Ledger 3.0 has no retention, archival, or cold-storage tier: the global log and audit history grow for the life of the cluster and are never truncated. Deleting a ledger reclaims that ledger's own projections but keeps its entries in the shared history, and the deletion is itself appended to the chain. Plan for monotonic growth — the levers are a compression profile and a volume-expansion path, not a retention policy.

Multiplying the current dataset by the voter count estimates cluster-wide storage cost, not the required size of one voter. Each voter still needs the complete per-node budget.

The usage store is normally small because it contains per-ledger counters and per-template records rather than transaction history. It still consumes data-volume I/O and grows independently on every member. Include its `formance.ledger.usagestore.level.size` and `formance.ledger.usagestore.memtable.size` signals when estimating headroom, especially while a node folds retained audit history after an upgrade or restore.

Ledger protects the cluster with independent high- and low-water marks. The current server defaults block writes at 80% use and resume only after use falls below 75%. This hysteresis prevents repeated open/close cycles near a limit.

Confirm how your Stack version's storage preset maps to these Ledger thresholds before sizing a volume. The Ledger server defaults apply wherever the Operator does not override them.

If disk or clock protection blocks writes, the member stays ready and keeps serving reads. Kubernetes readiness is therefore not proof that the cluster accepts mutations. Inspect the structured error reason and disk state.

| Write gate                                  | HTTP result | Structured reason           | Required response                                                                                      |
| ------------------------------------------- | ----------- | --------------------------- | ------------------------------------------------------------------------------------------------------ |
| WAL or data volume at the block mark        | `429`       | `WRITES_BLOCKED_DISK_FULL`  | Stop non-essential writes, expand or reclaim supported storage, then verify use below the resume mark. |
| Peer clock outside the configured threshold | `503`       | `WRITES_BLOCKED_CLOCK_SKEW` | Restore time synchronization across members; do not disable the check as the first response.           |

Check the member reached by the active `ledgerctl` profile:

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

Repeat the command against every member endpoint because disk usage is node-local.

## Size memory per voter

Ledger reports a conservative startup memory estimate. Use that estimate as a precheck and leave room for the Go runtime, gRPC connections, request bursts, telemetry, and Kubernetes overhead.

The largest configurable consumers at their current defaults are:

| Consumer                        | Current default budget                                                                                            | Main tradeoff                                                                        |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Pebble block cache              | 1 GiB                                                                                                             | More cache reduces data reads but directly increases resident memory.                |
| Pebble memtables                | Up to 1.5 GiB (`256 MiB × 6`)                                                                                     | Smaller buffers save memory but flush more often and reach write stalls sooner.      |
| Read-index cache and memtables  | About 320 MiB                                                                                                     | Smaller values reduce memory but increase query and index-build I/O.                 |
| Usage-store cache and memtables | 16 MiB cache plus up to four 16 MiB memtables before projection writes stop: about 80 MiB before runtime overhead | Usually small, but every member needs the headroom and catch-up adds background I/O. |
| Raft transport buffer           | 10 MiB per peer                                                                                                   | Larger buffers absorb network bursts but scale with member count.                    |
| FSM generation cache            | About 17 MiB at threshold 1,000 (2 generations x 1,000 entries x \~30 keys x \~300 bytes)                         | A larger working set reduces preloads but retains more entries.                      |
| Go runtime                      | \~200 MiB in the startup estimate; actual use is workload-dependent                                               | `GOMEMLIMIT` guides garbage collection but is not a hard container limit.            |

Set `GOMEMLIMIT` below the container memory limit so the runtime reacts before Kubernetes does. Approximately 90% is a starting point, not a guarantee: validate it with your connection count, request sizes, indexes, and telemetry. Fail the deployment precheck when the startup estimate already exceeds `GOMEMLIMIT`.

If a node cannot fit its memory budget, reduce consumers in this order and remeasure after each change:

1. `--pebble-cache-size`;
2. `--pebble-memtable-size`;
3. `--pebble-memtable-stop-writes-threshold`;
4. `--read-index-cache-size` and read-index memtable settings;
5. `--cache-rotation-threshold`.

Each reduction trades memory for disk I/O, preload latency, or earlier write stalls. Increasing memory without fixing insufficient disk throughput can move the failure rather than remove it.

Ledger 3.0 does not expose usage-store tuning as a public server or Stack Operator contract. Budget its default cache, memtables, disk, and catch-up work rather than inventing an unsupported deployment field.

## Establish a baseline

Use a staging cluster with the same voter count, storage class, failure-domain network, security, and telemetry path as production.

1. Load representative history, build the required indexes, and wait for the usage projection to catch up on every member — `formance.ledger.usage.builder.lag` at zero, meaning every available audit sequence has been indexed locally. See [Monitor Ledger](https://docs.formance.com/v4.0/modules/ledger/operations/monitoring).
2. Warm the cluster with normal reads and writes.
3. Run sustained and peak traffic with representative posting width and Numscript variables.
4. Record user request latency and error rate with CPU, memory, queue, WAL, apply, compaction, and disk signals.
5. Stop or restart one follower and measure both Raft catch-up and usage-projection catch-up while traffic continues.
6. Run a backup or index build during controlled load.
7. Keep the test running long enough to observe flush and compaction cycles.

Record the exact Stack release, Ledger version, resource limits, storage class, data size, client concurrency, and request distribution with the result. A number without this context is not a capacity commitment.

## Tune one constraint at a time

| Observed constraint                                      | Candidate change                                                        | Risk                                                                 | Verification and rollback                                                                                                              |
| -------------------------------------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| Read I/O and cache misses are high with memory available | Increase `--pebble-cache-size`                                          | Higher resident memory and OOM risk                                  | Compare read latency, disk reads, and memory; restore the previous value if headroom or latency worsens.                               |
| Write stalls coincide with memtable flush pressure       | Increase memtable budget or storage throughput                          | More memory or cost                                                  | Require fewer stalls without breaching memory; roll back the setting if GC or OOM pressure rises.                                      |
| Preload latency is high for an active working set        | Increase `--cache-rotation-threshold`                                   | More FSM cache memory and a rolling cluster change                   | Compare preload latency and memory; follow the rolling-change procedure to restore the prior threshold.                                |
| Query and index-build reads are I/O-bound                | Increase read-index cache or improve disk                               | More memory or storage cost                                          | Compare query latency, build time, memory, and compaction before and after.                                                            |
| Peer queues fill during network bursts                   | Fix peer latency or review transport buffers                            | Larger buffers can hide a persistently slow peer and use more memory | Require queue-full events to stop without increasing catch-up time or memory beyond budget.                                            |
| Numscript cache churn is high                            | Reuse program text with variables, then review `--numscript-cache-size` | A larger cache does not fix generated scripts                        | Verify stable script text and parse/cache behavior; restore the prior size if memory rises without a hit-rate benefit.                 |
| Large requests dominate tail latency                     | Reduce bulk size or concurrency                                         | Lower throughput                                                     | Compare throughput, p99 latency, memory, and retry blast radius; restore the previous client setting if the service objective worsens. |

These are correctness changes, not tuning

Do not disable the Pebble WAL (`--pebble-disable-wal`), weaken hash integrity, relax durability, or bypass validation to reach a benchmark target. Treat every one of those as a correctness change, not performance tuning.

## Apply a capacity change

### Precheck

1. Capture the baseline and the exact limiting signal.
2. Define the expected improvement, safety limit, and rollback trigger.
3. Confirm healthy quorum and current backups.
4. Confirm whether the setting is node-local, cluster-wide, persisted, or immutable.
5. Confirm the setting is supported by your Stack version's Operator fields; do not add an unsupported server flag to a workload template.

### Change and verify

Apply one declared change through the Stack Operator. For a rolling setting, change one follower, wait for catch-up, transfer leadership to an updated voter when required, then change the former leader. Follow [Upgrade Ledger](https://docs.formance.com/v4.0/modules/ledger/operations/upgrade) for the full sequence.

After the rollout:

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

Repeat the same workload and compare the agreed user and resource metrics. Keep the change only if it improves the measured constraint without reducing quorum, recovery headroom, correctness, or another service objective.

### Roll back

Stop the rollout at the first safety trigger. Restore the previous declared setting through the same Operator path, one member at a time when required. Wait for every member to catch up and repeat the controlled write/read and integrity checks. Do not combine several compensating tuning changes during rollback; that removes the baseline needed to understand the result.
