# Create Prepared Queries

Source: https://docs.formance.com/v4.0/modules/ledger/querying/prepared-queries

Stack: v4.0

A prepared query stores a named filter inside one ledger. Applications execute the name with runtime parameters instead of rebuilding the filter in every service.

Use a prepared query when a filter is a shared application contract, needs review before deployment, or must remain consistent across several callers. Keep an ad hoc filter when one caller owns a short-lived operational search.

The HTTP examples use `jq` and the `LEDGER_URL`, `LEDGER_NAME`, and `CURL_AUTH` variables defined in [Read Ledger Data](https://docs.formance.com/v4.0/modules/ledger/querying/read-ledger-data). Listing and executing prepared queries require `ledger:QueryRead`; creating, updating, and deleting them require `ledger:QueryWrite`. See [Authentication and Authorization](https://docs.formance.com/v4.0/modules/ledger/operations/authentication).

When mandatory request signing is enabled in the current 3.0 preview, the create, update, and delete examples on this page fail through both HTTP and `ledgerctl queries`: those direct paths submit unsigned mutations. Manage prepared-query definitions through a reviewed [configuration-as-code](https://docs.formance.com/v4.0/modules/ledger/operations/configuration-as-code) file and its signed `ledgerctl ledgers configuration apply` path, or use a version-pinned gRPC client that signs the exact `ApplyBatch`. Listing and executing queries remain read operations and continue to work.

## Prerequisites

Choose one target:

| Target         | `LIST` result | `AGGREGATE_VOLUMES` |
| -------------- | ------------- | ------------------- |
| `ACCOUNTS`     | Accounts      | Supported           |
| `TRANSACTIONS` | Transactions  | Not supported       |
| `LOGS`         | Ledger logs   | Not supported       |

The server supports `LIST` execution for all three targets over HTTP and gRPC.

Then verify that:

- every metadata field has a declared type for the selected target;
- every condition that needs an opt-in index has that index ready on the serving replica;
- the query name identifies its business purpose rather than its current implementation;
- callers have query-read permission and the deployment path has query-write permission.

Prepared queries are scoped to one ledger. They do not read across ledgers.

The create and update APIs accept textual or structured filters, but the representations are not equivalent for every condition. In particular, a transaction reference is available only as a structured `$match`. Review the [filter representation table](https://docs.formance.com/v4.0/modules/ledger/querying/filters-and-pagination#choose-a-filter-representation) before storing a query.

## Create a parameterized query with ledgerctl

The textual filter grammar represents a parameter as `$name`:

```bash
ledgerctl queries create accounts-by-status \
  --ledger "$LEDGER_NAME" \
  --target accounts \
  --filter 'metadata[status] == $status'
```

Ledger parses and validates the filter before storing it. A duplicate name is rejected; creation does not update an existing query.

List the stored definitions to verify the target and normalized filter:

```bash
ledgerctl queries list --ledger "$LEDGER_NAME" --json
```

There is no single-query read operation. Use the list command or HTTP list route and select the name in the client.

## Create a query with HTTP

The REST request can carry a structured filter:

```bash
curl --fail-with-body --silent --show-error \
  --request POST \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: create-accounts-by-status-query" \
  --data '{
    "name": "accounts-by-status",
    "target": "ACCOUNTS",
    "filter": {
      "$match": {
        "metadata[status]": {"$param": "status"}
      }
    }
  }' \
  "$LEDGER_URL/v3/$LEDGER_NAME/prepared-queries"
```

A successful creation returns `204 No Content`. Confirm it with:

```bash
curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/prepared-queries"
```

The create and update bodies also accept a textual filter as a JSON string. The list response exposes the stored filter in structured form.

## Execute a list query

ledgerctl limits in v3.0

The `ledgerctl` result renderer handles accounts and transactions only. Execute a `LOGS` query through HTTP or a gRPC client so log rows are returned to the caller. Do not use `ledgerctl queries execute --all` for an export in this release; follow `cursor.next` yourself until `hasMore` is false.

For an account or transaction query, execute with `ledgerctl` and provide each parameter as `key=value`:

```bash
ledgerctl queries execute accounts-by-status \
  --ledger "$LEDGER_NAME" \
  --param status=active \
  --page-size 100 \
  --json
```

The CLI sends parameter values as strings. Ledger converts them according to the typed field used by the filter. A value that cannot be converted is rejected rather than compared as a different type.

The equivalent HTTP request is:

```bash
curl --fail-with-body --silent --show-error \
  --request POST \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --data '{
    "mode": "LIST",
    "parameters": {"status": "active"},
    "pageSize": 100
  }' \
  "$LEDGER_URL/v3/$LEDGER_NAME/prepared-queries/accounts-by-status/execute"
```

The execution response is not wrapped in a top-level `data` field. A list result has this shape:

```json
{
  "cursor": {
    "pageSize": 100,
    "hasMore": true,
    "next": "eyJrZXkiOiJ1c2VyczphbGljZSJ9",
    "accountData": [
      {"address": "users:alice", "metadata": {"status": "active"}}
    ]
  }
}
```

The row field follows the target: `accountData`, `transactionData`, or `logData`.

`cursor.next` and `cursor.previous` are [page tokens](https://docs.formance.com/v4.0/modules/ledger/querying/filters-and-pagination#paginate-http-reads). The first page has no `previous`. When `hasMore` is true, send `cursor.next` unchanged in the next request:

```json
{
  "mode": "LIST",
  "parameters": {"status": "active"},
  "pageSize": 100,
  "cursor": "eyJrZXkiOiJ1c2VyczphbGljZSJ9"
}
```

The HTTP route also accepts `pageSize`, `cursor`, and `reverse` as query parameters. Query-parameter values override the request body. Use one location consistently so application logs show the effective request clearly. Keep the query name, parameters, page size, `reverse`, and any minimum sequence unchanged throughout the cursor chain. Follow `cursor.next` yourself until `hasMore` is false, or send `cursor.previous` the same way to return to the preceding page.

## Include a completed write

Add `minLogSequence` only when the prepared query must include a write that just completed. Derive it from the full gRPC `ApplyResponse`; do not use a transaction ID, timestamp, or estimated sequence:

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

`ApplyResponse.logs` is returned in commit order, so the last item is the highest sequence produced by the proposal. If the response has no fresh log, that call produced no new sequence to wait for, so the filter raises an error rather than yielding the string `null`, which `minLogSequence` would otherwise accept.

Prepared-query execution checks the local read-index position once. When it is behind, the gRPC API returns `READ_INDEX_NOT_CAUGHT_UP` instead of waiting. Application clients should retry only that structured `google.rpc.ErrorInfo.reason`, with a bound.

In Ledger v3.0, `ledgerctl` does not print the structured reason. Its stable signal for that same error is the server message containing the requested sequence. The loop below matches both that message and the exact captured sequence; every other failure stops immediately:

```bash
QUERY_READY=false
EXPECTED_LAG_PREFIX="read index has not caught up to sequence $MIN_LOG_SEQUENCE (current:"

for attempt in {1..30}; do
  if ledgerctl queries execute accounts-by-status \
    --ledger "$LEDGER_NAME" \
    --param status=active \
    --page-size 100 \
    --min-log-sequence "$MIN_LOG_SEQUENCE" \
    --json \
    >prepared-page.json 2>prepared-query.err
  then
    QUERY_READY=true
    break
  fi

  if ! grep -Fq "$EXPECTED_LAG_PREFIX" prepared-query.err; then
    cat prepared-query.err >&2
    exit 1
  fi

  sleep 2
done

if [ "$QUERY_READY" != true ]; then
  cat prepared-query.err >&2
  exit 1
fi
```

The HTTP execution body accepts the same number in its `minLogSequence` field; it is also a one-shot freshness gate, not a wait. Use the gRPC reason above when a client needs to distinguish the retryable lag from other failures in v3.0.

This freshness gate does not cover an index backfill or metadata-index version transition. Verify the field declaration and index readiness separately. Prepared-query execution does not accept a query checkpoint ID in Ledger v3.0. See [Choose Read Consistency and Use Checkpoints](https://docs.formance.com/v4.0/modules/ledger/querying/consistency-and-checkpoints#wait-for-the-read-index) for the complete sequence-capture workflow.

## Aggregate matching account volumes

An account prepared query can aggregate the input, output, and balance of every matching account:

```bash
ledgerctl queries execute accounts-by-status \
  --ledger "$LEDGER_NAME" \
  --param status=active \
  --mode aggregate \
  --json
```

With HTTP, set `mode` to `AGGREGATE_VOLUMES`. The response contains `aggregateResult` rather than `cursor`:

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

Aggregation is computed when the request runs. It is not a precomputed reporting table, so include its scan cost in capacity tests.

The HTTP response computes `balance` as `input - output`. The gRPC `AggregateResult` used by `ledgerctl` carries `input` and `output` but no balance field; compute that difference in the client when using gRPC.

## Evolve a query without surprising callers

An update replaces the filter atomically and keeps the target unchanged:

```bash
ledgerctl queries update accounts-by-status \
  --ledger "$LEDGER_NAME" \
  --filter 'metadata[status] == $status and address ^= "users:"'
```

Prepared queries do not expose version history through the read API. The audit trail records updates, but callers can retrieve only the current filter.

For a business-critical change, prefer a versioned rollout:

1. create a new name such as `accounts-by-status-v2`;
2. execute it with representative parameter sets;
3. compare its results with the existing query;
4. move callers to the new name;
5. remove the old query after the rollback window.

Changing a metadata field declaration does not convert existing stored values or validate every prepared query that uses the field. Review the existing values and prepared queries, then wait for the metadata index's new local version before depending on the new comparison semantics.

## Delete a query

Delete a query only after every caller has stopped using its name:

```bash
ledgerctl queries delete accounts-by-status --ledger "$LEDGER_NAME"
```

Or use HTTP:

```bash
curl --fail-with-body --silent --show-error \
  --request DELETE \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/prepared-queries/accounts-by-status"
```

A later execution of that name returns `NotFound`. Recreating the same name creates a new current definition; it does not restore the deleted definition's history.

## Diagnose execution failures

| Failure                          | Check                                                                    |
| -------------------------------- | ------------------------------------------------------------------------ |
| Missing parameter                | Send every `$param` referenced by the stored filter                      |
| Parameter conversion error       | Match the value to the declared metadata type                            |
| Index not found                  | Declare the index for the exact target and condition                     |
| HTTP `503` with `INDEX_BUILDING` | Wait for readiness on the serving replica and retry with bounded backoff |
| `READ_INDEX_NOT_CAUGHT_UP`       | Retry the same request with bounded backoff; stop on every other error   |
| Invalid mode                     | Use `LIST` for any target; use `AGGREGATE_VOLUMES` only for accounts     |
| Query no longer compiles         | Review recent metadata schema and index changes                          |
| Unexpected page contents         | Keep parameters, mode, page size, and cursor chain stable                |

Continue with [Analyze and Aggregate Ledger Data](https://docs.formance.com/v4.0/modules/ledger/querying/analyze-and-aggregate) when an application needs totals rather than rows.
