# Configure an Event Sink

Source: https://docs.formance.com/v4.0/modules/ledger/events/configure-sink

Stack: v4.0

Add an event sink when another system needs to react to Ledger activity: keeping a downstream service in sync, feeding an analytics warehouse, or notifying a customer, without polling the Ledger API. One sink reads supported changes from the global log and sends them to one external destination. Each named sink keeps its own cursor and error state, so one slow destination never holds back another sink or a Ledger write.

## Prerequisites

This guide uses `ledgerctl`, and shows the HTTP routes that add and remove a sink. Prepare the following:

- a configured `ledgerctl` profile for the target cluster;
- a principal with `ledger:OpsWrite` to add or remove a sink, and `ledger:OpsRead` to list sinks;
- `ledgerctl`, a gRPC client, or an HTTP client for the add and remove operations. The HTTP routes submit unsigned mutations, so use `ledgerctl` or a signed gRPC client when `require_signatures=true`;
- network access from every cluster member to the destination, because any member can become the leader;
- a destination ready to acknowledge writes;
- an idempotent consumer or deduplication policy;
- enough destination capacity for the retained history that a new sink will replay.

### Supported event types

The event system publishes these event types:

| Event type              | Published when                                         |
| ----------------------- | ------------------------------------------------------ |
| `CREATED_LEDGER`        | A ledger is created.                                   |
| `DELETED_LEDGER`        | A ledger is deleted.                                   |
| `COMMITTED_TRANSACTION` | A transaction is committed.                            |
| `REVERTED_TRANSACTION`  | A transaction is reverted.                             |
| `SAVED_METADATA`        | Account or transaction metadata is saved.              |
| `DELETED_METADATA`      | Account or transaction metadata is deleted.            |
| `SKIPPED_ORDER`         | A bulk order is skipped for an allowed business error. |

Ledger does not currently publish an event for every configuration change. For example, do not expect events for indexes, prepared queries, Numscript library entries, account types, metadata schema changes, or signing configuration.

NATS, Kafka, and HTTP events contain the complete committed log, including transaction postings and metadata. ClickHouse and Databricks store a flattened form of the same business data. Apply destination access controls and retention rules as carefully as you do for the Ledger API.

## Choose a destination

| Destination    | Use it for                                   | Delivery contract                                                                                                                                                                                               |
| -------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| NATS JetStream | Durable event-driven applications            | Ledger publishes one message per event to `{topic}.{ledger}.{lowercase_event_type}` and waits for the JetStream acknowledgement. Configure a stream that captures the resulting subjects.                       |
| Kafka          | Partitioned stream processing                | Ledger writes to one topic, uses the ledger name as the record key, adds an `event_type` header containing the lowercase form of the JSON body's uppercase event type, and waits for every record in the batch. |
| HTTP           | Webhooks and direct service integrations     | Ledger sends one `POST` per event. Any `2xx` response acknowledges it; another status or a 30-second timeout causes a retry. Optional HMAC signing is available, but arbitrary authorization headers are not.   |
| ClickHouse     | Operational analytics                        | Ledger creates the target table when needed and inserts batches. The table uses `ReplacingMergeTree`; duplicate removal happens during background merges.                                                       |
| Databricks     | Delta Lake analytics through a SQL Warehouse | Ledger creates a Delta table and inserts batches. The table does not remove duplicate deliveries for you.                                                                                                       |

Authentication options are limited

The current NATS configuration exposes only a URL and subject prefix. Kafka exposes a TLS switch and SASL `PLAIN`, `SCRAM-SHA-256`, or `SCRAM-SHA-512`; it does not expose custom CA or client-certificate fields. Confirm that these authentication options match your environment before creating the sink.

## Choose delivery settings

All sink types share these settings:

| Flag               | Effective default   | Meaning                                                                                                                            |
| ------------------ | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `--format`         | `json`              | `json` or `protobuf` for NATS, Kafka, and HTTP. ClickHouse and Databricks use their analytical row format and ignore this setting. |
| `--batch-size`     | `64`                | Maximum number of events acknowledged before the cursor advances. The current maximum is `100000`.                                 |
| `--batch-delay-ms` | `10`                | Maximum wait before Ledger flushes a non-full batch.                                                                               |
| `--event-types`    | All supported types | Comma-separated allow-list of event types.                                                                                         |

Keep the defaults for webhooks and other latency-sensitive consumers. Raise `--batch-size` for analytical destinations, where throughput matters more than per-event latency; the server rejects anything above `100000`.

A new sink name starts without a cursor. It replays every supported event still in the global log, then follows new commits. History is permanent in the primary store, so size the destination for a catch-up over the whole retained log rather than a recent window.

The cursor also advances past excluded and unsupported log entries.

If you widen `--event-types` later, Ledger does not republish the events that the old filter excluded. The cursor has already advanced past them.

## Protect sink credentials

Populate the environment variables in the following examples from your secret manager.

Sink secrets

`ledgerctl events add-sink` takes destination secrets as command arguments. Environment substitution keeps the literal out of the command text, but the expanded value is still visible to other processes on the host while the command runs, so run these commands from a restricted administration environment and disable shell tracing around each one. The HTTP route takes them in the request body instead.

Ledger stores sink configurations as submitted, replicates them with cluster state, and includes them in backups. The sink list returned over HTTP and gRPC to callers with `ledger:OpsRead` is redacted. The Kafka SASL password, the HTTP sink's HMAC secret, the Databricks token, and the Databricks OAuth client secret read as `[redacted]`. A password, a NATS user token, or a credential query parameter such as `password` or `token` inside the NATS URL, ClickHouse DSN, or HTTP endpoint reads as `xxxxx`. `ledgerctl events list` masks the secret fields again, as `(set)` or `(none)`.

The redaction does not cover:

- the rest of each URL, such as a token embedded in the HTTP endpoint's path, nor the Kafka SASL username or Databricks client ID;
- the global log entry that records the sink's creation. `GET /v3/_/logs/{sequence}`, gRPC `GetLog`, and `ledgerctl logs get` return it with the full configuration to callers with `ledger:OpsRead`;
- audit entry details, whose serialized orders carry the same request to callers with `ledger:AuditRead`;
- backups.

Restrict `ledger:OpsRead` and `ledger:AuditRead`, avoid logging raw log or audit responses, and treat backups as secret-bearing.

## Add the sink

Choose exactly one destination. Keep the default JSON format unless your consumer already decodes the `events.Event` protobuf message.

NATS JetStream

```bash
ledgerctl events add-sink \
  --name application-events \
  --nats-url "$NATS_URL" \
  --nats-topic ledger.events \
  --event-types COMMITTED_TRANSACTION,REVERTED_TRANSACTION
```

With this configuration, a committed transaction for the `orders` ledger is published on `ledger.events.orders.committed_transaction`.

Kafka

```bash
ledgerctl events add-sink \
  --name application-events \
  --kafka-brokers broker-1.example.com:9093,broker-2.example.com:9093 \
  --kafka-topic ledger-events \
  --kafka-tls \
  --kafka-sasl-mechanism SCRAM-SHA-256 \
  --kafka-sasl-username "$KAFKA_SASL_USERNAME" \
  --kafka-sasl-password "$KAFKA_SASL_PASSWORD"
```

Kafka preserves order within a partition. Because Ledger keys records by ledger name, do not assume that a consumer observes one global order across all partitions.

HTTP

```bash
ledgerctl events add-sink \
  --name application-webhook \
  --http-endpoint https://events.example.com/ledger \
  --http-secret "$LEDGER_WEBHOOK_SECRET" \
  --batch-size 64
```

Ledger signs the raw request body as `sha256=<hex HMAC-SHA256>` in `X-Webhook-Signature`. See [Consume, Monitor, and Recover Events](https://docs.formance.com/v4.0/modules/ledger/events/consume-and-recover) for receiver code.

ClickHouse

```bash
ledgerctl events add-sink \
  --name ledger-analytics \
  --clickhouse-dsn "$CLICKHOUSE_DSN" \
  --clickhouse-table ledger_events \
  --batch-size 256
```

The configured ClickHouse user needs permission to connect, create the table if it does not exist, and insert rows. The sink requires the experimental JSON and Variant types used by the generated table.

Databricks

```bash
ledgerctl events add-sink \
  --name ledger-analytics \
  --databricks-host "$DATABRICKS_HOST" \
  --databricks-http-path "$DATABRICKS_HTTP_PATH" \
  --databricks-catalog main \
  --databricks-schema finance \
  --databricks-table ledger_events \
  --databricks-client-id "$DATABRICKS_CLIENT_ID" \
  --databricks-client-secret "$DATABRICKS_CLIENT_SECRET"
```

Use either OAuth M2M as shown above or `--databricks-token "$DATABRICKS_TOKEN"`, never both. The identity needs permission to use the SQL Warehouse and create or insert into the target table.

Optional sinks depend on the image build

Only the HTTP sink is always compiled in. NATS, Kafka, ClickHouse, and Databricks are each behind a Go build tag, and a sink whose tag is absent fails to start with `unsupported events sink type: <type> (not compiled in this build)`. Official Ledger releases are built with all four. An image built from the repository Dockerfile is not: it enables no optional sink unless the build passes the tag. Confirm the build tags of the exact image you deploy before treating one of these integrations as production-supported.

### Add a sink over HTTP

`POST /v3/_/events-sinks` adds the same sink and requires `ledger:OpsWrite`. The body is the sink configuration itself, with no wrapper: a `name`, exactly one destination object (`nats`, `kafka`, `http`, `clickhouse`, or `databricks`), and the optional `format`, `batchSize`, `batchDelayMs`, `eventTypes`, and `controllerId` fields. Field names use protobuf JSON camelCase, so `--batch-size` becomes `batchSize`, and `eventTypes` is an array of event type names.

Set `LEDGER_URL` to the root immediately before Ledger's `/v3` routes, and export `LEDGER_TOKEN` from your secret manager. This example builds the body with `jq`, which reads the destination URL from the environment so that it never appears as a command argument:

```bash
jq -n '{
  name: "application-events",
  nats: {url: env.NATS_URL, topic: "ledger.events"},
  eventTypes: ["COMMITTED_TRANSACTION", "REVERTED_TRANSACTION"]
}' \
  | curl --fail-with-body --silent --show-error \
    -X POST "$LEDGER_URL/v3/_/events-sinks" \
    -H "Authorization: Bearer $LEDGER_TOKEN" \
    -H 'Content-Type: application/json' \
    -H 'Idempotency-Key: add-sink:application-events:v1' \
    --data-binary @-
```

A `201` response returns only the sink name, as `{"data":{"name":"application-events"}}`. It confirms that the configuration was committed, not that Ledger can reach the destination, so [verify delivery](#verify-delivery) as you would for a sink added with `ledgerctl`. An unknown field, a second destination object, or malformed JSON returns `400 INVALID_REQUEST`, and an existing name returns `409 SINK_ALREADY_EXISTS`. If the response is lost, retry with the same `Idempotency-Key` and body. Use a new key for any other operation, including adding a sink again after removing it.

The HTTP sink routes submit unsigned mutations, and Ledger rejects them when `require_signatures=true`. In that mode, use `ledgerctl events add-sink` and `ledgerctl events remove-sink` with a registered signing key, or a gRPC client that signs the `Apply` batch. See [Request and Response Signing](https://docs.formance.com/v4.0/modules/ledger/operations/signing).

## Verify delivery

Run this acceptance test in one Bash session. It creates a disposable normal ledger, commits one referenced transaction, finds that transaction's global `logSequence`, and waits for the chosen sink to acknowledge at least that sequence. Choose the mutation branch that matches the cluster's request-signing policy, then use the common delivery checks that follow it.

You need `curl`, `jq`, `ledgerctl`, and:

- an HTTP bearer token with the `ledger:LedgerRead`, `ledger:LedgerWrite`, `ledger:TransactionWrite`, and `ledger:OpsRead` granular scopes, or the default `ledger:write` and `ledger:read` scope bundles;
- a `ledgerctl` profile that reaches the same Ledger cluster over gRPC;
- the exact name of a sink whose event filter is empty or includes `COMMITTED_TRANSACTION`.

The HTTP ledger create, transaction create, and ledger delete routes used below always submit unsigned mutations. They fail when `require_signatures=true`. Do not lower the policy to run this test. Use the signed `ledgerctl` branch below, or a version-pinned gRPC client that signs the exact `ApplyBatch`, and keep the HTTP calls only for read checks. A global signing flag protects `ledgerctl` commands only when they use the signed `Apply` path; it does not make an unsigned HTTP or unary gRPC mutation compatible. See [Request and Response Signing](https://docs.formance.com/v4.0/modules/ledger/operations/signing#check-mutation-compatibility).

Set the HTTP endpoint, profile, and sink name, and take the bearer token from the environment rather than the script. `LEDGER_URL` is the root immediately before Ledger's `/v3` routes. Change `SINK_NAME` if you used `application-webhook` or `ledger-analytics` in the examples above.

```bash
set -euo pipefail

export LEDGER_URL="https://ledger.example.com"
# Export LEDGER_TOKEN from your secret manager before running this block, so the
# bearer token never reaches shell history or CI logs. This assertion fails fast
# if it is unset.
: "${LEDGER_TOKEN:?export the bearer token from your secret manager first}"
export LEDGER_TOKEN
export LEDGERCTL_PROFILE="events-acceptance"
export LEDGERCTL_AUTH_TOKEN="$LEDGER_TOKEN"
export SINK_NAME="application-events"

export RUN_ID="$(date -u +%Y%m%d%H%M%S)-$$"
export LEDGER_NAME="events-smoke-$RUN_ID"
export EVENT_REFERENCE="events-smoke-$RUN_ID"
export EVENT_IDEMPOTENCY_KEY="events-smoke:$RUN_ID"
```

First, assert that the named sink exists and will not filter out the test transaction:

```bash
ledgerctl events list --json > "/tmp/events-sinks-$RUN_ID.json"

jq -e --arg sink "$SINK_NAME" '
  [.sinks[] | select(.name == $sink)] as $matches
  | (($matches | length) == 1)
    and (
      ($matches[0].eventTypes | length) == 0
      or ($matches[0].eventTypes | index("COMMITTED_TRANSACTION") != null)
    )
' "/tmp/events-sinks-$RUN_ID.json" > /dev/null
```

Choose one of the following mutation branches. Both create the same ledger and transaction, so the common log and destination checks work without modification.

### Branch A: unsigned HTTP mutations

Use this branch only while `require_signatures=false`.

Create a dedicated ledger so its test log is easy to identify:

```bash
curl --fail-with-body --silent --show-error \
  -X POST "$LEDGER_URL/v3/$LEDGER_NAME" \
  -H "Authorization: Bearer $LEDGER_TOKEN" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: events-smoke:create:$RUN_ID" \
  --data '{"mode":"NORMAL"}' \
  | jq -e --arg ledger "$LEDGER_NAME" \
      '.data.name == $ledger' > /dev/null
```

Build one request body, commit it, and retry the exact same request. The second response must identify the same transaction; this proves that a lost HTTP response can be retried without emitting a second committed-transaction event.

```bash
export EVENT_BODY="$(
  jq -nc --arg reference "$EVENT_REFERENCE" '{
    reference: $reference,
    postings: [{
      source: "world",
      destination: "events:verification",
      asset: "USD/2",
      amount: 100
    }]
  }'
)"

curl --fail-with-body --silent --show-error \
  -X POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  -H "Authorization: Bearer $LEDGER_TOKEN" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $EVENT_IDEMPOTENCY_KEY" \
  --data "$EVENT_BODY" \
  > "/tmp/events-transaction-first-$RUN_ID.json"

curl --fail-with-body --silent --show-error \
  -X POST "$LEDGER_URL/v3/$LEDGER_NAME/transactions" \
  -H "Authorization: Bearer $LEDGER_TOKEN" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $EVENT_IDEMPOTENCY_KEY" \
  --data "$EVENT_BODY" \
  > "/tmp/events-transaction-retry-$RUN_ID.json"

jq -e \
  --arg reference "$EVENT_REFERENCE" \
  --slurpfile retry "/tmp/events-transaction-retry-$RUN_ID.json" '
    (.data.transaction.reference == $reference)
    and (.data.transaction.id == $retry[0].data.transaction.id)
  ' "/tmp/events-transaction-first-$RUN_ID.json" > /dev/null
```

### Branch B: mandatory request signatures

Use this branch when `require_signatures=true`. Configure the registered signing key through your secret manager, then create the ledger and transaction through `ledgerctl` commands that use the signed gRPC `Apply` path:

```bash
export LEDGER_SIGNING_KEY_FILE="/secure/path/application.seed"
export LEDGER_SIGNING_KEY_ID="application"

ledgerctl \
  --signing-key "$LEDGER_SIGNING_KEY_FILE" \
  --signing-key-id "$LEDGER_SIGNING_KEY_ID" \
  ledgers create "$LEDGER_NAME" \
  --idempotency-key "events-smoke:create:$RUN_ID"

ledgerctl \
  --signing-key "$LEDGER_SIGNING_KEY_FILE" \
  --signing-key-id "$LEDGER_SIGNING_KEY_ID" \
  transactions create \
  --ledger "$LEDGER_NAME" \
  --posting "world,events:verification,100,USD/2" \
  --reference "$EVENT_REFERENCE" \
  --json \
  > "/tmp/events-transaction-signed-$RUN_ID.json"
```

`ledgers create` signs its `--idempotency-key` into the batch, so after an ambiguous timeout you can rerun that command unchanged and receive the original result. `transactions create` has no idempotency-key option and submits an empty key: do not retry it after an ambiguous timeout until a read or the global log proves whether it committed. If this acceptance test must also prove transaction retry idempotency, use a signed gRPC client that persists the original idempotency key and resends the same requests under that key.

### Confirm the log sequence and sink cursor

Run these checks after either branch.

The transaction response does not expose its global log sequence. Poll the ledger log until the asynchronous read index exposes the entry, then extract the sequence from the matching reference:

```bash
export LOG_SEQUENCE=""
deadline=$((SECONDS + 30))

while [[ -z "$LOG_SEQUENCE" ]]; do
  ledgerctl logs list \
    --ledger "$LEDGER_NAME" \
    --page-size 10 \
    --json \
    > "/tmp/events-logs-$RUN_ID.json"

  LOG_SEQUENCE="$(
    jq -er --arg reference "$EVENT_REFERENCE" '
      [
        .[]
        | select(
            .payload.apply.log.data.createdTransaction.transaction.reference
            == $reference
          )
        | .sequence
      ]
      | if length == 1 then .[0] else empty end
    ' "/tmp/events-logs-$RUN_ID.json" || true
  )"

  if [[ -z "$LOG_SEQUENCE" && $SECONDS -ge $deadline ]]; then
    echo "Timed out while waiting for the transaction log" >&2
    exit 1
  fi

  [[ -n "$LOG_SEQUENCE" ]] || sleep 1
done

export LOG_SEQUENCE
jq -en --argjson sequence "$LOG_SEQUENCE" '$sequence > 0' > /dev/null
```

Finally, poll the sink status for up to 60 seconds. The assertion passes only when that sink's cursor is at or beyond the test transaction and its error field is empty:

```bash
deadline=$((SECONDS + 60))

while true; do
  ledgerctl events list --json > "/tmp/events-sink-status-$RUN_ID.json"

  if jq -e \
    --arg sink "$SINK_NAME" \
    --argjson sequence "$LOG_SEQUENCE" '
      .sinkStatuses[]
      | select(.sinkName == $sink)
      | ((.cursor | tonumber) >= $sequence)
        and ((.error == null) or ((.error.message // "") == ""))
    ' "/tmp/events-sink-status-$RUN_ID.json" > /dev/null; then
    break
  fi

  if ((SECONDS >= deadline)); then
    echo "Sink did not acknowledge logSequence $LOG_SEQUENCE within 60 seconds" >&2
    jq --arg sink "$SINK_NAME" \
      '.sinkStatuses[] | select(.sinkName == $sink)' \
      "/tmp/events-sink-status-$RUN_ID.json" >&2
    exit 1
  fi

  sleep 2
done

jq -e \
  --arg sink "$SINK_NAME" \
  --argjson sequence "$LOG_SEQUENCE" '
    .sinkStatuses[]
    | select(.sinkName == $sink)
    | {
        sinkName,
        cursor: (.cursor | tonumber),
        error
      }
    | select(.cursor >= $sequence)
    | select((.error == null) or ((.error.message // "") == ""))
  ' "/tmp/events-sink-status-$RUN_ID.json"
```

The final object is the Ledger-side acceptance result. A cursor at or above `LOG_SEQUENCE` means the sink acknowledged the complete batch containing the event. It does not establish exactly-once consumption: if Ledger published a batch but could not persist its new cursor before a failure or leader change, that batch can be delivered again. Deduplicate at the consumer with the stable cluster source you assign and the event's `logSequence`.

If the command times out, inspect the printed `error` and the Ledger server logs for `SINK_NAME`. Ledger keeps the cursor before a failed batch and retries publishing with exponential backoff. Correct destination connectivity, credentials, or acknowledgement behavior, then run the polling block again; there is no separate retry API to call.

### Confirm the destination and tear down

After the Ledger-side assertion passes, confirm that the destination contains the event with `reference == EVENT_REFERENCE` and `logSequence == LOG_SEQUENCE`:

| Destination | What to verify                                                                                                                                                                                                     |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| NATS        | The stream captures the configured subject prefix and the message contains the expected `reference` and `logSequence`.                                                                                             |
| Kafka       | The record is on the configured topic, its key is `LEDGER_NAME`, the body contains the expected `reference` and `logSequence`, and the decoded `event_type` header equals the lowercase form of the body's `type`. |
| HTTP        | The receiver durably stores the expected `reference` and `logSequence`, verifies the signature, and returns `2xx` only after that acceptance.                                                                      |
| ClickHouse  | `SELECT log_sequence, type, ledger, data.transaction.reference FROM ledger_events FINAL WHERE log_sequence = <LOG_SEQUENCE>` returns the expected ledger and reference.                                            |
| Databricks  | `SELECT log_sequence, type, ledger, data:transaction.reference FROM main.finance.ledger_events WHERE log_sequence = <LOG_SEQUENCE>` returns the expected ledger and reference.                                     |

For the Kafka event produced by this test, assert this exact relationship after decoding the header bytes as UTF-8:

```text
body.type == "COMMITTED_TRANSACTION"
headers["event_type"] == "committed_transaction"
headers["event_type"] == ascii_lowercase(body.type)
```

The header and the JSON enum are intentionally not byte-equal.

After confirming the destination, delete the test ledger with the same mutation branch you used to create it. The block runs under `set -euo pipefail`, so an unexpected response aborts the session and leaves the disposable ledger in place; re-run the teardown commands until the read check returns `404`.

For Branch A, reuse the derived idempotency key if the HTTP DELETE response is lost, then verify independently that the ledger is gone:

```bash
delete_status="$(
  curl --silent --show-error \
    -X DELETE "$LEDGER_URL/v3/$LEDGER_NAME" \
    -H "Authorization: Bearer $LEDGER_TOKEN" \
    -H "Idempotency-Key: events-smoke:delete:$RUN_ID" \
    --output /dev/null \
    --write-out '%{http_code}'
)"
[[ "$delete_status" == "204" ]]

get_status="$(
  curl --silent --show-error \
    -H "Authorization: Bearer $LEDGER_TOKEN" \
    "$LEDGER_URL/v3/$LEDGER_NAME" \
    --output /dev/null \
    --write-out '%{http_code}'
)"
[[ "$get_status" == "404" ]]
```

For Branch B, delete the ledger through the signed `Apply` path. This command does not carry an idempotency key, so reconcile an ambiguous result with the read check before considering another delete:

```bash
ledgerctl \
  --signing-key "$LEDGER_SIGNING_KEY_FILE" \
  --signing-key-id "$LEDGER_SIGNING_KEY_ID" \
  ledgers delete "$LEDGER_NAME" --yes

get_status="$(
  curl --silent --show-error \
    -H "Authorization: Bearer $LEDGER_TOKEN" \
    "$LEDGER_URL/v3/$LEDGER_NAME" \
    --output /dev/null \
    --write-out '%{http_code}'
)"
[[ "$get_status" == "404" ]]
```

A sink that `ledgerctl events list` reports as `healthy` is not necessarily delivering: that status only means no publish error is recorded, and an initial connection or configuration failure is not recorded there. A referenced test event, a destination receipt, and the asserted cursor advance are the acceptance criteria. See [Monitor each sink](https://docs.formance.com/v4.0/modules/ledger/events/consume-and-recover#monitor-each-sink).

## Replace or remove a sink

The current server rejects `add-sink` when the name already exists, even though some CLI help text describes the operation as an upsert. To replace a configuration safely:

1. Add the corrected configuration under a new name.
2. Allow for replay from the retained global log.
3. Verify a known event and cursor advancement on the new sink.
4. Confirm that the consumer deduplicates replayed events.
5. Remove the old sink.

```bash
ledgerctl events remove-sink --name application-events-old
```

Over HTTP, `DELETE /v3/_/events-sinks/{sinkName}` removes the sink with the same `ledger:OpsWrite` scope and returns `204`. An unknown name returns `404 SINK_NOT_FOUND`:

```bash
curl --fail-with-body --silent --show-error \
  -X DELETE "$LEDGER_URL/v3/_/events-sinks/application-events-old" \
  -H "Authorization: Bearer $LEDGER_TOKEN" \
  -H 'Idempotency-Key: remove-sink:application-events-old:v1'
```

A sink created with a `controllerId`, the opaque owner identity that an automated controller records on the sinks it manages, can be removed conditionally: pass the same value as the `controllerId` query parameter, or as `--controller-id` to `ledgerctl events remove-sink`. Ledger then removes the sink only when the stored value matches, and returns `409 SINK_CONTROLLER_MISMATCH` otherwise. Without it, removal is unconditional. `controllerId` guards against removing a sink that another controller owns; it is not an authorization check.

Removing the final sink stops event delivery. There is no public cursor reset or replay command. Do not rely on removing and re-adding the same name to reset its cursor; use a new name and account for retained-history replay instead.

Continue with [Consume, Monitor, and Recover Events](https://docs.formance.com/v4.0/modules/ledger/events/consume-and-recover) before sending production traffic.
