Preview. Stack v4.0 has not been released, and what is documented here can still change before it does. The current release is v3.2, which covers this as Accounts.Go to v3.2
Ledger

Metadata and Typed Values

Store application context and declare metadata types for reliable queries.

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#

TargetUse it forExample keys
LedgerConfiguration or ownership shared by the whole bookenvironment, region, team
AccountContext that follows one balance identitycustomerId, country, riskTier
TransactionContext for one business movementpaymentId, orderId, channel

Put stable balance identity in the account address. 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 in the hands-on walkthrough.

Write metadata#

The HTTP API infers metadata types from JSON:

JSON valueStored value
"text"String
42Unsigned integer
-42Signed integer
true or falseBoolean
Decimal numberRejected
Object or arrayRejected

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:

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#

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:

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.

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

SymptomCauseCorrection
A decimal metadata value is rejectedMetadata does not accept floating-point JSON valuesStore a non-monetary scaled integer or string; keep money in postings.
An HTTP integer above 2^53 - 1 changes by one or more unitsThe JSON number passed through float64 before Ledger stored itSend the exact decimal value as a string, then declare a numeric index type if queries need numeric comparisons.
A range query omits some historical entitiesOld values cannot be converted to the declared typeInventory and normalize source values before changing the declaration.
A raw read still returns a string after declaring uint8Declarations type index values, not stored response valuesTreat raw metadata and indexed interpretation as separate contracts.
A query stops working after removing a declarationRemoving the declaration also drops its indexUpdate dependent queries before removal.
Sending null leaves a key unchangedNull entries are skipped by the save parserCall the explicit delete endpoint.
A timestamp sorts unexpectedlyWriters used inconsistent RFC 3339 valuesStandardize UTC RFC 3339 strings and test boundary values.

When address shape itself must be validated, use account types rather than metadata.