# Metadata and Typed Values

Source: https://docs.formance.com/v4.0/modules/ledger/modeling/metadata

Stack: v4.0

Metadata attaches application context to a ledger, account, or transaction without changing its accounting identity. Use it for identifiers, classifications, workflow state, and reconciliation references. Keep monetary value in postings and volumes.

## Choose the right target

| Target      | Use it for                                          | Example keys                        |
| ----------- | --------------------------------------------------- | ----------------------------------- |
| Ledger      | Configuration or ownership shared by the whole book | `environment`, `region`, `team`     |
| Account     | Context that follows one balance identity           | `customerId`, `country`, `riskTier` |
| Transaction | Context for one business movement                   | `paymentId`, `orderId`, `channel`   |

Put stable balance identity in the [account address](https://docs.formance.com/v4.0/modules/ledger/modeling/chart-of-accounts). Put context that can change without moving a balance in account metadata.

To write metadata, declare types, and inspect the schema against a live ledger, follow [Metadata and typed values](https://docs.formance.com/v4.0/modules/ledger/hands-on#metadata-and-typed-values) in the hands-on walkthrough.

## Write metadata

The HTTP API infers metadata types from JSON:

| JSON value        | Stored value     |
| ----------------- | ---------------- |
| `"text"`          | String           |
| `42`              | Unsigned integer |
| `-42`             | Signed integer   |
| `true` or `false` | Boolean          |
| Decimal number    | Rejected         |
| Object or array   | Rejected         |

The Ledger 3.0 HTTP parser decodes a JSON number through `float64` before it creates a signed or unsigned metadata integer. A bare integer above `2^53 - 1` can therefore lose precision before Ledger stores it. Reject such values in the HTTP client or send their exact decimal form as a string.

This form preserves an exact large identifier over HTTP:

```json
{
  "externalSequence": "9007199254740993"
}
```

If queries must compare that field as a number, declare it as `uint64` and create its metadata index. Direct reads still return the stored string, while the index compares its decimal value as `uint64`. Do not use a large bare JSON number as a shortcut.

The same operation exists for ledger and transaction metadata:

```text
POST /v3/{ledgerName}/metadata
POST /v3/{ledgerName}/transactions/{transactionId}/metadata
```

A save merges the supplied keys with existing metadata. Supplying a key again replaces its value. It does not remove keys omitted from the request.

Do not rely on `null` in a save request to delete an existing key. The HTTP parser skips null entries. Use the target's `DELETE .../metadata/{key}` endpoint so the deletion is explicit and auditable.

## Declare types for indexed queries

A per-ledger metadata schema declares how a key should be interpreted when Ledger builds and queries a metadata index. Declarations are scoped independently to account, transaction, and ledger metadata.

Supported declarations are:

- `string`;
- `bool`;
- `int8`, `int16`, `int32`, and `int64`;
- `uint8`, `uint16`, `uint32`, and `uint64`;
- `datetime`.

Write datetime values as RFC 3339 strings, for example `2026-07-17T09:30:00Z`. Ledger's index representation uses signed microseconds since the Unix epoch, so it can order values before and after 1970. Fractions beyond microsecond precision are truncated for indexing.

## Understand what a declaration changes

In Ledger 3.0, a metadata type declaration changes how an index interprets one key:

- reads return the value in the JSON type originally written by the client;
- the declaration tells the metadata index how to convert and order that key;
- declaring a new type does not rewrite stored account or transaction metadata;
- changing a declaration schedules a new encoding for an existing index;
- removing a declaration also removes an index attached to that field.

This means a raw account read can still return `"2"` as a string even when the account schema declares `riskTier` as `uint8`. A typed query interprets the indexed representation as `uint8`.

Setting a type does not start a historical metadata conversion, and there is no conversion state to poll. `GET /metadata-schema` confirms the declaration only. Validate historical values yourself and monitor any related metadata index before a query depends on the new type.

Declare types before accepting production values and before creating their indexes. This avoids mixed representations and reduces the work required to validate historical data.

## Inspect the schema

Retrieving the stored declarations groups fields by target:

```json
{
  "data": {
    "accountFields": {
      "riskTier": { "declaredType": "uint8" },
      "externalSequence": { "declaredType": "uint64" }
    },
    "transactionFields": {
      "settledAt": { "declaredType": "datetime" }
    },
    "ledgerFields": {}
  }
}
```

The schema response confirms the declaration. Check the related metadata index separately before you depend on it for a production query.

## Build the index and verify every read replica

- 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.

This gate targets a deployed ledger with more than one replica, so set its name explicitly:

```bash
export LEDGER_NAME="your-ledger"
```

A type declaration does not create an index. Register the exact target and key, then keep the canonical ID returned by Ledger:

```bash
REQUESTED_INDEX_ID="metadata:TARGET_TYPE_ACCOUNT:riskTier"

INDEX_RESPONSE="$(curl --fail-with-body --silent --show-error \
  --request POST \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: create-account-risk-tier-index" \
  --data "$(jq -n --arg id "$REQUESTED_INDEX_ID" '{id: $id}')" \
  "$LEDGER_URL/v3/$LEDGER_NAME/indexes")"

INDEX_ID="$(jq -er '.data.id' <<<"$INDEX_RESPONSE")"
test "$INDEX_ID" = "$REQUESTED_INDEX_ID"
```

Index creation and type changes start asynchronous work on each replica. Configure one direct URL for every Ledger pod that can serve reads. A load-balanced URL cannot prove that every replica is ready:

```bash
export LEDGER_REPLICA_URLS="https://ledger-0.internal.example.com https://ledger-1.internal.example.com https://ledger-2.internal.example.com"
```

Poll the canonical status route on each replica. This gate succeeds only when the contacted replica serves the latest encoding and has no newer version in progress:

```bash
for endpoint in $LEDGER_REPLICA_URLS; do
  READY=false

  for attempt in $(seq 1 120); do
    STATUS="$(curl --fail-with-body --silent --show-error \
      "${CURL_AUTH[@]}" \
      "${endpoint%/}/v3/$LEDGER_NAME/indexes/$INDEX_ID/status")"

    jq -r --arg endpoint "$endpoint" '
      .data
      | [
          $endpoint,
          (.currentVersion // 0),
          (.pendingVersion // 0),
          (.index.forwardEncodingVersion // 0)
        ]
      | @tsv
    ' <<<"$STATUS"

    if jq -e '
      (.data.currentVersion // 0) > 0
      and (.data.pendingVersion // 0) == 0
      and .data.currentVersion == .data.index.forwardEncodingVersion
    ' <<<"$STATUS" >/dev/null; then
      READY=true
      break
    fi

    sleep 2
  done

  test "$READY" = true
done
```

Run the same gate after changing a declared type on an indexed key. The declaration becomes visible before every replica finishes rebuilding its local index, so `GET /metadata-schema` alone is not a readiness check. See [Wait for readiness](https://docs.formance.com/v4.0/modules/ledger/querying/indexes#wait-for-readiness) for the index lifecycle and failure modes.

## Validate historical values before a type change

Type conversion for an index follows explicit rules. Common conversions include decimal strings to integers, RFC 3339 strings to datetime, and `true`/`false` or `1`/`0` strings to booleans. Values outside a bounded integer range or strings with an invalid format cannot produce the requested typed index value.

Use this change sequence:

1. inventory existing values for the target and key;
2. test every known representation against the new type;
3. stop writers from producing incompatible values;
4. set the declaration;
5. monitor the associated index rebuild;
6. run representative equality and range queries;
7. compare query results with direct entity reads.

Do not infer successful historical conversion from the schema declaration alone. The declaration records intent; your validation proves that the existing values satisfy it.

## Remove a declaration

Removing a field declaration leaves the stored metadata values unchanged. It removes the typed interpretation and drops the metadata index for that field, so update dependent queries first.

## Common failure modes

| Symptom                                                       | Cause                                                            | Correction                                                                                                       |
| ------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| A decimal metadata value is rejected                          | Metadata does not accept floating-point JSON values              | Store a non-monetary scaled integer or string; keep money in postings.                                           |
| An HTTP integer above `2^53 - 1` changes by one or more units | The JSON number passed through `float64` before Ledger stored it | Send the exact decimal value as a string, then declare a numeric index type if queries need numeric comparisons. |
| A range query omits some historical entities                  | Old values cannot be converted to the declared type              | Inventory and normalize source values before changing the declaration.                                           |
| A raw read still returns a string after declaring `uint8`     | Declarations type index values, not stored response values       | Treat raw metadata and indexed interpretation as separate contracts.                                             |
| A query stops working after removing a declaration            | Removing the declaration also drops its index                    | Update dependent queries before removal.                                                                         |
| Sending `null` leaves a key unchanged                         | Null entries are skipped by the save parser                      | Call the explicit delete endpoint.                                                                               |
| A timestamp sorts unexpectedly                                | Writers used inconsistent RFC 3339 values                        | Standardize UTC RFC 3339 strings and test boundary values.                                                       |

When address shape itself must be validated, use [account types](https://docs.formance.com/v4.0/modules/ledger/modeling/account-types) rather than metadata.
