# Webhook Replay & Batch Dispatcher (`joe1981/webhook-replay-dispatcher`) Actor

Fan out a batch of JSON events to multiple webhook URLs with retries, cross-run business-key dedupe, failure replay, and one audit row per delivery.

- **URL**: https://apify.com/joe1981/webhook-replay-dispatcher.md
- **Developed by:** [joe](https://apify.com/joe1981) (community)
- **Categories:** Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$2.00 / 1,000 successful deliveries

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Webhook Replay & Batch Dispatcher

**Fan out a batch of JSON events to multiple webhook URLs with retries, business-key
deduplication across runs, failure replay, and one audit row per delivery.**

### Why this Actor exists

Apify already sends webhooks for run lifecycle events (`ACTOR.RUN.SUCCEEDED`, `FAILED`, …),
retries failed deliveries with exponential backoff, and recommends that receivers dedupe by
`runId`. So **"POST an event to a URL with retries" is already free on the platform** — an
Actor that only does that has no reason to exist.

This Actor covers the part the built-in webhook cannot:

| Need | Apify built-in webhook | This Actor |
|---|---|---|
| Payload | Fixed run lifecycle events | **Any JSON events you supply** (inline or from a URL) |
| Targets | One `requestUrl` per webhook | **Many destinations per event**, each retried and recorded separately |
| Idempotency | Receiver must dedupe by `runId` | **Business `event_id` dedupe persisted across runs** in the Key-Value Store |
| Recovery | Platform retries within one dispatch | **Replay previously failed events** with `replayFailed: true` |
| Audit | Run logs | **One Dataset row per delivery**: status, attempts, HTTP code, latency, error, payload hash |
| Cost rehearsal | — | **`dryRun`** computes the plan without sending a single request |

It is a **batch Actor**, not a 24/7 ingestion endpoint. If you need a public URL that
accepts live webhooks around the clock, run the GlueHub relay on your own domain; use this
Actor to re-drive, fan out, or reconcile events you already have.

### Input

| Field | Default | Meaning |
|---|---|---|
| `destinations` *(required)* | — | One or more HTTP(S) URLs — bare strings or `{"url": …, "id": …}` objects. Every event is POSTed to each. |
| `events` | `[]` | Arbitrary JSON array. Objects with `event_id` are deduped by that value; others by a sha256 of the payload. |
| `sourceUrl` | `""` | Extra events fetched from a JSON endpoint (bare array, `{"events":[…]}`, or a GlueHub `/echo/<token>` response). |
| `dedupeKey` | `event_id` | Business idempotency field. |
| `maxAttempts` | `3` | 1–10 attempts per (event, destination) pair. |
| `backoffSeconds` | `[1, 4, 10]` | Wait before each retry. |
| `timeoutSeconds` | `10` | Per-request timeout. |
| `concurrency` | `8` | Parallel deliveries. |
| `maxEvents` | `1000` | Hard cap on pairs per run, to bound cost. |
| `hmacSecret` | `""` | If set, adds `X-Glue-Signature: sha256=<HMAC of raw body>` and `X-Glue-Event-Id`. |
| `dryRun` | `false` | Emit audit rows, send nothing, charge nothing. |
| `replayFailed` | `false` | With no `events`, reload the previous run's failed events from KVS. |
| `chargeEventName` | `""` | Pay-Per-Event name; one charge per successful delivery when configured. |
| `allowPrivateTargets` | `false` | **Local testing only.** Off by default for SSRF safety. |

#### Minimal example

```json
{
  "destinations": ["https://your-app.example.com/hooks/orders"],
  "events": [
    { "event_id": "evt-001", "type": "order.created", "amount": 42 },
    { "event_id": "evt-001", "type": "order.created", "amount": 42 },
    { "event_id": "evt-002", "type": "order.paid", "amount": 42 }
  ]
}
```

The duplicate `evt-001` is collapsed. Run it again: nothing is re-delivered. Point one
destination at a URL that returns 500 and re-run with `replayFailed: true` to retry only
the failures.

### Output

**Dataset** — one row per delivery:

```json
{
  "event_id": "evt-001",
  "destination": "https://your-app.example.com/hooks/orders",
  "status": "delivered",
  "attempts": 2,
  "http_status": 200,
  "last_error": null,
  "latency_ms": 1013,
  "payload_sha256": "ad092d5e36ba7028",
  "at": "2026-11-15T07:16:06+00:00"
}
```

**Key-Value Store** — `OUTPUT` (run summary), `SEEN` (successfully delivered pairs, for
cross-run idempotency), `FAILED` (failed events, for replay).

### Security

Destination URLs are supplied by the person running the Actor. To stop the Actor from
being used to POST into private networks or cloud metadata endpoints, **private,
loopback, link-local, reserved and non-HTTP(S) targets are refused by default**. Only
`allowPrivateTargets: true` (intended for local testing) lifts that guard. Optional HMAC
signing lets receivers verify authenticity — compute it over the raw request body.

### Cost

**$2.00 per 1,000 successful deliveries** ($0.002 per delivery), billed as the
`delivery-ok` Pay-Per-Event. Nothing else is charged by this Actor: failed deliveries,
events skipped as duplicates, and dry runs are free. Platform usage (compute + storage)
is included in that price — you are not billed extra for it.

A typical run of 500 events to 2 destinations costs $2.00. Every charge corresponds to a
row in the dataset with `status: "delivered"`, so you can reconcile the bill against the
output one-to-one. The Actor uses no LLM, no browser and no proxy — just outbound HTTP and
a small amount of Key-Value Store state.

### Verified

`python tests/selftest.py` → **36/36 assertions pass** against a real local HTTP sink:
retries (503→200), exhaustion, multi-destination fan-out, in-run and cross-run dedupe,
failure replay, HMAC, dry run, Dataset/KVS writes, Pay-Per-Event charging, destination
normalisation, and the full `async with Actor` platform branch via an SDK stub.

On the Apify platform the published build was run against a live HTTP endpoint: every
delivery produced its own dataset row, cross-run dedupe was confirmed by re-running the
same input (`delivered 2` on the first run, `already_delivered_pairs 2` and
`delivered 0` on the second), and the default input succeeds out of the box.

# Actor input Schema

## `destinations` (type: `array`):

Each event is POSTed to every URL here. Accepts bare URL strings or {"url": "...", "id": "label"} objects. Each (event, destination) pair retries independently and gets its own audit row.

## `events` (type: `array`):

Arbitrary JSON payloads. Objects with an event_id field are deduplicated by that value; otherwise a sha256 of the payload is used.

## `sourceUrl` (type: `string`):

Fetch extra events from a JSON endpoint. Accepts a bare array, {"events": \[...]}, or a GlueHub /echo/<token> response with an items array. Merged with the events above.

## `dedupeKey` (type: `string`):

Field used as the business idempotency key. Successful (event, destination) pairs are remembered in the Key-Value Store, so re-running the Actor will not double-deliver.

## `maxAttempts` (type: `integer`):

1–10. Retries use the backoff schedule below.

## `backoffSeconds` (type: `array`):

Wait before each retry. Defaults to \[1, 4, 10], the same schedule as the GlueHub webhook relay.

## `timeoutSeconds` (type: `integer`):

Seconds to wait for a single POST before counting it as a failed attempt and retrying. Applies per (event, destination) pair.

## `concurrency` (type: `integer`):

Maximum number of (event, destination) pairs in flight at once. Higher values speed up large batches but increase load on your receiving endpoints.

## `maxEvents` (type: `integer`):

Hard cap on (event × destination) pairs in one run, to bound cost.

## `hmacSecret` (type: `string`):

If set, each POST carries X-Glue-Signature: sha256=<hmac of raw body> and X-Glue-Event-Id.

## `dryRun` (type: `boolean`):

Compute the plan and emit audit rows, but send no HTTP requests and do not charge.

## `replayFailed` (type: `boolean`):

If no events are supplied, reload the events that failed in the previous run from the Key-Value Store and retry them.

## `chargeEventName` (type: `string`):

Pay-Per-Event event name used for billing; defaults to the Actor primary event ("delivery-ok"). Only change this for local testing.

## `allowPrivateTargets` (type: `boolean`):

OFF by default: the Actor refuses localhost, private IPs, link-local metadata addresses and non-http(s) URLs to prevent SSRF. Enable ONLY when testing against a local sink.

## Actor input object example

```json
{
  "destinations": [
    "https://httpbin.org/post"
  ],
  "events": [
    {
      "event_id": "sample-1",
      "type": "order.created",
      "order_id": "A-1001",
      "amount": 49.9
    },
    {
      "event_id": "sample-2",
      "type": "order.paid",
      "order_id": "A-1001",
      "amount": 49.9
    }
  ],
  "sourceUrl": "",
  "dedupeKey": "event_id",
  "maxAttempts": 3,
  "backoffSeconds": [
    1,
    4,
    10
  ],
  "timeoutSeconds": 10,
  "concurrency": 8,
  "maxEvents": 1000,
  "dryRun": false,
  "replayFailed": false,
  "chargeEventName": "delivery-ok",
  "allowPrivateTargets": false
}
```

# Actor output Schema

## `deliveries` (type: `string`):

No description

## `runState` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("joe1981/webhook-replay-dispatcher").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("joe1981/webhook-replay-dispatcher").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call joe1981/webhook-replay-dispatcher --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,joe1981/webhook-replay-dispatcher"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/zbAQdjlBmYWYKJR82/builds/vyHjo0xZhOCq2yLEY/openapi.json
