id: kafka-kraft-metadata-quorum-health-sentinel
namespace: company.platform
description: Inspect the Apache Kafka KRaft metadata quorum, detect missing
voters, follower lag and repeated leader changes, and alert before controller
faults become a cluster-wide control-plane outage.
inputs:
- id: bootstrap_servers
type: STRING
defaults: "kafka:9092"
description: Comma-separated Kafka broker addresses reachable from the Docker
task runner.
- id: client_properties
type: SECRET
defaults: ""
description: Optional Kafka client.properties content for SASL or TLS. Keep
empty for plaintext clusters; use a secret expression for scheduled
production runs.
- id: expected_voter_ids
type: ARRAY
itemType: INT
defaults: []
description: Controller IDs that must be present in CurrentVoters. Leave empty
to accept the quorum's configured voter set.
- id: minimum_voter_count
type: INT
defaults: 3
min: 1
description: Minimum acceptable number of configured KRaft voters.
- id: max_follower_lag_records
type: INT
defaults: 1000
min: 0
description: Maximum acceptable MaxFollowerLag reported by the metadata quorum.
- id: max_follower_lag_time_ms
type: INT
defaults: 30000
min: 0
description: Maximum acceptable MaxFollowerLagTimeMs before a follower is
considered stale.
- id: leader_change_run_threshold
type: INT
defaults: 3
min: 1
description: Alert after the sampled leader differs for this many consecutive
scheduled runs. Set to 1 to report every observed leader change.
- id: kafka_tools_image
type: STRING
defaults: apache/kafka:4.1.0
description: Kafka image that supplies kafka-metadata-quorum.sh. Match this to
the cluster version if client compatibility requires it.
- id: docker_network_mode
type: STRING
defaults: bridge
description: Docker network used by the Kafka inspection container. Set it to
the network that can resolve the configured broker addresses.
triggers:
- id: every_five_minutes
type: io.kestra.plugin.core.trigger.Schedule
cron: "*/5 * * * *"
disabled: true
description: Disabled until connectivity, authentication and Slack delivery have
been verified with a manual execution.
tasks:
- id: inspect_quorum
type: io.kestra.plugin.scripts.shell.Commands
description: Run Kafka's read-only metadata quorum status and replication
inspections and retain the exact CLI responses as evidence.
containerImage: "{{ inputs.kafka_tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network_mode }}"
user: root
env:
BOOTSTRAP_SERVERS: "{{ inputs.bootstrap_servers }}"
CLIENT_PROPERTIES: "{{ inputs.client_properties }}"
outputFiles:
- status.txt
- replication.txt
commands:
- |
set -eu
KAFKA_BIN=/opt/kafka/bin
cd "$WORKING_DIR"
if [ -n "${CLIENT_PROPERTIES:-}" ]; then
printf '%s\n' "$CLIENT_PROPERTIES" > client.properties
chmod 600 client.properties
fi
run_quorum() {
if [ -s client.properties ]; then
"$KAFKA_BIN/kafka-metadata-quorum.sh" \
--bootstrap-server "$BOOTSTRAP_SERVERS" \
--command-config client.properties "$@"
else
"$KAFKA_BIN/kafka-metadata-quorum.sh" \
--bootstrap-server "$BOOTSTRAP_SERVERS" "$@"
fi
}
run_quorum describe --status > status.txt
run_quorum describe --replication > replication.txt
test -s status.txt
test -s replication.txt
- id: load_previous_observation
type: io.kestra.plugin.core.kv.Get
description: Load the prior leader observation so repeated leader changes can be
distinguished from one normal election.
key: kafka_kraft_quorum_observation
errorOnMissing: false
- id: assess_quorum
type: io.kestra.plugin.scripts.python.Script
description: Parse the real Kafka CLI output, apply voter and lag invariants,
and compare the leader with the previous scheduled observation.
containerImage: python:3.12-slim
inputFiles:
status.txt: "{{ outputs.inspect_quorum.outputFiles['status.txt'] }}"
replication.txt: "{{ outputs.inspect_quorum.outputFiles['replication.txt'] }}"
expected.json: "{{ inputs.expected_voter_ids | toJson }}"
previous.json: "{{ (outputs.load_previous_observation.value ?? {}) | toJson }}"
env:
MINIMUM_VOTER_COUNT: "{{ inputs.minimum_voter_count }}"
MAX_FOLLOWER_LAG_RECORDS: "{{ inputs.max_follower_lag_records }}"
MAX_FOLLOWER_LAG_TIME_MS: "{{ inputs.max_follower_lag_time_ms }}"
LEADER_CHANGE_RUN_THRESHOLD: "{{ inputs.leader_change_run_threshold }}"
script: |
import json
import os
import re
def load_json(path, fallback):
try:
with open(path, encoding="utf-8") as handle:
return json.load(handle)
except (FileNotFoundError, json.JSONDecodeError):
return fallback
def as_int(value, field):
match = re.search(r"-?\d+", str(value))
if not match:
raise ValueError(f"{field} is not an integer: {value!r}")
return int(match.group())
def parse_voters(value):
try:
return sorted({int(item.get("id", item) if isinstance(item, dict) else item) for item in json.loads(value)})
except (json.JSONDecodeError, TypeError, ValueError):
ids = re.findall(r"replicaId\s*=\s*(-?\d+)", value)
if not ids and re.fullmatch(r"\[\s*-?\d+(?:\s*,\s*-?\d+)*\s*\]", value):
ids = re.findall(r"-?\d+", value)
if not ids:
raise ValueError("CurrentVoters is not recognized JSON or a supported legacy voter list")
return sorted({int(item) for item in ids})
with open("status.txt", encoding="utf-8") as handle:
fields = dict(
(key.strip(), value.strip())
for line in handle
if ":" in line
for key, value in [line.split(":", 1)]
)
required = {
"ClusterId",
"LeaderId",
"LeaderEpoch",
"HighWatermark",
"MaxFollowerLag",
"MaxFollowerLagTimeMs",
"CurrentVoters",
}
missing_fields = sorted(required - fields.keys())
if missing_fields:
raise ValueError("Kafka status output is missing: " + ", ".join(missing_fields))
metrics = {name: as_int(fields[name], name) for name in required - {"ClusterId", "CurrentVoters"}}
current_voters = parse_voters(fields["CurrentVoters"])
expected_voters = sorted({int(item) for item in load_json("expected.json", [])})
previous = load_json("previous.json", {})
previous = previous if isinstance(previous, dict) else {}
rows = []
with open("replication.txt", encoding="utf-8") as handle:
for line in handle:
columns = re.split(r"\s+", line.strip())
if len(columns) < 7 or not columns[0].lstrip("-").isdigit():
continue
rows.append({"node_id": int(columns[0]), "lag": int(columns[3]), "role": columns[6]})
if not rows:
raise ValueError("Kafka replication output could not be parsed")
findings = []
def add(code, severity, message):
findings.append({"code": code, "severity": severity, "message": message})
leader_id = metrics["LeaderId"]
if leader_id < 0:
add("NO_LEADER", "CRITICAL", "The KRaft metadata quorum has no elected leader.")
elif leader_id not in current_voters:
add("LEADER_NOT_A_VOTER", "CRITICAL", f"Leader {leader_id} is absent from CurrentVoters {current_voters}.")
minimum_voters = int(os.environ["MINIMUM_VOTER_COUNT"])
if len(current_voters) < minimum_voters:
add("TOO_FEW_VOTERS", "CRITICAL", f"CurrentVoters contains {len(current_voters)} controller(s), below the required {minimum_voters}.")
missing_expected = sorted(set(expected_voters) - set(current_voters))
if missing_expected:
add("EXPECTED_VOTERS_MISSING", "CRITICAL", f"Expected controller IDs are missing: {missing_expected}.")
missing_rows = sorted(set(current_voters) - {row["node_id"] for row in rows})
if missing_rows:
add("VOTERS_WITHOUT_REPLICA_STATE", "CRITICAL", f"Configured voters have no replication-state row: {missing_rows}.")
leader_rows = [row["node_id"] for row in rows if row["role"].lower() == "leader"]
if leader_rows != [leader_id]:
add("LEADER_STATE_MISMATCH", "CRITICAL", f"Status LeaderId {leader_id} does not match exactly one Leader row in the replication view.")
lag_checks = [
("MaxFollowerLag", "MAX_FOLLOWER_LAG_RECORDS", "FOLLOWER_LAG", "records"),
("MaxFollowerLagTimeMs", "MAX_FOLLOWER_LAG_TIME_MS", "FOLLOWER_LAG_TIME", "ms"),
]
for field, env_name, code, unit in lag_checks:
limit = int(os.environ[env_name])
if metrics[field] > limit:
add(code, "WARNING", f"{field} is {metrics[field]} {unit}, above {limit} {unit}.")
prior_leader = previous.get("leader_id")
streak = int(previous.get("leader_change_streak", 0) or 0) + 1 if prior_leader is not None and prior_leader != leader_id else 0
if streak >= int(os.environ["LEADER_CHANGE_RUN_THRESHOLD"]):
add("REPEATED_LEADER_CHANGES", "WARNING", f"The sampled leader changed for {streak} consecutive runs; it is now controller {leader_id}.")
critical_count = sum(item["severity"] == "CRITICAL" for item in findings)
status = "CRITICAL" if critical_count else ("WARNING" if findings else "HEALTHY")
snapshot = {
"cluster_id": fields["ClusterId"],
"leader_id": leader_id,
"leader_epoch": metrics["LeaderEpoch"],
"high_watermark": metrics["HighWatermark"],
"current_voters": current_voters,
"max_follower_lag": metrics["MaxFollowerLag"],
"max_follower_lag_time_ms": metrics["MaxFollowerLagTimeMs"],
"leader_change_streak": streak,
"status": status,
"finding_codes": [item["code"] for item in findings],
}
summary = (
f"cluster={snapshot['cluster_id']} status={status} leader={leader_id} "
f"epoch={snapshot['leader_epoch']} voters={current_voters} "
f"maxLag={snapshot['max_follower_lag']} maxLagTimeMs={snapshot['max_follower_lag_time_ms']} "
f"findings={len(findings)}"
)
print("::" + json.dumps({"outputs": {
"status": status,
"finding_count": len(findings),
"critical_count": critical_count,
"findings": findings,
"summary": summary,
"snapshot": snapshot,
}}, separators=(",", ":")) + "::")
- id: route_result
type: io.kestra.plugin.core.flow.If
description: Page the platform team on actionable quorum findings; keep healthy
scheduled runs quiet but auditable.
condition: "{{ outputs.assess_quorum.vars.finding_count > 0 }}"
then:
- id: log_findings
type: io.kestra.plugin.core.log.Log
level: WARN
message: "KRaft quorum {{ outputs.assess_quorum.vars.summary }} details={{
outputs.assess_quorum.vars.findings | toJson }}"
- id: alert_platform_team
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Send one consolidated alert containing the quorum summary and every
classified finding.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: |
:rotating_light: *Kafka KRaft quorum {{ outputs.assess_quorum.vars.status }}*
`{{ outputs.assess_quorum.vars.summary }}`
{% for item in outputs.assess_quorum.vars.findings %}
• *{{ item.severity }} / {{ item.code }}*: {{ item.message }}
{% endfor %}
Execution: `{{ execution.id }}`
else:
- id: log_healthy
type: io.kestra.plugin.core.log.Log
message: "Kafka KRaft quorum is healthy: {{ outputs.assess_quorum.vars.summary
}}"
- id: remember_observation
type: io.kestra.plugin.core.kv.Set
description: Persist only the current quorum snapshot for leader-change
comparison during the next run.
key: kafka_kraft_quorum_observation
kvType: JSON
overwrite: true
value: "{{ outputs.assess_quorum.vars.snapshot | toJson }}"
errors:
- id: alert_inspection_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Treat an unreachable cluster, authentication error or unexpected
CLI response as unknown health rather than a clean run.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: ":warning: Kafka KRaft quorum inspection failed for `{{
inputs.bootstrap_servers }}` in execution `{{ execution.id }}`. Quorum
health is unknown; inspect the failed task and Kafka controller logs."
outputs:
- id: status
type: STRING
value: "{{ outputs.assess_quorum.vars.status }}"
- id: findings
type: JSON
value: "{{ outputs.assess_quorum.vars.findings }}"
- id: quorum_snapshot
type: JSON
value: "{{ outputs.assess_quorum.vars.snapshot }}"