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

# Alerts, triggers and webhooks

> Get notified when new content matches a search, run clustering and enrichment on a schedule, and receive or pull Mixpeek events.

Set up Mixpeek to tell you when something happens, or to do work on a schedule. Four tools cover this:

| You want to | Use |
| - | - |
| Be told when new content matches a search, or a search returns nothing | [Alert](#create-an-alert) |
| Re-cluster nightly, re-run enrichment, rerun a batch | [Trigger](#run-work-on-a-schedule-with-triggers) |
| Receive every event of a kind (documents written, a cluster run finished) at an HTTP endpoint | [Webhook](#receive-events-with-webhooks) |
| Read an ordered, resumable log of changes, for a consumer that can be offline | [Change feed](#pull-events-from-the-change-feed) |

A trigger runs work; its output is its run history. An alert watches a condition and sends a notification. A webhook pushes every event of the types you subscribe to; the change feed holds the same events for you to pull.

## Create an alert

An alert runs a [retriever](https://docs.mixpeek.com/docs/retrieve/retrievers.md) against your content and notifies you when the result meets its condition. Attached to a collection, it checks every new document as it is processed.

**Prerequisites:** a collection that processes documents, and a retriever that returns what you want to hear about. For "notify me when a document lands in a category", the retriever needs no embeddings: a single `attribute_filter` stage on the field your [taxonomy](https://docs.mixpeek.com/docs/enrich/taxonomies.md) writes is enough, because taxonomies run before alerts.

**1. Create the alert**

```bash cURL theme={null}
curl -X POST "https://api.mixpeek.com/v1/alerts" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "safety_content_monitor",
    "retriever_id": "'"$RETRIEVER_ID"'",
    "notification_config": {
      "channels": [
        { "channel_type": "webhook", "config": { "url": "https://hooks.yourcompany.com/mixpeek-alerts" } },
        { "channel_type": "slack", "config": { "channel": "#content-alerts" } }
      ],
      "include_matches": true,
      "include_scores": true
    }
  }'
```

```python Python theme={null}
import os
import requests

resp = requests.post(
    "https://api.mixpeek.com/v1/alerts",
    headers={
        "Authorization": f"Bearer {os.environ['MIXPEEK_API_KEY']}",
        "X-Namespace": os.environ["NAMESPACE_ID"],
    },
    json={
        "name": "safety_content_monitor",
        "retriever_id": os.environ["RETRIEVER_ID"],
        "notification_config": {
            "channels": [
                {"channel_type": "webhook", "config": {"url": "https://hooks.yourcompany.com/mixpeek-alerts"}},
                {"channel_type": "slack", "config": {"channel": "#content-alerts"}},
            ],
            "include_matches": True,
            "include_scores": True,
        },
    },
)
print(resp.json()["alert_id"])
```

```javascript JavaScript theme={null}
const resp = await fetch("https://api.mixpeek.com/v1/alerts", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MIXPEEK_API_KEY}`,
    "X-Namespace": process.env.NAMESPACE_ID,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: "safety_content_monitor",
    retriever_id: process.env.RETRIEVER_ID,
    notification_config: {
      channels: [
        { channel_type: "webhook", config: { url: "https://hooks.yourcompany.com/mixpeek-alerts" } },
        { channel_type: "slack", config: { channel: "#content-alerts" } },
      ],
      include_matches: true,
      include_scores: true,
    },
  }),
});
console.log((await resp.json()).alert_id);
```

**2. Attach it to a collection**

Add it to the collection's `alert_applications`, mapping document fields to the retriever's inputs:

```bash cURL theme={null}
curl -X PATCH "https://api.mixpeek.com/v1/collections/$COLLECTION_ID" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "alert_applications": [
      {
        "alert_id": "'"$ALERT_ID"'",
        "execution_mode": "on_ingest",
        "input_mappings": [
          { "input_key": "query_text", "source": { "source_type": "document_field", "path": "content" } }
        ]
      }
    ]
  }'
```

`source_type` is `document_field` (a dot path on the document) or `constant` (a fixed `value`).

**3. Process documents**

Upload objects as usual. After each batch, the alert runs once per new document in parallel, and sends one notification if any document matched.

### Conditions

| Field | Effect |
| - | - |
| `trigger_on` | `results` (default) fires when the retriever returns rows; `no_results` fires when it returns none |
| `min_count` | With `results`, the number of rows needed to fire |
| `threshold` | With `results`, compares one field of the first row: `{ "field": "score", "operator": "gte", "value": 0.92 }`. Operators: `gt`, `gte`, `lt`, `lte`, `eq`, `ne` |
| `cooldown_seconds` | No new notification within this many seconds of the last; a fire inside it is recorded with `suppressed: cooldown` |
| `renotify_interval_seconds` | While the condition keeps holding, notify again at this interval. Unset: notify once each time it starts to hold |
| `inputs` | Retriever inputs the alert always runs with; at ingest, mapped document fields override them |

A threshold field can be a top-level key such as `score` or an aggregate column, a dot path such as `metadata.price`, or a bare name looked up in the row's metadata. A missing field or a value of another type does not fire. A retriever that ends in an aggregate stage returns groups as rows, so `min_count: 3` means three groups. `min_count` or `threshold` with `trigger_on: no_results` returns `422` naming the field. A run that errors or returns degraded neither fires a `no_results` alert nor clears one. `last_fired_at` on the alert shows when it last notified.

`inputs` is how a time window works on every path: a retriever filter on `{{time_ago(minutes=INPUT.window_minutes)}}` with `"inputs": {"window_minutes": 60}` looks back one hour.

### When an alert is evaluated

`execution_mode` on the application is `on_ingest` (default), `scheduled` or `on_demand`.

* `on_ingest` evaluates the alert as each batch is processed.
* Every alert that is not `on_demand` is also evaluated by a background sweep. It runs after an alert is created, changed or deleted, and after a batch completes, at most once every 30 minutes. An alert that depends on the clock (`no_results`, a threshold, a cooldown, a re-notify interval or a templated input) is swept every 30 minutes. A document written through the API outside a batch reaches the sweep within 6 hours.
* To evaluate on your own schedule, create a trigger with `action_type: "alert_evaluation"` (below). While it is active, the sweep skips that alert in that namespace.
* `on_demand` alerts never run automatically.

The cooldown is shared by every path, so an alert that fired at ingest stays quiet on the sweep until the cooldown passes.

### Notification channels

| `channel_type` | `config` | Notes |
| - | - | - |
| `webhook` | `{ "url": "https://..." }` | POSTs the alert, its matches and scores as JSON |
| `slack` | `{ "channel": "#alerts" }` | Posts to the channel. Another key such as `channel_name` is refused |
| `email` | None needed | Sends only to the organization's `notifications_email`. A recipient list (`to`, `recipients`) is refused. Unset means no email |
| `batch` | `{ "collection_id": "col_alert_frames" }` | Processes the matched objects into another collection (below) |

> [accordion] Process matches into another collection with the batch channel
>
> After the batch that fired the alert completes, Mixpeek submits one batch per source bucket holding the objects whose documents matched. Output documents keep lineage back to those objects; list capture fields such as `captured_at` in the target collection's `field_passthrough` to copy them.
>
> | Key | Required | Description |
> | - | - | - |
> | `collection_id` | Yes | Collection that receives the objects. `target_collection_id` is accepted too. |
> | `bucket_id` | No | Limit to objects from this bucket. Defaults to the bucket in each document's lineage. |
> | `dedup_strategy` | No | `skip` (default), `replace` or `force`. With `skip`, an object is processed once even when it matches again. |
>
> The target must read from a bucket that holds the matched objects, must be user-defined (names starting `_` or `mxp_` are system collections), and must differ from the watched collection. A missing `collection_id`, an unknown key or a bad `dedup_strategy` returns `422` on save; the three target conditions are checked when the alert fires.
>
> The batch that fires the alert must leave the target out. A batch created without `collection_ids` covers every collection on the bucket, the target included, so with `dedup_strategy: skip` the follow-up batch skips those objects. Uploads through `POST /v1/buckets/{bucket_identifier}/objects?auto_process=true` and `POST /v1/buckets/{bucket_identifier}/objects/batch?auto_process=true` create that kind of batch. To test the channel, create the batch with `POST /v1/buckets/{bucket_identifier}/batches` and list `collection_ids` without the target.
>
> Each follow-up batch records its origin in `additional_data.triggered_by_alert`. If it cannot start, Mixpeek sends an `alert.execution.failed` event with the reason, after retrying transient errors 3 times.

### Check it worked

`GET /v1/alerts/{alert_id}/executions` lists each run with `triggered`, `match_count`, `duration_ms` and per-channel `deliveries`:

```bash cURL theme={null}
curl "https://api.mixpeek.com/v1/alerts/$ALERT_ID/executions" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID"
```

## Default alerts

Every new organization gets one system alert per built-in condition, across all its namespaces. They email the organization's `notifications_email`, which starts as the signup address; change it with `PATCH /v1/organizations`.

| Alert | Fires when | Ships |
| - | - | - |
| Batch failed | An ingestion batch ends failed | Enabled |
| Batch stalled | A batch makes no progress past the stall threshold | Enabled |
| Batch error rate | The share of failed objects in a batch passes the threshold | Enabled |
| Dead-letter queue growth | Sync objects exhaust their retries | Enabled |
| Provider quota exhausted | A batch hits a hard provider quota | Enabled |
| Retriever returning no results | A retriever's recent executions all return zero results | Enabled |
| Retriever getting no interactions | A retriever ran at least 10 times in the window and no result drew an interaction; quiet in a namespace that reports none | Enabled |
| Collection went stale | A collection with documents keeps the same count for a week | Enabled |
| Ingest stalled | A bucket that was receiving objects receives none for a day | Enabled |
| Spend reached 80 percent of the monthly budget | Month-to-date spend reaches 80% of the budget; quiet with no budget set | Enabled |
| Collection went empty | A collection that held documents drops to zero | Disabled |
| Collection drift | A collection's document count drops sharply | Disabled |
| Retriever latency spike | A retriever's p95 latency rises well above its baseline | Disabled |
| Retriever accuracy regression | A retriever's latest evaluation metric falls below its floor | Disabled |
| Retriever alignment regression | A retriever's benchmark NDCG drops sharply from the prior run | Disabled |
| Task queue degraded | A processing queue's backlog is not draining | Disabled |

List them with `GET /v1/organizations/alerts` and switch one with `PATCH /v1/organizations/alerts/{alert_identifier}` and `{"enabled": false}`. A default you change or disable is not recreated. Each condition is evaluated by a saved retriever named `system-<condition>` (for example `system-collection-stale`) and tagged `system-alert`; run it like any retriever to see what meets the condition now. Mixpeek never overwrites one you edited.

## Run work on a schedule with triggers

A trigger combines an action with a schedule. This one re-runs a cluster every night at 02:00 UTC:

```bash cURL theme={null}
curl -X POST "https://api.mixpeek.com/v1/triggers" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "nightly recluster",
    "action_type": "cluster",
    "action_config": { "cluster_id": "'"$CLUSTER_ID"'" },
    "trigger_type": "cron",
    "schedule_config": { "cron_expression": "0 2 * * *", "timezone": "UTC" }
  }'
```

| `action_type` | Runs | `action_config` |
| - | - | - |
| `cluster` | A [cluster](https://docs.mixpeek.com/docs/enrich/clusters.md) | `cluster_id`, optional `filters`, `output_collection_ids` |
| `taxonomy_enrichment` | A [taxonomy](https://docs.mixpeek.com/docs/enrich/taxonomies.md) over a collection | `collection_id`, `taxonomy_id`, optional `target_collection_id`, `incremental`, `batch_size`, `parallelism` |
| `batch_rerun` | Processing again for a collection's documents | `collection_id` |
| `collection_trigger` | A collection's configured processing | `collection_id` |
| `retriever_execution` | A saved retriever with fixed inputs, judged against acceptance criteria | See [Create trigger](https://docs.mixpeek.com/docs/api-reference/create-trigger.md) |
| `alert_evaluation` | One alert, on this schedule | `alert_id` |

| `trigger_type` | `schedule_config` |
| - | - |
| `cron` | `cron_expression` (5-field) and `timezone` |
| `interval` | `interval_seconds`, optional `start_immediately` |
| `conditional` | The condition, such as drift or volume past a threshold |

`trigger_type: "event"` is in the schema and rejected at create: nothing emits the events it would wait for yet. Use a short interval meanwhile.

With `taxonomy_enrichment`, set `incremental: true` to process only documents added since the last run, so you do not pay again for documents already labeled.

Manage triggers with `POST /v1/triggers/list`, `GET`, `PATCH` and `DELETE /v1/triggers/{trigger_id}`, `POST /v1/triggers/{trigger_id}/pause` and `/resume`. Run one now with `POST /v1/triggers/{trigger_id}/execute`, and read what ran and what failed with `GET /v1/triggers/{trigger_id}/history`.

Clusters also have their own triggers under `/v1/clusters/triggers`; see [Keep clusters current](https://docs.mixpeek.com/docs/enrich/clusters.md#keep-clusters-current).

## Receive events with webhooks

A webhook is defined for the organization and POSTs each event of the types you subscribe to.

```bash cURL theme={null}
curl -X POST "https://api.mixpeek.com/v1/organizations/webhooks" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "webhook_name": "prod-notifications",
    "event_types": ["collection.documents.written", "cluster.execution.completed"],
    "channels": [
      {
        "channel": "webhook",
        "configs": {
          "url": "https://hooks.yourcompany.com/mixpeek",
          "signing_secret": "'"$MIXPEEK_WEBHOOK_SECRET"'",
          "timeout": 10
        }
      }
    ]
  }'
```

`channel` is `webhook`, `slack` or `email`. Create and update refuse URLs that can never receive a delivery, such as `example.com` or `.test` and `.invalid` hosts.

### Events

The full list is the `WebhookEventType` enum in [Create webhook](https://docs.mixpeek.com/docs/api-reference/webhooks/create-webhook.md). Each resource also has `.created`, `.updated` and `.deleted` events, and clusters, triggers and alerts have `.execution.completed` and `.execution.failed`.

| Event | Sent when | Payload highlights |
| - | - | - |
| `collection.documents.written` | Documents are written to a collection | `collection_id`, `document_ids`, `index_signature` |
| `collection.documents.batch_completed` | A batch finished writing to one collection; one event per collection | `batch_id`, `collection_id`, `total_documents`, `status` |
| `object.created` | An object is registered in a bucket | `bucket_id`, `object_id`, metadata |
| `documents.updated.batch` | A batch of documents finished updating | `collection_id`, `document_ids` |
| `cluster.execution.completed` | A clustering run finished | `cluster_id`, `run_id`, artifact URIs |
| `taxonomy.updated` | A taxonomy definition changed | `taxonomy_id` |
| `alert.triggered` | An alert fired | The alert, with matches and scores when `include_matches` and `include_scores` are on |
| `alert.execution.failed` | An alert run, or its batch channel, failed | Alert, reason |
| `resource.executed` | Any primitive finished a run: retriever, taxonomy, cluster, collection, storage connection, alert or trigger | `resource_type`, `resource_id`, `execution_id`, `duration_ms`, `cost_credits`, `output_count`, `pinned_revision` |
| `resource.execution_failed` | The same run failed | The same fields, with `error_class` |

To receive runs of some primitives only, add `"resource_types": ["retriever"]` alongside `"event_types": ["resource.executed", "resource.execution_failed"]`. The filter applies to every event type; for per-kind events the resource type is the first part of the name. A finished batch sends one `resource.executed` per collection it wrote, with `resource_type` `collection` and the batch id as `execution_id`, and its credits split evenly across them. A retriever's `resource.executed` carries `pinned_revision.config`, the exact `stages`, `collection_ids` and `input_schema` that ran; send them to `POST /v1/retrievers/execute` (with `collection_ids` as `collection_identifiers`) to rerun that version.

### Payload and headers

```json Delivery body theme={null}
{
  "event_id": "evt_123",
  "event_type": "collection.documents.written",
  "occurred_at": "2025-10-28T10:03:22Z",
  "namespace_id": "ns_prod",
  "subject": { "type": "collection", "id": "col_products" },
  "metadata": { "document_count": 100, "collection_id": "col_products", "index_signature": "sig_xyz789" },
  "cache_scope": { "scope": "collection", "collection_id": "col_products" }
}
```

Each delivery carries `X-Mixpeek-Event` (the event type) and `X-Mixpeek-Event-Id` (the same on a retry, so you can drop duplicates). `cache_scope` (`collection`, `namespace` or `key`) tells you which retriever caches to invalidate.

### Verify a delivery

With a `signing_secret`, every delivery carries `X-Mixpeek-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256>`. The HMAC is over `<t>.` followed by the raw body, keyed by your secret. Recompute it over the raw bytes before parsing JSON, compare in constant time, and reject timestamps more than 300 seconds from your clock.

```python verify_signature.py theme={null}
import hashlib
import hmac
import time


def verify(raw_body: bytes, header: str, secret: str, tolerance_s: int = 300) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    t, sig = parts.get("t", ""), parts.get("v1", "")
    if not t.isdigit() or abs(time.time() - int(t)) > tolerance_s:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, sig)
```

The secret is stored encrypted and reads back as `redacted`. To also gate access with a credential your endpoint already checks, add it under `configs.headers`, for example `{"Authorization": "Bearer <token>"}`. Mixpeek sends header values exactly as stored and returns them in plain text when you read the webhook; it does not mint or refresh tokens. A header you set with the same name as one of Mixpeek's replaces it.

### Delivery behavior

* Mixpeek retries with exponential backoff until your endpoint returns `2xx`. Return `200` within 10 seconds and do heavy work in the background.
* Handlers must be idempotent; deduplicate on `event_id`.
* After 30 failed deliveries in a row spanning at least two hours, Mixpeek pauses the webhook (`is_active: false`, with `paused_reason`) and alerts your organization. Any success resets the count. Update the webhook to turn it back on.
* A batch submitted with its own `webhook_url` gets one unsigned `POST` with `batch_id`, `status`, `documents_written`, `progress` and `completed_at` when it ends, retried 3 times (after 2, 4 and 8 seconds) on `5xx` or `429`. For an authenticated callback, subscribe to `collection.documents.batch_completed` instead.

## Pull events from the change feed

`GET /v1/events` returns your organization's events in order, for 90 days. You hold the position, so a consumer that stops resumes where it left off.

```bash cURL theme={null}
curl "https://api.mixpeek.com/v1/events?limit=100" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY"
```

```json Response theme={null}
{
  "results": [
    {
      "seq": 84213,
      "cursor": "b3BhcXVlLXN0cmluZw==",
      "namespace_id": "ns_0fda3a08ba",
      "event_type": "collection.documents.written",
      "resource_type": "collection",
      "operation": "insert",
      "payload": { "collection_id": "col_products", "document_ids": ["doc_1"] },
      "created_at": "2026-08-22T19:04:11Z"
    }
  ],
  "next_cursor": "b3BhcXVlLW5leHQ=",
  "has_more": true
}
```

| Parameter | Meaning |
| - | - |
| `cursor` | Position from a prior `next_cursor`. Omit to start at the oldest retained event. |
| `namespace_id` | Only this namespace |
| `event_type` | Only this event type, from the webhook vocabulary |
| `limit` | 1 to 1,000, default 100 |

An empty page returns the cursor you sent, so a poller can call again with the same value. `seq` is monotonic per organization and orders events across namespaces. `operation` is `insert`, `update`, `delete` or `other`.

> [!WARNING]
>
> * **A cursor is valid only for the filters that produced it.** Change `namespace_id` or `event_type` while reusing a cursor and the feed skips events with no error. Start from no cursor when filters change.
> * **Expiry is permanent.** Events older than 90 days are deleted. A consumer down longer must resync current state.
> * **`payload` is not a stable contract.** Read `event_type`, `resource_type`, `operation` and the ids, and fetch the resource for its current state.

Batch processing writes one `collection.documents.written` event per flushed chunk (with `batch_id`, `document_ids` and `count`), emitted only after the documents are confirmed in storage. When the batch ends, one `collection.documents.batch_completed` per collection carries `total_documents` counted from the store, or `null` if the count failed. Delivery is at-least-once, and a chunk event can be lost if the writer dies between the storage confirm and the emit. To check completeness, compare the union of `document_ids` across a batch's chunk events with `total_documents`; on a mismatch, list the collection's documents filtered by that `batch_id`.

## What goes wrong

| Symptom | Cause |
| - | - |
| `422` creating an alert | `min_count` or `threshold` with `trigger_on: no_results`, or a bad `batch` channel key |
| Alert never emails | The organization has no `notifications_email` |
| Alert fires once and then stays quiet | `cooldown_seconds`, or no `renotify_interval_seconds` while the condition holds |
| `trigger_type: "event"` rejected | Event triggers are not available; use `interval` or `cron` |
| Webhook stops delivering | It paused after 30 failures; check `is_active` and `paused_reason`, fix the endpoint, update the webhook |
| Change feed consumer missed events | It reused a cursor after changing filters, or was down for more than 90 days |

## Related

* [Taxonomies](https://docs.mixpeek.com/docs/enrich/taxonomies.md) and [Clusters](https://docs.mixpeek.com/docs/enrich/clusters.md): the enrichment these tools schedule and watch
* [Monitoring and troubleshooting](https://docs.mixpeek.com/docs/production/monitoring.md): analytics, logs and batch diagnostics
* [Create alert](https://docs.mixpeek.com/docs/api-reference/alerts/create-alert.md), [Create webhook](https://docs.mixpeek.com/docs/api-reference/webhooks/create-webhook.md), [List events](https://docs.mixpeek.com/docs/api-reference/events/list-events.md) in the API reference


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