id: temporal-activity-retry-exhaustion-dead-letter-guard
namespace: company.platform
description: |
Audits Temporal Server namespaces for workflow executions caught in infinite activity retry loops,
terminates or quarantines stuck workflows, persists dead-letter records to Kestra KV, and dispatches Slack incident alerts.
inputs:
- id: temporal_api_url
type: STRING
displayName: Temporal HTTP API URL
defaults: "http://localhost:7233"
description: Base HTTP URL of Temporal Server Frontend or Web UI proxy (e.g.
http://temporal-frontend.temporal.svc.cluster.local:7233).
- id: temporal_namespace
type: STRING
displayName: Temporal Namespace
defaults: "default"
description: Target Temporal namespace containing workflow executions to audit.
- id: visibility_query
type: STRING
displayName: Visibility Query Filter
defaults: "ExecutionStatus = 'Running' OR ExecutionStatus = 'TimedOut' OR
ExecutionStatus = 'Failed'"
description: Temporal SQL-like visibility filter query used to discover target
workflow executions.
- id: max_activity_retry_threshold
type: INT
displayName: Max Activity Retry Threshold
defaults: 10
description: Maximum allowable activity retry attempts before flagging infinite
exponential backoff retry exhaustion.
- id: quarantine_action
type: SELECT
displayName: Quarantine Action
values:
- TERMINATE
- CANCEL
- OBSERVE_ONLY
defaults: TERMINATE
description: Remediation action to apply against running workflows identified in
stuck activity retry loops.
- id: max_executions_to_scan
type: INT
displayName: Max Executions to Scan
defaults: 50
description: Maximum number of workflow executions to retrieve and inspect in a
single audit run.
- id: alert_on_quarantine
type: BOOL
displayName: Alert On Dead-Letter Quarantine
defaults: true
description: Toggle whether high-priority Slack notifications are dispatched
when dead-lettered executions are detected.
- id: fail_on_quarantine
type: BOOL
displayName: Gate Execution on Quarantine
defaults: false
description: When true, marks the Kestra execution as failed if any workflows
are quarantined or dead-lettered.
- id: temporal_web_url
type: STRING
displayName: Temporal Web UI Base URL
defaults: "http://localhost:8233"
description: Base URL of the Temporal Web UI used to generate deep links for
incident triage.
- id: slack_channel
type: STRING
displayName: Slack Incident Channel
defaults: "#temporal-incidents"
description: Slack channel destination for high-priority dead-letter queue and
retry exhaustion alerts.
triggers:
- id: periodic_audit_schedule
type: io.kestra.plugin.core.trigger.Schedule
cron: "*/10 * * * *"
disabled: true
description: Regular schedule to audit Temporal workflows for activity retry
exhaustion every 10 minutes.
- id: on_demand_audit_webhook
type: io.kestra.plugin.core.trigger.Webhook
key: "{{ secret('TEMPORAL_AUDIT_WEBHOOK_KEY') }}"
description: Webhook trigger allowing external monitoring or incident systems to
initiate an immediate dead-letter audit.
tasks:
- id: audit_and_quarantine_workflows
type: io.kestra.plugin.scripts.python.Script
description: Queries Temporal Server HTTP visibility API, inspects pending
activities for retry exhaustion, executes quarantine actions, and extracts
failure stack traces.
containerImage: python:3.11-slim
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
env:
TEMPORAL_API_URL: "{{ inputs.temporal_api_url }}"
TEMPORAL_NAMESPACE: "{{ inputs.temporal_namespace }}"
TEMPORAL_AUTH_TOKEN: "{{ secret('TEMPORAL_AUTH_TOKEN') }}"
VISIBILITY_QUERY: "{{ inputs.visibility_query }}"
MAX_RETRY_THRESHOLD: "{{ inputs.max_activity_retry_threshold }}"
QUARANTINE_ACTION: "{{ inputs.quarantine_action }}"
MAX_EXECUTIONS_SCAN: "{{ inputs.max_executions_to_scan }}"
TEMPORAL_WEB_URL: "{{ inputs.temporal_web_url }}"
script: |
import json
import os
import sys
import urllib.request
import urllib.parse
import urllib.error
from datetime import datetime, timezone
api_url = os.environ.get("TEMPORAL_API_URL", "http://localhost:7233").rstrip("/")
namespace = os.environ.get("TEMPORAL_NAMESPACE", "default")
token = os.environ.get("TEMPORAL_AUTH_TOKEN", "").strip()
visibility_query = os.environ.get("VISIBILITY_QUERY", "ExecutionStatus = 'Running' OR ExecutionStatus = 'TimedOut' OR ExecutionStatus = 'Failed'")
max_retry_threshold = int(os.environ.get("MAX_RETRY_THRESHOLD", 10))
quarantine_action = os.environ.get("QUARANTINE_ACTION", "TERMINATE").upper()
max_scan = int(os.environ.get("MAX_EXECUTIONS_SCAN", 50))
temporal_web_url = os.environ.get("TEMPORAL_WEB_URL", "http://localhost:8233").rstrip("/")
def send_request(url, method="GET", body=None):
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": "Kestra-Temporal-DeadLetter-Guard/1.0"
}
if token:
headers["Authorization"] = f"Bearer {token}"
data = json.dumps(body).encode("utf-8") if body is not None else None
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=15) as resp:
content = resp.read().decode("utf-8")
return resp.status, json.loads(content) if content else {}
except urllib.error.HTTPError as he:
err_body = he.read().decode("utf-8") if he.fp else ""
try:
parsed = json.loads(err_body)
except Exception:
parsed = {"error": err_body}
return he.code, parsed
except Exception as e:
return 0, {"error": str(e)}
print(f"Starting Temporal Dead-Letter Guard audit on namespace '{namespace}'...")
print(f"Target API: {api_url} | Query: {visibility_query} | Retry Threshold: {max_retry_threshold}")
encoded_query = urllib.parse.quote(visibility_query)
primary_url = f"{api_url}/api/v1/namespaces/{namespace}/workflow-executions?query={encoded_query}&pageSize={max_scan}"
status_code, response_data = send_request(primary_url)
if status_code == 404:
fallback_url = f"{api_url}/namespaces/{namespace}/workflows?query={encoded_query}"
status_code, response_data = send_request(fallback_url)
executions = []
if status_code in (200, 201):
executions = response_data.get("executions", [])
else:
err_msg = response_data.get("message") or response_data.get("error", f"HTTP {status_code}")
print(f"Notice: Visibility query returned status {status_code}: {err_msg}")
scanned_count = len(executions)
quarantined_count = 0
stuck_retry_count = 0
timed_out_count = 0
failed_count = 0
dead_letter_records = []
for ex in executions:
exec_info = ex.get("execution", {})
wf_id = exec_info.get("workflowId") or ex.get("workflowId", "unknown")
run_id = exec_info.get("runId") or ex.get("runId", "unknown")
wf_type = ex.get("type", {}).get("name") or ex.get("workflowType", "unknown")
status_str = str(ex.get("status", "")).upper()
task_queue = ex.get("taskQueue") or ex.get("executionConfig", {}).get("taskQueue", {}).get("name", "unknown")
start_time = ex.get("startTime", "")
is_running = ("RUNNING" in status_str) or (status_str == "1")
is_timed_out = ("TIMED_OUT" in status_str) or (status_str == "5")
is_failed = ("FAILED" in status_str) or (status_str == "3")
encoded_wf_id = urllib.parse.quote(wf_id, safe="")
triage_url = f"{temporal_web_url}/namespaces/{namespace}/workflows/{encoded_wf_id}/{run_id}/history"
if is_running:
desc_url = f"{api_url}/api/v1/namespaces/{namespace}/workflows/{encoded_wf_id}/executions/{run_id}"
d_code, d_data = send_request(desc_url)
if d_code == 404:
desc_url = f"{api_url}/namespaces/{namespace}/workflows/{encoded_wf_id}/runs/{run_id}/info"
d_code, d_data = send_request(desc_url)
pending_activities = d_data.get("pendingActivities", [])
for act in pending_activities:
attempt = int(act.get("attempt", 1))
act_id = act.get("activityId", "unknown")
act_type = act.get("activityType", {}).get("name", "unknown")
last_failure = act.get("lastFailure", {})
failure_msg = last_failure.get("message", "Activity exceeded retry limit")
stack_trace = last_failure.get("stackTrace", "No stack trace provided")
worker_id = act.get("lastWorkerIdentity", "unknown")
if attempt >= max_retry_threshold:
stuck_retry_count += 1
action_taken = "OBSERVED"
if quarantine_action == "TERMINATE":
term_url = f"{api_url}/api/v1/namespaces/{namespace}/workflows/{encoded_wf_id}/terminate"
term_payload = {
"runId": run_id,
"reason": f"Quarantined by Kestra Dead-Letter Guard: Activity '{act_type}' exceeded max retry threshold ({attempt} attempts)."
}
t_code, _ = send_request(term_url, method="POST", body=term_payload)
if t_code == 404:
term_url = f"{api_url}/namespaces/{namespace}/workflows/{encoded_wf_id}/terminate"
t_code, _ = send_request(term_url, method="POST", body=term_payload)
action_taken = "TERMINATED" if t_code in (200, 201) else f"TERMINATE_FAILED_HTTP_{t_code}"
quarantined_count += 1
elif quarantine_action == "CANCEL":
cancel_url = f"{api_url}/api/v1/namespaces/{namespace}/workflows/{encoded_wf_id}/cancel"
cancel_payload = {
"runId": run_id,
"reason": f"Quarantined by Kestra Dead-Letter Guard: Activity '{act_type}' exceeded max retry threshold ({attempt} attempts)."
}
c_code, _ = send_request(cancel_url, method="POST", body=cancel_payload)
if c_code == 404:
cancel_url = f"{api_url}/namespaces/{namespace}/workflows/{encoded_wf_id}/cancel"
c_code, _ = send_request(cancel_url, method="POST", body=cancel_payload)
action_taken = "CANCELLED" if c_code in (200, 201) else f"CANCEL_FAILED_HTTP_{c_code}"
quarantined_count += 1
dead_letter_records.append({
"workflow_id": wf_id,
"run_id": run_id,
"workflow_type": wf_type,
"task_queue": task_queue,
"incident_type": "ACTIVITY_RETRY_EXHAUSTION",
"activity_id": act_id,
"activity_type": act_type,
"attempt_count": attempt,
"max_retry_threshold": max_retry_threshold,
"last_failure_message": failure_msg,
"stack_trace": stack_trace[:1500],
"last_worker_identity": worker_id,
"action_taken": action_taken,
"start_time": start_time,
"triage_url": triage_url,
"detected_at": datetime.now(timezone.utc).isoformat()
})
elif is_timed_out:
timed_out_count += 1
dead_letter_records.append({
"workflow_id": wf_id,
"run_id": run_id,
"workflow_type": wf_type,
"task_queue": task_queue,
"incident_type": "WORKFLOW_TIMED_OUT",
"activity_id": "N/A",
"activity_type": "N/A",
"attempt_count": 0,
"max_retry_threshold": max_retry_threshold,
"last_failure_message": "Workflow reached maximum execution timeout without completion",
"stack_trace": "WorkflowExecutionTimeout expired in Temporal Cluster",
"last_worker_identity": "TemporalServer",
"action_taken": "RECORDED_DEAD_LETTER",
"start_time": start_time,
"triage_url": triage_url,
"detected_at": datetime.now(timezone.utc).isoformat()
})
elif is_failed:
failed_count += 1
dead_letter_records.append({
"workflow_id": wf_id,
"run_id": run_id,
"workflow_type": wf_type,
"task_queue": task_queue,
"incident_type": "WORKFLOW_FAILED",
"activity_id": "N/A",
"activity_type": "N/A",
"attempt_count": 0,
"max_retry_threshold": max_retry_threshold,
"last_failure_message": "Workflow closed in FAILED state",
"stack_trace": "Workflow execution failed",
"last_worker_identity": "TemporalServer",
"action_taken": "RECORDED_DEAD_LETTER",
"start_time": start_time,
"triage_url": triage_url,
"detected_at": datetime.now(timezone.utc).isoformat()
})
has_dead_letters = len(dead_letter_records) > 0
overall_status = "DEAD_LETTER_INCIDENT_DETECTED" if has_dead_letters else "NOMINAL_HEALTHY"
diag_lines = []
for idx, dl in enumerate(dead_letter_records[:5], 1):
diag_lines.append(
f"[{idx}] {dl['incident_type']} | WF: {dl['workflow_id']} | Type: {dl['workflow_type']}\n"
f" Activity: {dl['activity_type']} (Attempts: {dl['attempt_count']}/{dl['max_retry_threshold']})\n"
f" Action: {dl['action_taken']} | Worker: {dl['last_worker_identity']}\n"
f" Error: {dl['last_failure_message'][:150]}\n"
f" Triage: {dl['triage_url']}"
)
diagnostic_summary = "\n\n".join(diag_lines) if diag_lines else "Zero dead-letter or retry exhaustion incidents detected."
manifest = {
"status": overall_status,
"has_dead_letters": has_dead_letters,
"namespace": namespace,
"scanned_count": scanned_count,
"dead_letter_count": len(dead_letter_records),
"quarantined_count": quarantined_count,
"stuck_retry_count": stuck_retry_count,
"timed_out_count": timed_out_count,
"failed_count": failed_count,
"quarantine_action_policy": quarantine_action,
"audit_timestamp": datetime.now(timezone.utc).isoformat(),
"records": dead_letter_records
}
print(f"Temporal Dead-Letter Audit completed. Status: {overall_status}")
print(f"Scanned: {scanned_count} | Dead-Letters: {len(dead_letter_records)} | Quarantined: {quarantined_count}")
output_payload = {
"outputs": {
"status": overall_status,
"has_dead_letters": has_dead_letters,
"scanned_count": scanned_count,
"dead_letter_count": len(dead_letter_records),
"quarantined_count": quarantined_count,
"stuck_retry_count": stuck_retry_count,
"timed_out_count": timed_out_count,
"failed_count": failed_count,
"diagnostic_summary": diagnostic_summary,
"dead_letter_summary": manifest
}
}
print("::" + json.dumps(output_payload) + "::")
- id: record_dead_letter_state_kv
type: io.kestra.plugin.core.kv.Set
description: Persists the structured dead-letter audit manifest and quarantined
execution inventory into Kestra namespace KV store.
key: "temporal_dlq_{{ inputs.temporal_namespace }}"
value: "{{ outputs.audit_and_quarantine_workflows.vars.dead_letter_summary |
toJson }}"
kvType: JSON
- id: evaluate_incident_notification
type: io.kestra.plugin.core.flow.If
description: Dispatches high-priority Slack incident alert when dead-lettered or
quarantined workflows are detected.
condition: "{{ inputs.alert_on_quarantine and
outputs.audit_and_quarantine_workflows.vars.has_dead_letters }}"
then:
- id: dispatch_slack_dead_letter_alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Dispatches rich diagnostic alert to Slack containing workflow ID,
run ID, failing activity type, retry attempts, and stack trace.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "{{ inputs.slack_channel }}",
"attachments": [
{
"color": "#E01E5A",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "🚨 CRITICAL: Temporal Activity Retry Exhaustion & DLQ Alert",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Namespace:* `{{ inputs.temporal_namespace }}`\n*Incident Summary:* Detected *{{ outputs.audit_and_quarantine_workflows.vars.dead_letter_count }}* workflow execution(s) in dead-letter state.\n• *Quarantined Stuck Retries:* `{{ outputs.audit_and_quarantine_workflows.vars.stuck_retry_count }}`\n• *Timed Out Executions:* `{{ outputs.audit_and_quarantine_workflows.vars.timed_out_count }}`\n• *Failed Executions:* `{{ outputs.audit_and_quarantine_workflows.vars.failed_count }}`\n• *Quarantine Action Applied:* `{{ inputs.quarantine_action }}`"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Dead-Letter Diagnostic Overview:*\n```\n{{ outputs.audit_and_quarantine_workflows.vars.diagnostic_summary }}\n```"
}
},
{
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": "Kestra Flow: `{{ flow.id }}` | Execution: `{{ execution.id }}` | KV Store: `temporal_dlq_{{ inputs.temporal_namespace }}`"
}
]
}
]
}
]
}
else:
- id: log_nominal_health
type: io.kestra.plugin.core.log.Log
description: Logs nominal status when zero workflow executions exceed activity
retry limits.
message: "Temporal namespace '{{ inputs.temporal_namespace }}' dead-letter guard
check PASSED. Scanned {{
outputs.audit_and_quarantine_workflows.vars.scanned_count }}
execution(s); 0 retry exhaustions or unhandled failures detected."
- id: gate_on_quarantine_policy
type: io.kestra.plugin.core.flow.If
description: Optionally halts execution with failure when dead-lettered
workflows require operator intervention.
condition: "{{ inputs.fail_on_quarantine and
outputs.audit_and_quarantine_workflows.vars.has_dead_letters }}"
then:
- id: halt_pipeline
type: io.kestra.plugin.core.execution.Fail
description: Fails execution to prevent downstream dependency cascading during
dead-letter backlog.
errorMessage: "Temporal dead-letter guard detected {{
outputs.audit_and_quarantine_workflows.vars.dead_letter_count }}
quarantined or failed workflow execution(s) in namespace '{{
inputs.temporal_namespace }}'."
errors:
- id: notify_system_error_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alerts on-call engineers if the Kestra flow fails due to network
outage or unexpected exceptions.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "{{ inputs.slack_channel }}",
"attachments": [
{
"color": "#FF0000",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "🔥 ERROR: Temporal Dead-Letter Guard Execution Failed",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "The watchdog flow encountered an unhandled error while inspecting Temporal namespace `{{ inputs.temporal_namespace }}`.\n*Kestra Flow:* `{{ flow.id }}`\n*Execution ID:* `{{ execution.id }}`\nPlease verify connectivity to `{{ inputs.temporal_api_url }}`."
}
}
]
}
]
}