# Retry Writes Safely

Source: https://docs.formance.com/v4.0/modules/ledger/transactions/idempotency-and-references

Stack: v4.0

Network failures make a write outcome uncertain: the client may lose the response after Ledger committed the transaction. An idempotency key gives every retry of one logical operation the same outcome. A transaction reference adds a permanent business-level uniqueness rule inside one ledger.

Use both for production transactions. They solve different problems.

| Control           | Scope                                     | Retention                         | Purpose                                                               |
| ----------------- | ----------------------------------------- | --------------------------------- | --------------------------------------------------------------------- |
| `Idempotency-Key` | Entire Ledger cluster, across all ledgers | Configurable; 24 hours by default | Replays the original outcome for a technical retry.                   |
| `reference`       | One ledger                                | Retained with the transaction     | Prevents two transactions from claiming the same business identifier. |

## Prerequisites

You need an existing normal ledger and a token with `ledger:write` for the transaction plus `ledger:read` for the account check.

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 address with one that matches 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 WALLET_ACCOUNT="wallets:$RUN_ID"
export PAYMENT_REFERENCE="deposit:$RUN_ID"
export IDEMPOTENCY_KEY="payments-api:$RUN_ID"
```

Choose an idempotency key before the first attempt. Keep it stable through every retry, and keep the full request body with the operation in your application state or durable job record.

## Submit and replay one operation

Store the body in one shell variable so both attempts send identical content:

```bash
PAYMENT_BODY=$(jq --compact-output --null-input \
  --arg reference "$PAYMENT_REFERENCE" \
  --arg account "$WALLET_ACCOUNT" \
  '{
    reference: $reference,
    postings: [
      {
        source: "world",
        destination: $account,
        amount: 5000,
        asset: "EUR/2"
      }
    ]
  }')
```

Send the first attempt:

```bash
curl --fail-with-body --silent --show-error \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $IDEMPOTENCY_KEY" \
  --data "$PAYMENT_BODY" \
  > /tmp/idempotency-first.json
```

Then replay the same request with the same key:

```bash
curl --fail-with-body --silent --show-error \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $IDEMPOTENCY_KEY" \
  --data "$PAYMENT_BODY" \
  > /tmp/idempotency-replay.json
```

Both responses identify the same transaction:

```bash
FIRST_ID=$(jq -er \
  '.data.transaction.id | tostring | select(test("^[1-9][0-9]*$"))' \
  /tmp/idempotency-first.json) &&
REPLAY_ID=$(jq -er \
  '.data.transaction.id | tostring | select(test("^[1-9][0-9]*$"))' \
  /tmp/idempotency-replay.json) &&

test -n "$FIRST_ID" &&
test -n "$REPLAY_ID" &&
test "$FIRST_ID" = "$REPLAY_ID"
```

Verify the accounting state independently. The wallet must receive EUR 50.00 once, not twice:

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

Expected volume:

```json
{
  "input": "5000",
  "output": "0",
  "balance": "5000"
}
```

## Detect an incorrect retry

Ledger hashes the logical request content. Reusing the key with a changed amount returns `409 Conflict` instead of applying a different operation:

```bash
CHANGED_BODY=$(jq --compact-output \
  '.postings[0].amount = 9000' \
  <<<"$PAYMENT_BODY")

HTTP_STATUS=$(curl --silent --show-error \
  --output /tmp/idempotency-conflict.json \
  --write-out "%{http_code}" \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $IDEMPOTENCY_KEY" \
  --data "$CHANGED_BODY")

test "$HTTP_STATUS" = "409" &&
jq -e '
  select(.errorCode == "IDEMPOTENCY_KEY_CONFLICT")
  | {errorCode, errorMessage}' \
  /tmp/idempotency-conflict.json
```

The machine-readable reason is `IDEMPOTENCY_KEY_CONFLICT`. Do not respond by generating a new key automatically: first determine whether the caller intended a new operation or sent a corrupted retry.

## Enforce business uniqueness with a reference

The reference remains unique for the lifetime of the ledger, independent of the idempotency-key window. A second request with a new key but the same reference returns a transaction-reference conflict:

```bash
HTTP_STATUS=$(curl --silent --show-error \
  --output /tmp/reference-conflict.json \
  --write-out "%{http_code}" \
  --request POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  --header "Authorization: Bearer $LEDGER_TOKEN" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $IDEMPOTENCY_KEY:replacement" \
  --data "$PAYMENT_BODY")

test "$HTTP_STATUS" = "409" &&
jq -e '
  select(.errorCode == "TRANSACTION_REFERENCE_CONFLICT")
  | {errorCode, errorMessage}' \
  /tmp/reference-conflict.json
```

The reason is `TRANSACTION_REFERENCE_CONFLICT`. Treat it as success only after you verify that the existing transaction represents the same business event and amount. A shared reference alone does not prove that two request bodies were equivalent.

The reference conflict is reported only when the transaction commits, which happens after its Numscript has executed. Because funds are checked during execution, a resubmission can fail before the duplicate reference is ever evaluated, raising an insufficient-funds error (`INSUFFICIENT_FUNDS` in v3, `INSUFFICIENT_FUND` in v2), for example, instead of `TRANSACTION_REFERENCE_CONFLICT`. This is most visible with scripts whose postings depend on live balances (for example an amount derived from `overdraft()` or `balance()`), but it can affect any script whose replay no longer has sufficient funds at the source.

Do not depend on receiving `TRANSACTION_REFERENCE_CONFLICT` from a resubmission to tell you an operation already ran. Prefer a durable idempotency key, which is evaluated before execution and replays the original outcome. Querying for the reference beforehand is a useful guard, but only a positive match is conclusive: an empty result is inconclusive, because the original request may still be committing or a reference-filtered read may lag the write.

## Design keys that survive retries

An HTTP idempotency key can contain up to 256 UTF-8 bytes. Use a stable namespace plus an opaque operation ID, for example `payments-api:evt-7e49c4c9`. ASCII keys make this limit unambiguous. Do not include access tokens, customer names, or other sensitive values.

Idempotency keys are cluster-global. The same key used for `ledger-a` and `ledger-b` refers to one operation and can conflict. Include the producing service or tenant in the key when several systems generate IDs independently.

The server retains keys for the configured TTL:

- the default is 24 hours;
- operators can choose another duration;
- `0` disables expiration;
- as soon as the TTL expires, Ledger can treat the same key as new; background eviction only removes the expired storage entry.

Set the idempotency TTL longer than the maximum retry and delayed-delivery window of every writer. Once a key expires, a retry can create a new transaction. A transaction reference remains the durable guard for operations that have a business identifier.

## Decide whether to retry

| Outcome                                                                                                             | Retry decision                                                                                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Timeout or connection reset                                                                                         | Retry the identical request with the same key after bounded backoff.                                                                                                                                                                                      |
| `503`                                                                                                               | Inspect `errorCode`, honor `Retry-After` when present, and retry the identical request with the same key only while the outcome is uncertain. Stop repeated deterministic input failures such as Numscript `PRELOAD_UNAVAILABLE` and correct the request. |
| Invalid JSON, invalid path parameters, authentication failure, or another rejection before Ledger accepts the write | Correct the request or credentials. Do not infer from the HTTP status that Ledger retained the key. Use a new key when the logical request content changes.                                                                                               |
| Definitive business failure recorded as the operation's outcome                                                     | Keep the failure as the result of that logical operation. Ledger retains and replays these failures while the key remains live, even if account state later changes. A corrected operation needs a new key.                                               |
| `409` idempotency conflict                                                                                          | Stop. Compare the attempted request with the original operation.                                                                                                                                                                                          |
| `409` reference conflict                                                                                            | Retrieve and verify the transaction that already owns the reference.                                                                                                                                                                                      |
| `401` or `403`                                                                                                      | Repair credentials or permissions before retrying. Keep the same key and body if the logical operation is unchanged.                                                                                                                                      |

Persist every response with your operation record. That record, not the HTTP status, is what tells a later retry which key and which body to reuse.

The literal `latest` selector is hashed as `latest` and re-resolved on every execution: a retained key replays its first outcome, while an operation without a retained key executes whatever version is greatest at that moment. Ledger never rewrites a submitted selector to a concrete version, so a changed resolution cannot turn an unchanged body into an idempotency conflict. Pin an exact semantic version for retryable production writes.

## Apply the same rule to other writes

The HTTP contract also accepts `Idempotency-Key` on revert, on every transaction, account, and ledger metadata write and delete, and on the numscript save. The REST bulk endpoint uses the `ik` field on each element when it processes elements sequentially. See [Process Operations in Bulk](https://docs.formance.com/v4.0/modules/ledger/transactions/bulk) before retrying a partial batch.

Continue with [Revert Transactions](https://docs.formance.com/v4.0/modules/ledger/transactions/revert) when a committed operation needs an auditable correction.
