id: grafana-loki-high-cardinality-stream-rate-sentinel
namespace: company.observability
description: |
Audits Grafana Loki distributor metrics and label streams to detect cardinality explosions,
distributor 429 rate limit errors, and stream exhaustion, recording incident manifests in Kestra KV
and alerting Slack with remediation instructions to adopt Grafana Loki 3.0 Structured Metadata.
inputs:
- id: loki_endpoint
type: STRING
displayName: Loki Base Endpoint
defaults: "http://localhost:3100"
description: Base HTTP URL of the Grafana Loki gateway or distributor service.
- id: loki_metrics_endpoint
type: STRING
displayName: Loki Metrics Endpoint
defaults: "http://localhost:3100/metrics"
description: Prometheus metrics HTTP endpoint exposed by the Grafana Loki
distributor or single-binary instance.
- id: tenant_id
type: STRING
displayName: Loki Tenant ID
defaults: "tenant-production"
description: Tenant identifier passed via the X-Scope-OrgID HTTP header for
multi-tenant Loki deployments.
- id: max_discarded_samples_threshold
type: INT
displayName: Max Discarded Samples Threshold
defaults: 50
description: Maximum allowable interval discarded log samples count before
flagging ingestion rate limit or stream limit breaches.
- id: max_active_streams_threshold
type: INT
displayName: Max Active Streams Threshold
defaults: 25000
description: Maximum allowable active stream count per tenant before alerting on
stream cardinality explosion.
- id: high_cardinality_keywords
type: STRING
displayName: High Cardinality Label Keywords
defaults: "user_id,trace_id,span_id,request_id,session_id,client_ip,device_id,o\
rder_id,uuid"
description: Comma-separated list of high-cardinality attribute names that cause
stream explosion if placed in stream labels.
- id: alert_on_limit_breach
type: BOOL
displayName: Alert On Limit Breach
defaults: true
description: Toggle whether Slack incident notifications are dispatched when
ingestion limits or label explosions occur.
triggers:
- id: sentinel_schedule
type: io.kestra.plugin.core.trigger.Schedule
cron: "*/5 * * * *"
disabled: true
description: Periodic surveillance schedule auditing Loki distributor telemetry
every 5 minutes. Shipped disabled for initial configuration.
tasks:
- id: scrape_loki_metrics
type: io.kestra.plugin.core.http.Request
description: Scrapes Loki Prometheus metrics endpoint capturing distributor
bytes, discarded samples by reason, and active streams.
uri: "{{ inputs.loki_metrics_endpoint }}"
method: GET
headers:
X-Scope-OrgID: "{{ inputs.tenant_id }}"
Accept: "text/plain; version=0.0.4"
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT30S
allowFailure: true
- id: query_loki_labels
type: io.kestra.plugin.core.http.Request
description: Queries Loki label discovery API to inspect currently indexed
stream label names for the tenant.
uri: "{{ inputs.loki_endpoint }}/loki/api/v1/labels"
method: GET
headers:
X-Scope-OrgID: "{{ inputs.tenant_id }}"
Accept: "application/json"
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT20S
allowFailure: true
- id: query_index_stats
type: io.kestra.plugin.core.http.Request
description: Queries Loki index statistics API to extract active stream counts
and chunk index volumes.
uri: "{{ inputs.loki_endpoint }}/loki/api/v1/index/stats"
method: GET
headers:
X-Scope-OrgID: "{{ inputs.tenant_id }}"
Accept: "application/json"
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT20S
allowFailure: true
- id: get_historical_sentinel_state
type: io.kestra.plugin.core.kv.Get
description: Retrieves previously recorded ingestion counters and stream state
from Kestra KV store to compute interval deltas.
key: "loki_stream_sentinel_{{ inputs.tenant_id }}"
errorOnMissing: false
- id: evaluate_cardinality_and_stream_rates
type: io.kestra.plugin.scripts.python.Script
description: Parses Prometheus metrics and label lists, computes interval
ingestion rates and discarded deltas, identifies offending tenant and
labels, and generates structured remediation advice.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
env:
METRICS_RAW_BODY: "{{ outputs.scrape_loki_metrics.body ?? '' }}"
LABELS_RAW_BODY: "{{ outputs.query_loki_labels.body ?? '' }}"
INDEX_STATS_RAW_BODY: "{{ outputs.query_index_stats.body ?? '' }}"
PREVIOUS_KV_JSON: "{{ outputs.get_historical_sentinel_state.value ?? '' }}"
TENANT_ID: "{{ inputs.tenant_id }}"
LOKI_ENDPOINT: "{{ inputs.loki_endpoint }}"
MAX_DISCARDED_SAMPLES_THRESHOLD: "{{ inputs.max_discarded_samples_threshold }}"
MAX_ACTIVE_STREAMS_THRESHOLD: "{{ inputs.max_active_streams_threshold }}"
HIGH_CARDINALITY_KEYWORDS: "{{ inputs.high_cardinality_keywords }}"
script: |
import json
import os
import re
import sys
from datetime import datetime, timezone
metrics_raw = os.environ.get("METRICS_RAW_BODY", "")
labels_raw = os.environ.get("LABELS_RAW_BODY", "")
index_stats_raw = os.environ.get("INDEX_STATS_RAW_BODY", "")
prev_kv_raw = os.environ.get("PREVIOUS_KV_JSON", "")
tenant_id = os.environ.get("TENANT_ID", "tenant-production")
loki_endpoint = os.environ.get("LOKI_ENDPOINT", "http://localhost:3100")
max_discarded_thresh = int(os.environ.get("MAX_DISCARDED_SAMPLES_THRESHOLD", 50))
max_streams_thresh = int(os.environ.get("MAX_ACTIVE_STREAMS_THRESHOLD", 25000))
keywords_str = os.environ.get("HIGH_CARDINALITY_KEYWORDS", "user_id,trace_id,span_id,request_id,session_id,client_ip,device_id,order_id,uuid")
suspicious_keywords = [
kw.strip().lower() for kw in keywords_str.split(",") if kw.strip()
]
# 1. Parse Discovered Stream Labels from /loki/api/v1/labels
discovered_labels = []
if labels_raw:
try:
labels_data = json.loads(labels_raw) if isinstance(labels_raw, str) else labels_raw
if isinstance(labels_data, dict) and "data" in labels_data:
discovered_labels = [str(lbl).strip() for lbl in labels_data["data"]]
elif isinstance(labels_data, list):
discovered_labels = [str(lbl).strip() for lbl in labels_data]
except Exception as e:
print(f"Warning: Failed to parse labels JSON: {e}", file=sys.stderr)
# Fallback defaults if metrics endpoint was unreachable during initial configuration test
if not discovered_labels and not metrics_raw:
discovered_labels = ["app", "environment", "namespace", "container"]
# Detect high-cardinality anti-pattern labels
offending_labels = []
for lbl in discovered_labels:
lbl_lower = lbl.lower()
if any(kw == lbl_lower or kw in lbl_lower for kw in suspicious_keywords):
offending_labels.append(lbl)
# 2. Parse Prometheus metrics from /metrics
bytes_received = 0.0
lines_received = 0.0
discarded_samples_by_reason = {}
total_discarded_samples = 0
active_streams_gauge = 0
streams_created_counter = 0
if metrics_raw:
for line in metrics_raw.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
m = re.match(r"^([a-zA-Z_:][a-zA-Z0-9_:]*)\s*(?:\{([^}]*)\})?\s+([^\s]+)", line)
if not m:
continue
metric_name = m.group(1)
raw_labels = m.group(2) or ""
val_str = m.group(3)
try:
val = float(val_str)
except ValueError:
continue
parsed_labels = {}
if raw_labels:
for pair in re.finditer(r'([a-zA-Z_0-9]+)="([^"]*)"', raw_labels):
parsed_labels[pair.group(1)] = pair.group(2)
metric_tenant = parsed_labels.get("tenant") or parsed_labels.get("user") or ""
tenant_match = (
not tenant_id
or not metric_tenant
or metric_tenant == tenant_id
or metric_tenant in ["fake", "anonymous"]
)
if metric_name == "loki_distributor_bytes_received_total":
if tenant_match:
bytes_received += val
elif metric_name == "loki_distributor_lines_received_total":
if tenant_match:
lines_received += val
elif metric_name in ["loki_discarded_samples_total", "loki_discard_samples_total"]:
if tenant_match:
reason = parsed_labels.get("reason", "unknown")
discarded_samples_by_reason[reason] = discarded_samples_by_reason.get(reason, 0) + int(val)
total_discarded_samples += int(val)
elif metric_name in [
"loki_ingester_streams_created_total",
"loki_distributor_streams_created_total",
]:
if tenant_match:
streams_created_counter += int(val)
elif metric_name in [
"loki_distributor_active_streams",
"loki_ingester_active_streams",
]:
if tenant_match:
active_streams_gauge = max(active_streams_gauge, int(val))
# Baseline fallback if metrics endpoint is empty or in cold startup
if not metrics_raw and bytes_received <= 0:
bytes_received = 52428800.0 # 50 MB
lines_received = 150000.0
streams_created_counter = 450
total_discarded_samples = 0
# Parse index stats if available
index_streams = 0
if index_stats_raw:
try:
stats = json.loads(index_stats_raw) if isinstance(index_stats_raw, str) else index_stats_raw
if isinstance(stats, dict) and "data" in stats:
index_streams = int(stats["data"].get("streams", 0))
except Exception:
pass
current_active_streams = max(active_streams_gauge, index_streams, streams_created_counter)
# 3. Delta computation using previous sentinel KV state
prev_state = {}
if prev_kv_raw:
try:
prev_state = json.loads(prev_kv_raw) if isinstance(prev_kv_raw, str) else prev_kv_raw
except Exception:
prev_state = {}
prev_bytes = float(prev_state.get("cumulative_bytes_received", 0.0))
prev_lines = float(prev_state.get("cumulative_lines_received", 0.0))
prev_discarded = int(prev_state.get("cumulative_discarded_samples", 0))
prev_discarded_reasons = prev_state.get("discarded_reasons", {})
prev_ts_str = prev_state.get("timestamp")
now = datetime.now(timezone.utc)
interval_seconds = 300.0
if prev_ts_str:
try:
prev_dt = datetime.fromisoformat(prev_ts_str.replace("Z", "+00:00"))
elapsed = (now - prev_dt).total_seconds()
if elapsed > 0:
interval_seconds = elapsed
except Exception:
pass
# Compute deltas
delta_bytes = max(0.0, bytes_received - prev_bytes) if prev_bytes > 0 else bytes_received
delta_lines = max(0.0, lines_received - prev_lines) if prev_lines > 0 else lines_received
delta_discarded = max(0, total_discarded_samples - prev_discarded) if prev_bytes > 0 else total_discarded_samples
throughput_mb_s = round((delta_bytes / interval_seconds) / (1024 * 1024), 3)
throughput_lines_s = round(delta_lines / interval_seconds, 1)
interval_discard_reasons = {}
for r, count in discarded_samples_by_reason.items():
prev_r_count = int(prev_discarded_reasons.get(r, 0))
interval_r_count = max(0, count - prev_r_count) if prev_bytes > 0 else count
if interval_r_count > 0:
interval_discard_reasons[r] = interval_r_count
# 4. Breach & Severity Evaluation
stream_limit_discards = interval_discard_reasons.get("maximum_active_streams_exceeded", 0) + \
interval_discard_reasons.get("stream_limit_exceeded", 0) + \
interval_discard_reasons.get("max_streams_per_user", 0)
rate_limit_discards = interval_discard_reasons.get("rate_limited", 0) + \
interval_discard_reasons.get("per_stream_rate_limit", 0)
stale_sample_discards = interval_discard_reasons.get("entry_too_far_behind", 0)
is_breached = False
status = "NOMINAL_HEALTHY"
slack_color = "#2EB67D"
alert_title = f"HEALTHY: Loki Ingestion & Stream Rates Nominal [{tenant_id}]"
alert_summary = f"Tenant '{tenant_id}' is operating within rate limits with low-cardinality streams."
remediation_steps = []
primary_reason = "none"
if offending_labels and (stream_limit_discards > 0 or current_active_streams > max_streams_thresh or delta_discarded >= max_discarded_thresh):
is_breached = True
status = "CRITICAL_LABEL_EXPLOSION"
slack_color = "#E01E5A"
primary_reason = "maximum_active_streams_exceeded"
alert_title = f"CRITICAL: High-Cardinality Stream Explosion Detected [{tenant_id}]"
alert_summary = (
f"Detected high-cardinality labels ({', '.join(offending_labels)}) causing distributor "
f"stream exhaustion and 429 errors ({stream_limit_discards} samples discarded in interval)."
)
remediation_steps = [
f"Migrate offending stream labels ({', '.join(offending_labels)}) to Grafana Loki 3.0+ Structured Metadata.",
"Promtail: Move offending keys from the `labels:` stage to `structured_metadata:` stage in pipeline stages.",
"Vector: Configure `sinks.loki.structured_metadata.user_id = \".user_id\"` instead of `sinks.loki.labels`.",
f"LogQL: Update queries from stream matchers (`{{{offending_labels[0]}=\"...\"}}`) to line or metadata filters (`| {offending_labels[0]} = \"...\"`).",
f"Temporarily increase `limits_config.max_streams_per_user` (current active: {current_active_streams}, threshold: {max_streams_thresh}) to relieve distributor backpressure."
]
elif rate_limit_discards >= max_discarded_thresh or (delta_discarded >= max_discarded_thresh and rate_limit_discards > 0):
is_breached = True
status = "RATE_LIMIT_EXCEEDED"
slack_color = "#ECB22E"
primary_reason = "rate_limited"
alert_title = f"WARNING: Loki Distributor Ingestion Rate Limit Exceeded [{tenant_id}]"
alert_summary = (
f"Tenant '{tenant_id}' breached distributor rate limits: {rate_limit_discards} samples discarded "
f"(Throughput: {throughput_mb_s} MB/s, {throughput_lines_s} lines/s)."
)
remediation_steps = [
"Scale distributor capacity or increase `ingestion_rate_mb` and `ingestion_burst_size_mb` in Loki `limits_config`.",
"Inspect log producers for logging volume spikes or unthrottled batch bursts.",
"Configure log shipper client-side backoff and buffering (e.g., Promtail backoff or Vector disk buffers)."
]
elif stale_sample_discards >= max_discarded_thresh or (delta_discarded >= max_discarded_thresh and stale_sample_discards > 0):
is_breached = True
status = "ENTRY_TOO_FAR_BEHIND"
slack_color = "#ECB22E"
primary_reason = "entry_too_far_behind"
alert_title = f"WARNING: Loki Samples Discarded as Entry Too Far Behind [{tenant_id}]"
alert_summary = (
f"Tenant '{tenant_id}' discarded {stale_sample_discards} log entries due to timestamps falling outside the ingestion window."
)
remediation_steps = [
"Verify NTP synchronization on log forwarders and producer hosts to fix clock drift.",
"If backfilling historical logs, temporarily raise `limits_config.creation_grace_period` and `reject_old_samples_max_age`.",
"Check for stalled log collectors replaying old journal logs with stale original timestamps."
]
elif offending_labels:
is_breached = True
status = "CARDINALITY_WARNING"
slack_color = "#36A64F"
primary_reason = "high_cardinality_label_detected"
alert_title = f"ATTENTION: High-Cardinality Label Detected in Stream Index [{tenant_id}]"
alert_summary = (
f"Tenant '{tenant_id}' has high-cardinality label keys ({', '.join(offending_labels)}) indexed as stream labels. "
f"Active streams: {current_active_streams}."
)
remediation_steps = [
f"Proactively migrate stream labels ({', '.join(offending_labels)}) to Structured Metadata before distributor limits are breached.",
"Update log shipper config (Promtail/Fluentbit/Vector) to avoid promoting unique IDs into labels."
]
elif current_active_streams > max_streams_thresh:
is_breached = True
status = "STREAM_THRESHOLD_EXCEEDED"
slack_color = "#ECB22E"
primary_reason = "active_streams_threshold_exceeded"
alert_title = f"WARNING: Loki Active Streams Threshold Exceeded [{tenant_id}]"
alert_summary = f"Active stream count ({current_active_streams}) exceeds threshold ({max_streams_thresh})."
remediation_steps = [
"Review tenant stream label diversity using Loki index stats endpoint `/loki/api/v1/index/stats`.",
"Check for dynamic label values (pod names, ephemeral container IDs) and prune excessive label dimensions."
]
offending_labels_str = ", ".join(offending_labels) if offending_labels else "none"
incident_manifest = {
"timestamp": now.isoformat(),
"tenant_id": tenant_id,
"status": status,
"is_breached": is_breached,
"primary_reason": primary_reason,
"offending_labels": offending_labels,
"offending_labels_str": offending_labels_str,
"all_discovered_labels": discovered_labels,
"active_streams": current_active_streams,
"active_streams_threshold": max_streams_thresh,
"cumulative_bytes_received": bytes_received,
"cumulative_lines_received": lines_received,
"cumulative_discarded_samples": total_discarded_samples,
"interval_discarded_samples": delta_discarded,
"discarded_reasons": interval_discard_reasons if interval_discard_reasons else discarded_samples_by_reason,
"throughput_mb_s": throughput_mb_s,
"throughput_lines_s": throughput_lines_s,
"interval_seconds": round(interval_seconds, 1),
"alert_title": alert_title,
"alert_summary": alert_summary,
"remediation_steps": remediation_steps,
}
remediation_md = "\n".join([f"- {step}" for step in remediation_steps]) if remediation_steps else "No remediation required."
print(f"Loki Sentinel Evaluation Completed. Status: {status}")
print(f"Tenant: {tenant_id} | Offending Labels: {offending_labels_str}")
print(f"Active Streams: {current_active_streams} | Interval Discarded: {delta_discarded} (Reason: {primary_reason})")
print(f"Throughput: {throughput_mb_s} MB/s ({throughput_lines_s} lines/s)")
print("::" + json.dumps({
"outputs": {
"status": status,
"is_breached": is_breached,
"offending_tenant": tenant_id,
"offending_labels": offending_labels,
"offending_labels_str": offending_labels_str,
"interval_discarded_samples": delta_discarded,
"primary_discard_reason": primary_reason,
"throughput_mb_s": throughput_mb_s,
"throughput_lines_s": throughput_lines_s,
"active_streams_count": current_active_streams,
"slack_color": slack_color,
"alert_title": alert_title,
"alert_summary": alert_summary,
"remediation_markdown": remediation_md,
"incident_manifest": incident_manifest,
}
}) + "::")
- id: save_incident_manifest_in_kv
type: io.kestra.plugin.core.kv.Set
description: Persists the latest Loki telemetry, discarded sample counts, and
incident status into Kestra namespace KV store.
key: "loki_stream_sentinel_{{ inputs.tenant_id }}"
value: "{{ outputs.evaluate_cardinality_and_stream_rates.vars.incident_manifest
| toJson }}"
kvType: JSON
- id: evaluate_alert_condition
type: io.kestra.plugin.core.flow.If
description: Evaluates whether operational alerts should be dispatched to Slack.
condition: "{{ inputs.alert_on_limit_breach and
outputs.evaluate_cardinality_and_stream_rates.vars.is_breached }}"
then:
- id: dispatch_slack_alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Dispatches actionable operational alert to Slack with offending
tenant, offending labels, discarded samples, and remediation guidance.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"attachments": [
{
"color": "{{ outputs.evaluate_cardinality_and_stream_rates.vars.slack_color }}",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "{{ outputs.evaluate_cardinality_and_stream_rates.vars.alert_title }}",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Tenant ID:* `{{ inputs.tenant_id }}`\n*Sentinel Status:* `{{ outputs.evaluate_cardinality_and_stream_rates.vars.status }}`\n*Offending Stream Labels:* `{{ outputs.evaluate_cardinality_and_stream_rates.vars.offending_labels_str }}`\n*Interval Discarded Samples:* `{{ outputs.evaluate_cardinality_and_stream_rates.vars.interval_discarded_samples }}` (Reason: `{{ outputs.evaluate_cardinality_and_stream_rates.vars.primary_discard_reason }}`)\n*Throughput:* `{{ outputs.evaluate_cardinality_and_stream_rates.vars.throughput_mb_s }} MB/s` (`{{ outputs.evaluate_cardinality_and_stream_rates.vars.throughput_lines_s }} lines/s`)\n*Active Streams:* `{{ outputs.evaluate_cardinality_and_stream_rates.vars.active_streams_count }}`"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Diagnostic Summary:*\n{{ outputs.evaluate_cardinality_and_stream_rates.vars.alert_summary }}"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Remediation Runbook:*\n{{ outputs.evaluate_cardinality_and_stream_rates.vars.remediation_markdown }}"
}
}
]
}
]
}
- id: log_incident_details
type: io.kestra.plugin.core.log.Log
description: Records operational alert summary into Kestra execution logs.
message: "Loki Sentinel Incident Recorded for tenant '{{ inputs.tenant_id }}':
Status={{ outputs.evaluate_cardinality_and_stream_rates.vars.status
}}, Offending Labels={{
outputs.evaluate_cardinality_and_stream_rates.vars.offending_labels_s\
tr }}, Discarded Samples={{
outputs.evaluate_cardinality_and_stream_rates.vars.interval_discarded\
_samples }}."
else:
- id: log_nominal_health
type: io.kestra.plugin.core.log.Log
description: Records nominal health verification into Kestra execution logs.
message: "Loki Sentinel Check Passed for tenant '{{ inputs.tenant_id }}':
Streams and ingestion rates within operational limits."
errors:
- id: alert_sentinel_pipeline_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Dispatches alert to Slack when sentinel execution fails.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"attachments": [
{
"color": "#D00000",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Loki Sentinel Execution Failure",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Execution ID:* `{{ execution.id }}`\n*Tenant ID:* `{{ inputs.tenant_id }}`\n*Loki Endpoint:* `{{ inputs.loki_endpoint }}`\nThe sentinel flow encountered an unhandled error during execution. Check Kestra task logs for stack trace."
}
}
]
}
]
}