id: webhook-circuit-breaker-quarantine-sentinel
namespace: company.team
description: |
Protect downstream microservices from webhook storms during outages.
Tracks consecutive delivery failures in Kestra's KV store. When failures reach
a threshold, trips the circuit to OPEN, instantly quarantines incoming payloads
to internal dead-letter storage without dropping events, and alerts Slack.
concurrency:
limit: 1
behavior: QUEUE
triggers:
- id: inbound_webhook
type: io.kestra.plugin.core.trigger.Webhook
description: Exposes an authenticated webhook endpoint for external event
producers (Stripe, GitHub, Shopify, etc.).
key: "{{ secret('WEBHOOK_SECRET_KEY') }}"
inputs:
- id: receiver_url
type: STRING
defaults: "https://httpbin.org/post"
description: Downstream HTTP endpoint where incoming webhook events are forwarded.
required: true
- id: failure_threshold
type: INT
defaults: 3
description: Number of consecutive delivery failures before tripping the circuit
to OPEN.
min: 1
max: 10
required: true
- id: request_timeout
type: STRING
defaults: "PT10S"
description: ISO-8601 duration timeout for forwarding the HTTP request to the receiver.
required: true
tasks:
- id: check_circuit_state
type: io.kestra.plugin.scripts.python.Script
description: Inspect the current circuit breaker state and consecutive failure
count from the KV store.
taskRunner:
type: io.kestra.plugin.core.runner.Process
env:
CIRCUIT_STATE_RAW: "{{ kv('webhook_circuit_state', errorOnMissing=false) ?? '' }}"
FAILURE_COUNT_RAW: "{{ kv('webhook_circuit_failures', errorOnMissing=false) ?? '0' }}"
THRESHOLD: "{{ inputs.failure_threshold }}"
script: |
import json
import os
state = os.environ.get("CIRCUIT_STATE_RAW", "").strip() or "CLOSED"
try:
failures = int(os.environ.get("FAILURE_COUNT_RAW", "0"))
except ValueError:
failures = 0
threshold = int(os.environ.get("THRESHOLD", "3"))
allow_delivery = (state == "CLOSED")
print(f"Circuit check: state={state}, consecutive_failures={failures}, threshold={threshold}, allow_delivery={allow_delivery}")
print("::" + json.dumps({
"outputs": {
"state": state,
"consecutive_failures": failures,
"allow_delivery": allow_delivery
}
}) + "::")
- id: route_delivery_or_quarantine
type: io.kestra.plugin.core.flow.If
description: Branch based on circuit state. If OPEN, quarantine immediately. If
CLOSED, attempt delivery.
condition: "{{ outputs.check_circuit_state.vars.allow_delivery }}"
then:
- id: attempt_forward
type: io.kestra.plugin.core.http.Request
description: Forward the raw webhook payload to the downstream endpoint.
allowFailed prevents non-2xx responses from crashing the flow before
state can be recorded.
uri: "{{ inputs.receiver_url }}"
method: POST
contentType: application/json
timeout: "{{ inputs.request_timeout }}"
options:
allowFailed: true
body: "{{ (trigger.body ?? {}) | toJson }}"
- id: evaluate_delivery_outcome
type: io.kestra.plugin.core.flow.If
description: Check if downstream returned a successful 2xx response.
condition: "{{ outputs.attempt_forward.code >= 200 and
outputs.attempt_forward.code < 300 }}"
then:
- id: reset_circuit_on_success
type: io.kestra.plugin.core.kv.Set
description: Reset consecutive failures to 0 and ensure circuit is marked
CLOSED.
key: webhook_circuit_failures
value: "0"
- id: mark_circuit_closed
type: io.kestra.plugin.core.kv.Set
description: Confirm circuit state is CLOSED.
key: webhook_circuit_state
value: "CLOSED"
else:
- id: record_delivery_failure
type: io.kestra.plugin.scripts.python.Script
description: Compute incremented consecutive failure count and determine if the
circuit should trip.
taskRunner:
type: io.kestra.plugin.core.runner.Process
env:
CURRENT_FAILURES: "{{ outputs.check_circuit_state.vars.consecutive_failures }}"
THRESHOLD: "{{ inputs.failure_threshold }}"
STATUS_CODE: "{{ outputs.attempt_forward.code }}"
script: |
import json
import os
curr = int(os.environ.get("CURRENT_FAILURES", "0")) + 1
threshold = int(os.environ.get("THRESHOLD", "3"))
tripped = curr >= threshold
new_state = "OPEN" if tripped else "CLOSED"
print(f"Delivery failed with HTTP {os.environ.get('STATUS_CODE')}. New failures={curr}, trip_circuit={tripped}")
print("::" + json.dumps({
"outputs": {
"new_failure_count": curr,
"tripped": tripped,
"new_state": new_state
}
}) + "::")
- id: update_failure_counter
type: io.kestra.plugin.core.kv.Set
description: Save updated failure count to KV store.
key: webhook_circuit_failures
value: "{{ outputs.record_delivery_failure.vars.new_failure_count }}"
- id: trip_circuit_state
type: io.kestra.plugin.core.kv.Set
description: Update circuit state in KV store.
key: webhook_circuit_state
value: "{{ outputs.record_delivery_failure.vars.new_state }}"
- id: quarantine_failed_delivery
type: io.kestra.plugin.core.storage.Write
description: Persist the failed event and failure diagnostic envelope to
internal storage.
extension: ".json"
content: |
{
"quarantine_id": {{ execution.id | toJson }},
"timestamp": {{ execution.startDate | toJson }},
"circuit_state": {{ outputs.record_delivery_failure.vars.new_state | toJson }},
"reason": "Downstream endpoint HTTP {{ outputs.attempt_forward.code }} failure",
"receiver_url": {{ inputs.receiver_url | toJson }},
"payload": {{ (trigger.body ?? {}) | toJson }}
}
- id: alert_circuit_trip
type: io.kestra.plugin.core.flow.If
description: If failures met or exceeded threshold, send an incident alert to
Slack.
condition: "{{ outputs.record_delivery_failure.vars.tripped }}"
then:
- id: notify_slack_trip
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Post a critical circuit trip alert to Slack.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": ":rotating_light: *Webhook Circuit Breaker TRIPPED to OPEN* for flow `{{ flow.id }}`!\nDownstream service `{{ inputs.receiver_url }}` failed {{ outputs.record_delivery_failure.vars.new_failure_count }} consecutive times (last status: {{ outputs.attempt_forward.code }}).\nSubsequent webhook traffic will be automatically quarantined to DLQ storage.\nExecution: `{{ execution.id }}`."
}
else:
- id: quarantine_open_payload
type: io.kestra.plugin.core.storage.Write
description: Circuit is OPEN. Intercept and store the payload immediately in
internal dead-letter storage without bombarding the failing service.
extension: ".json"
content: |
{
"quarantine_id": {{ execution.id | toJson }},
"timestamp": {{ execution.startDate | toJson }},
"circuit_state": "OPEN",
"reason": "Circuit breaker OPEN: downstream service unavailable. Quarantined to prevent event loss.",
"receiver_url": {{ inputs.receiver_url | toJson }},
"payload": {{ (trigger.body ?? {}) | toJson }}
}
- id: notify_slack_quarantine
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alert the operations channel that an incoming webhook was safely
intercepted and quarantined.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": ":warning: *Webhook Quarantined (Circuit OPEN)* in flow `{{ flow.id }}`.\nEvent intercepted and saved to storage: `{{ outputs.quarantine_open_payload.uri }}`.\nDownstream receiver `{{ inputs.receiver_url }}` is currently paused to allow recovery.\nExecution: `{{ execution.id }}`."
}
errors:
- id: alert_infrastructure_error
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alert when the circuit breaker flow itself experiences an
infrastructure error (e.g., storage or KV outage).
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": ":x: *Webhook Circuit Sentinel INFRASTRUCTURE ERROR* in flow `{{ flow.id }}` (Execution `{{ execution.id }}`).\nCheck Kestra execution logs for internal error details."
}
outputs:
- id: final_circuit_state
type: STRING
description: Circuit state at the conclusion of this execution (CLOSED or OPEN).
value: "{{ outputs.record_delivery_failure is defined ?
outputs.record_delivery_failure.vars.new_state : (outputs.attempt_forward
is defined and outputs.attempt_forward.code >= 200 and
outputs.attempt_forward.code < 300 ? 'CLOSED' :
outputs.check_circuit_state.vars.state) }}"
- id: delivery_status_code
type: INT
description: HTTP status code received from the downstream receiver, or null if
delivery was skipped due to OPEN circuit.
value: "{{ outputs.attempt_forward.code ?? null }}"
- id: dead_letter_uri
type: STRING
description: Storage URI of the quarantined event artifact if written to DLQ,
otherwise empty.
value: "{{ outputs.quarantine_open_payload.uri ??
(outputs.quarantine_failed_delivery.uri ?? '') }}"