# Database webhooks
Source: https://sovaria.in/docs/database-webhooks

Call your own HTTPS endpoint when rows are inserted, updated or deleted: setup, the payload, signatures and custom headers, retries and dead letters, the delivery log, replay, testing and limits.

A database webhook sends a signed `POST` to your URL after rows of a table change — to update a search index, notify a service, or start a Zapier, n8n or Make workflow ([Zapier, n8n and Make](https://sovaria.in/docs/integration-automation)). Delivery happens after the write is committed and is retried until your endpoint accepts it, so a slow or broken endpoint never slows or breaks your app.

To run your own code instead of calling a URL, use a [function trigger](https://sovaria.in/docs/function-triggers). To change data in the same transaction, use a [trigger](https://sovaria.in/docs/database-triggers). To update screens live, use [Database change events](https://sovaria.in/docs/realtime-database-changes).

## Create a webhook

1. **New webhook** — Open **Schema › Webhooks** and click **New webhook**.
2. **Name and URL** — A name your team will recognise, and a public `https://` URL. Private, internal and loopback addresses are refused, when you save and again before every delivery.
3. **Table and events** — One table, or **All tables**. Events: `INSERT`, `UPDATE`, `DELETE`, or all three.
4. **Signing secret** — A random `whsec_…` secret is generated for you (**New** makes another). Copy it now: it is shown once, and the API never returns it.
5. **Headers (optional)** — Extra headers sent with every delivery, such as `Authorization: Bearer …` for an endpoint that expects its own key.
6. **Create, then test** — **Send a test event** from the row menu posts a sample event (`"type": "webhook.test"`) and shows the status code your endpoint returned.

HTTP:
```bash
curl -s -X POST "$SOVARIA_URL/api/v1/webhooks" \
  -H "Authorization: Bearer $SERVICE_ROLE_KEY" -H "Content-Type: application/json" \
  -d '{
    "name": "Orders to search index",
    "url": "https://api.example.com/hooks/orders",
    "table": "orders",
    "events": ["INSERT", "UPDATE"],
    "secret": "whsec_…",
    "headers": { "X-Source": "sovaria" }
  }'
```

## What is sent

JSON:
```json
{
  "type": "database.change",
  "project_id": "…",
  "table": "orders",
  "event": "INSERT",
  "timestamp": "2026-10-17T10:15:02.120Z",
  "event_id": "…",
  "data": { "row_count": 1 }
}
```

Like realtime change events, the payload says **that** rows changed and how many — not their contents, which may be private. Fetch the rows you need with a server key, for example the rows of `orders` changed since your last sync.

| Header | Value |
|---|---|
| `Content-Type` | `application/json` |
| `X-Sovaria-Delivery` | A unique id for this delivery; the same on every retry of it. |
| `X-Sovaria-Signature` | `sha256=<hex>`: HMAC-SHA-256 of the raw request body with your secret. |
| Your headers | Whatever you added. Sovaria's own headers above take precedence over yours with the same name. |

## Check the signature

Anyone can post to a public URL. Before trusting a delivery, recompute the signature from the **raw** body (before parsing JSON) and compare it in constant time.

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

const app = express()
app.post('/hooks/orders', express.raw({ type: 'application/json' }), (req, res) => {
  const expected = 'sha256=' + crypto.createHmac('sha256', process.env.WEBHOOK_SECRET).update(req.body).digest('hex')
  const got = req.get('X-Sovaria-Signature') ?? ''
  const ok = got.length === expected.length && crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected))
  if (!ok) return res.status(401).end()

  const event = JSON.parse(req.body.toString('utf8'))
  // Skip duplicates: the same event_id can arrive twice after a timeout.
  queueSync(event.table, event.event_id)
  res.status(204).end()
})
```

Python:
```python
import hashlib, hmac, json, os
from flask import Flask, request, abort

app = Flask(__name__)

@app.post("/hooks/orders")
def orders_hook():
    raw = request.get_data()
    expected = "sha256=" + hmac.new(os.environ["WEBHOOK_SECRET"].encode(), raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(request.headers.get("X-Sovaria-Signature", ""), expected):
        abort(401)
    event = json.loads(raw)
    queue_sync(event["table"], event.get("event_id"))
    return "", 204
```

Sovaria function:
```python
# A public HTTP function (it defines fetch): only HTTP functions receive the raw body the signature covers.
import hashlib, hmac, os

from sovaria_functions import Response

def fetch(request):
    expected = "sha256=" + hmac.new(os.environ["WEBHOOK_SECRET"].encode(), request.body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(request.headers.get("x-sovaria-signature", ""), expected):
        return Response("bad signature", status=401)
    event = request.json()
    queue_sync(event["table"], event.get("event_id"))
    return Response("", status=204)
```

To receive it in a Sovaria function, make the function **public** and give it a `fetch(request)` handler (an HTTP function): `request.body` is the raw body and `request.headers` includes `x-sovaria-signature`, `x-sovaria-event` and `x-sovaria-delivery`. A JSON `handler(event, context)` gets the parsed body only, so it can't check the signature.

> **Tip:** Answer quickly with a `2xx` and do the work in the background. A delivery that takes longer than 10 seconds counts as failed and is retried.

## Delivery and retries

- Events are written to an outbox with the change and sent by a background worker, so your app's writes never wait for your endpoint.
- A delivery succeeds on any `2xx` within 10 seconds. Otherwise it is retried after 10 seconds, 1 minute, 5 minutes, 30 minutes, 2 hours and 6 hours — 7 attempts over about 9 hours.
- Deliveries can repeat (a retry after your endpoint timed out but did the work): use `event_id` to ignore duplicates.
- Order isn't guaranteed across retries. Use `timestamp`, or read the current rows, rather than relying on arrival order.
- Paused webhooks receive nothing; events from while they were paused aren't queued for later.
- Writes made over a direct Postgres connection don't go through the API and don't send webhooks. Use a [trigger](https://sovaria.in/docs/database-triggers) for logic that must run on every write.

## Delivery log

The list shows, for each webhook, how many deliveries are waiting or have failed and when it last delivered. **Delivery log** in the row menu opens its recent deliveries:

| Status | Means |
|---|---|
| **Delivered** | Your endpoint answered `2xx`. Shows the attempt count and when. |
| **Retrying** | An attempt failed; the next one is scheduled. Shows the last status code or error. |
| **Failed** | All 7 attempts failed, on a plan without a dead-letter queue. Kept for the log. |
| **Gave up** | All attempts failed, on a plan with a dead-letter queue. Listed under **Gave up after retries**, where you can send it again. |

The log keeps deliveries for your plan's replay window, and at least 7 days.

## Dead letters and replay

- **Send again** on an event that gave up (a dead letter) puts it back in the queue with a fresh set of attempts — once you have fixed your endpoint. Over the API: `POST /api/v1/webhooks/dead-letter/{id}/redrive`.
- **Send past events again** (in the delivery log) re-sends every delivered, failed or dead event of a webhook since a time you choose, within your plan's replay window — for example after restoring your own system from a backup. Replayed deliveries are new deliveries with their own ids; your duplicate check on `event_id` still works.

|  | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Event pipes | 5 | 200 | 1,000 | 5,000 | 20,000 |
| Webhook targets | 10 | 200 | 1,000 | 5,000 | 20,000 |
| Dead letter queue | — | — | ✓ | ✓ | ✓ |
| Event replay | 1 day | 30 days | 90 days | 365 days | 730 days |

## Webhooks over the API

| Call | Does |
|---|---|
| `GET /api/v1/webhooks` | List webhooks (secrets are never returned). |
| `POST /api/v1/webhooks` | Create one: `name`, `url`, `table`, `events`, `secret`, `headers`. |
| `PUT /api/v1/webhooks/{id}` | Change any field; `enabled: false` pauses it. |
| `DELETE /api/v1/webhooks/{id}` | Delete it. |
| `POST /api/v1/webhooks/test/{id}` | Send a test event; returns your endpoint's status code. |
| `GET /api/v1/webhooks/{id}/deliveries` | Recent deliveries (`limit` up to 200). |
| `POST /api/v1/webhooks/{id}/replay` | Re-send events between `since` and `until`. |
| `GET /api/v1/webhooks/dead-letter` | Dead letters of the project. |
| `POST /api/v1/webhooks/dead-letter/{id}/redrive` | Send a dead letter again. |

These need a project team member or the service role key ([API keys](https://sovaria.in/docs/api-keys)).

## Troubleshooting

| Symptom | Check |
|---|---|
| Nothing arrives | The webhook is on, the table and events match, and the write went through the API (not a direct connection). **Send a test event** to test the URL on its own. |
| `401` / `403` in the log | Your endpoint refused it: check the signature with the raw body, or the headers your endpoint expects. |
| Timeouts | Answer within 10 seconds; move slow work to a queue. |
| URL refused when saving | It must be public `https://`. `localhost`, private networks and cloud metadata addresses are refused; use a tunnel for local testing. |
| The same event twice | Expected after a timeout: skip events whose `event_id` you have handled. |
