id: nats-jetstream-redelivery-ack-guard
namespace: company.team
description: |
Inspect one durable JetStream consumer without fetching or acknowledging its messages.
Alert once when redeliveries, unacknowledged work, or backlog crosses a threshold.
An operator may approve a bounded five-minute delivery pause after a fresh recheck.
concurrency: { limit: 1, behavior: QUEUE }
triggers:
- id: incident_webhook
type: io.kestra.plugin.core.trigger.Webhook
key: nats-jetstream-guard-change-me
description: "POST
/api/v1/main/executions/webhook/company.team/nats-jetstream-redelivery-ac\
k-guard/nats-jetstream-guard-change-me after a JetStream consumer advisory
or on-call request. Replace the key before enabling."
- id: periodic_sweep
type: io.kestra.plugin.core.trigger.Schedule
cron: "*/5 * * * *"
disabled: true
description: Enable after setting the inputs and secrets; the sweep checks the
durable consumer every five minutes.
inputs:
- id: nats_url
type: STRING
defaults: nats://nats:4222
description: NATS server address reachable from the Kestra worker; change the
host for your cluster.
- id: stream
type: STRING
defaults: ORDERS
description: Exact JetStream stream name to inspect; the guard refuses names
that could change the API subject.
- id: consumer
type: STRING
defaults: workers
description: Exact durable consumer name to inspect; the guard never creates or
resets this consumer.
- id: redelivery_threshold
type: INT
defaults: 1
description: Alert when the current count of redelivered messages reaches this
value; tune to your workload.
- id: ack_pending_threshold
type: INT
defaults: 10
description: Alert when at least this many deliveries still await explicit
acknowledgment.
- id: backlog_threshold
type: INT
defaults: 100
description: Alert when at least this many stream messages await delivery to
this consumer.
- id: offer_pause
type: BOOL
defaults: true
description: Offer a human-approved five-minute delivery pause on a newly
degraded state; turn off for read-only monitoring.
tasks:
- id: validate_scope
type: io.kestra.plugin.core.flow.If
description: Reject unsafe subject tokens and zero thresholds before contacting NATS.
condition: >-
{{ (inputs.stream | toJson | jq('test("^[A-Za-z0-9_-]{1,64}$")') | first)
and (inputs.consumer | toJson | jq('test("^[A-Za-z0-9_-]{1,64}$")') | first)
and (inputs.nats_url | toJson | jq('test("^nats://[A-Za-z0-9.-]+:[0-9]{1,5}$")') | first)
and inputs.redelivery_threshold > 0
and inputs.ack_pending_threshold > 0
and inputs.backlog_threshold > 0 }}
then:
- id: scope_valid
type: io.kestra.plugin.core.log.Log
message: "Validated consumer scope and positive thresholds."
else:
- id: reject_scope
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Invalid JetStream guard scope: use nats://host:port without
embedded credentials, 1-64 safe characters for stream/consumer, and
positive thresholds."
- id: inspect_consumer
type: io.kestra.plugin.nats.core.Request
description: Read the native JetStream consumer-info API; this never pulls or
ACKs messages.
url: "{{ inputs.nats_url }}"
subject: "$JS.API.CONSUMER.INFO.{{ inputs.stream }}.{{ inputs.consumer }}"
from:
data: "{}"
requestTimeout: PT5S
retry: { type: exponential, interval: PT2S, maxInterval: PT30S, maxAttempts: 3 }
- id: check_info_reply
type: io.kestra.plugin.core.flow.If
description: JetStream errors arrive as JSON inside successful NATS replies, so
reject them explicitly.
condition: >-
{{ (outputs.inspect_consumer.response ?? '') != ''
and (fromJson(outputs.inspect_consumer.response).error ?? '') == ''
and (fromJson(outputs.inspect_consumer.response).stream_name ?? '') == inputs.stream
and (fromJson(outputs.inspect_consumer.response).name ?? '') == inputs.consumer }}
then:
- id: info_valid
type: io.kestra.plugin.core.log.Log
message: "JetStream consumer-info reply matches the requested durable."
else:
- id: reject_info_reply
type: io.kestra.plugin.core.execution.Fail
errorMessage: "JetStream consumer-info reply was empty, an API error, or named a
different consumer. Check the stream, durable name, and NATS
permissions."
- id: snapshot
type: io.kestra.plugin.core.output.OutputValues
description: Expose the native counters so the alert and downstream flows use
the same observed snapshot.
values:
stream: "{{ fromJson(outputs.inspect_consumer.response).stream_name }}"
consumer: "{{ fromJson(outputs.inspect_consumer.response).name }}"
ack_pending: "{{ fromJson(outputs.inspect_consumer.response).num_ack_pending ?? 0 }}"
redelivered: "{{ fromJson(outputs.inspect_consumer.response).num_redelivered ?? 0 }}"
backlog: "{{ fromJson(outputs.inspect_consumer.response).num_pending ?? 0 }}"
max_ack_pending: "{{
fromJson(outputs.inspect_consumer.response).config.max_ack_pending ?? 0
}}"
delivered_sequence: "{{
fromJson(outputs.inspect_consumer.response).delivered.consumer_seq ?? 0
}}"
ack_floor_sequence: "{{
fromJson(outputs.inspect_consumer.response).ack_floor.consumer_seq ?? 0
}}"
paused: "{{ fromJson(outputs.inspect_consumer.response).paused ?? false }}"
- id: classify
type: io.kestra.plugin.core.output.OutputValues
description: Redelivery, in-flight ACK pressure, backlog, and hard max-ACK
saturation each indicate a degraded durable consumer.
values:
status: >-
{{ (outputs.snapshot.values.redelivered | number) >=
inputs.redelivery_threshold
or (outputs.snapshot.values.ack_pending | number) >= inputs.ack_pending_threshold
or (outputs.snapshot.values.backlog | number) >= inputs.backlog_threshold
or ((outputs.snapshot.values.max_ack_pending | number) > 0
and (outputs.snapshot.values.ack_pending | number) >= (outputs.snapshot.values.max_ack_pending | number))
? 'DEGRADED' : 'HEALTHY' }}
- id: previous_state
type: io.kestra.plugin.core.output.OutputValues
description: Capture the old state before the transition marker is updated.
values:
status: "{{ kv('NATS_GUARD_' ~ inputs.stream ~ '_' ~ inputs.consumer,
errorOnMissing=false) ?? 'UNKNOWN' }}"
- id: change_only
type: io.kestra.plugin.core.flow.If
description: Compare with a per-consumer KV marker so repeated sweeps do not
page on unchanged pressure.
condition: "{{ outputs.classify.values.status !=
outputs.previous_state.values.status }}"
then:
- id: alert_incident
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.classify.values.status == 'DEGRADED' }}"
then:
- id: notify_degraded
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: >-
JetStream {{ inputs.stream }}/{{ inputs.consumer }} DEGRADED: {{
outputs.snapshot.values.redelivered }} redelivered, {{
outputs.snapshot.values.ack_pending }} awaiting ACK (limit {{
outputs.snapshot.values.max_ack_pending }}), {{
outputs.snapshot.values.backlog }} awaiting delivery. Inspect the
worker and its ACK/error logs; do not ACK unprocessed messages.
Review Kestra execution {{ execution.id }} for the current state
and any pause approval.
retry: { type: exponential, interval: PT2S, maxInterval: PT30S, maxAttempts: 3 }
- id: alert_recovery
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.classify.values.status == 'HEALTHY' and
outputs.previous_state.values.status == 'DEGRADED' }}"
then:
- id: notify_recovered
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: "JetStream {{ inputs.stream }}/{{ inputs.consumer }} recovered:
redelivered={{ outputs.snapshot.values.redelivered }}, awaiting
ACK={{ outputs.snapshot.values.ack_pending }}, backlog={{
outputs.snapshot.values.backlog }}. Check that normal processing
has resumed. Execution {{ execution.id }}."
retry: { type: exponential, interval: PT2S, maxInterval: PT30S, maxAttempts: 3 }
- id: remember_state
type: io.kestra.plugin.core.kv.Set
key: "NATS_GUARD_{{ inputs.stream }}_{{ inputs.consumer }}"
value: "{{ outputs.classify.values.status }}"
kvType: STRING
- id: propose_bounded_pause
type: io.kestra.plugin.core.flow.If
description: Ask only when an incident is new; the default is to take no action.
condition: >-
{{ inputs.offer_pause and outputs.classify.values.status == 'DEGRADED'
and outputs.previous_state.values.status != 'DEGRADED' }}
then:
- id: approve_pause
type: io.kestra.plugin.core.flow.Pause
description: Pausing stops new deliveries for at most five minutes but leaves
ACKs and stored messages intact.
pauseDuration: PT15M
behavior: WARN
onResume:
- id: action
type: SELECT
values: [ REPORT_ONLY, PAUSE_5_MIN ]
defaults: REPORT_ONLY
description: Choose PAUSE_5_MIN only after checking the worker; this does not
ACK or delete messages.
- id: act_on_approval
type: io.kestra.plugin.core.flow.If
condition: "{{ (outputs.approve_pause.onResume.action ?? 'REPORT_ONLY') ==
'PAUSE_5_MIN' }}"
then:
- id: recheck_consumer
type: io.kestra.plugin.nats.core.Request
description: Re-read the same durable after the approval; refuse a stale
decision if pressure cleared or another pause began.
url: "{{ inputs.nats_url }}"
subject: "$JS.API.CONSUMER.INFO.{{ inputs.stream }}.{{ inputs.consumer }}"
from:
data: "{}"
requestTimeout: PT5S
retry: { type: exponential, interval: PT2S, maxInterval: PT30S, maxAttempts: 3 }
- id: recheck_before_pause
type: io.kestra.plugin.core.flow.If
description: A bad or changed API response is not permission to mutate the
consumer.
condition: >-
{{ (outputs.recheck_consumer.response ?? '') != ''
and (fromJson(outputs.recheck_consumer.response).error ?? '') == ''
and (fromJson(outputs.recheck_consumer.response).stream_name ?? '') == inputs.stream
and (fromJson(outputs.recheck_consumer.response).name ?? '') == inputs.consumer
and not (fromJson(outputs.recheck_consumer.response).paused ?? false)
and ((fromJson(outputs.recheck_consumer.response).num_redelivered ?? 0) >= inputs.redelivery_threshold
or (fromJson(outputs.recheck_consumer.response).num_ack_pending ?? 0) >= inputs.ack_pending_threshold
or (fromJson(outputs.recheck_consumer.response).num_pending ?? 0) >= inputs.backlog_threshold) }}
then:
- id: pause_deliveries
type: io.kestra.plugin.nats.core.Request
description: NATS itself auto-resumes at the timestamp; no ACK, reset, purge, or
consumer deletion occurs.
url: "{{ inputs.nats_url }}"
subject: "$JS.API.CONSUMER.PAUSE.{{ inputs.stream }}.{{ inputs.consumer }}"
from:
data: >-
{"pause_until":"{{ now() | dateAdd(5, 'MINUTES') }}"}
requestTimeout: PT5S
retry: { type: exponential, interval: PT2S, maxInterval: PT30S, maxAttempts: 3 }
- id: verify_pause_reply
type: io.kestra.plugin.core.flow.If
condition: >-
{{ (outputs.pause_deliveries.response ?? '') != ''
and (fromJson(outputs.pause_deliveries.response).error ?? '') == ''
and (fromJson(outputs.pause_deliveries.response).paused ?? false) }}
then:
- id: pause_confirmed
type: io.kestra.plugin.core.log.Log
message: "NATS confirmed a bounded delivery pause."
else:
- id: fail_pause_reply
type: io.kestra.plugin.core.execution.Fail
errorMessage: "JetStream did not confirm the bounded pause. Inspect consumer
info before attempting another action."
- id: notify_paused
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: "JetStream {{ inputs.stream }}/{{ inputs.consumer }} deliveries
paused until {{
fromJson(outputs.pause_deliveries.response).pause_until }}
after approval in {{ execution.id }}. ACKs still work. Repair
the worker now; NATS auto-resumes."
retry: { type: exponential, interval: PT2S, maxInterval: PT30S, maxAttempts: 3 }
else:
- id: log_stale_approval
type: io.kestra.plugin.core.log.Log
message: "Pause approval skipped for {{ inputs.stream }}/{{ inputs.consumer }}:
pressure cleared, another pause exists, or consumer info
changed/failed. No consumer mutation was requested."
errors:
- id: alert_guard_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: >-
JetStream guard FAILED for {{ inputs.stream }}/{{ inputs.consumer }} in
Kestra {{ execution.id }}. The consumer was not acknowledged, reset, or
deleted. Inspect the failed task and NATS API permissions; check consumer
info directly before taking manual action. Failed task {{ (errorLogs() |
first).taskId ?? 'unknown' }}. Possible causes: invalid scope, NATS
connection/permission or API reply failure, or Slack delivery failure.
Inspect the task log for the exact cause.
outputs:
- id: status
type: STRING
value: "{{ outputs.classify.values.status ?? 'UNKNOWN' }}"
- id: counters
type: JSON
value: >-
{{ (outputs.snapshot.values ?? {}) | toJson }}