Kestra flow hardening
Audit one or more existing Kestra flows and add production-hardening controls — retries, timeouts, concurrency limits, error/finally/afterExecution handlers, SLAs, checks, and idempotency guards. Produces a severity-ranked findings report, then applies confirmed edits. Use when users ask to harden, audit, review, or make a flow more production-ready, resilient, or idempotent — not for authoring new flows (use kestra-flow).
By- name:
- kestra-flow-hardening
- description:
- Audit one or more existing Kestra flows and add production-hardening controls — retries, timeouts, concurrency limits, error/finally/afterExecution handlers, SLAs, checks, and idempotency guards. Produces a severity-ranked findings report, then applies confirmed edits. Use when users ask to harden, audit, review, or make a flow more production-ready, resilient, or idempotent — not for authoring new flows (use kestra-flow).
Kestra Flow Hardening Skill
Audit existing Kestra flows, surface resilience / idempotency / guardrail gaps as a severity-ranked report, then apply the edits the user confirms.
This is the auditing counterpart to the sibling skills:
| Skill | Owns |
|---|---|
kestra-flow |
Authoring — create / modify / debug flow YAML from intent |
kestra-flow-hardening |
Auditing — find gaps, recommend + apply guardrails |
kestra-ops |
Operating — validate / deploy / run via kestractl |
Hand off to kestra-flow for "build a new flow" and to kestra-ops for "validate / deploy this".
When to use
Trigger on requests to harden, audit, review, or make production-ready / resilient / idempotent:
- "Harden this flow / these flows for production."
- "Audit my flow — what's missing for reliability?"
- "Add retries, timeouts, and error handling to this flow."
- "Review this namespace's flows for resilience gaps."
Do not use this skill to author a brand-new flow from a description — that is kestra-flow.
Required inputs
- One or more flows, in priority order:
- Inline YAML pasted into the chat
- File path(s), glob, or directory (e.g.
./flows/,./flows/*.yml) - Live instance — flows fetched via
kestra-ops/kestractl(the user pairs the skills; this skill does not require a running instance) - A namespace / directory batch
- Kestra version and edition (OSS / EE). Ask once if unknown; default to latest OSS. Used to gate version-/edition-specific recommendations.
Workflow
Step 1 — Fetch the flow schema (authoritative)
curl -s https://api.kestra.io/v1/plugins/schemas/flow
Read the raw JSON. The schema is the source of truth for which properties and types
exist in the target version. Never recommend a property absent from the schema — this is
what catches version traps such as retry.maxAttempt (pre-0.24) vs retry.maxAttempts.
Step 2 — Confirm scope and context
- Resolve the input form (paste / file / glob / dir / namespace).
- Confirm version + edition (default latest OSS if not given).
- For a directory or namespace, gather all target flows before reporting.
Step 3 — Calibrate by flow signals (proportionality)
Hardening must be proportional to what the flow does and where it runs. Read these signals and tailor the audit — do not apply a fixed checklist to every flow:
- Triggers / scheduling present → concurrency, SLA, and overlap behavior become relevant; a manually-run flow needs them far less.
- Real side-effects (writes, external calls, cloud jobs, scripts) → resilience and idempotency findings matter; a pure-compute or log-only flow does not need them.
- Namespace as env hint —
prod.*/staging.*raises the bar;dev.*/sandbox.*/tutorial.*gets a lighter touch ("this looks like dev — hardening deferred unless you're promoting it"). - Controls already present → acknowledge them; never re-flag what's already there.
Never invent risk. If a flow is genuinely sound, returning "No critical or high findings; this flow is reasonably hardened" is a correct, encouraged outcome. Do not manufacture Low-severity nits to look busy.
Step 4 — Run the audit taxonomy
Evaluate each relevant dimension. For exact, copy-pasteable YAML per construct and the
"when to apply / when NOT to" guidance, load
references/hardening-patterns.md.
Resilience
- Retries on transient-failure-prone tasks (HTTP, JDBC, cloud APIs) — see idempotency tiers below.
- Timeouts on every runnable task (scripts, queries, cloud jobs — hang and cost control).
- Flow-level
retrywhere whole-execution replay makes sense.
Failure handling
errors(global) for alerting; localerrorsinside flowable tasks for targeted cleanup.finallyfor resource teardown (containers, temp infra) — runs while execution is still RUNNING.afterExecutionfor final-state-based notifications (SUCCESS / FAILED / WARNING) viarunIf.allowFailure/allowWarningon genuinely non-critical tasks only.
Concurrency & idempotency
concurrencylimit +behavior(QUEUE / CANCEL / FAIL) for flows hitting shared / rate-limited systems.- Idempotency guard —
system.correlationId+ duplicate check (EE) or KV-based state guard (OSS). - Trigger
allowConcurrent/ Schedule overlap behavior.
Guardrails & contracts
checks(≥ 1.2) for pre-execution input validation.sla—MAX_DURATION/EXECUTION_ASSERTIONwith breach labels + alerting.- Input typing —
SELECT/ENUM/SECRETinstead of looseSTRING.
Hygiene
- Subflow extraction when a flow exceeds ~100 tasks or bloats the execution context.
store: true/storesfor large outputs instead of carrying data in the execution context.- Descriptions, labels, naming conventions.
- No hardcoded secrets / credentials (reuse
kestra-flow's rule — see Shared rules below).
Platform-fit & maintainability (advisory — not hardening, never a blocker) These are recommendations, not risks. They never carry a severity and never block; they surface in a separate Advisory section (see report format). Use them to nudge users toward better-maintained flows, not to gate anything.
- Long inline scripts → Namespace Files. A
Scripttask with a large inlinescript:/commands:block (roughly > 15–20 lines, or containing real program logic) is harder to read, test, and version. Recommend moving the code into a Namespace File and calling it from aCommandstask (namespaceFiles: {enabled: true, include: [...]}), or reading it viaread('path')in aScripttask. Kestra's own guidance:Commandsfor production workloads,Scriptfor quick iteration. - Scripts duplicating plugin functionality → native plugin. When a script reimplements
something a Kestra plugin already does, recommend the native task — less custom code to
maintain. Pattern-match common usage to plugin families and verify the task exists in the
fetched schema before naming it:
curl/wget/requests→io.kestra.plugin.core.http.Request/Downloadpsql/mysql/sqlite3→ the matching JDBC plugin (io.kestra.plugin.jdbc.*)aws/gcloud/azCLI → the cloud plugins (io.kestra.plugin.aws|gcp|azure.*)dbt→io.kestra.plugin.dbt.*;gitclone →io.kestra.plugin.git.Clone
- If Namespace Files are available in context, assess how much of the scripted logic could be replaced by native tasks and quantify it ("~X of N steps map to native plugin tasks").
Step 5 — Classify each finding by severity
| Severity | Definition | Example |
|---|---|---|
| Critical | Will cause data corruption, duplicate side-effects, or silent loss in production | Retry / allowFailure on a non-idempotent write; no concurrency limit on non-atomic state updates; hardcoded secret |
| High | Will cause outages / hangs / cost-blowouts or undetected failures | No timeout on a cloud / script task; no errors alerting; no SLA on a business-critical schedule |
| Medium | Degraded resilience / recoverability | Missing transient retries on HTTP / JDBC; no finally teardown leaking resources; loose input typing |
| Low | Hygiene / maintainability | Missing descriptions / labels; naming; large-output store unset |
Platform-fit recommendations (long scripts → Namespace Files; scripts → native plugins) are not assigned a severity. They are reported separately as Advisory and never block.
Step 6 — Apply the idempotency judgment (before recommending retries)
A retry is good advice for a flaky read and catastrophic for a non-idempotent write (double-charge, duplicate insert). Classify every candidate task before recommending:
| Tier | How detected | Retry recommendation |
|---|---|---|
| Safe | Read-only by type (HTTP GET, SELECT, fetch / list, Log) | Recommend retries freely |
| Conditionally safe | Write with a natural idempotency key, or transactional / upsert task | Recommend retries with the precondition stated |
| Unsafe / unknown | Opaque scripts, POST / PUT to unknown endpoints, non-transactional writes | Do NOT recommend a blind retry. Flag the idempotency question in the report with both branches: dedup guard (correlationId / KV) vs. retry-if-safe. Let the user decide at confirm-time. |
Step 7 — Emit the report
Format (findings numbered globally so the user can select by number):
## Hardening audit: <flow id> (<namespace>, v<X.Y>, OSS/EE)
### Critical
1. **<title>** — `tasks.<id>`
Risk: <what breaks in production if unfixed>
Caveat: <e.g. only safe if this endpoint dedupes on a key>
Proposed: <the edit, or both branches for unknown-safety tasks>
### High
2. ...
### Medium
### Low
### Advisory (platform-fit) — not hardening, optional
- **Long inline script** — `tasks.transform`
Move the ~40-line script into a Namespace File and call it from a `Commands` task
(versioned, testable, editable in the Code Editor).
- **Script duplicates a plugin** — `tasks.fetch`
This `curl` shell task can be `io.kestra.plugin.core.http.Request` (verified in schema).
---
Summary: N Critical · N High · N Medium · N Low · N Advisory
Reply with the numbers to apply (e.g. `1,4,7`), `all`, or `none`.
- Group by severity; each finding states risk + caveat + proposed fix + severity.
- Diffs are deferred to confirm-time — keep the report scannable.
- Mark structural edits (idempotency-guard insertion, flow-level retry behavior) clearly, since they add tasks rather than tweak one line.
- Batch: emit one consolidated report ranked by severity across all flows, with a per-flow summary table; then edit flow-by-flow on confirm.
- EE-only findings (e.g. correlationId guard): always label as EE, give the OSS fallback (KV guard), and frame the EE path as a value-add.
Step 8 — Apply confirmed edits
On apply 1,4,7 / all:
- Surgical, structure-preserving edits. Touch only the relevant tasks / blocks. Preserve root
id/namespace, task ordering, and comments. Never restructure unrelated parts. - File input → edit the file in place. Pasted YAML → return the modified YAML. Batch → edit each file.
- Re-validate every edit against the fetched schema (properties and types must exist).
- The initial number-selection is informed consent (the report already stated each risk / caveat) — do not re-prompt per finding, but show the diff as you apply it.
- Suggest
kestractl flow validate(viakestra-ops) as an optional final gate; do not require a live instance.
Shared rules (inherited from kestra-flow)
Do not restate — reuse the kestra-flow skill's rules so they don't drift:
- Schema compliance — only schema-defined task types and properties.
- No hardcoded secrets / credentials — use
inputsof typeSECRETor{{ secret('...') }}. - Quoting — prefer double quotes; single quotes inside when needed.
- Structural preservation — touch only the relevant part; preserve
id/namespace.
Example prompts
- "Harden this flow for production." (inline paste)
- "Audit
./flows/ingest.ymland add retries and timeouts where safe." - "Review all flows in
./flows/for resilience gaps and rank them worst-first." - "Make this scheduled flow idempotent — it sometimes runs twice." (idempotency tier judgment)
- "Add alerting and an SLA to this business-critical flow."
Open this reference as its own page
Hardening Patterns Reference
Canonical, copy-pasteable YAML for each hardening construct, with when to apply and
when NOT to. Validate every property against the live schema
(curl -s https://api.kestra.io/v1/plugins/schemas/flow) before recommending — versions
differ, and a property absent from the schema must not be used.
Version / edition gates (verify against the fetched schema):
concurrency ≥ 0.13 · sla ≥ 0.20 · finally ≥ 0.21 · afterExecution ≥ 0.22 ·
checks ≥ 1.2 · retry.maxAttempts (was maxAttempt before 0.24) ·
system.correlationId idempotency via the executions search API is Enterprise-only.
Retries (task-level)
Apply to Safe / Conditionally-safe tasks prone to transient failure (HTTP, JDBC, cloud APIs). Never apply a blind retry to an Unsafe/unknown write — use an idempotency guard instead.
- id: fetch_api
type: io.kestra.plugin.core.http.Request
uri: https://api.example.com/data
timeout: PT30S # bound a single attempt
retry:
type: exponential # constant | exponential | random
maxAttempts: 5
interval: PT10S # base interval
maxInterval: PT5M # exponential only
maxDuration: PT30M # total budget across all attempts + delays
warningOnRetry: true # mark execution WARNING if any retry happened
constant— fixedinterval.exponential—interval×delayFactor(default 2), capped atmaxInterval.random— betweenminIntervalandmaxInterval.timeoutbounds one attempt;retry.maxDurationbounds the whole task (all attempts + delays). Keepinterval<maxDurationor retries never run.
Retries (flow-level)
Apply when whole-execution replay is the right recovery unit.
retry:
maxAttempts: 3
type: constant
interval: PT1S
behavior: CREATE_NEW_EXECUTION # or RETRY_FAILED_TASK
CREATE_NEW_EXECUTION— increments the execution attempt; also restarts subflows as new executions.RETRY_FAILED_TASK— re-runs only the failed task; same execution.
Timeout
Apply to every runnable task that calls out or runs code — especially scripts, queries,
and cloud jobs (hang prevention + cost control). There is no flow-level timeout — use an
SLA MAX_DURATION for that.
- id: costly_query
type: io.kestra.plugin.scripts.shell.Commands
commands: ["sleep 10"]
timeout: PT5S # ISO-8601; exceeded → attempt fails
Errors — global handler (alerting)
Apply when failures would otherwise go unnoticed. Runs sequentially when any task errors.
errors:
- id: alert_on_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK') }}"
messageText: "Failure: {{ flow.namespace }}.{{ flow.id }} exec {{ execution.id }}"
Errors — local handler (targeted cleanup)
Apply inside a flowable task to scope handling / cleanup to its children only.
tasks:
- id: stage
type: io.kestra.plugin.core.flow.Sequential
tasks:
- id: risky
type: io.kestra.plugin.core.execution.Fail
errors:
- id: cleanup_stage
type: io.kestra.plugin.core.log.Log
message: "Cleaning up after {{ task.id }}"
allowFailure / allowWarning
Apply only to genuinely non-critical tasks so downstream work continues.
- id: flaky_optional
type: io.kestra.plugin.core.execution.Fail
allowFailure: true # downstream continues; execution ends WARNING
# allowWarning: true # warnings don't fail the run; execution ends SUCCESS
finally — always-run cleanup
Apply for teardown that must happen regardless of outcome (stop containers, release infra). Runs while the execution is still RUNNING. Not for business logic.
finally:
- id: stop_container
type: io.kestra.plugin.docker.Stop
containerId: "{{ outputs.start.taskRunner.containerId }}"
afterExecution — final-state actions
Apply for notifications / reporting that branch on the terminal state. Errors here do
not change the final execution state (wrap in a Sequential with errors if you need a state change).
afterExecution:
- id: on_success
runIf: "{{ execution.state == 'SUCCESS' }}"
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK') }}"
messageText: "{{ flow.id }} succeeded"
- id: on_failure
runIf: "{{ execution.state == 'FAILED' }}"
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK') }}"
messageText: "{{ flow.id }} FAILED"
Choosing between the three end-of-flow constructs:
errors→ failure-specific handling; available locally inside flowable tasks.finally→ cleanup that must always run; fires while RUNNING.afterExecution→ branch on final SUCCESS / FAILED / WARNING after the run finishes.
Concurrency limit
Apply when a flow hits a shared / rate-limited downstream (DB, SaaS API, warehouse) or needs "only one at a time" semantics. Do not use it to throttle worker CPU/RAM.
concurrency:
limit: 2
behavior: QUEUE # QUEUE | CANCEL | FAIL
QUEUEholds excess executions (each holds a DB lock — beware large backlogs).- Caveat: when executions start from a trigger, the trigger locks until it finishes, so
behaviormay not apply — new trigger executions are simply skipped. Pair with triggerallowConcurrent.
Trigger overlap
Apply to schedules that can fire faster than the flow completes.
triggers:
- id: schedule
type: io.kestra.plugin.core.trigger.Schedule
cron: "*/5 * * * *"
allowConcurrent: false # skip a new run while the previous is still running
Idempotency guard — OSS (KV-based)
Apply when the same business event may arrive more than once and you must process it once. OSS-portable: persist a marker in the KV store and short-circuit duplicates.
tasks:
- id: check_seen
type: io.kestra.plugin.core.kv.Get
key: "processed_{{ inputs.idempotencyKey }}"
errorOnMissing: false
- id: guard
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.check_seen.value ?? '' != '' }}"
then:
- id: skip
type: io.kestra.plugin.core.log.Log
message: "Duplicate {{ inputs.idempotencyKey }} — skipping"
else:
- id: do_work
type: io.kestra.plugin.core.log.Log
message: "Processing {{ inputs.idempotencyKey }}"
- id: mark_seen
type: io.kestra.plugin.core.kv.Set
key: "processed_{{ inputs.idempotencyKey }}"
value: "{{ now() }}"
Idempotency guard — Enterprise (system.correlationId)
EE value-add: a built-in execution label that propagates to subflows. Set it at execution creation (API-triggered) or store the provider key as a custom label (webhook), then guard against an existing SUCCESS execution with the same key.
# webhook variant: provider key arrives in headers after the execution is created
variables:
idem_key: "{{ trigger.headers['Idempotency-Key'] | first }}"
tasks:
- id: set_key
type: io.kestra.plugin.core.execution.Labels
labels:
idempotency.key: "{{ vars.idem_key }}"
- id: check_existing
type: io.kestra.plugin.core.http.Request
uri: "http://localhost:8080/api/v1/{{ kv('KESTRA_TENANT') }}/executions/search?filters[labels][EQUALS][idempotency.key]={{ vars.idem_key }}&filters[state][IN]=SUCCESS&size=1"
headers:
Authorization: "Bearer {{ secret('KESTRA_API_TOKEN') }}"
- id: maybe_skip
type: io.kestra.plugin.core.flow.If
condition: "{{ not (outputs.check_existing.body contains '\"total\":0') }}"
then:
- id: skip
type: io.kestra.plugin.core.log.Log
message: "Duplicate {{ vars.idem_key }} — skipping"
else:
- id: process
type: io.kestra.plugin.core.log.Log
message: "Processing {{ vars.idem_key }}"
The duplicate check is not atomic. For strict once-only under concurrent load, enforce uniqueness at the source (broker dedup, DB unique constraint, API-gateway idempotency).
Checks — pre-execution input validation (≥ 1.2)
Apply to block / fail / warn on bad inputs before any task runs.
checks:
- message: "Prod runs only allowed 06:00–22:00 UTC"
condition: "{{ inputs.env != 'prod' or (inputs.run_date | date('HH') | number >= 6 and inputs.run_date | date('HH') | number < 22) }}"
style: ERROR
behavior: BLOCK_EXECUTION # BLOCK_EXECUTION | FAIL_EXECUTION | CREATE_EXECUTION
Most restrictive behavior wins: BLOCK_EXECUTION → FAIL_EXECUTION → CREATE_EXECUTION.
SLA (≥ 0.20)
Apply duration targets / assertions on business-critical flows, with breach labels for alerting.
sla:
- id: maxDuration
type: MAX_DURATION # or EXECUTION_ASSERTION
duration: PT8H
behavior: CANCEL # CANCEL | FAIL | NONE
labels:
sla: miss
reason: durationExceeded
Pair breach labels with a Flow trigger that alerts on FAILED / CANCELLED executions
labeled sla: miss.
Input typing
Tighten loose STRING inputs into constrained types — a cheap, high-value guardrail.
inputs:
- id: environment
type: SELECT # constrained set instead of free STRING
values: [dev, staging, prod]
defaults: dev
- id: api_token
type: SECRET # never a plain STRING for credentials
Hygiene
- Subflow extraction — flows over ~100 TaskRuns degrade; isolate heavy sections into a
Subflowtask (new execution = isolated context). - Large outputs — set
store: true/ usestoresso big data is written to internal storage and only a URI rides in the execution context (the context has a ~1 MB practical limit). Withstore: true, read{{ outputs.task.uri }}, not.value. - Descriptions / labels / naming — add
descriptionto flow and non-obvious tasks; addlabelsfor filtering / ownership; follow namespace naming conventions. - Secrets — never hardcode; use
{{ secret('NAME') }}orSECRET-typed inputs.
Platform-fit & maintainability (advisory)
These are recommendations, not hardening — never a severity, never a blocker. Report them in the separate Advisory section. They reduce the amount of custom code a user maintains.
Long inline script → Namespace File + Commands
When a Script task carries a large inline block, move the code to a Namespace File and call
it from a Commands task. The code becomes versioned (revision history), testable, editable in
the Code Editor, and reusable across flows. Pass values via env.
# BEFORE — long inline logic in the flow YAML
- id: transform
type: io.kestra.plugin.scripts.python.Script
beforeCommands: ["pip install pandas requests"]
script: |
import pandas as pd, requests, os
# ...40+ lines of real logic...
# AFTER — code lives in a Namespace File (e.g. scripts/transform.py)
- id: transform
type: io.kestra.plugin.scripts.python.Commands
namespaceFiles:
enabled: true
include:
- scripts/transform.py # only mount what this task needs
beforeCommands: ["pip install pandas requests"]
commands: ["python scripts/transform.py"]
env:
INPUT_URI: "{{ inputs.uri }}" # Commands receive values via env, not templating
namespaceFiles.enabled: truemounts files into the working directory (needed when a CLI command reads them from disk). Useincludeto mount only what's required.- For a
Scripttask that takes a string, you can instead inline the file content withscript: "{{ read('scripts/transform.py') }}"— no mounting needed.read()resolves files from the same namespace as the flow.
Script duplicating plugin functionality → native plugin
When a script reimplements something a plugin already does, recommend the native task — but verify the task exists in the fetched schema before naming it.
# BEFORE — shell task wrapping curl
- id: fetch
type: io.kestra.plugin.scripts.shell.Commands
commands:
- curl -s "https://api.example.com/data" -o out.json
# AFTER — native HTTP task (typed outputs, retries, no shell/JSON plumbing)
- id: fetch
type: io.kestra.plugin.core.http.Download
uri: https://api.example.com/data
Common mappings (confirm against the schema / plugin list):
| Scripted with | Prefer native plugin |
|---|---|
curl / wget / requests |
io.kestra.plugin.core.http.Request / Download |
psql / mysql / sqlite3 |
io.kestra.plugin.jdbc.* Query / Queries |
aws / gcloud / az CLI |
`io.kestra.plugin.aws |
dbt commands |
io.kestra.plugin.dbt.* |
git clone |
io.kestra.plugin.git.Clone |
If Namespace Files are available in context, read them and assess how much of the scripted logic maps to native tasks — quantify it ("~X of N steps map to native plugin tasks") so the user can judge the migration effort.
More in this playbook
Automation inventory
Use this skill when a company does not know everything that runs on its behalf, or must decide what to keep: "list all our automations", "what integrations do we have", "find shadow automations", "who owns this workflow", "the builder left, what breaks", "prepare for the audit", "consolidate our automation tools", "clean up old workflows". Produces a register of every automation with its owner, the identity and credentials it runs as, its blast radius and bus factor, and a keep, fix, merge or retire decision for each, approved by the owners before anything is changed.
SecurityMITMake credential requests
Use when an agent needs a Make connection or key, or approved authorization repair, for Endpoints or custom-app testing. Guides owner authorization in Make and hands back managed connection or key IDs, never raw secrets. No scenario required.
SecurityMITInstruction surface security
Hardens agent runtimes against persistent prompt injection or unauthorized changes to instructions and permissions. Use to audit what agents auto-load, design reviewed activation for project rules, skills, memory, or tool configuration, and test whether trust boundaries hold after reload, restart, or delegation.


