# Subscribe to events

> Receive platform content and Koil lifecycle events at your own endpoint, queue, or stream.

An Event Destination tells Koil where to deliver events and which topics it receives: an HTTPS endpoint (a webhook), or a queue or stream you run. Koil delivers one stream per destination, whether a platform reported a change by webhook or Koil found it by polling.

Start here after you have connected at least one profile with [Connect platform accounts](https://docs.koil.co/guides/connect-platform-accounts).

## Choose a destination type

Most integrations start with a webhook: an HTTPS endpoint in the backend you already run, with every delivery signed so you can verify it came from Koil. Choose a queue or stream instead when your system already consumes one, or when you would rather not expose a public endpoint: Koil writes each event straight to it with a credential you grant, and your workers consume at their own pace.

Every type receives the same topics, the same [event](https://docs.koil.co/guides/subscribe-to-events#the-event), and the same [retries](https://docs.koil.co/guides/subscribe-to-events#receiving-deliveries). What differs is the transport, where the [routing fields](https://docs.koil.co/guides/subscribe-to-events#routing-fields) travel, and how you [trust a delivery](https://docs.koil.co/guides/subscribe-to-events#trusting-deliveries).

| Type | Delivers each event to |
| --- | --- |
| `webhook` | An HTTPS endpoint, as a signed `POST` |
| `aws_sqs` | An Amazon SQS queue |
| `aws_eventbridge` | An Amazon EventBridge event bus |
| `aws_kinesis` | An Amazon Kinesis data stream |
| `aws_s3` | An Amazon S3 bucket, as an object |
| `gcp_pubsub` | A Google Cloud Pub/Sub topic |
| `azure_servicebus` | An Azure Service Bus queue or topic |
| `kafka` | A Kafka topic |
| `rabbitmq` | A RabbitMQ exchange |
| `cloudflare_queues` | A Cloudflare Queue |
| `hookdeck` | A Hookdeck Event Gateway source |

The [API endpoints](https://docs.koil.co/openapi/event-destinations/v1-event-destinations-post) reference lists the `config` and `credentials` each type takes.

## How it works

1.  Set up the receiving side. For a webhook, an HTTPS endpoint in your backend that accepts `POST` requests, [verifies the signature](https://docs.koil.co/guides/verify-webhooks), stores or enqueues the event, and returns `2xx`. For a queue or stream, the queue, topic, or bucket; a credential that can only publish to it; and a consumer that reads from it.
    
2.  Check which collections emit events for a Profile. `GET /v1/profiles/{profileId}/capabilities` lists the profile's collections; each one's `emits` holds the actions Koil can collect for it (`created`, `updated`, …), empty when the credential's scopes don't cover the collection. `GET /v1/collections` lists the same for every platform, before any profile exists.
    
3.  Create an Event Destination with the topics you want. `POST /v1/event-destinations`
    
4.  Store the returned `id`.
    

## Create a destination

This one sends one profile's comments and DMs to a webhook:

```bash
curl -X POST "https://api.koil.co/v1/event-destinations" \
  -H "Authorization: Bearer $KOIL_API_KEY" \
  -H "Koil-Version: 2026-12-08" \
  -H "Content-Type: application/json" \
  -d '{
  "type": "webhook",
  "topics": [
    "content.instagram.media.comments.*",
    "content.instagram.dm.messages.*",
    "publish_request.*"
  ],
  "scope": {
    "type": "profiles",
    "profileIds": [
      "prof_123"
    ]
  },
  "config": {
    "url": "https://example.com/koil/events"
  },
  "credentials": {
    "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"
  }
}'
```

A queue or stream takes its address in `config` and the credential Koil publishes with in `credentials`. This one sends every content and publish event to an SQS queue:

```bash
curl -X POST "https://api.koil.co/v1/event-destinations" \
  -H "Authorization: Bearer $KOIL_API_KEY" \
  -H "Koil-Version: 2026-12-08" \
  -H "Content-Type: application/json" \
  -d '{
  "type": "aws_sqs",
  "topics": [
    "content.*",
    "publish_request.*"
  ],
  "config": {
    "queueUrl": "https://sqs.us-east-1.amazonaws.com/123456789012/koil-events"
  },
  "credentials": {
    "key": "AKIA_EXAMPLE_KEY_ID",
    "secret": "example-secret-access-key"
  }
}'
```

-   **`type`** — the transport, one of the [destination types](https://docs.koil.co/guides/subscribe-to-events#choose-a-destination-type). It decides what `config` and `credentials` take, which the [API endpoints](https://docs.koil.co/openapi/event-destinations/v1-event-destinations-post) reference lists for each type, so a client generated from the [OpenAPI document](https://docs.koil.co/openapi.json) types them too. A setting the type does not take, or one it requires that you left out, is refused with a `validation_error` naming it (`unknown_field` or `missing_field` at `/config/<key>` or `/credentials/<key>`), as is a value of the wrong kind.
-   **`topics`** — what this destination receives: exact topics, or patterns where `*` matches any run of characters. `*` is everything, `publish_request.*` one family, `content.*.comments.*` every platform's comments and replies, `content.*.messages.*` every DM, and `*.deleted` every deletion. Each must be a topic in the [Events reference](https://docs.koil.co/events) or a pattern that matches one; the API refuses anything else with a `validation_error` naming it.
-   **`scope`** — optional. Omit it, or send `{ "type": "organization" }`, for every Profile in the Organization, now and future. Send `{ "type": "profiles", "profileIds": [...] }` (at least one id) to receive only those profiles' events. A scoped destination receives only the families whose events name a Profile in `context`: `content.*`, `publish_request.*`, `backfill_request.*`, and `profile.*`. `connection.*`, `media.*`, and `event_destination.*` never reach it, so a topic that matches only those is refused; a broader pattern such as `*` is accepted and delivers just the four. Use a separate destination without a scope for the others.
-   **`config`** — where to deliver: a webhook's `url`, an SQS queue's `queueUrl`, a Pub/Sub `projectId` and `topic`, and so on. Reads return it.
-   **`credentials`** — write-only: no read or `event_destination.*` event returns them, so keep them in your secret store. For a queue or stream, the credential Koil publishes with: an AWS access key pair, a Google Cloud service-account key, a Kafka SASL username and password. Give it permission to publish to that one queue, topic, or bucket and nothing else. A `PATCH` of `credentials` replaces it at once, so to change it, create the new credential, `PATCH` it in, then revoke the old one. A webhook's `customHeaders` are the headers to add to each delivery, by name: `{ "Authorization": "Bearer …" }`. Its `secret` is the key deliveries are signed with, in the [Standard Webhooks](https://www.standardwebhooks.com/) format: `whsec_` then the base64 of 24 to 64 random bytes (`echo "whsec_$(openssl rand -base64 32)"`). Omit it to have one generated, and read it with `GET /v1/event-destinations/{eventDestinationId}/secret`, the only response that returns it. You may instead supply your own, for example when you manage destinations as code; to change it later, [rotate it](https://docs.koil.co/guides/verify-webhooks#rotating-the-secret), since a `PATCH` of `credentials.secret` swaps it at once and deliveries in flight fail your check.

The destination keeps the request's `Koil-Version` as its `apiVersion` and receives every event rendered in that version. It can't be changed; to upgrade, create a new destination. See [Versioning](https://docs.koil.co/concepts/versioning#what-a-version-pins).

Send an [`Idempotency-Key`](https://docs.koil.co/concepts/idempotency) so a retry of a create that failed lands on the destination it may have made rather than adding a second one. Destinations are managed through the API only.

To change a destination, send `PATCH /v1/event-destinations/{eventDestinationId}` with only what changes, such as `{ "enabled": true }` to re-enable it:

```bash
curl -X PATCH "https://api.koil.co/v1/event-destinations/des_6tW2fQ9mLp" \
  -H "Authorization: Bearer $KOIL_API_KEY" \
  -H "Koil-Version: 2026-12-08" \
  -H "Content-Type: application/json" \
  -d '{
  "enabled": true
}'
```

`config` and `credentials` are each replaced whole: send every setting the destination should keep, since an optional one left out is unset. A webhook's `secret` is the exception; left out, it is kept. Leaving out `config` or `credentials` keeps all of it, so a change to `config` alone doesn't touch the credentials. `metadata` is merged into what is stored, as on every resource. A `PATCH` that changes `config` or `credentials` must also send the destination's `type`, which decides what they take. A destination's type never changes, so a `type` other than its own is refused with a `validation_error` at `/type`.

## A new destination's first events

A destination receives events from when Koil starts collecting what it covers, usually within a few minutes of creating it or widening its topics or scope. Content from before that is not delivered to it; use a [backfill request](https://docs.koil.co/guides/backfill) for anything older.

## Topics

The [Events reference](https://docs.koil.co/events) lists every topic Koil emits, with the schema of each delivery; the [OpenAPI document](https://docs.koil.co/openapi.json) describes the same deliveries under `webhooks`, one envelope schema per topic plus `Event`, their union by `topic`, so a generated client can type its event handlers. Subscribing to a family with `.*` also covers actions a collection gains later.

Event delivery is unlimited under fair use, and only `content.*` deliveries count toward it. Koil's lifecycle topics — `publish_request.*`, `backfill_request.*`, `media.*`, `connection.*`, `profile.*`, `event_destination.*` — never count, so following your own publishes costs nothing.

## The event

Every delivery is one JSON object with the same envelope, on every destination type — webhook, queue, or stream (a few queues nest it under `data`, [below](https://docs.koil.co/guides/subscribe-to-events#routing-fields)). This is the `publish_request.succeeded` event that follows the [Quickstart](https://docs.koil.co/quickstart)'s comment:

```json
{
  "id": "evt_57e1eff7cdb9425dec65f416b3264c62540d3d0d",
  "topic": "publish_request.succeeded",
  "time": "2026-05-01T10:00:04.000Z",
  "apiVersion": "2026-12-08",
  "context": {
    "organizationId": "org_01J9Z3QK7X2M4N8P6R5T0VWYAB",
    "publishRequestId": "sandbox_pub_7GhQ2dLkP0aZ1xYc9VwN",
    "profileId": "sandbox_prof_4T2cgH9gnSqEb9DrntKA",
    "collection": "youtube.videos.comments",
    "mode": "sandbox"
  },
  "data": {
    "kind": "publish_request",
    "mode": "sandbox",
    "id": "sandbox_pub_7GhQ2dLkP0aZ1xYc9VwN",
    "status": "succeeded",
    "collection": "youtube.videos.comments",
    "profileId": "sandbox_prof_4T2cgH9gnSqEb9DrntKA",
    "externalId": "sandbox_comment_1",
    "metadata": {},
    "createdAt": "2026-05-01T10:00:00.000Z",
    "updatedAt": "2026-05-01T10:00:04.000Z",
    "startedAt": "2026-05-01T10:00:01.000Z",
    "succeededAt": "2026-05-01T10:00:04.000Z"
  }
}
```

-   `id` is stable per logical event: dedupe on it.
-   `topic` says what happened; the [Events reference](https://docs.koil.co/events) has the schema of each topic's `context` and `data`.
-   `apiVersion` is the version the event is rendered in: its destination's `apiVersion`.
-   `context` is Koil's context for the event. `mode` is `live` or `sandbox`, so one endpoint can serve both modes. A `content.*` event's context also names the observing profile (`profileId`, `platformId`, `collection`, and `platformProfileExternalId`, the profile's own platform id). A lifecycle event's context adds only the ids to route on: its resource's id and, for a publish request, backfill request, or Profile, the profile it belongs to.
-   A `content.*` event's `data` is the collection's schema — the same shape `GET /v1/profiles/{profileId}/content/{collection}` returns — so an event and a read of the same item are interchangeable.
-   A deletion's `data` (a `content.*` topic whose action is `deleted`) is smaller: the deleted item's `kind` and `externalId`, plus its relations where the platform sends them (a comment's `containerId` and `target`) and `ownerAuthored` where Koil knows it. Platforms send no content with a deletion, so there is none to deliver; look the item up by `externalId` in what you stored.
-   A lifecycle event's (`publish_request.*`, `backfill_request.*`, `media.*`, `connection.*`, `profile.*`, `event_destination.*`) `data` is its resource exactly as the resource's read returns it, in the same schema: the `publish_request.succeeded` above carries what `GET /v1/publish-requests/{publishRequestId}` answered at that moment. A deletion carries the resource as it last stood. The [Events reference](https://docs.koil.co/events) names each topic's read. `data` is the resource as of that transition, not as it is now, so `GET` the resource for its current state; and since deliveries are not ordered, order a resource's events by its `updatedAt` rather than by arrival.
-   Every comment (`*.comments`) is a `Comment`, every DM (`*.messages`) a `Message`, and every post, video, or story (`*.posts`) a `Post`, whatever the platform: the same `containerId`, `target`, `references`, `text`, `author`, `engagement`, `permalink`, and `publishedAt` (comments also `hidden` and `updatedAt`), with a post's own photos and videos as `media` and the files a comment or DM carries as `attachments`, named and shaped the same way, so one handler serves them all. `containerId` is where the item lives: a comment's post or video, a DM's conversation, the same on reads and events, so an inbox groups by it. `target` points at the one thing the item responds to, `{ kind, externalId }`: a top-level comment's post, a reply's comment, a DM's quoted message. `references` lists what the item's text or body points at, each `{ type, target, span? }`: a `mention` of an account (with the part of `text` it occupies), or an `embed` of other content, such as a video shared into a TikTok DM. A platform adds its own fields beside them, and reports only some of the shared ones, so each is optional. An attachment is often only the platform's id for the file (`externalId`), which [resolves](https://docs.koil.co/api#fetching-attachments) to a URL; its URLs, like a post's, are signed and expire, so fetch rather than store them. Likewise every mention record (`*.mentions`) is a `Mention`, the post or comment that mentions the account: its `variant` (`post` or `comment`) is always set, and `containerId` (a comment's post), `text`, `author`, `permalink`, and `publishedAt` are named the same way. And every reaction record (`*.reactions`) is a `Reaction`: one account's reaction to one item, always with a `target`, and with `emoji` where the platform sends one (a platform with named reactions, such as LinkedIn, reports its own `reactionType` instead). Every conversation (`*.conversations`), 1:1 or group, is a `Conversation`, whose `externalId` is the `containerId` its messages carry, with the `counterpart` of a 1:1 conversation, whether it is still a `messageRequest`, and `updatedAt` where the platform says; a WhatsApp group lists its own `participants` instead. The API reference publishes all six, with the `PostMedia`, `Attachment`, `Engagement` and `Reference` blocks they use, as shared schemas. [Content](https://docs.koil.co/concepts/content) explains `kind`, `containerId`, `target`, and the other fields content shares.
-   Enum values are snake\_case whatever the platform's own casing (`held_for_review`, `pending`), and a platform state Koil does not model yet arrives as `other` rather than failing the read; the platform's own value is in `platformRaw` when you read the item with `includePlatformRaw=true`.

How Koil learned of a change — a platform webhook, polling, or a backfill — is deliberately not part of the event: an event means the same thing however it was collected.

Koil delivers both sides of a conversation. Content the profile wrote itself — an agent replying in the platform's app, or a reply you published through Koil — arrives as a normal event with `data.ownerAuthored: true`. Inboxes should show it; automations that respond to events must skip it, or a bot will answer its own replies. `ownerAuthored` is absent when Koil cannot tell who wrote the item (TikTok's comment webhook, for one, does not say). Absent means unknown, not someone else: an automation should also skip an item whose `data.externalId` is the `externalId` of a publish request it created (`publish_request.succeeded` carries it).

### Routing fields

A few routing fields of `context` (`mode`, the Profile, platform and collection, and a lifecycle event's resource id) are also sent beside the event, for infrastructure that routes without parsing it; [Verify webhook deliveries](https://docs.koil.co/guides/verify-webhooks) lists them. Each is keyed by its hyphenated name (`profile-id`), like the `event-id`, `topic`, and `timestamp` every delivery carries beside them. Where the keys go depends on the destination type:

-   **`webhook`** — headers prefixed `webhook-` (the event id's is `webhook-id`).
-   **`aws_sqs`** — one `metadata` message attribute, a JSON object of every key.
-   **`aws_eventbridge`, `aws_kinesis`, `cloudflare_queues`** — in the message itself, which is `{ "metadata": { … }, "data": <the event> }` (on EventBridge, the event's `detail`).
-   **Other queues and streams** — one message attribute, header, or property per key.

A destination selects events by its `topics` and `scope` alone, so route any further on these fields: a Pub/Sub subscription filter or a Service Bus subscription rule matches them as message attributes, an EventBridge rule as part of the event's `detail`, and a `kafka` or `aws_kinesis` destination's `partitionKeyTemplate` can key each record by one, such as `metadata."profile-id"`.

The event is complete without them, and they are not covered by the webhook signature: route on them before verifying if you like, but once a delivery verifies, read the topic and routing values from the body.

## Receiving deliveries

An attempt succeeds when your webhook endpoint answers `2xx`, or when the queue or stream accepts the message. It fails, and is retried, on a status of `400` or above, a timeout, a connection error, or a refusal from the queue's service, such as a credential that lacks permission or a queue that no longer exists. A webhook endpoint should return `2xx` only once the event is durably stored or enqueued.

Delivery is at-least-once: retries, replays, and an item Koil observes again (a backfill, a platform resending a webhook) reuse the event `id`, and Koil suppresses a repeat only within a short window, so dedupe on the `id`. Dedupe in the consumer that acts on the event, so that a queue's own redeliveries are covered too.

An event `id` is per Profile. When two Profiles reach the same platform account, Koil delivers each item once for each of them, with a different `id` and `context.profileId`. The Profiles can belong to different parties in your product (different customers, or different customers of one customer), and only your product knows whether their copies of an item are one record. Route each event by its `context.profileId` to whoever owns that Profile. Where you do want one record for both, key it on the item's `data.externalId` ([Content](https://docs.koil.co/concepts/content#kind-and-externalid) covers the one exception), never on the event `id`.

These limits apply to every destination type:

-   **Timeout.** Each attempt waits 5 seconds for your endpoint or queue to accept the delivery; a slower answer is a failed attempt.
-   **Retries.** A failed delivery is retried 16 times: 30 seconds after the first attempt, then at doubling intervals up to 8 hours 32 minutes (1, 2, 4 … 512 minutes), then five times 12 hours apart. That is 17 attempts over a little more than three days (77 hours). After the last one Koil stops trying; [retry the delivery](https://docs.koil.co/guides/subscribe-to-events#delivery-history-and-retries) once your endpoint is fixed.
-   **Disabling.** Koil doesn't disable a destination because its deliveries fail: however long your endpoint is down, every event gets the full retry schedule. A destination you disable (`PATCH /v1/event-destinations/{eventDestinationId}` with `{ "enabled": false }`) receives nothing until you re-enable it. Retries that come due while it is disabled are dropped, so [retry what failed](https://docs.koil.co/guides/subscribe-to-events#delivery-history-and-retries) once it is enabled again; events published while it was disabled are never attempted, so they can't be retried.

Persist what your product needs from the stream — inbox items, workflow state, analytics. Koil does not keep platform content, and there is no aggregate read across collections.

## Trusting deliveries

A webhook endpoint is public, so anyone can send it a request: every webhook delivery is signed, and you [verify the signature](https://docs.koil.co/guides/verify-webhooks) before acting on it.

A queue or stream is not public, so its deliveries are not signed: a message on it was written by something holding a credential that can publish to it. Use a queue or topic dedicated to Koil, and give publish access only to the credential on the destination, so whatever arrives there came from Koil. There is no secret to read or rotate (`GET /v1/event-destinations/{eventDestinationId}/secret` and `rotate-secret` answer `404` for these types); you manage the credential itself, as [above](https://docs.koil.co/guides/subscribe-to-events#create-a-destination).

## Delivery history and retries

`GET /v1/event-destinations/{eventDestinationId}/attempts` lists a destination's delivery attempts, newest first. Each names the event (`eventId`, `topic`), how the attempt ended (`status`, and `responseCode`: the HTTP status a webhook endpoint answered with, otherwise an error code), its `attemptNumber`, and when it was made. Filter by `status`, `topic`, or `eventId`. An attempt describes a delivery, not the event's body.

```bash
curl "https://api.koil.co/v1/event-destinations/des_6tW2fQ9mLp/attempts?status=failed" \
  -H "Authorization: Bearer $KOIL_API_KEY" \
  -H "Koil-Version: 2026-12-08"
```

Once your endpoint or queue is fixed, `POST /v1/event-destinations/{eventDestinationId}/events/{eventId}/retry` delivers that event again, as a new attempt with `manual: true`.

```bash
curl -X POST "https://api.koil.co/v1/event-destinations/des_6tW2fQ9mLp/events/evt_4Hq8mZt2Rv/retry" \
  -H "Authorization: Bearer $KOIL_API_KEY" \
  -H "Koil-Version: 2026-12-08"
```

After an outage, retry everything that failed during it with one request: `POST /v1/event-destinations/{eventDestinationId}/retry` with `include: "failed"`, `since`, and `until` once the outage is over (it defaults to the time of the request). Every event whose delivery failed in that window and has not succeeded since is delivered again, once, however many of its attempts failed. The request needs an [`Idempotency-Key`](https://docs.koil.co/concepts/idempotency) and answers `202` at once; the retry then runs in the background, paced to about 10 events a second, so your endpoint is not flooded as it comes back. Follow it in the attempts, where each delivery it makes has `manual: true`. It stops early if the destination is disabled or deleted, and running it again over the same window retries only what has still not arrived.

```bash
curl -X POST "https://api.koil.co/v1/event-destinations/des_6tW2fQ9mLp/retry" \
  -H "Authorization: Bearer $KOIL_API_KEY" \
  -H "Koil-Version: 2026-12-08" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
  "include": "failed",
  "since": "2026-07-03T18:00:00Z",
  "until": "2026-07-06T09:00:00Z"
}'
```

If your side lost events it had already acknowledged (a consumer that answered `2xx` and then failed to store them, or a database restored from a backup), send `include: "all"` instead: every event attempted in the window is delivered again, whether or not it arrived. The window is judged by when events were attempted, not when they happened, and at 10 events a second a busy day takes a while to replay, so keep it to what you lost.

```bash
curl -X POST "https://api.koil.co/v1/event-destinations/des_6tW2fQ9mLp/retry" \
  -H "Authorization: Bearer $KOIL_API_KEY" \
  -H "Koil-Version: 2026-12-08" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
  "include": "all",
  "since": "2026-07-03T18:00:00Z",
  "until": "2026-07-04T18:00:00Z"
}'
```

Both retries need the destination enabled, and reach only events it already has an attempt for, still in the delivery log ([Data and storage](https://docs.koil.co/concepts/data-and-storage)). An event published while the destination was disabled was never attempted, so neither can deliver it. A [backfill request](https://docs.koil.co/guides/backfill) recovers content the platform can still list; content it can't, such as WhatsApp messages and statuses or mentions on Instagram, Facebook and LinkedIn, reaches a destination only as it happens, so one disabled at the time never receives it.
