# Update Ledger Clients

Source: https://docs.formance.com/v4.0/modules/ledger/migration/update-clients

Stack: v4.0

Shared accounting concepts do not make Ledger v2 clients wire-compatible with the target. The target serves business endpoints under `/v3` and does not expose a Ledger v2 compatibility API.

Update and test clients before the production cutover. During mirroring, point non-production readers at the target; keep production writes on Ledger v2.

## Build a workflow inventory

Review behavior, not only endpoint names. For every workflow, record:

| Contract area  | What to verify                                                               |
| -------------- | ---------------------------------------------------------------------------- |
| Endpoint       | Method, `/v3` path, ledger name, and protocol.                               |
| Authentication | Issuer, audience, bearer token, and required read/write scope.               |
| Request        | Field names, amount encoding, metadata types, and mutually exclusive inputs. |
| Response       | Wrapper, field names, post-commit volume snapshots, and absent fields.       |
| Pagination     | Cursor direction, page size, continuation value, and termination condition.  |
| Filtering      | Filter syntax, type conversion, and required indexes.                        |
| Errors         | HTTP or gRPC status, domain reason, retryability, and conflict handling.     |
| Idempotency    | Key construction, scope, payload reuse, and retention assumptions.           |
| SDK            | Package major, generated method, numeric type, and timestamp type.           |
| Observability  | Correlation, audit lookup, metrics, and alert ownership.                     |

Cover create, revert, account reads, transaction reads, metadata, filters, pagination, bulk, Numscript, and events when your application uses them.

## Update the base endpoint and authentication

HTTP calls move from Ledger v2 paths to `/v3/{ledgerName}/...`. Look up each call in the [Endpoint Map](https://docs.formance.com/v4.0/modules/ledger/migration/endpoint-map): some change method or merge into another endpoint, and some have no equivalent. Send the target access token in the standard header:

```http
Authorization: Bearer <access-token>
```

Do not reuse a Ledger v2 token without verifying its issuer, audience, and scopes against the target. Test from every application environment, including workers and scheduled jobs.

Use [Authentication](https://docs.formance.com/v4.0/modules/ledger/operations/authentication) to map target identities and effective scopes before changing an application endpoint.

HTTP and gRPC do not expose every operational capability symmetrically. Select the protocol per workflow and keep cluster operations out of normal application clients.

## Update transaction writes

A transaction request declares exactly one content source:

- explicit `postings`;
- an inline Numscript `script`;
- a `scriptReference` to a saved program.

Use the `Idempotency-Key` HTTP header for request idempotency. Do not add a body-level idempotency key.

Ledger v2 transaction response fields for pre-commit and effective volumes are not part of the target contract. The target computes and returns `postCommitVolumes` unconditionally; there is no volume-expansion parameter to opt into. Read it at `data.transaction.postCommitVolumes` on create and at `data.revertTransaction.postCommitVolumes` on revert.

`postCommitVolumes` is an immutable snapshot taken at that transaction's sequence. It is never recomputed from later state, so it is not a current balance. If an application needs durable current balances, read the affected account or run the required aggregate query instead of reusing a write response.

## Redesign idempotency keys

Idempotency covers more target operations and uses a cluster-level namespace. A key that was treated as independent per Ledger v2 ledger can conflict when reused on the target.

The observable failure is specific: when a key is reused anywhere in the cluster for different request content, the target rejects the request with HTTP `409` and `errorCode: IDEMPOTENCY_KEY_CONFLICT`. Assert on that pair in test cases 2 and 5 below. A key is at most 256 bytes. Keys expire after the cluster's `--idempotency-ttl`, which defaults to 24 hours and never expires when set to `0`; a retry sent after that window re-executes the request instead of replaying the first outcome.

Construct keys from stable business identity, for example:

```text
create-transaction:tenant-42:main:payment-018f1
```

Test all of these cases:

1. same key and same payload;
2. same key and a different payload;
3. a retry after a client timeout;
4. the same business reference with a new idempotency key;
5. the same key accidentally reused for another ledger or operation.

See [Idempotency and References](https://docs.formance.com/v4.0/modules/ledger/transactions/idempotency-and-references) for the target request and conflict behavior.

## Replace Ledger Schema workflows

Ledger v2 combined several concerns behind one schema API. The target models them independently:

| Ledger v2 responsibility    | Target resource                    |
| --------------------------- | ---------------------------------- |
| Validate account addresses  | Account types and enforcement mode |
| Define metadata fields      | Typed metadata schema              |
| Reuse transaction templates | Versioned Numscript library        |
| Reuse query templates       | Prepared queries                   |

There is no single schema version that selects all four resources for a transaction. Update deployment and application ownership for each resource you use.

## Update reads and filters

The target introduces typed filters, explicit indexes, prepared queries, and query checkpoints. Verify:

- the fields and types accepted by each query target;
- which filter requires an index;
- that every required index is ready before switching readers;
- that the client follows the target pagination contract rather than deserializing a Ledger v2 cursor shape;
- whether the workflow needs an HTTP live read or a gRPC consistency option.

Some Ledger v2 read capabilities have no target spelling at all: the account date fields and any filter or ordering over them, the `/volumes` point-in-time parameters, the `prefix=` and `reference=` query parameters, and the per-account `balances` and `volumes` routes. [Removed Capabilities](https://docs.formance.com/v4.0/modules/ledger/migration/removed-capabilities) lists each one with its replacement. Check a read path against that page before rewriting it — a workflow that depends on one of those needs a design decision, not a new call site.

Do not compare complete source and target JSON payloads byte for byte. Normalize each workflow to the business fields it depends on.

Use [Filters and Pagination](https://docs.formance.com/v4.0/modules/ledger/querying/filters-and-pagination) and [Indexes](https://docs.formance.com/v4.0/modules/ledger/querying/indexes) to build and verify each production read path.

### Translate filters

Ledger v2 filters move into the `filter` query parameter, which takes a textual expression or a structured JSON one; see [Filter and Paginate Results](https://docs.formance.com/v4.0/modules/ledger/querying/filters-and-pagination). Most v2 JSON filters keep their shape. Check each one against these changes:

| Ledger v2                                                      | Ledger 3.0                                                                                                                                                                                              |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| JSON query body or `query` parameter                           | `filter` query parameter, textual or structured                                                                                                                                                         |
| `prefix=users:` on accounts or volumes                         | `filter=address ^= "users:"`                                                                                                                                                                            |
| `reference=order-1001` on transactions                         | `filter={"$match":{"reference":"order-1001"}}`, structured only                                                                                                                                         |
| `startTime` and `endTime`                                      | `startDate` and `endDate`                                                                                                                                                                               |
| `account` on transactions                                      | `address`, with the transaction-address index                                                                                                                                                           |
| `source`, `destination`, `reverted`, and `$exists` on metadata | Unchanged. `source` and `destination` each need their own index                                                                                                                                         |
| `inserted_at` and `reverted_at` on transactions                | `insertedAt` and `revertedAt`, structured only, each with its own index                                                                                                                                 |
| `updated_at` on transactions                                   | No equivalent                                                                                                                                                                                           |
| `balance[USD/2]` on accounts or volumes                        | No equivalent. Read `volumes` from the account list and compare balances in the client                                                                                                                  |
| `id` and `type` on logs                                        | `logId`, structured only. `type` has no equivalent                                                                                                                                                      |
| Address segment wildcards: `order::pending`, `users:...`       | `address ^= "order:"`, then narrow with metadata. An empty segment or a trailing `...` is not a wildcard                                                                                                |
| `$in`                                                          | Textual `in (...)`, or `$or` of `$match` conditions                                                                                                                                                     |
| `$like`                                                        | No equivalent. Use an address prefix, or an exact `reference` match                                                                                                                                     |
| `first_usage`, `insertion_date`, `updated_at` on accounts      | Not filterable. Use a typed `datetime` account metadata key with an index; see [Removed Capabilities](https://docs.formance.com/v4.0/modules/ledger/migration/removed-capabilities#account-date-fields) |
| Metadata filters on any key                                    | A declared metadata type and a ready metadata index per key                                                                                                                                             |
| Metadata compared as strings, with no range operators          | Values compared as the declared type. Numeric keys accept range operators                                                                                                                               |

Remove `prefix=` and `reference=` from every call. Ledger 3.0 ignores both parameters rather than rejecting them, so a v2 call that still sends one returns the unfiltered list.

A trailing colon also changes meaning. In Ledger v2, `users:` matched exactly one more segment. In Ledger 3.0, `address ^= "users:"` and `{"$match":{"address":"users:"}}` match every address that starts with `users:`, at any depth, including `users:alice:wallet`. The closest Ledger v2 spelling is `users:...`.

#### Worked examples

The examples below show one Ledger v2 call and its Ledger 3.0 replacement. `V2_URL` is the base URL of your Ledger v2 instance; `LEDGER_URL`, `LEDGER_NAME`, and `CURL_AUTH` are defined in [Read Ledger Data](https://docs.formance.com/v4.0/modules/ledger/querying/read-ledger-data). The data is the same on both sides: accounts under `users:` carry `status`, `tier`, and `score` metadata, and `users:alice:wallet` sits one level below `users:alice`.

##### Accounts under a prefix, by metadata

The Ledger v2 call returns active accounts exactly one segment below `users:`:

```bash
curl --get "$V2_URL/v2/$LEDGER_NAME/accounts" \
  --data-urlencode 'query={"$and":[{"$match":{"address":"users:"}},{"$match":{"metadata[status]":"active"}}]}'
```

In Ledger 3.0, declare `status` as a `string` account metadata key and create the `metadata:TARGET_TYPE_ACCOUNT:status` index, then send either form:

Textual

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'filter=address ^= "users:" and metadata[status] == "active"' \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts"
```

Structured JSON

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'filter={"$and":[{"$match":{"address":"users:"}},{"$match":{"metadata[status]":"active"}}]}' \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts"
```

Ledger v2 returns `users:alice` and `users:bob`. Ledger 3.0 also returns `users:alice:wallet`, because the prefix covers every depth. Ledger 3.0 has no one-segment match: when depth matters, drop addresses that contain another `:` after the prefix in the client, or tag the accounts you want with metadata and filter on that.

##### Transactions involving an account, in a date range

The Ledger v2 call returns transactions that touch `users:alice` in March and April 2026:

```bash
curl --get "$V2_URL/v2/$LEDGER_NAME/transactions" \
  --data-urlencode 'query={"$and":[{"$match":{"account":"users:alice"}},{"$gte":{"timestamp":"2026-03-01T00:00:00Z"}},{"$lt":{"timestamp":"2026-05-01T00:00:00Z"}}]}'
```

In Ledger 3.0, `account` becomes `address`. Create the `tx_builtin:TX_BUILTIN_INDEX_ADDRESS` and `tx_builtin:TX_BUILTIN_INDEX_TIMESTAMP` indexes, then send either form:

Textual

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'filter=address == "users:alice" and timestamp >= "2026-03-01T00:00:00Z" and timestamp < "2026-05-01T00:00:00Z"' \
  "$LEDGER_URL/v3/$LEDGER_NAME/transactions"
```

Structured JSON

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'filter={"$and":[{"$match":{"address":"users:alice"}},{"$gte":{"timestamp":"2026-03-01T00:00:00Z"}},{"$lt":{"timestamp":"2026-05-01T00:00:00Z"}}]}' \
  "$LEDGER_URL/v3/$LEDGER_NAME/transactions"
```

Both versions return the same transactions. The date bounds can also move out of the filter into `startDate=2026-03-01T00:00:00Z` and `endDate=2026-05-01T00:00:00Z`, which the ledger combines with `filter` using AND.

##### A transaction by reference

The Ledger v2 call selects one transaction by its reference:

```bash
curl --get "$V2_URL/v2/$LEDGER_NAME/transactions" \
  --data-urlencode 'query={"$match":{"reference":"order-1003"}}'
```

Ledger 3.0 accepts the same structured condition. Create the `tx_builtin:TX_BUILTIN_INDEX_REFERENCE` index first. The textual form has no `reference` field, so keep this filter structured:

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'filter={"$match":{"reference":"order-1003"}}' \
  "$LEDGER_URL/v3/$LEDGER_NAME/transactions"
```

If the Ledger v2 client sent `reference=order-1003` instead, replace the parameter with this filter. Ledger 3.0 ignores `reference=` and returns every transaction.

##### Numeric metadata

Ledger v2 stored metadata as strings, so a numeric value was matched as text and range operators were rejected:

```bash
curl --get "$V2_URL/v2/$LEDGER_NAME/accounts" \
  --data-urlencode 'query={"$match":{"metadata[score]":"15"}}'
```

In Ledger 3.0, declare `score` as `int64` and create the `metadata:TARGET_TYPE_ACCOUNT:score` index. Write the account metadata as a number. The textual form matches the number directly; the structured form expresses equality as a closed range:

Textual

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'filter=metadata[score] == 15' \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts"
```

Structured JSON

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'filter={"$and":[{"$gte":{"metadata[score]":15}},{"$lte":{"metadata[score]":15}}]}' \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts"
```

Keeping the Ledger v2 string, `{"$match":{"metadata[score]":"15"}}`, fails with `400` and `FILTER_COMPILATION_ERROR`, because the value does not match the declared type. Range filters such as `metadata[score] >= 15` now work, which Ledger v2 did not allow on metadata.

## Update bulk handling

The HTTP bulk route is `/v3/{ledgerName}/bulk`; Ledger v2 `_bulk` paths do not carry over. The target returns per-element results and distinguishes business failures from infrastructure failures.

Choose the failure model explicitly:

- the default sequential mode commits successful elements in order and stops after the first failure;
- `continueOnFailure=true` continues with later independent elements after a business failure;
- `atomic=true` submits the complete array as one Apply batch, so every element commits or none commits.

In atomic mode, send one batch-level `Idempotency-Key` header and preserve it with the exact array on an ambiguous retry. Per-element `ik` values identify requests only in sequential mode. Do not combine `atomic=true` with `continueOnFailure=true`: an atomic batch has no successful prefix to continue after.

The `release/v3.0` HTTP handler supports `atomic=true` even though the current OpenAPI parameter description still says that it is not supported. Pin the application to the released server contract, inspect every per-element result, and test sequential failure, continuation, atomic rollback, and ambiguous whole-batch retries before enabling production bulk traffic.

See [Bulk Transactions](https://docs.formance.com/v4.0/modules/ledger/transactions/bulk) for the target request and result model.

## Replace event integrations

Ledger v2 exporters and pipelines are not target client APIs. However, mirroring does not hide imported history from the target event system. Each supported Ledger v2 change becomes an ordinary target log and produces the same standard event type as a target-native change, such as `COMMITTED_TRANSACTION`, `REVERTED_TRANSACTION`, `SAVED_METADATA`, or `DELETED_METADATA`.

A new sink replays imported Ledger v2 history

A newly created target sink starts at cursor `0` and replays every supported event still present in the target global log, including the history imported from Ledger v2. Pointed at a live consumer, it re-fires the payouts, webhooks, and notifications that Ledger v2 already delivered. The sink configuration exposes no start cursor that skips this replay.

Do not point a new target sink at a consumer that can immediately repeat production side effects. Stage the destination or consumer in quarantine first: accept and inspect replayed messages, but suppress notifications, payouts, webhooks, projections, and any other externally visible effect until the approved cutover boundary.

Inventory each consumer and define:

- the target event sink and event types;
- a target-delivery identity, normally the target cluster identity plus `logSequence`, for at-least-once redelivery;
- a business-effect identity that is stable across the Ledger v2 pipeline and the target replay;
- the durable sink and consumer checkpoints used to prove that historical replay has drained;
- at-least-once delivery handling;
- the exact boundary after which target events may produce business effects;
- the source consumer stop point and the target consumer activation point.

The target `logSequence` identifies delivery inside the target cluster, but it does not identify an effect that the Ledger v2 consumer already applied. Build the cross-version key from business data that survives mirroring—for example, a unique transaction reference when your domain guarantees one—and specify a key for every event type that causes an effect. If no stable cross-version identity exists for a workflow, keep its target effects disabled until you have reconciled and checkpointed the replay explicitly.

During rehearsal, let the target sink replay into quarantine, verify the standard target event shapes, and test the same mirrored business change against the Ledger v2 receipt history. Record the point through which every replayed event is durably accepted without repeating an effect. This is a consumer-side migration checkpoint, not a sink start-cursor setting.

Data parity does not prove event-consumer compatibility. A successful rehearsal must prove both full replay handling and safe activation for the first post-boundary target event.

Use [Configure an Event Sink](https://docs.formance.com/v4.0/modules/ledger/events/configure-sink) and [Consume and Recover](https://docs.formance.com/v4.0/modules/ledger/events/consume-and-recover) to define the target delivery and recovery path.

## Integration test gate

Run a non-production client against a disposable normal ledger for writes and against the mirror for reads.

- [ ] Create a transaction with the target request shape.
- [ ] Retry it with the same idempotency key.
- [ ] Read it by ID and business reference.
- [ ] Read affected accounts and volumes.
- [ ] Revert a transaction and verify the compensating state.
- [ ] Save and delete account and transaction metadata.
- [ ] Traverse more than one page for each list workflow.
- [ ] Exercise every production filter after indexes are ready.
- [ ] Test expected 4xx conflicts and retryable infrastructure failures.
- [ ] Authenticate every application identity.
- [ ] Replay target events into quarantine without producing business effects.
- [ ] Deduplicate an imported event against the corresponding Ledger v2 business effect.
- [ ] Record the replay checkpoint and prove that only post-boundary events can activate effects.

Do not generate a production client from a branch snapshot. Pin the SDK or generated client to the same released contract as the target deployed by Stack v4.

Continue with [Create a Mirror](https://docs.formance.com/v4.0/modules/ledger/migration/create-mirror).
