# Analyze and Aggregate Ledger Data

Source: https://docs.formance.com/v4.0/modules/ledger/querying/analyze-and-aggregate

Stack: v4.0

Use analysis to understand the shape of existing accounts and transactions. Use statistics for broad counts, and use volume aggregation when an application needs totals over a defined account set.

- A running Ledger endpoint, from a Stack deployment or a local server

- A bearer token with read and write access, if authentication is enabled

- Bash, curl and jq in your shell

Ledger's base URL depends on how it is deployed. A Ledger server you run yourself answers at the root of its host. Behind a Formance Stack, requests pass through the Stack Gateway, which serves Ledger under `/api/ledger`. If you reach Ledger through your Stack's domain you are going through the Gateway; if you started the server yourself, you are not.

Run the commands for your deployment in a shell, and keep that same shell for the rest of the guide. `set -eo pipefail` stops the shell at the first failing command instead of carrying on with an empty value:

Formance Stack

```bash
set -eo pipefail

export LEDGER_URL="https://stack.example.com/api/ledger"
export LEDGER_TOKEN="<bearer-token>"
CURL_AUTH=(-H "Authorization: Bearer $LEDGER_TOKEN")
```

The token needs `ledger:read` and `ledger:write`. `ledger` is the default auth service name. If your deployment uses another service name, replace `ledger` with your configured name.

Local server, no auth

```bash
set -eo pipefail

export LEDGER_URL="http://localhost:9000"
CURL_AUTH=()
```

`CURL_AUTH` stays empty, so every command below works unchanged whether or not authentication is enabled.

The HTTP examples below use that connection. In addition:

- Configure an authenticated `ledgerctl` profile or provide its connection and authentication flags.
- Select a ledger that already contains representative data, and export its name as `LEDGER_NAME`.
- Before filtering on metadata, declare the field type and wait for its index to become ready.

Grant the scope required by the exact interface:

| Operation                 | HTTP scope                   | gRPC or `ledgerctl` scope |
| ------------------------- | ---------------------------- | ------------------------- |
| Analyze accounts          | `ledger:AccountRead`         | `ledger:AccountRead`      |
| Analyze transactions      | `ledger:AccountRead` in v3.0 | `ledger:TransactionRead`  |
| Read statistics           | `ledger:LedgerRead`          | `ledger:LedgerRead`       |
| Aggregate account volumes | `ledger:AccountRead`         | `ledger:AccountRead`      |

The HTTP and gRPC transaction-analysis scopes differ in Ledger v3.0. Grant only the scope used by the application's chosen interface. See [Authentication and Authorization](https://docs.formance.com/v4.0/modules/ledger/operations/authentication).

These operations answer different questions:

| Operation            | Question                                                              | Read behavior                                                 |
| -------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------- |
| Account analysis     | Which address patterns and metadata keys exist?                       | Full account scan                                             |
| Transaction analysis | Which movement patterns and volume distributions exist?               | Full transaction scan                                         |
| Ledger statistics    | How many records or usage events have been counted?                   | Synchronous boundaries plus local asynchronous usage counters |
| Volume aggregation   | What are the input, output, and balance totals for selected accounts? | Reads every matching account volume                           |

## Analyze account structure

Account analysis groups addresses into patterns and suggests variable segments. Run it before formalizing account types or when reviewing whether the live chart of accounts still matches the intended model.

```bash
ledgerctl accounts analyze \
  --ledger "$LEDGER_NAME" \
  --threshold 10 \
  --json
```

The threshold controls how many distinct children the analyzer accepts before it classifies a segment as variable. A value of `0` uses the server default of `10`.

Capture the HTTP result and verify that the pattern counts cover the scanned accounts:

```bash
ACCOUNT_ANALYSIS="$(curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'variableThreshold=10' \
  "$LEDGER_URL/v3/$LEDGER_NAME/analyze-accounts")"

jq -e '
  .data.totalAccounts as $total
  | ([.data.patterns[].accountCount] | add // 0) == $total
' <<<"$ACCOUNT_ANALYSIS"
```

The check prints `true` and exits with status `0` when every scanned account belongs to one returned pattern. The response also provides fixed and variable segments, examples, distinct-value counts, assets, and metadata keys.

Review each suggestion before turning it into an account type. A changing identifier and a finite business category can look similar to a statistical analyzer but need different constraints in the model.

## Analyze transaction flows

Transaction analysis normalizes posting addresses and groups transactions by movement structure:

```bash
ledgerctl transactions analyze \
  --ledger "$LEDGER_NAME" \
  --threshold 10 \
  --json
```

Capture the HTTP result and verify its totals:

```bash
TRANSACTION_ANALYSIS="$(curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'variableThreshold=10' \
  "$LEDGER_URL/v3/$LEDGER_NAME/analyze-transactions")"

jq -e '
  .data.totalTransactions as $total
  | .data.totalReverted as $reverted
  | (([.data.flowPatterns[].transactionCount] | add // 0) == $total)
    and ($reverted <= $total)
' <<<"$TRANSACTION_ANALYSIS"
```

The check prints `true` only when the flow groups cover the scanned transactions and the reverted count does not exceed the total. Each flow also reports:

- its normalized posting signature;
- a `simple`, `multiSource`, `multiDestination`, or `complex` structure;
- transaction and temporal statistics;
- source and destination patterns;
- asset and color dimensions;
- exact volume strings and metadata keys.

Use the result to find undocumented flows and select representative test cases. The analyzer does not declare an account type, create an index, or change a transaction.

## Make analysis repeatable

Each analysis request uses one internally consistent snapshot, but two separate requests do not share a snapshot. Writes committed between account analysis and transaction analysis can therefore make the two totals describe different moments.

The analysis routes accept neither `minLogSequence` nor a query checkpoint. When a paired result must be reproducible:

1. enter [Maintenance Mode](https://docs.formance.com/v4.0/modules/ledger/operations/maintenance-mode) to pause writes;
2. run both analyses and save their JSON responses;
3. verify the count invariants above;
4. leave maintenance mode only after every required analysis finishes.

If writes cannot pause, treat the result as discovery data. Record when each request started and ended, but do not present the pair as one frozen reconciliation.

Account and transaction analysis scan the complete target. Run them during a planned capacity window on a large ledger.

## Read ledger statistics

Read the live counters with:

```bash
ledgerctl ledgers stats --ledger "$LEDGER_NAME" --json
```

Or use HTTP:

```bash
LEDGER_STATS="$(curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/stats")"

jq '.data' <<<"$LEDGER_STATS"
```

The response contains exactly these counters:

| Counter                                                                                                                                  | Source and freshness                                            |
| ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| `transactionCount`, `logCount`                                                                                                           | Ledger boundaries maintained synchronously with committed state |
| `volumeCount`, `referenceCount`, `postingCount`, `ephemeralEvictedCount`, `transientUsedCount`, `revertCount`, `numscriptExecutionCount` | Local usage projection updated asynchronously on each replica   |

The seven usage counters can briefly lag a completed write and can differ between replicas while they catch up. They describe volume cells and usage events; there is no account-count or metadata-count field. Do not use them as an instant write receipt or a single-request cutover gate.

The gRPC statistics request accepts `--checkpoint-id`; the HTTP route does not. At a query checkpoint, only `transactionCount` and `logCount` describe the frozen state. Ledger returns the seven usage counters as `0` because they are unavailable at that checkpoint, not because the historical ledger had no such activity.

When data is changing or a replica's derived usage view is rebuilding, use the transaction and log boundaries together with specific logs, audit entries, and integrity checks. Allow the local usage projections to converge before comparing their seven counters.

Statistics show broad growth; they do not identify which records changed. Use [Read Ledger Data](https://docs.formance.com/v4.0/modules/ledger/querying/read-ledger-data) for a transaction-to-audit trace and [Verify Ledger Integrity](https://docs.formance.com/v4.0/modules/ledger/operations/integrity) for an integrity assessment.

## Aggregate volumes with HTTP

Without a selector, the volume route aggregates every account in the ledger and returns input, output, and balance totals by asset and color:

```bash
VOLUME_RESULT="$(curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/volumes")"

jq '.data' <<<"$VOLUME_RESULT"
```

Limit and group the account set with HTTP query parameters. `filter` is the only account selector this route accepts:

```bash
SCOPED_VOLUMES="$(curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'filter=address ^= "users:"' \
  --data-urlencode 'groupByPrefixes=users:retail:,users:business:' \
  --data-urlencode 'useMaxPrecision=true' \
  "$LEDGER_URL/v3/$LEDGER_NAME/volumes")"

jq '.data' <<<"$SCOPED_VOLUMES"
```

| Parameter         | Effect                                                                |
| ----------------- | --------------------------------------------------------------------- |
| `filter`          | Selects the accounts to aggregate, using the account filter grammar   |
| `groupByPrefixes` | Assigns each matching account to the first declared prefix it matches |
| `useMaxPrecision` | Merges the same asset base at the highest observed precision          |
| `collapseColors`  | Sums every color for an asset and returns the result with `color: ""` |

The route ignores an unrecognized query parameter rather than rejecting it, and the aggregate response carries no account addresses. A misspelled or unsupported selector therefore returns `200` with a whole-ledger total that looks exactly like a scoped one. Assert the scope rather than assuming it.

Prove that the selector narrowed the account set by running the same aggregate twice, changing only the filter, and requiring the two totals to differ. Compare the amounts as the decimal strings the route returns, never as converted numbers:

```bash
export ACCOUNT_SELECTOR='address ^= "users:"'

aggregate_totals() {
  curl --fail-with-body --silent --show-error --get \
    "${CURL_AUTH[@]}" \
    "$@" \
    "$LEDGER_URL/v3/$LEDGER_NAME/volumes" \
    | jq -cS '[.data.volumes[] | {asset, color, input, output}] | sort'
}

SCOPED_TOTALS="$(aggregate_totals --data-urlencode "filter=$ACCOUNT_SELECTOR")"
WHOLE_LEDGER_TOTALS="$(aggregate_totals)"

if [ "$SCOPED_TOTALS" != "$WHOLE_LEDGER_TOTALS" ]; then
  echo "scope applied"
else
  echo "scope NOT applied: the selector was ignored and this total covers every account" >&2
  exit 1
fi
```

Both requests pass the same aggregation options, so the only difference between them is the selector. Equal totals mean the selector did not narrow anything. Run this against a ledger that holds accounts outside the selected subtree: where the subtree is the entire ledger the two totals are legitimately equal, and the check cannot distinguish that from an ignored selector.

Prefix matching is not segment-aware. `accounts:1` also matches `accounts:10` and `accounts:11`; include the delimiter when the chart of accounts requires a whole segment. When group prefixes overlap, declaration order matters: the first match wins, so an account is not double-counted. Accounts that match none of the group prefixes are omitted from the grouped result.

By default, colors remain separate. Use `collapseColors=true` only when the report intentionally removes that dimension.

The HTTP response keeps amounts as decimal strings and includes the computed balance:

```json
{
  "data": {
    "volumes": [
      {
        "asset": "USD/2",
        "color": "",
        "input": "15000",
        "output": "2500",
        "balance": "12500"
      }
    ]
  }
}
```

For a known fixture, compare exact strings rather than converting amounts to a JavaScript `Number`:

```bash
export EXPECTED_ASSET="USD/2"
export EXPECTED_COLOR=""
export EXPECTED_INPUT="15000"
export EXPECTED_OUTPUT="2500"
export EXPECTED_BALANCE="12500"

jq -e \
  --arg asset "$EXPECTED_ASSET" \
  --arg color "$EXPECTED_COLOR" \
  --arg input "$EXPECTED_INPUT" \
  --arg output "$EXPECTED_OUTPUT" \
  --arg balance "$EXPECTED_BALANCE" '
    any(.data.volumes[];
      .asset == $asset
      and .color == $color
      and .input == $input
      and .output == $output
      and .balance == $balance
    )
  ' <<<"$VOLUME_RESULT"
```

The check prints `true` only when the expected asset and color bucket has all three exact values. Use an arbitrary-precision integer or decimal library when the application must calculate with these strings.

## Aggregate a filtered account set with gRPC

`ledgerctl` accepts the account filter grammar as well as minimum-sequence and checkpoint controls. A metadata filter requires a declared field and a ready account metadata index.

When the aggregate must include a completed write, derive the sequence from the full gRPC `ApplyResponse`:

```bash
MIN_LOG_SEQUENCE="$(
  jq -er '
    .logs[-1].sequence // error("the response contains no new log sequence")
    | tostring
  ' apply-response.json
)"

ledgerctl accounts aggregate-volumes \
  --ledger "$LEDGER_NAME" \
  --filter 'metadata[status] == "active"' \
  --min-log-sequence "$MIN_LOG_SEQUENCE" \
  --json
```

`ApplyResponse.logs` is returned in commit order, so its last entry provides the highest sequence from 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. This gRPC read waits for the local read index to reach the captured sequence. It does not wait for a metadata-index backfill or version transition.

For a point-in-time reconciliation, first run the complete [checkpoint capture, readiness, and cleanup workflow](https://docs.formance.com/v4.0/modules/ledger/querying/consistency-and-checkpoints#freeze-a-view-with-a-query-checkpoint). That workflow derives `CHECKPOINT_ID` from the create response, probes the serving replica, and installs a cleanup trap. Then use the captured value rather than selecting an ID from a list:

```bash
: "${CHECKPOINT_ID:?create and verify a query checkpoint first}"

ledgerctl accounts aggregate-volumes \
  --ledger "$LEDGER_NAME" \
  --filter 'address ^= "users:"' \
  --checkpoint-id "$CHECKPOINT_ID" \
  --json
```

Repeat every related read with that same checkpoint ID, and let the capture workflow delete that exact ID after all consumers finish. The direct HTTP volume route accepts the generic `filter` parameter but exposes neither `minLogSequence` nor checkpoint controls.

The raw gRPC `AggregateResult` carries `input` and `output`, but no `balance` field. A client that consumes this message directly must compute `input - output` with an arbitrary-precision type. `ledgerctl accounts aggregate-volumes --json` performs that calculation and includes `balance` in its JSON output. When an aggregate filter becomes a shared application contract, store it as an account [prepared query](https://docs.formance.com/v4.0/modules/ledger/querying/prepared-queries) and execute it in `AGGREGATE_VOLUMES` mode; prepared-query execution supports a minimum sequence but not a query checkpoint in v3.0.

## Interpret results responsibly

- `input` and `output` are cumulative movements over the selected account set.
- The HTTP volume route and `ledgerctl accounts aggregate-volumes --json` report `balance` as `input - output` for the returned asset and color bucket.
- A zero balance does not prove that no transactions exist; equal input and output can net to zero.
- Analysis, statistics, and aggregation describe data. They do not prove ledger integrity.

See [Filter and Paginate Results](https://docs.formance.com/v4.0/modules/ledger/querying/filters-and-pagination) and [Create and Manage Indexes](https://docs.formance.com/v4.0/modules/ledger/querying/indexes) when an aggregate filter depends on an opt-in index.
