# Consume, Monitor, and Recover Events

Source: https://docs.formance.com/v4.0/modules/ledger/events/consume-and-recover

Stack: v4.0

This page covers the consumer side: processing Ledger events without applying a business effect twice, verifying webhook authenticity, watching each sink's progress, and getting a stalled sink moving again.

Ledger advances a sink cursor only after the destination acknowledges a batch. If delivery succeeds but Ledger cannot persist the new cursor before a restart or leader change, it sends that batch again. Consumers must therefore accept duplicate deliveries without applying the same business effect twice.

## Read the event contract

NATS, Kafka, and HTTP receive the complete event envelope:

| Field         | Meaning                                                                                                                        |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `app`         | Stable producer identifier. Always `ledger`.                                                                                   |
| `version`     | Event envelope generation. Always `v3`.                                                                                        |
| `type`        | One of the [supported event types](https://docs.formance.com/v4.0/modules/ledger/events/configure-sink#supported-event-types). |
| `ledger`      | Ledger name associated with the event.                                                                                         |
| `date`        | Timestamp assigned to the committed change.                                                                                    |
| `logSequence` | Monotonically increasing position in the cluster's global log.                                                                 |
| `log`         | Complete committed log and its typed payload.                                                                                  |

In JSON, `logSequence` is an unsigned 64-bit number. Use an integer-safe JSON parser and an integer or decimal database type. JavaScript's `number` type cannot represent every 64-bit value exactly.

ClickHouse and Databricks use a different storage shape. They write `log_sequence`, `type`, `ledger`, and `date` columns, then store a flattened event payload in `data`. Do not write one decoder and assume that all five destinations receive the same representation.

## Deduplicate before applying side effects

Use the pair `(source, logSequence)` as the event identity. `logSequence` is unique inside one Ledger cluster, but the envelope does not include a cluster identifier. Assign a stable `source` value in your integration when several clusters feed the same consumer.

Give each cluster its own analytical table

The analytical row shape has no place to record that `source`: ClickHouse and Databricks tables hold only `log_sequence`, `type`, `ledger`, `date`, and `data`. Point each cluster at its own table. If two clusters write to one ClickHouse table, `ReplacingMergeTree` sorts by `(ledger, log_sequence)` and collapses two distinct events that happen to share that pair; on Databricks, deduplicating by `log_sequence` in a query discards them the same way.

A receipt table can enforce this rule:

```sql
CREATE TABLE ledger_event_receipts (
    source        text           NOT NULL,
    log_sequence numeric(20, 0) NOT NULL,
    received_at  timestamptz    NOT NULL DEFAULT now(),
    PRIMARY KEY (source, log_sequence)
);
```

For every event, insert the receipt and apply the business change in one database transaction:

```sql
BEGIN;

INSERT INTO ledger_event_receipts (source, log_sequence)
VALUES (:source, :log_sequence)
ON CONFLICT DO NOTHING
RETURNING log_sequence;

-- Apply the business change only when the INSERT returned a row.

COMMIT;
```

If the business change and receipt cannot share a transaction, use an inbox/outbox workflow that records the receipt durably before an asynchronous worker runs the side effect.

Do not deduplicate with only `logSequence <= lastProcessedSequence`. Kafka partitions, NATS subjects, and concurrent webhook workers can expose events out of order. A single high-water mark could then discard a valid event that arrives later.

Sequence gaps are also valid. Filters advance the sink cursor past excluded event types, and Ledger does not publish events for every internal log entry. Use `logSequence` to identify and compare events, not to require a contiguous series.

## Acknowledge only durable work

| Destination    | Consumer acknowledgement rule                                                                                                                                            |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| NATS JetStream | Acknowledge the message after the receipt and business change commit. Configure consumer redelivery limits and route terminal failures from your application.            |
| Kafka          | Commit the consumer offset after the receipt and business change commit. The ledger name is the record key, so Kafka preserves per-ledger order within a partition.      |
| HTTP           | Return `2xx` only after durable acceptance. Ledger retries network errors, timeouts, and non-`2xx` responses.                                                            |
| ClickHouse     | Use the table as an analytical projection. Query with `FINAL` or `GROUP BY` when exact counts matter because `ReplacingMergeTree` removes duplicate rows asynchronously. |
| Databricks     | Deduplicate `log_sequence` in your query or downstream table. The generated Delta table uses ordinary inserts and does not collapse re-delivered rows.                   |

The event producer scans the global log in order, but the destination can partition or process messages concurrently. If a workflow requires ordering, define the scope that matters—usually one ledger or one business entity—and serialize that scope in the consumer.

## Verify HTTP webhook signatures

When an HTTP sink has a secret, Ledger sends these headers:

| Header                | Value                                                  |
| --------------------- | ------------------------------------------------------ |
| `Content-Type`        | `application/json` or `application/protobuf`           |
| `X-Event-Type`        | Lowercase event type                                   |
| `X-Ledger`            | Ledger name                                            |
| `X-Log-Sequence`      | Global log sequence                                    |
| `X-Webhook-Signature` | `sha256=<hex HMAC-SHA256>` when a secret is configured |

Calculate the HMAC over the raw request body before parsing or modifying it:

```typescript
import { createHmac, timingSafeEqual } from "node:crypto"

export function verifyLedgerWebhook(
  rawBody: Buffer,
  suppliedSignature: string | undefined,
  secrets: readonly string[],
): boolean {
  if (!suppliedSignature) {
    return false
  }

  const supplied = Buffer.from(suppliedSignature, "utf8")
  let accepted = false

  for (const secret of secrets) {
    const expected = Buffer.from(
      `sha256=${createHmac("sha256", secret).update(rawBody).digest("hex")}`,
      "utf8",
    )

    if (supplied.length === expected.length && timingSafeEqual(supplied, expected)) {
      accepted = true
    }
  }

  return accepted
}
```

Reject an invalid signature without running the consumer. The verifier accepts a set of secrets rather than one because a sink configuration cannot be updated in place: rotating a webhook secret means adding a second sink that carries the new secret, then removing the old sink once you have confirmed the new one. Both sinks deliver during that window, each signing with its own secret, so keep every valid secret in `secrets` until the old sink is gone. The replacement sink also starts without a cursor and replays the retained global log, so expect the receiver to absorb that catch-up as duplicate deliveries against its receipt table.

## Monitor each sink

Read the cluster-wide status with a principal that has `ledger:OpsRead`:

```bash
ledgerctl events list --json \
  | jq '.sinkStatuses[] | {sinkName, cursor, error}'
```

The CLI masks secrets in its structured output. The fields have these operational meanings:

| Field              | Meaning                                                                                                                   |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `sinkName`         | Stable identity of the configuration, cursor, and error state.                                                            |
| `cursor`           | Highest global-log position the sink has processed. It can include filtered entries that produced no destination message. |
| `error.message`    | Latest publish failure for a sink that started successfully.                                                              |
| `error.occurredAt` | Time at which Ledger most recently recorded that failure.                                                                 |

Poll this status and run a periodic synthetic delivery check. The current release branch does not expose a stable event-specific metrics contract, and status alone cannot prove end-to-end delivery.

| Signal                                                            | Likely meaning                                                                                 | Action                                                                                             |
| ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| Cursor advances and the test event is present                     | The sink is reading and the destination is acknowledging events.                               | Continue monitoring receipt latency and consumer failures.                                         |
| Error is present and cursor stops                                 | A running sink cannot publish.                                                                 | Restore the destination or credentials, then wait for the error to clear and cursor to advance.    |
| Cursor stays at `0` with no error                                 | There may be no supported event, or sink startup may have failed before error reporting began. | Commit a test event and inspect Ledger server logs for the sink name.                              |
| Cursor passes an enabled test event but the consumer sees nothing | Ledger processed the event, but filtering, routing, or consumer configuration may be wrong.    | Check the sink event filter, NATS subject, Kafka topic and key, webhook logs, or analytical table. |
| One sink stalls while another advances                            | Each sink progresses independently.                                                            | Repair only the stalled destination; Ledger writes and other sinks continue.                       |
| Duplicate `logSequence` values appear                             | Delivery succeeded before the cursor update completed, or a batch was partially acknowledged.  | Keep one receipt and suppress the repeated side effect.                                            |
| Sequence values contain gaps                                      | Filters or unsupported internal logs were skipped.                                             | Do not treat gaps alone as data loss. Verify a known event instead.                                |

A sink shown without an error is not necessarily delivering. Connection failures during initial startup are written to Ledger server logs but are not currently reflected in `SinkStatus`. Always require a destination receipt and cursor advancement for readiness.

## Recover a running sink after a destination outage

Once a sink has started, publish failures leave its cursor unchanged and record an error. Ledger retries with exponential backoff, starting around one second and capping around one minute. A successful batch advances the cursor and clears the error.

1. Leave the sink configured while you restore the destination if its address and credentials remain valid.
2. Confirm that Ledger writes still succeed; event delivery is asynchronous and must not be part of transaction availability.
3. Restore network access, broker availability, webhook responses, or analytical-store capacity.
4. Poll `ledgerctl events list --json` until the error clears and the cursor advances.
5. Commit a uniquely referenced test transaction.
6. Confirm its `logSequence` at the destination and in your receipt table.
7. Confirm that a repeated delivery would not repeat the business side effect.

Do not manually move the cursor forward to silence an error. Ledger exposes no public cursor mutation, replay, or sink-level dead-letter API.

## Recover an initial startup failure

An invalid address, missing build feature, or failed connection can prevent NATS, Kafka, ClickHouse, or Databricks from starting before publish retries exist. In that case, the status can remain error-free and the sink does not automatically reconnect through the publish backoff.

1. Inspect the Ledger server logs for the sink name and the connection error.
2. Confirm that the deployed binary includes the destination's optional sink feature.
3. Correct networking, privileges, and credentials.
4. Add the corrected configuration under a new sink name.
5. Generate a test event and verify its receipt and cursor.
6. Remove the failed configuration only after the new sink works.

A new name replays every supported event in the global log from the beginning. Plan destination capacity and rely on consumer deduplication during that catch-up.

## Run a failure drill

Complete this drill before depending on a sink in production:

1. Deliver a baseline test event and record its `logSequence` and the sink cursor.
2. Make the destination unavailable without stopping Ledger.
3. Commit another uniquely referenced transaction and confirm that the Ledger write succeeds.
4. For a sink that had already started, confirm that its cursor stops and an error appears.
5. Restore the destination.
6. Confirm that the error clears and the cursor passes the test event's sequence.
7. Confirm that the receipt table contains one row and the business effect occurred once, even if the destination received the event more than once.

See [Configure an Event Sink](https://docs.formance.com/v4.0/modules/ledger/events/configure-sink) when you need to change destination settings or event filters.
