# Receiving webhooks

> Verify each request's signature, answer fast, and handle retries, duplicates and ordering.

This page covers everything your endpoint does with a webhook request. [Webhooks](https://docs.mothership.com/reference/webhooks) lists the events and what each one sends.

A handler that holds up in production does five things, in this order:

1. Reads the raw request body.
2. Verifies `X-Mothership-Signature` against it, and answers `401` if it doesn't match.
3. Skips the request if it already processed that `X-Mothership-Delivery-Id`.
4. Hands the event to a queue or background job.
5. Answers `200` within 30 seconds.

## Verify the signature

Anyone can send a request to your endpoint, so check every one before you act on it. Each webhook configuration has its own `secretKey`, which [Create a webhook configuration](https://docs.mothership.com/reference/createwebhookconfig) and [Retrieve a webhook configuration](https://docs.mothership.com/reference/fetchwebhookconfig) return.

```json Create Webhook 201 Response
{
  "data": {
    "id": "48asjgaoi33nkl4t3lae",
    "createdAt": "2019-03-20T16:17:13.424Z",
    "status": "active",
    "subscribedEvents": ["shipment.purchased", "billOfLading.created", "proofOfDelivery.created"],
    "webhookUrl": "https://www.yourserver.io/webhook/mothership",
    "secretKey": "de3ADDAek3245DLAdANe91Dn3asklAMSsna03aGKkl23agsJea"
  }
}
```

`X-Mothership-Signature` is the hex-encoded HMAC-SHA256 of the raw request body, keyed with that secret. Compute the same HMAC over the body exactly as you received it, then compare the two with a constant-time comparison.

> [!WARNING] Sign the raw body
> Compute the signature before parsing the JSON. Parsing and re-serializing the body can change spacing or key order, and the signature will no longer match.

Both examples read the secret from the `MOTHERSHIP_WEBHOOK_SECRET` environment variable. Keep it in your secret store, not in source control, and give each configuration's secret its own entry.

```javascript Node.js
import crypto from 'node:crypto'
import express from 'express'

const app = express()
// Check the signature against the raw body, before any JSON parsing.
const rawBody = express.raw({ type: 'application/json' })

app.post('/webhooks/mothership', rawBody, (req, res) => {
  const expected = crypto
    .createHmac('sha256', process.env.MOTHERSHIP_WEBHOOK_SECRET)
    .update(req.body)
    .digest('hex')
  const received = req.get('X-Mothership-Signature') ?? ''

  if (
    !/^[a-f0-9]{64}$/.test(received) ||
    !crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected))
  ) {
    return res.sendStatus(401)
  }

  const event = JSON.parse(req.body.toString('utf8'))
  // event.eventType, event.data, event.sentAt, event.deliveryAttempt, event.pendingRetries
  res.sendStatus(200)
})
```
```python Python
import hashlib
import hmac
import os
import re

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["MOTHERSHIP_WEBHOOK_SECRET"].encode()

@app.post("/webhooks/mothership")
def mothership_webhook():
    # Check the signature against the raw body, before any JSON parsing.
    expected = hmac.new(SECRET, request.get_data(), hashlib.sha256).hexdigest()
    received = request.headers.get("X-Mothership-Signature", "")
    if not re.fullmatch(r"[a-f0-9]{64}", received) or not hmac.compare_digest(received, expected):
        abort(401)

    event = request.get_json()
    # event["eventType"], event["data"], event["sentAt"], event["deliveryAttempt"], event["pendingRetries"]
    return "", 200
```

To see why a signature doesn't match, paste the body and secret here. It shows the signature you should get, and the one you get if the body was parsed first.

## Answer within 30 seconds

Mothership counts any `2xx` answer within 30 seconds as delivered. Any other status, a timeout or a connection error is a failure, and the event is sent again.

Verify the signature, record the event and answer. Do the slow work, such as calling the Dashboard API or updating other systems, in a background job afterwards. A handler that does everything before it answers turns a slow database into a pile of retries.

## Retries

Each event gets up to 17 attempts. The wait between them starts at 5 seconds and doubles each time, so retries continue for about four days.

| Attempts | About this long after the first |
| --- | --- |
| 1 | Right away |
| 2 to 6 | 5 s, 15 s, 35 s, 75 s, 2.6 min |
| 7 to 10 | 5 min, 11 min, 21 min, 43 min |
| 11 to 14 | 1.4 h, 2.8 h, 5.7 h, 11 h |
| 15 to 17 | 23 h, 1.9 days, 3.8 days |

Each retry carries the next `deliveryAttempt` and one fewer `pendingRetries`, so `pendingRetries` of `0` means this is the last automatic attempt. After that, the request and every response your endpoint gave stay in the webhook logs on the [Webhooks page in the dashboard](https://dashboard.mothership.com/developers/webhooks), where you can resend the delivery once your endpoint is fixed.

## Handle duplicates

The same event can reach you more than once. The usual cause is a retry after your endpoint did the work but the `2xx` never made it back. Every attempt and resend of one delivery carries the same `X-Mothership-Delivery-Id`, so record the IDs you have processed and skip one you have seen. Store the ID in the same transaction as the work it guards.

Writes keyed on the record help too. Saving "shipment `MS123456` is `Delivered`" twice does no harm.

## Handle ordering

Events can arrive out of order, for example when one is retried while a later one goes straight through. Don't use arrival order to decide which state is current.

- `shipment.rebill.status.updated` and `shipment.rebill.dispute.status.updated` carry `statusUpdatedAt`, and every invoice event carries `invoice.updatedAt`. Ignore an event older than the state you already have.
- The other rebill events have no time to compare, apart from `acceptedAt`, `finalizedAt`, `waivedAt` or `voidedAt` on the event of that name. When their order matters, call [Retrieve a rebill](https://docs.mothership.com/reference/fetchrebillbyid) for the current state.
- Shipment status events carry no time, and a shipment can move back to an earlier status, so a late event and a real step back look the same. Don't rank statuses to drop one. When the current status matters, call [Get shipment details](https://docs.mothership.com/reference/getshipmentdetails).
- When in doubt, treat the webhook as a signal and fetch the record: [Get shipment details](https://docs.mothership.com/reference/getshipmentdetails), [Retrieve a rebill](https://docs.mothership.com/reference/fetchrebillbyid) or [Retrieve an invoice](https://docs.mothership.com/reference/fetchinvoicebyid).

## Stay compatible

Mothership can add keys to an event's `data` at any time. It doesn't change or remove existing keys, their types or their formats without announcing it in the [changelog](https://docs.mothership.com/changelog) first. So:

- Answer `2xx` to an `eventType` you don't handle, so a configuration that subscribes to more than your code handles doesn't build up retries.
- Ignore keys you don't know instead of rejecting the request.
- Read keys by name. Key order isn't part of the contract.
- Expect a key an event's page marks as "can be missing" to be absent, and a "nullable" one to be `null`.

## Endpoint requirements

Use an `https` URL on a domain name, reachable from the public internet. The dashboard accepts only those. The API also accepts `http` URLs and public IP addresses, but `http` sends every event unencrypted, so don't use it.

However the URL was set, Mothership doesn't send webhooks to `localhost` or to private, loopback, link-local or reserved addresses, including through a redirect. It checks the address each time it sends, so a domain that later points at one of them stops receiving events.

## Test your endpoint

**Send test** on an endpoint on the [Webhooks page in the dashboard](https://dashboard.mothership.com/developers/webhooks) posts one signed [`webhook.test`](https://docs.mothership.com/reference/webhook-test) event to it and shows the status code your endpoint returned. It isn't retried. Use it to check your endpoint is reachable and verifies signatures before real events arrive.

## Before you go live

- The endpoint is `https` and reachable from the internet.
- Every request's signature is checked against the raw body, in constant time.
- The endpoint answers `2xx` within 30 seconds and does slow work afterwards.
- A repeated `X-Mothership-Delivery-Id` is skipped.
- State changes go by the timestamps in `data`, not arrival order.
- Unknown event types get a `2xx`, and unknown keys are ignored.
- The secret lives in a secret store.
- Someone checks the webhook logs when deliveries fail.