id: scylladb-tombstone-ratio-and-latency-guard
namespace: company.team
description: >-
Evaluate ScyllaDB tombstone-to-live-row scan ratio and query read latency from
Prometheus metrics, trip a circuit breaker on reporting pipelines if the ratio
exceeds 10:1, and trigger automated keyspace table compaction via REST API.
inputs:
- id: keyspace
type: STRING
defaults: "reporting"
displayName: Keyspace Name
description: ScyllaDB keyspace containing the wide table subjected to scheduled
analytical or reporting scans.
- id: table
type: STRING
defaults: "event_aggregates"
displayName: Table Name
description: Target column family or table to monitor for tombstone accumulation
and read latency degradation.
- id: max_tombstone_ratio
type: FLOAT
defaults: 10.0
displayName: Max Tombstone Scan Ratio
description: Circuit breaker threshold representing maximum allowed ratio of
scanned tombstones to live rows read (10:1 default).
- id: max_read_latency_ms
type: FLOAT
defaults: 50.0
displayName: Max Read Latency (ms)
description: Maximum allowable coordinator read latency in milliseconds before
tripping the safety breaker on degraded wide partition scans.
- id: auto_compact
type: BOOL
defaults: true
displayName: Auto Trigger Compaction
description: Automatically dispatch an API call to ScyllaDB REST proxy to
trigger table-level compaction when the circuit breaker trips.
- id: flush_memtables
type: BOOL
defaults: true
displayName: Flush Memtables Before Compaction
description: Whether to flush active memtables to SSTables before compaction to
ensure recent soft-deletes are merged and purged.
- id: dry_run
type: BOOL
defaults: false
displayName: Dry Run Mode
description: Execute telemetry evaluation and calculate tombstone ratio without
invoking compaction or failing the execution.
- id: fail_on_breach
type: BOOL
defaults: true
displayName: Fail Execution on Circuit Trip
description: Fail the workflow execution when the breaker trips, halting
downstream scheduled reporting pipelines.
triggers:
- id: periodic_safety_check
type: io.kestra.plugin.core.trigger.Schedule
cron: "*/15 * * * *"
disabled: true
description: Periodic 15-minute safety evaluation before heavy reporting queries
execute.
- id: on_demand_safety_gate
type: io.kestra.plugin.core.trigger.Webhook
key: "{{ secret('SCYLLADB_GUARD_WEBHOOK_KEY') }}"
description: On-demand webhook trigger for upstream analytical pipeline
orchestrators to verify table health before launching batch queries.
tasks:
- id: fetch_prometheus_metrics
type: io.kestra.plugin.core.http.Request
description: Fetch Prometheus metrics directly from the ScyllaDB metrics
endpoint or Prometheus monitoring server.
method: GET
uri: "{{ secret('SCYLLADB_METRICS_URL') }}"
headers:
Accept: "text/plain, application/json;q=0.9"
Authorization: "Bearer {{ secret('SCYLLADB_METRICS_TOKEN') }}"
timeout: PT30S
retry:
type: exponential
maxAttempts: 3
interval: PT2S
maxInterval: PT10S
- id: evaluate_tombstone_ratio
type: io.kestra.plugin.scripts.python.Script
description: Parse ScyllaDB Prometheus metrics, calculate tombstone-to-live-cell
scan ratio and read latency, and evaluate circuit breaker thresholds.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
inputFiles:
metrics.raw: "{{ outputs.fetch_prometheus_metrics.body }}"
env:
KEYSPACE: "{{ inputs.keyspace }}"
TABLE: "{{ inputs.table }}"
MAX_TOMBSTONE_RATIO: "{{ inputs.max_tombstone_ratio }}"
MAX_READ_LATENCY_MS: "{{ inputs.max_read_latency_ms }}"
outputFiles:
- tombstone-latency-report.json
script: |
import json
import os
import re
from pathlib import Path
metrics_file = Path("metrics.raw")
raw_content = metrics_file.read_text(encoding="utf-8") if metrics_file.exists() else ""
target_ks = os.environ.get("KEYSPACE", "").strip()
target_table = os.environ.get("TABLE", "").strip()
max_ratio = float(os.environ.get("MAX_TOMBSTONE_RATIO", "10.0"))
max_latency = float(os.environ.get("MAX_READ_LATENCY_MS", "50.0"))
tombstones = 0.0
rows_read = 0.0
latency_sum = 0.0
latency_count = 0.0
direct_latency_ms = 0.0
parsed_mode = "unknown"
try:
data = json.loads(raw_content)
if isinstance(data, dict):
if "tombstones_scanned" in data or "scylla_query_tombstones_scanned_total" in data:
parsed_mode = "rest_proxy_json"
tombstones = float(data.get("tombstones_scanned") or data.get("scylla_query_tombstones_scanned_total", 0.0))
rows_read = float(data.get("rows_read") or data.get("scylla_query_rows_read_total", 0.0))
direct_latency_ms = float(data.get("read_latency_ms") or data.get("latency_ms", 0.0))
elif data.get("status") == "success" and "data" in data:
parsed_mode = "prometheus_api_json"
for item in data["data"].get("result", []):
metric = item.get("metric", {})
name = metric.get("__name__", "")
val = float(item.get("value", [0, 0])[1])
ks = metric.get("ks") or metric.get("keyspace", "")
table = metric.get("table") or metric.get("cf", "")
if target_ks and ks and ks != target_ks:
continue
if target_table and table and table != target_table:
continue
if "tombstone" in name:
tombstones += val
elif "rows_read" in name or "rows" in name:
rows_read += val
elif "latency_sum" in name:
latency_sum += val
elif "latency_count" in name:
latency_count += val
elif "read_latency" in name or "reads_latency" in name:
direct_latency_ms = max(direct_latency_ms, val if val > 1.0 else val * 1000.0)
except Exception:
pass
if parsed_mode == "unknown" and raw_content:
parsed_mode = "prometheus_text"
for line in raw_content.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split()
if len(parts) < 2:
continue
metric_str, val_str = parts[0], parts[1]
try:
val = float(val_str)
except ValueError:
continue
label_match = re.match(r"^([a-zA-Z_:][a-zA-Z0-9_:]*)\s*(?:\{(.*)\})?$", metric_str)
if not label_match:
continue
name = label_match.group(1)
raw_labels = label_match.group(2) or ""
labels = dict(re.findall(r'([a-zA-Z0-9_]+)="([^"]*)"', raw_labels))
ks = labels.get("ks") or labels.get("keyspace", "")
table = labels.get("table") or labels.get("cf", "")
if target_ks and ks and ks != target_ks:
continue
if target_table and table and table != target_table:
continue
if "tombstone" in name:
tombstones += val
elif "rows_read" in name:
rows_read += val
elif "latency_sum" in name:
latency_sum += val
elif "latency_count" in name:
latency_count += val
elif "reads_latency" in name or "read_latency" in name:
direct_latency_ms = max(direct_latency_ms, val if val > 1.0 else val * 1000.0)
if latency_count > 0:
computed_latency_ms = (latency_sum / latency_count) * 1000.0
elif direct_latency_ms > 0:
computed_latency_ms = direct_latency_ms
else:
computed_latency_ms = 0.0
ratio = tombstones / max(rows_read, 1.0)
ratio_breached = bool(ratio > max_ratio)
latency_breached = bool(computed_latency_ms > max_latency)
circuit_breaker_tripped = bool(ratio_breached or latency_breached)
report = {
"keyspace": target_ks,
"table": target_table,
"parser_format": parsed_mode,
"tombstones_scanned": round(tombstones, 2),
"rows_read": round(rows_read, 2),
"tombstone_ratio": round(ratio, 2),
"max_tombstone_ratio": round(max_ratio, 2),
"read_latency_ms": round(computed_latency_ms, 2),
"max_read_latency_ms": round(max_latency, 2),
"ratio_breached": ratio_breached,
"latency_breached": latency_breached,
"circuit_breaker_tripped": circuit_breaker_tripped,
"verdict": "TRIPPED" if circuit_breaker_tripped else "HEALTHY",
}
Path("tombstone-latency-report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
print(f"Metrics evaluated [{parsed_mode}]: tombstones={tombstones}, rows={rows_read}, ratio={ratio:.2f}:1 (threshold: {max_ratio}:1), latency={computed_latency_ms:.2f}ms (threshold: {max_latency}ms) -> verdict={report['verdict']}")
print("::" + json.dumps({
"outputs": {
"tombstones_scanned": round(tombstones, 2),
"rows_read": round(rows_read, 2),
"tombstone_ratio": round(ratio, 2),
"read_latency_ms": round(computed_latency_ms, 2),
"ratio_breached": ratio_breached,
"latency_breached": latency_breached,
"circuit_breaker_tripped": circuit_breaker_tripped,
"verdict": report["verdict"]
}
}) + "::")
- id: breaker_gate
type: io.kestra.plugin.core.flow.If
description: Branch execution based on whether the circuit breaker was tripped
by excessive tombstone ratios (>10:1) or read latency degradation.
condition: "{{ outputs.evaluate_tombstone_ratio.vars.circuit_breaker_tripped }}"
then:
- id: log_breaker_tripped
type: io.kestra.plugin.core.log.Log
description: Log detailed circuit breaker warning with measured tombstone scan
ratio and read latency.
level: WARN
message: >-
CIRCUIT BREAKER TRIPPED for {{ inputs.keyspace }}.{{ inputs.table }}:
Tombstone-to-live-cell ratio is {{
outputs.evaluate_tombstone_ratio.vars.tombstone_ratio }}:1 (threshold:
{{ inputs.max_tombstone_ratio }}:1, tombstones_scanned={{
outputs.evaluate_tombstone_ratio.vars.tombstones_scanned }},
rows_read={{ outputs.evaluate_tombstone_ratio.vars.rows_read }}). Read
latency is {{ outputs.evaluate_tombstone_ratio.vars.read_latency_ms }}
ms (threshold: {{ inputs.max_read_latency_ms }} ms). Wide table
partition scanning across soft-deleted rows is severely degrading
query latency.
- id: compaction_gate
type: io.kestra.plugin.core.flow.If
description: Check if automatic table compaction is enabled and not running in
dry-run mode.
condition: "{{ inputs.auto_compact and not inputs.dry_run }}"
then:
- id: trigger_table_compaction
type: io.kestra.plugin.core.http.Request
description: Dispatch major compaction on the affected keyspace and table via
the ScyllaDB REST administration API.
method: POST
uri: "{{ secret('SCYLLADB_API_URL') }}/storage_service/keyspace_compaction/{{
inputs.keyspace }}?cf={{ inputs.table }}&flush_memtables={{
inputs.flush_memtables }}"
headers:
Authorization: "Bearer {{ secret('SCYLLADB_API_TOKEN') }}"
Content-Type: "application/json"
retry:
type: exponential
maxAttempts: 3
interval: PT5S
maxInterval: PT30S
- id: log_compaction_triggered
type: io.kestra.plugin.core.log.Log
description: Log confirmation that ScyllaDB compaction was successfully
triggered.
message: >-
Compaction request dispatched for {{ inputs.keyspace }}.{{
inputs.table }} via ScyllaDB REST API (status={{
outputs.trigger_table_compaction.status }}). SSTable compaction
will purge soft-deleted cells older than gc_grace_seconds.
- id: notify_slack_incident
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Send alert to Slack detailing the tripped circuit breaker and
initiated remediation.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{{ {
"text": ":warning: *ScyllaDB Tombstone Scan Ratio Circuit Breaker TRIPPED*\n" ~
"*Keyspace / Table*: `" ~ inputs.keyspace ~ "." ~ inputs.table ~ "`\n" ~
"*Tombstone Ratio*: `" ~ outputs.evaluate_tombstone_ratio.vars.tombstone_ratio ~ ":1` (Max Allowed: `" ~ inputs.max_tombstone_ratio ~ ":1`)\n" ~
"*Tombstones Scanned*: `" ~ outputs.evaluate_tombstone_ratio.vars.tombstones_scanned ~ "` | *Live Rows Read*: `" ~ outputs.evaluate_tombstone_ratio.vars.rows_read ~ "`\n" ~
"*Read Latency*: `" ~ outputs.evaluate_tombstone_ratio.vars.read_latency_ms ~ " ms` (Threshold: `" ~ inputs.max_read_latency_ms ~ " ms`)\n" ~
"*Compaction Action*: " ~ (inputs.auto_compact and not inputs.dry_run ? "Triggered via REST API" : "Skipped (dry_run=" ~ inputs.dry_run ~ ", auto_compact=" ~ inputs.auto_compact ~ ")") ~ "\n" ~
"*Status*: Downstream scheduled analytical queries halted to protect cluster read capacity."
} | toJson }}
- id: enforce_breaker_halt
type: io.kestra.plugin.core.flow.If
description: Fail the workflow execution to halt downstream scheduled reporting
jobs when fail_on_breach is enabled.
condition: "{{ inputs.fail_on_breach and not inputs.dry_run }}"
then:
- id: trip_circuit_breaker
type: io.kestra.plugin.core.execution.Fail
description: Trip circuit breaker to halt scheduled reporting queries and
prevent cluster read saturation.
errorMessage: >-
Safety gate tripped: ScyllaDB table '{{ inputs.keyspace }}.{{
inputs.table }}' has tombstone-to-live ratio {{
outputs.evaluate_tombstone_ratio.vars.tombstone_ratio }}:1
exceeding safety limit {{ inputs.max_tombstone_ratio }}:1 (read
latency: {{ outputs.evaluate_tombstone_ratio.vars.read_latency_ms
}}ms vs threshold {{ inputs.max_read_latency_ms }}ms). Downstream
reporting queries halted. Compaction initiated.
else:
- id: log_healthy_gate
type: io.kestra.plugin.core.log.Log
description: Log nominal partition scan metrics when tombstone ratio and read
latencies are healthy.
message: >-
ScyllaDB safety gate PASSED for {{ inputs.keyspace }}.{{ inputs.table
}}. Tombstone scan ratio is {{
outputs.evaluate_tombstone_ratio.vars.tombstone_ratio }}:1 (<= {{
inputs.max_tombstone_ratio }}:1), read latency is {{
outputs.evaluate_tombstone_ratio.vars.read_latency_ms }} ms (<= {{
inputs.max_read_latency_ms }} ms). Downstream scheduled analytical
queries may safely proceed.