> ## Documentation Index
> Fetch the complete documentation index at: https://docs.momentco.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Handling Events

> Deduplicate webhook events, handle events that arrive out of order, and act on terminal outcomes once

Webhook events can arrive more than once, for example when a delivery is retried. They can also arrive out of order, so a newer event for an object may be received before an older one. This happens because each event is delivered and retried independently, so a retried older event can land after a newer one. See [Why Events Arrive Out of Order](#why-events-arrive-out-of-order).

Your integration should therefore process each event only once, and ignore any event that is older than the data it has already stored.

> [!NOTE]
>
> Always [verify](https://docs.momentco.io/api-reference/webhooks/verification.md) a webhook before handling it.

***

## Identifiers and Timestamps

Each webhook request carries three request headers alongside the payload, and the payload carries both an event `id` and the object. Each value serves a different purpose and none can be substituted for another.

| Value | Location | Across retries | Purpose |
| - | - | - | - |
| `id` | Root of the payload | Same | **Event identity.** Identifies the event, so it can be used to detect an event you have already processed. Distinct from both `webhook-id` and `data.id`. |
| `data.id` | Object in `data` | Same | **Object identity.** Identifies the object, for example the payment session, that you store and update. |
| `updated_at` | Object in `data` | Same | **Ordering.** Records when the object last changed, so it determines whether an event is newer than the state you have stored. |
| `webhook-id` | Request header | Same | **Delivery identity.** Identifies the message, so it can be used to detect a delivery you have already processed. |
| `webhook-timestamp` | Request header | New for each attempt | **Replay protection.** Records when this delivery attempt was made. See [Verifying Events](https://docs.momentco.io/api-reference/webhooks/verification.md#verifying-events). |
| `webhook-signature` | Request header | New for each attempt | **Authenticity.** Signs the `webhook-id`, `webhook-timestamp` and body of this delivery attempt. See [Verifying Events](https://docs.momentco.io/api-reference/webhooks/verification.md#verifying-events). |

***

## Acknowledge Then Process

Your endpoint must respond with a 2xx status code within 15 seconds, as described in [Processing Events](https://docs.momentco.io/api-reference/webhooks/setup.md#processing-events). If it takes longer, the delivery is treated as failed and retried, even if your endpoint is still working on the first attempt. This creates the duplicate and concurrent processing that the rest of this page guards against.

To avoid this, keep the work done during the request to a minimum:

1. Verify the webhook.
2. Store the event, for example in a queue or a table of received events.
3. Respond with a 2xx status code.
4. Process the event separately, for example in a background worker.

Background workers can also process events out of order, so apply the same rules to them that are described below.

Respond with a 2xx status code to any event type your integration does not handle, and ignore it, so that new event types do not cause retries or disable your endpoint.

***

## Handling Duplicate Events

Duplicate processing of events can be prevented at the request-level by processing events in an idempotent-safe manner. Each webhook request includes two identifiers you can use for this.

The `webhook-id` request header uniquely identifies the message. It stays the same across every retry of that message, while the `webhook-timestamp` changes with each delivery attempt.

The event `id` at the root of the message body uniquely identifies the event itself across all retries or replays. It is a separate value from the `webhook-id`, and also from the `id` of the object inside `data`.

To prevent duplicate deliveries, store the `webhook-id` in a persistent data store and ensure that a request with the same identifier has not been processed before.

To prevent duplicate logical events, store the event `id` in the same way. This is the most reliable key for business logic, because it identifies the event regardless of how or where it was delivered. Use it when you register more than one endpoint that feeds the same system, so an event received at each endpoint is only processed once.

Checking both the `webhook-id` and the event `id` ensures that a retried delivery of the same message, and a repeat of the same event, are each processed only once.

Keep stored identifiers for at least as long as deliveries can be retried. The [retry schedule](https://docs.momentco.io/api-reference/webhooks/setup.md#processing-events) spans about 28 hours, so keeping identifiers for a few days also covers events that are replayed later.

Beyond request-level handling, integrations should always implement operation-level idempotency, as request-level deduplication is often only applied over a limited time window. Operation-level idempotency ensures that repeated or delayed business events do not cause inconsistent state changes after that window has expired.

To achieve operation-level idempotency, compare the object's `updated_at` with the value you have stored before applying an event, as described in [Handling Out of Order Events](#handling-out-of-order-events). A duplicate or delayed event never carries a later `updated_at` than the state you have stored, so it is ignored.

The `updated_at` comparison, together with side effects that run only once as described in [Act on a Terminal Outcome Once](#act-on-a-terminal-outcome-once), is what keeps your data correct. Checking the `webhook-id` and event `id` is a fast way to skip work that has already been done, but correctness should not depend on it.

***

## Handling Out of Order Events

### Why Events Arrive Out of Order

Several events can be emitted for the same object within a short period of time, and each one is delivered independently. Events can therefore arrive out of order when:

* An earlier event fails delivery and is [retried](https://docs.momentco.io/api-reference/webhooks/setup.md#processing-events) after a later event has already been delivered.
* Multiple events for the same object are delivered concurrently, and your endpoint processes them in parallel.
* Network conditions delay one request relative to another.

For example, your endpoint can receive `payment_session.completed` and only afterwards receive a retry of an earlier `payment_session.updated` event for the same payment session. Applying the second event blindly would move your stored payment session back to an older state.

### Use `updated_at` to Order Events

Every event carries a full snapshot of the object in the `data` field, and that object includes an `updated_at` field. The `updated_at` value records when the object last changed state, so it is the reliable way to tell whether an event is newer or older than the state you have already stored.

Store the `updated_at` value alongside each object you persist. When an event arrives:

1. Look up the stored object using the object's `id` inside `data`, for example the payment session ID. Do not use the event `id` at the root of the payload, which identifies the event rather than the object.
2. If no stored object exists, apply the event and store its `updated_at`.
3. If the event's `updated_at` is **later** than the stored `updated_at`, apply the event and store the new `updated_at`.
4. Otherwise the event is stale or a duplicate. Ignore it.

In every case, respond with a 2xx status code. A stale event has been received successfully, and any other response would only cause it to be retried.

> [!NOTE]
>
> Compare `updated_at` values only between events for the same object. A `payment_session` and its related `payment` are separate objects, each with its own `updated_at`, and should be tracked independently.

If an event references a related object you have not stored yet, for example a `payment_id` on a payment session, process the event anyway rather than responding with an error. The related object's own events provide its details when they arrive.

> [!TIP]
>
> Because each event contains the complete object, you never need to replay a missed intermediate event. The latest snapshot already reflects every earlier change.

> [!WARNING]
>
> Do not use `webhook-timestamp` to order events. A new timestamp is generated for every delivery attempt, so a retry of an older event carries a later `webhook-timestamp` than a newer event that was delivered on its first attempt.

> [!WARNING]
>
> Do not rely on the event `type` to infer order. For example, a `payment_session.updated` event can arrive after `payment_session.completed`. Always compare `updated_at`.

***

## Handling Terminal Outcomes

Many objects, such as payment sessions, follow a lifecycle that ends in a terminal state. For example, a `payment_session` ends as `completed`, `expired`, or `cancelled`. The terminal state is usually the point at which your integration acts, for example by fulfilling an order.

The lifecycle page for each product defines its states, which of them are terminal, and the action to take on each outcome. For example, see the [Payment Session Lifecycle](https://docs.momentco.io/documentation/collect/payment-sessions/lifecycle.md) and [Handling fulfilment](https://docs.momentco.io/documentation/collect/payment-sessions/lifecycle.md#handling-fulfilment).

### Respect the Lifecycle

Once an object reaches a terminal state, its status does not change again. If an event appears to move a stored object out of a terminal state, it is an older event that arrived late, and the `updated_at` comparison described in [Use `updated_at` to Order Events](#use-updated_at-to-order-events) ignores it.

A terminal status does not always mean the object stops changing. Some objects can still be updated after reaching a terminal state, and each update emits a new event. Continue to apply newer events to an object in a terminal state using the `updated_at` comparison.

As an additional safeguard, you can also reject any update that would move a stored object out of a terminal state, or that is not a valid transition in the object's lifecycle.

### Act on a Terminal Outcome Once

More than one event can report the same terminal state for an object. For example, both a `payment_session.updated` and a `payment_session.completed` event can carry a `payment_session` with a `status` of `completed`. These are separate events, each with its own event `id` and `webhook-id`, so deduplicating on those identifiers alone does not prevent a side effect from running twice.

To act on a terminal outcome exactly once:

* Decide what to do from the object's fields, for example `status` and `payment_outcome` on a `payment_session`, rather than from the event `type`.
* Record each side effect against the object's `data.id`, for example by marking the payment session as fulfilled, and skip the side effect if it has already been recorded.
* Make the check and the record a single atomic operation, for example with a unique constraint on `data.id` in the table that records fulfilment, so that two events processed concurrently cannot both trigger it.

***

## Apply Updates Atomically

If your endpoint processes requests concurrently, two events for the same object can be handled at the same time. Reading the stored `updated_at` and then writing in a separate step leaves room for a stale event to overwrite a newer one.

Perform the comparison and the write in a single conditional operation instead. For example, in PostgreSQL:

```sql theme={"system"}
INSERT INTO payment_sessions (id, status, payment_outcome, updated_at, payload)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE
SET status          = EXCLUDED.status,
    payment_outcome = EXCLUDED.payment_outcome,
    updated_at      = EXCLUDED.updated_at,
    payload         = EXCLUDED.payload
WHERE payment_sessions.updated_at < EXCLUDED.updated_at;
```

This statement inserts a new row the first time an object is seen, and updates the existing row only when the incoming `updated_at` is later than the stored one. If the incoming event is older than or equal to the stored state, no row is changed and the event is safely ignored.

***

## Reconciling Missed Events

Some events may never reach your endpoint. An event is marked as failed once all [retry attempts](https://docs.momentco.io/api-reference/webhooks/setup.md#processing-events) are exhausted, and an endpoint is disabled if all attempts to it fail for 5 days.

If events are persistently failing, or your endpoint has been disabled, contact [customer success](https://docs.momentco.io/documentation/support.md) to re-enable your endpoint and to have events from the affected period replayed. Replayed events keep their event `id`, so the deduplication and ordering rules on this page handle them safely.

***

## Sample Code

The examples below run in the background worker described in [Acknowledge Then Process](#acknowledge-then-process), after the webhook has been [verified](https://docs.momentco.io/api-reference/webhooks/verification.md#verifying-events) and acknowledged. They use two helpers:

* `upsertIfNewer` runs the conditional upsert from [Apply Updates Atomically](#apply-updates-atomically), so stale and duplicate events change nothing.
* `fulfilOrderOnce` fulfils an order at most once per payment session, even when events are retried or processed concurrently.

> [accordion] Code Snippet - Handle a payment session event
>
> ```javascript Node.js theme={"system"}
> async function handlePaymentSessionEvent(event) {
>   const incoming = event.data;
>
>   // Inserts the first time, updates only if incoming.updated_at is later.
>   await upsertIfNewer(incoming);
>
>   // Decide from the latest stored state, not the incoming snapshot.
>   const session = await db.paymentSessions.findById(incoming.id);
>
>   if (session.status === 'completed' && session.payment_outcome === 'paid') {
>     await fulfilOrderOnce(session);
>   }
> }
>
> async function upsertIfNewer(session) {
>   // UPSERT_PAYMENT_SESSION_SQL is the statement from "Apply Updates Atomically".
>   await db.query(UPSERT_PAYMENT_SESSION_SQL, [
>     session.id,
>     session.status,
>     session.payment_outcome,
>     session.updated_at,
>     session,
>   ]);
> }
>
> async function fulfilOrderOnce(session) {
>   await db.transaction(async (tx) => {
>     // Create the fulfilment record the first time. The primary key prevents duplicates.
>     await tx.query(
>       `INSERT INTO fulfilments (payment_session_id, status)
>        VALUES ($1, 'pending')
>        ON CONFLICT (payment_session_id) DO NOTHING`,
>       [session.id]
>     );
>
>     // Lock the record so a concurrent event waits here until this transaction ends.
>     const { rows } = await tx.query(
>       `SELECT status FROM fulfilments WHERE payment_session_id = $1 FOR UPDATE`,
>       [session.id]
>     );
>
>     if (rows[0].status === 'done') {
>       return; // Already fulfilled.
>     }
>
>     // Pass the session ID as an idempotency key to any downstream system.
>     await fulfilOrder(session, { idempotencyKey: session.id });
>
>     await tx.query(
>       `UPDATE fulfilments SET status = 'done' WHERE payment_session_id = $1`,
>       [session.id]
>     );
>   });
> }
> ```
>
> ```python Python theme={"system"}
> def handle_payment_session_event(event: dict) -> None:
>     incoming = event["data"]
>
>     # Inserts the first time, updates only if incoming["updated_at"] is later.
>     upsert_if_newer(incoming)
>
>     # Decide from the latest stored state, not the incoming snapshot.
>     session = db.payment_sessions.find_by_id(incoming["id"])
>
>     if session["status"] == "completed" and session["payment_outcome"] == "paid":
>         fulfil_order_once(session)
>
>
> def upsert_if_newer(session: dict) -> None:
>     # UPSERT_PAYMENT_SESSION_SQL is the statement from "Apply Updates Atomically".
>     db.execute(
>         UPSERT_PAYMENT_SESSION_SQL,
>         (
>             session["id"],
>             session["status"],
>             session["payment_outcome"],
>             session["updated_at"],
>             session,
>         ),
>     )
>
>
> def fulfil_order_once(session: dict) -> None:
>     with db.transaction() as tx:
>         # Create the fulfilment record the first time. The primary key prevents duplicates.
>         tx.execute(
>             """
>             INSERT INTO fulfilments (payment_session_id, status)
>             VALUES (%s, 'pending')
>             ON CONFLICT (payment_session_id) DO NOTHING
>             """,
>             (session["id"],),
>         )
>
>         # Lock the record so a concurrent event waits here until this transaction ends.
>         status = tx.fetch_one(
>             "SELECT status FROM fulfilments WHERE payment_session_id = %s FOR UPDATE",
>             (session["id"],),
>         )["status"]
>
>         if status == "done":
>             return  # Already fulfilled.
>
>         # Pass the session ID as an idempotency key to any downstream system.
>         fulfil_order(session, idempotency_key=session["id"])
>
>         tx.execute(
>             "UPDATE fulfilments SET status = 'done' WHERE payment_session_id = %s",
>             (session["id"],),
>         )
> ```

The handler always attempts the conditional write and then reads the stored session, rather than returning early when an event looks stale. This matters when fulfilment fails after the session has been stored. When the event is processed again, for example when your worker retries the job, it still reaches the fulfilment step because the decision is based on the stored state.

`fulfilOrderOnce` records fulfilment in a `fulfilments` table keyed on the payment session ID:

* The first event for a session creates the record. Later events find the existing record instead of creating a second one.
* `FOR UPDATE` locks the record, so a concurrent event for the same session waits until the first transaction finishes, then sees that fulfilment is `done` and skips it.
* If fulfilment fails, the transaction rolls back and the record is not marked `done`, so a retry attempts fulfilment again.
* If fulfilment succeeds but the transaction fails to commit, a retry runs fulfilment again. Passing the session ID as an idempotency key to downstream systems prevents a second order in that case.

> [!NOTE]
>
> Store `updated_at` in a timestamp column rather than as a string, so that the database compares the values as timestamps.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.