# Choose Read Consistency and Use Checkpoints

Source: https://docs.formance.com/v4.0/modules/ledger/querying/consistency-and-checkpoints

Stack: v4.0

Choose read consistency from the business consequence of stale or changing data. A user-facing balance usually needs a fresh live read. A dashboard can often accept bounded lag. A reconciliation that spans several requests needs a query checkpoint.

A query checkpoint freezes one committed sequence of the ledger so that many reads — several queries, and every page of each — all describe the same unchanging state, even while writes continue.

The commands assume an authenticated `ledgerctl` profile, `jq`, and `export LEDGER_NAME=main`. Entity reads require their normal read scopes. Creating or deleting a query checkpoint, and setting or deleting its schedule, requires `ledger:ClusterWrite`; listing, inspecting, or reading the schedule requires `ledger:ClusterRead`. See [Authentication and Authorization](https://docs.formance.com/v4.0/modules/ledger/operations/authentication).

## Choose a live-read mode

Both APIs accept a consistency level on reads. HTTP reads take it in the `X-Consistency` request header, and gRPC reads take it in the `x-consistency` metadata field. `ledgerctl` exposes it as a global `--consistency` flag.

A read barrier is a round-trip to a majority of nodes that confirms the reading node has seen every committed write; it costs latency and needs that majority reachable.

| Mode           | Guarantee                                                                                                | Cost and availability                                                                                                                                | Use it for                                                           |
| -------------- | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| `linearizable` | Confirms the latest committed state with the cluster before reading                                      | Uses a Raft read barrier, requires a working quorum, and can wait while the node catches up                                                          | Balances, transaction confirmation, decisions based on current state |
| `stale`        | Reads the contacted node's local state without a read barrier, and never forwards the read to the leader | Can return older committed data. A read that uses an index or the audit trail still waits for that node's local index to catch up with its own state | Dashboards, diagnostics, and other lag-tolerant views                |

`linearizable` is the default for both gRPC and HTTP reads. A missing or empty value selects it. Values are matched without regard to case or surrounding whitespace:

```bash
# Default linearizable read
ledgerctl accounts get users:alice --ledger "$LEDGER_NAME"

# Read local state without waiting for a barrier
ledgerctl --consistency stale accounts list --ledger "$LEDGER_NAME" --page-size 100
```

Over HTTP, send the header on the read. This example uses the `LEDGER_URL` and `CURL_AUTH` connection from [Read Ledger Data](https://docs.formance.com/v4.0/modules/ledger/querying/read-ledger-data):

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  -H "X-Consistency: stale" \
  --data-urlencode 'pageSize=100' \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts"
```

Do not use `stale` for a check that authorizes a withdrawal, confirms a write, or decides whether money can move. The response can predate a write that another caller has already observed.

The two transports treat an unrecognized value differently. HTTP rejects an unknown value, a repeated `X-Consistency` header, or a comma-separated list of values with `400 INVALID_REQUEST` before reading anything. It applies this check to every `/v3` route, writes included, although a valid value has no effect on a write. gRPC ignores an unknown value and serves a linearizable read, and it reads only the first `x-consistency` value. Ledger 3.0 has no `leader` mode. HTTP rejects `leader`, while gRPC and `ledgerctl --consistency leader` serve a linearizable read without an error.

The direct HTTP list routes do not expose checkpoint or minimum-sequence options. Each response therefore reflects live state, and two requests can observe different commits while writes continue. A linearizable barrier also does not guarantee that asynchronous query indexes have processed that state. Use gRPC or `ledgerctl` for a fixed checkpoint or a minimum-sequence control.

## Wait for the read index

A successful write can return before the node serving a later query has indexed that write. The read index is the replica's local view optimized for queries. When a follow-up query must include a write, capture the highest global log sequence from the full gRPC `ApplyResponse` and pass that value as `minLogSequence` or `--min-log-sequence`.

The following example assumes the application saved the complete response as `apply-response.json`:

```bash
MIN_LOG_SEQUENCE="$(
  jq -er '
    .logs[-1].sequence // error("the response contains no new log sequence")
    | tostring
  ' apply-response.json
)"
TRANSACTION_ID="$(
  jq -er '
    [.logs[]
      | .payload.apply.log.data.createdTransaction.transaction.id // empty]
    | if length > 0 then .[0] | tostring
      else error("the response contains no created transaction")
      end
  ' apply-response.json
)"
TRANSACTION_FILTER="$(
  jq -nc --arg id "$TRANSACTION_ID" '
    {"$and":[{"$gte":{"id":$id}},{"$lte":{"id":$id}}]}
  '
)"

ledgerctl transactions list \
  --ledger "$LEDGER_NAME" \
  --filter "$TRANSACTION_FILTER" \
  --min-log-sequence "$MIN_LOG_SEQUENCE" \
  --page-size 2 \
  --json \
  | jq -e --arg id "$TRANSACTION_ID" \
      'any(.[]; (.id | tostring) == $id)'
```

`ApplyResponse.logs` is returned in commit order, so the last entry carries the highest sequence produced by that proposal. A response with no fresh log produced no new sequence to wait for, so the filter raises an error rather than yielding the string `null`, which `--min-log-sequence` would otherwise accept. The final `jq` prints `true` and exits with status `0` only when the read contains the transaction returned by the write. Direct gRPC list and aggregation calls wait until the contacted node has indexed `MIN_LOG_SEQUENCE`, or until the request times out. Do not estimate this value from a transaction ID or a timestamp.

`ledgerctl transactions create --json` prints the created transaction, not the full `ApplyResponse` wrapper. An application that needs a sequence bound must retain `logs[].sequence` from its gRPC `Apply` call, or obtain the correlated global sequence through the [transaction-to-audit trace](https://docs.formance.com/v4.0/modules/ledger/querying/read-ledger-data#trace-a-successful-transaction).

`minLogSequence` guarantees general read-index progress. It does not prove that an index backfill or metadata-index version transition has switched to its new version. Verify index readiness separately on every serving replica.

The REST prepared-query execution route is the one HTTP query surface that accepts `minLogSequence` in its request body. Prepared-query execution uses it as a freshness gate rather than waiting inside the request. On gRPC, prepared-query execution returns `READ_INDEX_NOT_CAUGHT_UP` when the local index is behind, which a client can retry with bounded backoff; use that surface for reason-specific retries in v3.0. This one-shot gate is specific to prepared-query execution: the direct gRPC list and aggregation calls above wait instead of returning that reason. The direct account, transaction, log, and audit list routes do not expose the field.

Support differs by operation. Every row below describes the gRPC and `ledgerctl` surfaces, not the direct HTTP list routes:

| Operation (gRPC and `ledgerctl`)  | `minLogSequence`         | Query checkpoint                          |
| --------------------------------- | ------------------------ | ----------------------------------------- |
| Account, transaction, or log list | Yes                      | Yes                                       |
| Audit list                        | Yes                      | Yes, with the filtered-read warning below |
| Audit get or `--expand`           | No                       | No                                        |
| Account volume aggregation        | Yes                      | Yes                                       |
| Prepared-query execution          | Yes, as a freshness gate | No                                        |
| Ledger statistics                 | No                       | Yes, with limited counter semantics       |
| Account or transaction analysis   | No                       | No                                        |

## Freeze a view with a query checkpoint

A checkpoint captures both the ledger data and its derived query data at that sequence, so a checkpoint-scoped read never mixes a frozen entity with a live index.

```mermaid
flowchart LR
    Writes["Live writes continue"] --> Live["Current ledger state"]
    Live -->|"create checkpoint"| Frozen["Frozen main store and read index"]
    Frozen --> A["Account pages"]
    Frozen --> T["Transaction pages"]
    Frozen --> V["Volume aggregation"]
    A --> Reconciliation["One consistent reconciliation"]
    T --> Reconciliation
    V --> Reconciliation
```

Create the checkpoint and derive both returned values from the command output:

```bash
CHECKPOINT_JSON="$(ledgerctl query-checkpoint create --json)"
CHECKPOINT_ID="$(jq -er '.checkpointId | tostring' <<<"$CHECKPOINT_JSON")"

cleanup_checkpoint() {
  local exit_status=$?
  trap - EXIT INT TERM

  if [ -n "${CHECKPOINT_ID:-}" ]; then
    if ! ledgerctl query-checkpoint delete "$CHECKPOINT_ID"; then
      printf '%s\n' \
        "Checkpoint cleanup failed for ID: $CHECKPOINT_ID" \
        "Ledger will not delete this checkpoint automatically." \
        "Delete it manually after resolving the error:" \
        "  ledgerctl query-checkpoint delete $(printf '%q' "$CHECKPOINT_ID")" \
        >&2

      if [ "$exit_status" -eq 0 ]; then
        exit_status=1
      fi
    fi
  fi

  exit "$exit_status"
}
trap cleanup_checkpoint EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

# Parsed after the trap is armed: a failure here must still delete the
# checkpoint the create call already made durable.
CHECKPOINT_MAX_SEQUENCE="$(jq -er '.maxSequence | tostring' <<<"$CHECKPOINT_JSON")"

CHECKPOINT_REGISTERED=false
EXPECTED_NOT_FOUND="query checkpoint $CHECKPOINT_ID not found"

for attempt in {1..30}; do
  if CHECKPOINT_INFO="$(
    ledgerctl query-checkpoint info "$CHECKPOINT_ID" --json \
      2>checkpoint-info.err
  )"
  then
    if ! jq -e \
      --arg id "$CHECKPOINT_ID" \
      --arg max "$CHECKPOINT_MAX_SEQUENCE" '
        (.checkpointId | tostring) == $id
        and (.maxSequence | tostring) == $max
      ' <<<"$CHECKPOINT_INFO"
    then
      exit 1
    fi

    CHECKPOINT_REGISTERED=true
    break
  fi

  if ! grep -Fq "$EXPECTED_NOT_FOUND" checkpoint-info.err; then
    cat checkpoint-info.err >&2
    exit 1
  fi

  sleep 2
done

if [ "$CHECKPOINT_REGISTERED" != true ]; then
  cat checkpoint-info.err >&2
  exit 1
fi
```

The `tostring` conversions are required, not defensive noise: `query-checkpoint create --json` reports `checkpointId` and `maxSequence` as JSON numbers, while `query-checkpoint info --json` reports the same two fields as JSON strings, so the comparison must be made on a common type. This check prints `true` only when one contacted replica has registered the exact checkpoint that was just created. A replica that has not yet applied the creation can temporarily return `NotFound`, so the loop retries only the exact captured ID and stops on every other error. Keep `CHECKPOINT_ID` in the same job that performs and later deletes the reconciliation.

The `EXIT` trap is a last-resort cleanup guard, not a retention policy. An interrupt exits with status `130`, a termination signal exits with status `143`, and the cleanup preserves any other existing failure status. If its deletion fails, it prints the captured checkpoint ID and the exact manual command instead of hiding the failure. Ledger does not expire the checkpoint automatically.

There is no separate `READY` field in checkpoint information. A successful checkpoint-scoped read is the readiness criterion for the replica that served it. Probe with bounded retries:

```bash
CHECKPOINT_READY=false
EXPECTED_NOT_READY="query checkpoint $CHECKPOINT_ID read index is still building"

for attempt in {1..30}; do
  if ledgerctl accounts list \
    --ledger "$LEDGER_NAME" \
    --checkpoint-id "$CHECKPOINT_ID" \
    --page-size 1 \
    --json \
    >/dev/null 2>checkpoint-read.err
  then
    CHECKPOINT_READY=true
    break
  fi

  if ! grep -Fq "$EXPECTED_NOT_READY" checkpoint-read.err; then
    cat checkpoint-read.err >&2
    exit 1
  fi

  sleep 2
done

if [ "$CHECKPOINT_READY" != true ]; then
  cat checkpoint-read.err >&2
  exit 1
fi
```

The gRPC error carries `CHECKPOINT_NOT_READY` in `google.rpc.ErrorInfo.reason`. Application clients should retry only that reason. Ledger v3.0's `ledgerctl` output omits the structured reason, so the shell loop matches the exact server message and checkpoint ID that represent it; every other failure stops immediately.

The probe proves readiness only for the replica that served it. Keep subsequent reconciliation reads on that ready route, or repeat the probe against every pod-direct endpoint that can receive them.

Use the same captured ID for every read in the reconciliation:

```bash
ledgerctl accounts list \
  --ledger "$LEDGER_NAME" \
  --checkpoint-id "$CHECKPOINT_ID" \
  --page-size 500 \
  --json

ledgerctl transactions list \
  --ledger "$LEDGER_NAME" \
  --checkpoint-id "$CHECKPOINT_ID" \
  --page-size 500 \
  --json

ledgerctl accounts aggregate-volumes \
  --ledger "$LEDGER_NAME" \
  --checkpoint-id "$CHECKPOINT_ID" \
  --json
```

Follow each emitted cursor with the same checkpoint ID until the traversal finishes. Do not switch back to a live read between pages.

Do not combine an audit filter with a checkpoint when completeness is required. In Ledger v3.0, an audit entry that the asynchronous audit index had not processed when the checkpoint was created can remain absent from a filtered checkpoint read. Read the checkpoint's audit stream without a filter, then filter it in the client.

Checkpoint reads ignore `minLogSequence`: the checkpoint already identifies one past sequence.

After every consumer finishes, delete the exact captured checkpoint and verify that it no longer appears in the registry:

```bash
if ! ledgerctl query-checkpoint delete "$CHECKPOINT_ID"; then
  exit 1
fi

CHECKPOINT_DELETED=false

for attempt in {1..30}; do
  if ! ledgerctl query-checkpoint list --json \
    >checkpoint-registry.json 2>checkpoint-registry.err
  then
    cat checkpoint-registry.err >&2
    exit 1
  fi

  if jq -e --arg id "$CHECKPOINT_ID" \
      'all(.[]; (.checkpointId | tostring) != $id)' \
      checkpoint-registry.json >/dev/null
  then
    CHECKPOINT_DELETED=true
    break
  fi

  sleep 2
done

if [ "$CHECKPOINT_DELETED" != true ]; then
  printf '%s\n' \
    "Checkpoint $CHECKPOINT_ID still present in the registry after the delete." \
    "Confirm it against each replica before deleting it again." >&2
  exit 1
fi

CHECKPOINT_ID=""
trap - EXIT INT TERM
```

The loop retries because `list` is served by one replica. Deletion propagates the same way creation does, so a list routed to a replica that has not applied it yet still reports the checkpoint. Without the retry a successful cleanup can exit non-zero, which leaves `CHECKPOINT_ID` set and makes the `EXIT` trap issue a second delete for a checkpoint that is already gone.

Clearing `CHECKPOINT_ID` before disarming the trap is what makes the confirmed path skip that second delete. Absence from the registry does not prove that every replica has reclaimed the checkpoint's disk space. Do not derive a deletion candidate from the most recent list entry; another job may have created a checkpoint in the meantime.

## Handle checkpoint readiness

Checkpoint materialization happens independently on each replica. If a read is routed to a replica that has not yet materialized the checkpoint, it returns `CHECKPOINT_NOT_READY`. Creation waits only for the replica that handled the create command.

Treat the outcomes differently:

| Outcome                                     | Meaning                                                         | Client action                                                                     |
| ------------------------------------------- | --------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `CHECKPOINT_NOT_READY` / gRPC `Unavailable` | The checkpoint exists, but this replica has not materialized it | Retry with bounded backoff or route subsequent reads to the replica that is ready |
| `NotFound`                                  | The checkpoint does not exist or was deleted                    | Stop retrying and confirm the checkpoint ID                                       |

Ledger never returns a partially built checkpoint.

If one replica remains `CHECKPOINT_NOT_READY` beyond your operational timeout, route the reconciliation to a ready replica or recreate the checkpoint. Repeated retries cannot repair a checkpoint that the replica can no longer materialize.

## Schedule checkpoints

Schedule creation when a recurring reconciliation needs predictable cut-off points:

```bash
# Every day at midnight
ledgerctl query-checkpoint set-schedule '0 0 * * *'

ledgerctl query-checkpoint get-schedule
```

The scheduler accepts a standard five-field cron expression or a six-field expression with leading seconds. Only the leader creates the checkpoint when the schedule fires.

Ledger does not delete old query checkpoints automatically. Define a retention policy and use the captured-ID deletion workflow above after every consumer has finished.

```bash
# Disable future scheduled creation
ledgerctl query-checkpoint delete-schedule
```

## Request-signing limitations

In the current 3.0 preview, `ledgerctl query-checkpoint create` and `ledgerctl query-checkpoint delete` call unary gRPC methods that submit unsigned mutations. They fail while mandatory request signing is enabled. A configured checkpoint schedule also submits each scheduled creation unsigned, so the schedule can remain visible without producing checkpoints.

Before enabling mandatory signatures, finish every checkpoint-based reconciliation, delete its captured checkpoint, remove any checkpoint schedule, and verify the checkpoint registry. Existing checkpoint reads remain available after the policy change, but the current CLI cannot delete those checkpoints. Do not depend on checkpoint creation or cleanup again until the deployed release provides a tested signed path for both operations.

## Keep checkpoints distinct from backups

| Mechanism          | Purpose                                                   | Query interface                       | Retention         |
| ------------------ | --------------------------------------------------------- | ------------------------------------- | ----------------- |
| Query checkpoint   | Repeatable, point-in-time application reads               | Ledger read APIs with a checkpoint ID | Explicit deletion |
| Raft snapshot      | Restore consensus state for cluster operation             | Not an application-query surface      | Managed by Ledger |
| Full backup        | Recover a complete durable state                          | Read after restore                    | Backup policy     |
| Incremental backup | Add committed changes since the preceding backup boundary | Read after a compatible restore chain | Backup policy     |

Ledger keeps log and audit history permanently in the primary store, so no history ages out from under a read or from behind a checkpoint. Checkpoint creation takes no sequence argument: a new checkpoint freezes the state current at creation time, and reaching an earlier point means having created a checkpoint then. A query checkpoint is still a read tool, not a disaster-recovery artifact: do not use it as the only copy of ledger data.

Continue with [Create and Manage Indexes](https://docs.formance.com/v4.0/modules/ledger/querying/indexes) when a filtered read needs an opt-in index before it can serve traffic.
