id: webhook-delivery-replay-ledger
namespace: company.team
description: |
Accept a signed webhook, record it once in PostgreSQL, and deliver its payload
to an internal HTTP endpoint with a stable idempotency key. Keep each attempt
in a ledger. A failed delivery can be replayed only after human approval;
a disabled schedule can recover pending work after a worker interruption.
concurrency: { limit: 1, behavior: QUEUE }
triggers:
- id: signed_event
type: io.kestra.plugin.core.trigger.Webhook
description: POST text/plain JSON to this keyed URL with X-Webhook-Signature-256
set to sha256=<HMAC of the exact UTF-8 body>. text/plain preserves bytes
for signature verification.
key: "{{ secret('WEBHOOK_LEDGER_KEY') }}"
inputs:
operation: INGEST
- id: recover_pending
type: io.kestra.plugin.core.trigger.Schedule
description: Enable after configuring the receiver; it picks up pending or
expired leased deliveries, never failed ones.
cron: "*/5 * * * *"
disabled: true
inputs:
operation: SWEEP
inputs:
- id: operation
type: SELECT
values: [ INGEST, REPLAY, SWEEP ]
defaults: SWEEP
description: INGEST is set by the webhook, REPLAY requests approval for one
failed event, and SWEEP recovers pending work.
- id: event_id
type: STRING
defaults: ""
validator: ^$|^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$
description: Event ID to replay when operation is REPLAY; leave empty for
webhook ingestion or a sweep.
- id: receiver_url
type: STRING
defaults: http://host.docker.internal:9996/events
description: Internal callback URL. Point it at a receiver that verifies the
outbound HMAC and deduplicates Idempotency-Key.
- id: wire_attempts
type: INT
defaults: 3
min: 1
max: 5
description: Maximum HTTP attempts per claimed delivery; transient failures back
off exponentially.
- id: lease_seconds
type: INT
defaults: 120
min: 30
description: A SENDING claim older than this can be recovered by SWEEP after a
worker crash; the receiver must deduplicate the event ID.
- id: approval_timeout
type: STRING
defaults: P1D
description: ISO-8601 duration to wait for a person to approve replay of a
failed delivery.
- id: kestra_url
type: STRING
defaults: http://localhost:8080
description: Public Kestra UI base URL placed in the replay approval and failure alerts.
tasks:
- id: verify_inbound
type: io.kestra.plugin.scripts.python.Script
description: Validate the exact text/plain request body and its HMAC before
touching PostgreSQL or the receiver.
taskRunner: { type: io.kestra.plugin.core.runner.Process }
env:
OPERATION: "{{ inputs.operation }}"
REPLAY_ID: "{{ inputs.event_id }}"
BODY: "{{ trigger.body ?? '' }}"
HEADERS_JSON: "{{ (trigger.headers ?? {}) | toJson }}"
SIGNING_SECRET: "{{ secret('WEBHOOK_SIGNING_SECRET') }}"
script: |
import hashlib
import hmac
import json
import os
import re
result = {"valid": True, "reason": "not an ingest", "event_id": "", "payload_text": "", "payload_sha256": ""}
if os.environ["OPERATION"] == "REPLAY" and not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,99}", os.environ.get("REPLAY_ID", "")):
result.update(valid=False, reason="REPLAY requires a valid event_id")
if os.environ["OPERATION"] == "INGEST":
body = os.environ.get("BODY", "")
headers = json.loads(os.environ.get("HEADERS_JSON") or "{}")
supplied = next((v for k, values in headers.items() if k.lower() == "x-webhook-signature-256" for v in (values if isinstance(values, list) else [values])), "")
supplied = str(supplied)
digest = supplied[7:] if supplied.lower().startswith("sha256=") else supplied
expected = hmac.new(os.environ["SIGNING_SECRET"].encode(), body.encode(), hashlib.sha256).hexdigest()
if len(body.encode()) > 65536 or not re.fullmatch(r"[0-9a-fA-F]{64}", digest) or not hmac.compare_digest(digest.lower(), expected):
result.update(valid=False, reason="missing or invalid signature, or body exceeds 64 KiB")
else:
try:
event = json.loads(body)
event_id = event["event_id"]
payload = event["payload"]
if not isinstance(event_id, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,99}", event_id):
raise ValueError("invalid event_id")
if not isinstance(payload, dict):
raise ValueError("payload must be an object")
payload_text = json.dumps(payload, separators=(",", ":"), sort_keys=True, ensure_ascii=False)
result.update(event_id=event_id, payload_text=payload_text, payload_sha256=hashlib.sha256(payload_text.encode()).hexdigest(), reason="verified")
except (ValueError, KeyError, TypeError) as exc:
result.update(valid=False, reason="invalid event envelope: " + str(exc)[:120])
print("inbound: " + result["reason"])
print("::" + json.dumps({"outputs": result}) + "::")
- id: reject_bad_inbound
type: io.kestra.plugin.core.flow.If
condition: "{{ not outputs.verify_inbound.vars.valid }}"
then:
- id: reject_request
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Webhook rejected before persistence: {{
outputs.verify_inbound.vars.reason }}"
- id: ensure_ledger
type: io.kestra.plugin.jdbc.postgresql.Queries
description: Idempotent schema creation; the event row and attempt history
survive Kestra restarts.
url: "{{ secret('POSTGRES_URL') }}"
username: "{{ secret('POSTGRES_USERNAME') }}"
password: "{{ secret('POSTGRES_PASSWORD') }}"
sql: |
CREATE TABLE IF NOT EXISTS webhook_delivery_ledger (
event_id text PRIMARY KEY,
payload_text text NOT NULL,
payload_sha256 char(64) NOT NULL,
state text NOT NULL CHECK (state IN ('PENDING', 'SENDING', 'FAILED', 'DELIVERED')),
claim_token text,
claimed_at timestamptz,
delivery_rounds integer NOT NULL DEFAULT 0,
wire_attempts integer NOT NULL DEFAULT 0,
last_error text,
created_at timestamptz NOT NULL DEFAULT now(),
delivered_at timestamptz
);
CREATE TABLE IF NOT EXISTS webhook_delivery_attempt (
event_id text NOT NULL REFERENCES webhook_delivery_ledger(event_id),
execution_id text NOT NULL,
wire_attempts integer NOT NULL,
http_status integer,
result text NOT NULL,
detail text,
finished_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (event_id, execution_id)
);
retry: { type: exponential, interval: PT2S, maxInterval: PT30S, maxAttempts: 3 }
- id: ingest_new_event
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.operation == 'INGEST' }}"
then:
- id: store_event
type: io.kestra.plugin.jdbc.postgresql.Query
description: Insert once by event ID and reject an ID reused with a different
payload; duplicate webhooks cannot re-dispatch.
url: "{{ secret('POSTGRES_URL') }}"
username: "{{ secret('POSTGRES_USERNAME') }}"
password: "{{ secret('POSTGRES_PASSWORD') }}"
fetchType: FETCH_ONE
parameters:
id: "{{ outputs.verify_inbound.vars.event_id }}"
payload: "{{ outputs.verify_inbound.vars.payload_text }}"
digest: "{{ outputs.verify_inbound.vars.payload_sha256 }}"
sql: |
WITH inserted AS (
INSERT INTO webhook_delivery_ledger(event_id, payload_text, payload_sha256, state)
VALUES (CAST(:id AS text), CAST(:payload AS text), CAST(:digest AS text), 'PENDING')
ON CONFLICT (event_id) DO NOTHING RETURNING event_id
)
SELECT EXISTS(SELECT 1 FROM inserted) AS inserted,
(EXISTS(SELECT 1 FROM inserted) OR
(SELECT payload_sha256 = CAST(:digest AS text) FROM webhook_delivery_ledger WHERE event_id = CAST(:id AS text))) AS hash_matches
- id: reject_id_collision
type: io.kestra.plugin.core.flow.If
condition: "{{ not outputs.store_event.row.hash_matches }}"
then:
- id: fail_id_collision
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Event ID {{ outputs.verify_inbound.vars.event_id }} already
exists with a different payload"
- id: ask_before_replay
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.operation == 'REPLAY' }}"
then:
- id: inspect_failed
type: io.kestra.plugin.jdbc.postgresql.Query
description: An operator may request replay only for a known FAILED event; read
current state before asking.
url: "{{ secret('POSTGRES_URL') }}"
username: "{{ secret('POSTGRES_USERNAME') }}"
password: "{{ secret('POSTGRES_PASSWORD') }}"
fetchType: FETCH_ONE
parameters:
id: "{{ inputs.event_id }}"
sql: "SELECT coalesce((SELECT state FROM webhook_delivery_ledger WHERE event_id
= CAST(:id AS text)), 'NOT_FOUND') AS state"
- id: require_failed_event
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.inspect_failed.row.state != 'FAILED' }}"
then:
- id: reject_replay_request
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Replay requires a current FAILED row for event {{ inputs.event_id
}}; found {{ outputs.inspect_failed.row.state }}"
- id: failed_only
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.inspect_failed.row.state == 'FAILED' }}"
then:
- id: request_replay_approval
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: One approval request for the specified failed event, with a direct
execution link.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text":"Approve replay of FAILED webhook {{ inputs.event_id }}? Review its ledger and receiver before resuming {{ inputs.kestra_url }}/ui/main/executions/company.team/{{ flow.id }}/{{ execution.id }}. A denial leaves it FAILED."}
- id: approve_replay
type: io.kestra.plugin.core.flow.Pause
description: Approval is required even if the same event failed on an earlier
replay.
pauseDuration: "{{ inputs.approval_timeout }}"
behavior: WARN
onResume:
- id: approved
type: BOOL
displayName: Approve replay
defaults: false
description: Set true only after checking the failed ledger row and the
receiver.
- id: approver_note
type: STRING
displayName: Approval note
defaults: reviewed
description: Ticket or reason recorded in the execution history.
- id: claim_due_delivery
type: io.kestra.plugin.jdbc.postgresql.Query
description: Atomic row claim. A late replay approval is rechecked against
FAILED; sweeps may reclaim only expired SENDING leases.
url: "{{ secret('POSTGRES_URL') }}"
username: "{{ secret('POSTGRES_USERNAME') }}"
password: "{{ secret('POSTGRES_PASSWORD') }}"
fetchType: FETCH_ONE
parameters:
operation: "{{ inputs.operation }}"
incoming_id: "{{ outputs.verify_inbound.vars.event_id }}"
inserted: "{{ outputs.store_event.row.inserted ?? false }}"
replay_id: "{{ inputs.event_id }}"
approved: "{{ outputs.approve_replay.onResume.approved ?? false }}"
lease: "{{ inputs.lease_seconds }}"
token: "{{ execution.id }}"
sql: |
WITH pick AS (
SELECT event_id, state AS previous_state FROM webhook_delivery_ledger
WHERE (CAST(:operation AS text) = 'INGEST' AND CAST(:inserted AS boolean)
AND event_id = CAST(:incoming_id AS text) AND state = 'PENDING')
OR (CAST(:operation AS text) = 'REPLAY' AND CAST(:approved AS boolean)
AND event_id = CAST(:replay_id AS text) AND state = 'FAILED')
OR (CAST(:operation AS text) = 'SWEEP' AND
(state = 'PENDING' OR (state = 'SENDING' AND claimed_at < now() - CAST(:lease AS integer) * interval '1 second')))
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1
), claimed AS (
UPDATE webhook_delivery_ledger d SET state = 'SENDING', claim_token = CAST(:token AS text),
claimed_at = now(), delivery_rounds = delivery_rounds + 1
FROM pick WHERE d.event_id = pick.event_id
RETURNING d.event_id, d.payload_text, d.delivery_rounds
)
SELECT coalesce((SELECT event_id FROM claimed), '') AS event_id,
coalesce((SELECT payload_text FROM claimed), '') AS payload_text,
coalesce((SELECT delivery_rounds FROM claimed), 0) AS delivery_rounds,
coalesce((SELECT previous_state FROM pick), '') AS previous_state
retry: { type: exponential, interval: PT2S, maxInterval: PT30S, maxAttempts: 3 }
- id: deliver_claimed
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.claim_due_delivery.row.event_id != '' }}"
then:
- id: post_to_receiver
type: io.kestra.plugin.scripts.python.Script
description: HMAC-sign the payload and use the stable event ID as
Idempotency-Key; retry only network, 429 and 5xx failures.
taskRunner: { type: io.kestra.plugin.core.runner.Process }
env:
EVENT_ID: "{{ outputs.claim_due_delivery.row.event_id }}"
PAYLOAD: "{{ outputs.claim_due_delivery.row.payload_text }}"
RECEIVER_URL: "{{ inputs.receiver_url }}"
ATTEMPTS: "{{ inputs.wire_attempts }}"
OUTBOUND_SECRET: "{{ secret('DELIVERY_SIGNING_SECRET') }}"
script: |
import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.request
event_id = os.environ["EVENT_ID"]
body = os.environ["PAYLOAD"].encode()
signature = hmac.new(os.environ["OUTBOUND_SECRET"].encode(), body, hashlib.sha256).hexdigest()
result = {"success": False, "wire_attempts": 0, "http_status": 0, "detail": "not attempted"}
for attempt in range(1, int(os.environ["ATTEMPTS"]) + 1):
result["wire_attempts"] = attempt
req = urllib.request.Request(os.environ["RECEIVER_URL"], data=body, method="POST", headers={
"Content-Type": "application/json",
"X-Delivery-Id": event_id,
"Idempotency-Key": event_id,
"X-Delivery-Signature-256": "sha256=" + signature,
})
try:
with urllib.request.urlopen(req, timeout=5) as response:
result["http_status"] = response.status
acknowledgement = json.loads(response.read(8192))
if response.status == 200 and acknowledgement.get("accepted") is True and acknowledgement.get("event_id") == event_id:
result.update(success=True, detail="receiver acknowledged matching event_id")
break
result["detail"] = "invalid receiver acknowledgement"
if response.status < 500:
break
except urllib.error.HTTPError as exc:
result["http_status"] = exc.code
result["detail"] = "HTTP " + str(exc.code)
if exc.code != 429 and exc.code < 500:
break
except (urllib.error.URLError, TimeoutError, ValueError, json.JSONDecodeError) as exc:
result["detail"] = type(exc).__name__
if attempt < int(os.environ["ATTEMPTS"]):
time.sleep(min(2 ** (attempt - 1), 4))
print("delivery " + event_id + ": " + ("acknowledged" if result["success"] else result["detail"]))
print("::" + json.dumps({"outputs": result}) + "::")
- id: record_outcome
type: io.kestra.plugin.jdbc.postgresql.Query
description: Update the claimed row and append one durable attempt record in the
same PostgreSQL statement.
url: "{{ secret('POSTGRES_URL') }}"
username: "{{ secret('POSTGRES_USERNAME') }}"
password: "{{ secret('POSTGRES_PASSWORD') }}"
fetchType: FETCH_ONE
parameters:
id: "{{ outputs.claim_due_delivery.row.event_id }}"
token: "{{ execution.id }}"
ok: "{{ outputs.post_to_receiver.vars.success }}"
wire_attempts: "{{ outputs.post_to_receiver.vars.wire_attempts }}"
status: "{{ outputs.post_to_receiver.vars.http_status }}"
detail: "{{ outputs.post_to_receiver.vars.detail }}"
sql: |
WITH updated AS (
UPDATE webhook_delivery_ledger SET
state = CASE WHEN CAST(:ok AS boolean) THEN 'DELIVERED' ELSE 'FAILED' END,
wire_attempts = wire_attempts + CAST(:wire_attempts AS integer),
last_error = CASE WHEN CAST(:ok AS boolean) THEN NULL ELSE CAST(:detail AS text) END,
delivered_at = CASE WHEN CAST(:ok AS boolean) THEN now() ELSE delivered_at END,
claim_token = NULL, claimed_at = NULL
WHERE event_id = CAST(:id AS text) AND claim_token = CAST(:token AS text) AND state = 'SENDING'
RETURNING event_id, state
), logged AS (
INSERT INTO webhook_delivery_attempt(event_id, execution_id, wire_attempts, http_status, result, detail)
SELECT event_id, CAST(:token AS text), CAST(:wire_attempts AS integer), CAST(:status AS integer), state, CAST(:detail AS text)
FROM updated ON CONFLICT (event_id, execution_id) DO NOTHING RETURNING event_id
)
SELECT coalesce((SELECT state FROM updated), 'CLAIM_LOST') AS state,
EXISTS(SELECT 1 FROM logged) AS attempt_logged
- id: fail_if_claim_lost
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.record_outcome.row.state == 'CLAIM_LOST' }}"
then:
- id: report_claim_loss
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Claim lost while recording {{
outputs.claim_due_delivery.row.event_id }}; inspect receiver
before replaying"
- id: notify_failed_delivery
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.record_outcome.row.state == 'FAILED' and
outputs.claim_due_delivery.row.previous_state != 'FAILED' }}"
then:
- id: alert_failed_delivery
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Give the operator the exact event to inspect and the safe replay
action.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text":"Webhook {{ outputs.claim_due_delivery.row.event_id }} failed delivery after {{ outputs.post_to_receiver.vars.wire_attempts }} HTTP attempt(s): {{ outputs.post_to_receiver.vars.detail }}. Inspect the receiver and ledger, then run {{ flow.id }} with operation=REPLAY and event_id={{ outputs.claim_due_delivery.row.event_id }} for approval. Execution {{ execution.id }}."}
- id: warn_on_failed_delivery
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.record_outcome.row.state == 'FAILED' }}"
then:
- id: end_with_warning
type: io.kestra.plugin.core.execution.Exit
state: WARNING
errors:
- id: alert_flow_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Infrastructure or validation failure needs human review; a SENDING
claim may be recovered after its lease expires.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {'text': 'Webhook ledger flow ' ~ flow.id ~ ' failed at ' ~
tasksWithState('FAILED')[0]['taskId'] ~ ' in execution ' ~ execution.id ~
'. Cause: ' ~ errorLogs() ~ '. Inspect logs and the PostgreSQL ledger. A
stranded SENDING claim can be swept after ' ~ inputs.lease_seconds ~ '
seconds: ' ~ inputs.kestra_url ~ '/ui/main/executions/company.team/' ~
flow.id ~ '/' ~ execution.id} | toJson }}
outputs:
- id: event_id
type: STRING
value: "{{ outputs.claim_due_delivery.row.event_id ?? '' }}"
- id: result
type: STRING
value: "{{ outputs.record_outcome.row.state ?? 'NO_DELIVERY' }}"