# Idempotency

Source: https://docs.formance.com/v3.2/modules/ledger/working-with/idempotency

Stack: v3.2

When building financial applications, preventing duplicate transactions is critical. The Formance Ledger provides two mechanisms to ensure transaction uniqueness: **idempotency keys** and **references**.

## Idempotency Keys

Add an `Idempotency-Key` header to your request. If you execute the same request twice with the same key, the system will skip processing and return the original successful response.

### How it works

1. When you send a request with an idempotency key, the ledger stores a hash of the request along with the response
2. If you retry with the same key and identical request, the ledger returns the cached response with an `Idempotency-Hit: true` header
3. If you retry with the same key but different request parameters, the ledger returns a validation error

### Supported endpoints

Idempotency keys work on all write endpoints:

- Create transaction (including batch and Numscript)
- Update metadata (account or transaction)
- Revert transaction

### Scope

Idempotency keys are scoped to a specific ledger. The same key can be used on different ledgers without conflict.

### Example

curl

```bash
curl -X POST $FORMANCE_API_URL/api/ledger/v2/my-ledger/transactions \
  -H "Idempotency-Key: unique-key-123" \
  -H "Content-Type: application/json" \
  -d '{
    "postings": [
      {
        "source": "world",
        "destination": "users:alice",
        "amount": 100,
        "asset": "USD/2"
      }
    ]
  }'
```

### Replay

Retrying the same request with the same key returns the cached response — no second transaction is created. The response body is identical to the original, and the response includes an `Idempotency-Hit: true` header:

```http
HTTP/1.1 200 OK
Idempotency-Hit: true
```

If the request body differs from the original, the ledger returns a `VALIDATION` error instead. See [Validation Errors](#validation-errors).

## References

A `reference` is a field in the transaction body that acts as a unique identifier. If a transaction with the same reference already exists, the ledger returns an error.

### Example

curl

```bash
curl -X POST $FORMANCE_API_URL/api/ledger/v2/my-ledger/transactions \
  -H "Content-Type: application/json" \
  -d '{
    "reference": "order-12345-payment",
    "postings": [
      {
        "source": "world",
        "destination": "users:alice",
        "amount": 100,
        "asset": "USD/2"
      }
    ]
  }'
```

fctl

```bash
fctl ledger transactions num - --confirm --ledger my-ledger --reference order-12345-payment <<< 'send [USD/2 100] ( source = @world destination = @users:alice )'
```

## Choosing Between Idempotency Keys and References

| Use Case                                             | Recommended     | Reason                                          |
| ---------------------------------------------------- | --------------- | ----------------------------------------------- |
| Retry logic for network failures                     | Idempotency Key | System returns success on retry                 |
| Mapping to external entities (e.g., orders, refunds) | Reference       | Get an error if duplicate, useful for debugging |
| Unknown or dynamic transaction identity              | Idempotency Key | Works with any unique value                     |

Use a **reference** when you have a unique entity in your system that the transaction should match (e.g., a `refund` object creating a unique ledger transaction). You'll get an error if you try to re-submit with the same reference.

Use an **idempotency key** when the identity is less obvious or you want silent duplicate handling. The system will skip processing and return success on retry.

## Validation Errors

Reusing an idempotency key with different request content returns a `VALIDATION` error (HTTP 400). The ledger compares a hash of the request inputs against the hash stored with the original log entry; a mismatch is rejected.

### Error format

```json
{
  "errorCode": "VALIDATION",
  "errorMessage": "invalid idempotency hash when using idempotency key 'unique-key-123', has computed 'abc123...' but 'xyz789...' is stored"
}
```

### Common causes

- Changing any field in the request body (including metadata)
- Using a different endpoint path
- Modifying the request after a previous successful call

### Best practices

1. **Use unique keys for each distinct transaction** - Generate a new key for each new transaction
2. **Keep request parameters consistent** - If retrying, ensure all parameters match the original request exactly
3. **Use a new key if parameters change** - If you need to modify the transaction, generate a new idempotency key

Changing **any** part of the transaction, including metadata, will trigger a `VALIDATION` error when reusing an idempotency key.

Transactions written by Ledger 2.1 or earlier have no stored idempotency hash. For those entries the hash comparison is skipped and the original response is replayed, for backward compatibility.

For idempotency keys in bulk operations, see [Bulk Processing](https://docs.formance.com/v3.2/modules/ledger/working-with/bulk-processing#idempotency-in-bulk-operations).
