# Process Operations in Bulk

Source: https://docs.formance.com/v4.0/modules/ledger/transactions/bulk

Stack: v4.0

The REST bulk endpoint reduces request overhead when several independent operations target the same ledger.

Use one transaction with several postings when the movements form one accounting event. Use bulk when each element is an independent operation with its own identity and result.

## Prerequisites

You need an existing normal ledger, a token with the write scopes required by every element, and `ledger:read` for the account checks in this guide. With the default scope mapping, the virtual `ledger:write` scope covers all four: `ledger:TransactionWrite` for `CREATE_TRANSACTION` and `REVERT_TRANSACTION`, `ledger:MetadataWrite` for `ADD_METADATA` and `DELETE_METADATA`. Bulk checks the required scope per element.

These HTTP write examples assume that the cluster accepts unsigned requests. If your cluster requires Ed25519 request signatures, follow [Configure Request and Response Signing](https://docs.formance.com/v4.0/modules/ledger/operations/signing) and use a signed gRPC client or `ledgerctl` configured with a signing key; the HTTP write handlers submit unsigned requests.

If the ledger enforces account types, replace the demo addresses with values that match its configured patterns.

```bash
set -eo pipefail

export LEDGER_URL="https://ledger.example.com"
export LEDGER_NAME="main"
export LEDGER_TOKEN="replace-with-an-access-token"
export RUN_ID=${RUN_ID:-"$(date +%s)$$"}

export BULK_PREFIX="bulk-demo:$RUN_ID"
export BULK_WALLET_1="bulk:$RUN_ID:wallet:1"
export BULK_WALLET_2="bulk:$RUN_ID:wallet:2"
export BULK_WALLET_3="bulk:$RUN_ID:wallet:3"
export BULK_DUPLICATE_REFERENCE="$BULK_PREFIX:duplicate-reference"
```

Give every element a distinct `ik` value. This is the per-operation idempotency key used by the normal sequential REST path.

## REST surface

This guide covers `POST /v3/{ledgerName}/bulk` with an `application/json` array. The ledger name in the path applies to every element, so one REST bulk request cannot span ledgers.

The REST endpoint accepts these actions:

| `action`             | `data`                                                                                      |
| -------------------- | ------------------------------------------------------------------------------------------- |
| `CREATE_TRANSACTION` | The same `postings`, `script`, or `scriptReference` fields as a transaction create request. |
| `ADD_METADATA`       | `targetType`, `targetId`, and `metadata` for an account or transaction.                     |
| `REVERT_TRANSACTION` | `id` plus optional `force`, `atEffectiveDate`, and `metadata`.                              |
| `DELETE_METADATA`    | `targetType`, `targetId`, and `key` for an account or transaction.                          |

Account-type bulk actions exist on the gRPC surface but are not accepted by this REST endpoint. Do not infer parity between the two transports.

A bulk result exposes only the created transaction for a `CREATE_TRANSACTION` element, and a successful non-create element omits `data` entirely. Post-commit volumes ride on that created transaction, and no request field adds volumes to any other element. Verify affected accounts with separate reads.

## Observe the default stop behavior

By default, Ledger processes elements in order and stops after the first failure; operations that completed before it remain committed. The second element below deliberately reuses the first element's transaction reference. The third element is valid but appears after the failure.

```bash
BULK_BODY=$(jq --compact-output --null-input \
  --arg prefix "$BULK_PREFIX" \
  --arg duplicateReference "$BULK_DUPLICATE_REFERENCE" \
  --arg wallet1 "$BULK_WALLET_1" \
  --arg wallet2 "$BULK_WALLET_2" \
  --arg wallet3 "$BULK_WALLET_3" \
  '[
    {
      action: "CREATE_TRANSACTION",
      ik: ($prefix + ":1"),
      data: {
        reference: $duplicateReference,
        postings: [
          {source: "world", destination: $wallet1, amount: 1000, asset: "USD/2"}
        ]
      }
    },
    {
      action: "CREATE_TRANSACTION",
      ik: ($prefix + ":2"),
      data: {
        reference: $duplicateReference,
        postings: [
          {source: "world", destination: $wallet2, amount: 2000, asset: "USD/2"}
        ]
      }
    },
    {
      action: "CREATE_TRANSACTION",
      ik: ($prefix + ":3"),
      data: {
        reference: ($prefix + ":third"),
        postings: [
          {source: "world", destination: $wallet3, amount: 3000, asset: "USD/2"}
        ]
      }
    }
  ]')
```

Submit the request without `continueOnFailure`:

```bash
HTTP_STATUS=$(curl --silent --show-error \
  --output /tmp/bulk-stop.json \
  --write-out "%{http_code}" \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/bulk" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  --header "Content-Type: application/json" \
  --data "$BULK_BODY")

test "$HTTP_STATUS" = "409" &&
jq -e '
  .data as $results
  | ($results | length) == 3
    and $results[0].responseType == "CREATE_TRANSACTION"
    and ($results[0].logID > 0)
    and $results[1].responseType == "ERROR"
    and $results[1].errorCode == "TRANSACTION_REFERENCE_CONFLICT"
    and $results[2].responseType == "ERROR"
    and $results[2].logID == 0' \
  /tmp/bulk-stop.json
```

Expected result:

1. the first element has `responseType: "CREATE_TRANSACTION"` and a non-zero `logID`;
2. the second has `responseType: "ERROR"` and `errorCode: "TRANSACTION_REFERENCE_CONFLICT"`;
3. the third has no committed log because processing stopped;
4. the top-level status is a business `4xx`, driven by the second element.

Verify the state rather than inferring it from the top-level status:

```bash
curl --fail-with-body --silent --show-error \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts/$BULK_WALLET_1" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  | jq -e '
      .data.volumes[]
      | select(.asset == "USD/2" and .color == "")
      | .volumes.input == "1000"
        and .volumes.output == "0"
        and .volumes.balance == "1000"' &&

curl --fail-with-body --silent --show-error \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts/$BULK_WALLET_3" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  | jq -e '
      (.data.volumes | type) == "array"
      and (.data.volumes | length) == 0'
```

Both assertions return `true`. The first account has USD 10.00. Ledger returns an empty account view for an address with no volumes or metadata, so the empty volume list—not a `404` status—shows that the third operation did not run.

## Continue after business failures

Set `continueOnFailure=true` when independent later elements should still run after a per-element business `4xx`:

```bash
HTTP_STATUS=$(curl --silent --show-error \
  --output /tmp/bulk-continue.json \
  --write-out "%{http_code}" \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/bulk?continueOnFailure=true" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  --header "Content-Type: application/json" \
  --data "$BULK_BODY")

test "$HTTP_STATUS" = "200" &&
jq -e '
  .data as $results
  | ($results | length) == 3
    and $results[0].responseType == "CREATE_TRANSACTION"
    and ($results[0].logID > 0)
    and $results[1].responseType == "ERROR"
    and $results[1].errorCode == "TRANSACTION_REFERENCE_CONFLICT"
    and $results[2].responseType == "CREATE_TRANSACTION"
    and ($results[2].logID > 0)' \
  /tmp/bulk-continue.json
```

The first element replays its original result through `$BULK_PREFIX:1`. The second replays its reference-conflict outcome through `$BULK_PREFIX:2`. The third now commits under `$BULK_PREFIX:3`.

`continueOnFailure` changes the top-level status and whether later elements run. It does not hide per-element errors. Inspect every item in `.data`, even when the HTTP response is `200`.

## Turn an expected conflict into a recorded skip

Some import and replay workflows expect a specific business conflict. Add `skippableReasons` to that element to record a no-op instead of an error:

```bash
jq --null-input \
  --arg ik "$BULK_PREFIX:expected-duplicate" \
  --arg reference "$BULK_DUPLICATE_REFERENCE" \
  --arg destination "bulk:$RUN_ID:wallet:ignored" \
  '[
    {
      action: "CREATE_TRANSACTION",
      ik: $ik,
      skippableReasons: ["TRANSACTION_REFERENCE_CONFLICT"],
      data: {
        reference: $reference,
        postings: [
          {source: "world", destination: $destination, amount: 9999, asset: "USD/2"}
        ]
      }
    }
  ]' \
  | curl --fail-with-body --silent --show-error \
      --request POST "$LEDGER_URL/v3/$LEDGER_NAME/bulk" \
      --header "Authorization: Bearer $LEDGER_TOKEN" \
      --header "Content-Type: application/json" \
      --data @- \
  > /tmp/bulk-skip.json

jq -e \
  --arg ledger "$LEDGER_NAME" \
  --arg reference "$BULK_DUPLICATE_REFERENCE" \
  '.data[0] as $result
   | $result.responseType == "CREATE_TRANSACTION"
     and ($result.logID > 0)
     and $result.data.skipped
     and ($result.data.reason == "TRANSACTION_REFERENCE_CONFLICT")
     and ($result.data.context.ledger == $ledger)
     and ($result.data.context.reference == $reference)
     and ($result.data.context.existingTransactionId | test("^[1-9][0-9]*$"))' \
  /tmp/bulk-skip.json
```

The skipped result contains this information; the concrete reference and transaction ID depend on the run:

```json
{
  "skipped": true,
  "reason": "TRANSACTION_REFERENCE_CONFLICT",
  "context": {
    "ledger": "main",
    "reference": "bulk-demo:<run ID>:duplicate-reference",
    "existingTransactionId": "<non-zero original transaction ID>"
  }
}
```

A skipped element creates an auditable skip log but does not apply the attempted posting.

The REST whitelist is intentionally narrow:

| Action               | Supported skippable reason       |
| -------------------- | -------------------------------- |
| `CREATE_TRANSACTION` | `TRANSACTION_REFERENCE_CONFLICT` |
| `REVERT_TRANSACTION` | `TRANSACTION_ALREADY_REVERTED`   |
| `DELETE_METADATA`    | `METADATA_NOT_FOUND`             |

Ledger rejects reasons outside the action's whitelist when it processes that element. In sequential mode, earlier elements may already have committed; in atomic mode, the whole batch fails. `ADD_METADATA` has no REST skippable reason.

## Make the whole batch atomic

Set `atomic=true` when every element must commit or none may commit. Ledger sends the array as one atomic batch. Use one `Idempotency-Key` header for that batch; per-element `ik` values belong to sequential mode and do not identify an atomic request.

The example below deliberately repeats a reference inside a new atomic batch. The conflict rejects both elements:

```bash
ATOMIC_PREFIX="$BULK_PREFIX:atomic"
ATOMIC_WALLET_1="bulk:$RUN_ID:atomic:wallet:1"
ATOMIC_WALLET_2="bulk:$RUN_ID:atomic:wallet:2"
ATOMIC_REFERENCE="$ATOMIC_PREFIX:duplicate-reference"

ATOMIC_BODY=$(jq --compact-output --null-input \
  --arg reference "$ATOMIC_REFERENCE" \
  --arg wallet1 "$ATOMIC_WALLET_1" \
  --arg wallet2 "$ATOMIC_WALLET_2" \
  '[
    {
      action: "CREATE_TRANSACTION",
      data: {
        reference: $reference,
        postings: [
          {source: "world", destination: $wallet1, amount: 1000, asset: "USD/2"}
        ]
      }
    },
    {
      action: "CREATE_TRANSACTION",
      data: {
        reference: $reference,
        postings: [
          {source: "world", destination: $wallet2, amount: 2000, asset: "USD/2"}
        ]
      }
    }
  ]')

HTTP_STATUS=$(curl --silent --show-error \
  --output /tmp/bulk-atomic.json \
  --write-out "%{http_code}" \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/bulk?atomic=true" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $ATOMIC_PREFIX:batch" \
  --data "$ATOMIC_BODY")

test "$HTTP_STATUS" = "409" &&
jq -e '
  (.data | length) == 2
  and all(.data[];
    .responseType == "ERROR"
    and .errorCode == "TRANSACTION_REFERENCE_CONFLICT"
    and .logID == 0)' \
  /tmp/bulk-atomic.json
```

Verify that neither account received funds:

```bash
(
for ACCOUNT in "$ATOMIC_WALLET_1" "$ATOMIC_WALLET_2"; do
  curl --fail-with-body --silent --show-error \
    "$LEDGER_URL/v3/$LEDGER_NAME/accounts/$ACCOUNT" \
    --header "Authorization: Bearer $LEDGER_TOKEN" \
    | jq -e '
        (.data.volumes | type) == "array"
        and (.data.volumes | length) == 0' \
    || exit 1
done
)
```

Do not combine `atomic=true` with `continueOnFailure=true`: atomic execution has no successful prefix to continue after. If several postings describe one accounting event, a single transaction remains the clearer model; use atomic bulk for distinct operations that share one commit boundary.

## Handle response classes

Bulk failures fall into three groups:

| Response                                    | Meaning                                                                                          | Client action                                                                                                                                                                                                                                               |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Request-level `400`, `401`, `403`, or `413` | Ledger rejected the request before processing elements                                           | Correct the body, credentials, scopes, or configured batch-size limit. Do not assume any element result from a missing `.data` array.                                                                                                                       |
| Per-element business `4xx`                  | One operation failed validation, lookup, conflict, or a precondition                             | Inspect each item. In sequential mode, preceding items may have committed and later items did not run. In atomic mode, no element commits.                                                                                                                  |
| `429`, `500`, or `503`                      | A rate limit, service failure, stale input resolution, or unavailable Numscript preload occurred | `continueOnFailure` does not turn these into `200`. Inspect `errorCode`, honor `Retry-After` when present, and retry only with bounded backoff. A repeated `PRELOAD_UNAVAILABLE` can indicate invalid Numscript input rather than an infrastructure outage. |

The maximum number of elements is a server setting. Ledger returns `413` with `BULK_SIZE_EXCEEDED` when the request exceeds that configured limit. Split work into bounded batches instead of assuming one fixed limit across environments.

## Retry a bulk request

For a sequential top-level `500` or `503`, inspect every `errorCode`, then retry the same array after bounded backoff while the outcome is uncertain. Preserve every element's `ik` and original `data`. Elements that committed replay their outcomes; elements that did not run can proceed. Stop and validate the program and variables if Numscript `PRELOAD_UNAVAILABLE` persists.

For an atomic timeout or retryable service failure, resend the exact array with the same batch-level `Idempotency-Key` header. Do not add or change per-element keys. No successful prefix can escape a failed atomic batch, but the stable batch key protects a commit whose response was lost.

For a completed response with business errors:

1. persist the result for every element;
2. treat a successful or explicitly skipped item as complete;
3. diagnose each failed item by `errorCode`;
4. create a corrected operation with a new `ik` only when its logical content changes;
5. verify balances, metadata, or reversion state independently.

Do not generate fresh keys for an unchanged whole-batch retry. That can duplicate the elements that committed before the failure.

Continue with [Write Transactions](https://docs.formance.com/v4.0/modules/ledger/transactions) to choose between a single transaction, a saved Numscript program, and a bulk request.
