Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Operations 12 min read

AIOps in Practice: Dynamic Alert Rule Tuning with Prometheus Forecasts and DeepSeek, with Diff & Rollback

This article demonstrates an AIOps workflow that fetches historical metrics from Prometheus, computes 10-minute forecasts, uses DeepSeek to generate updated alert rules with adjusted thresholds, presents a diff for human review, validates with promtool, backs up the original rules.yml, and supports rollback via timestamped backups.

Problem: Static Alert Thresholds Cause Noise and Missed Alerts

The author describes a common operations pain point: alert thresholds in rules.yml remain static for long periods. A CPU alert set at > 20% fires continuously when actual usage hovers around 50%, while a threshold that hasn't been updated for a quarter may trigger too late when the system is truly saturated.

Solution Overview: Historical Prediction + LLM-Generated Rules with Human-in-the-Loop

The implemented workflow:

Query Prometheus for historical metric data (1 day, 7 days, 30 days, 1 year with appropriate step intervals).

Compute per-series statistics: minimum, average, P95, latest value, per-minute slope, and a 10-minute linear extrapolation.

Feed these statistics to DeepSeek with a strict system prompt that constrains the model to output a complete, valid rules.yml YAML adjusting only adjustable: true thresholds.

Present a diff (red for old, green for new) in a web UI; the operator must check "I have verified the diff" before the write button enables.

Write the candidate file to rules.yml.candidate, validate with promtool check rules if available; on failure delete candidate and abort.

On success, backup the original as rules.yml.bak.<timestamp>, then atomically replace.

Trigger Prometheus /-/reload; if the new rules misbehave, restore a backup and reload again.

Fetching Historical Data from Prometheus

The UI lets the operator select a time range (default "past 1 day") and automatically sets the step: 60s for 1 day, 5m for 7 days, 30m for 30 days, 6h for 1 year. All 9 existing alerts are queried in parallel using their original PromQL expressions. Example queries for CPU and memory:

{
  "alert": "物理节点cpu使用率",
  "unit": "%",
  "direction": "higher_is_worse",
  "query": '(100 - avg(irate(node_cpu_seconds_total{mode="idle"}[5m])) by (instance) * 100)'
},
{
  "alert": "物理节点内存使用率",
  "unit": "%",
  "direction": "higher_is_worse",
  "query": (
    "(node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + "
    "node_memory_Buffers_bytes + node_memory_Cached_bytes)) / "
    "node_memory_MemTotal_bytes * 100"
  )
}

The Python function used to call Prometheus /api/v1/query_range:

def query_range(base, query, start, end, step):
    response = requests.get(
        f"{base}/api/v1/query_range",
        params={"query": query, "start": start, "end": end, "step": step},
        timeout=(5, 90),
    )
    response.raise_for_status()
    body = response.json()
    if body.get("status") != "success":
        raise RuntimeError(body.get("error") or "Prometheus query failed")
    return body.get("data", {}).get("result") or []

Computing 10-Minute Forecasts

The 10-minute prediction is not generated by the LLM. The backend calculates a simple linear extrapolation from the last ~30 minutes of data:

slope = recent_slope_per_min(times, values)
last = values[-1]
return {
    "p95": round_num(series.quantile(0.95)),
    "last": round_num(last),
    "slope_per_min": round_num(slope),
    "predict_10min": round_num(last + slope * 10),
}

For instance, node-a showed CPU latest 50.9, P95 57.0, 10-minute prediction 49.5. With the old threshold > 20 the alert would fire constantly.

Generating Rules with DeepSeek Under Strict Constraints

Clicking "Generate 10-minute alert rules" sends the aggregated statistics to DeepSeek. The system prompt enforces seven key constraints: rules_yml must be a complete YAML preserving original groups, alert names, and labels.

Only adjust thresholds for series that have historical data and adjustable: true. InstanceDown expression must remain up == 0.

For "higher_is_worse" metrics: threshold must be above both the 10-minute prediction and recent P95, with headroom; percentage between 0 and 100.

For "lower_is_worse" metrics: threshold must be below the prediction, with headroom.

The prediction window is 10 minutes, but for duration need not become 10m; in noisy environments for can be set to 30s–2m.

Do not add, delete, or rename alerts or metric names.

In the demonstrated run, DeepSeek made four changes:

CPU threshold: 20 → 65; for: 2s → 1m (to avoid spike-triggered alerts).

Memory threshold: 20 → 75.

Disk capacity threshold: 80 → 88.

Disk I/O ("lower_is_worse"): threshold moved below the prediction, not raised like CPU.

Nginx 2xx rate, InstanceDown, network traffic, TCP connections left unchanged.

Human Review via Diff and Safe Write with Validation and Rollback

The deployment page shows the full candidate YAML on the left and a diff against the currently loaded version below. The YAML must pass syntax validation (write button stays disabled otherwise) and the operator must tick "I have verified the diff". The diff shows only threshold and for changes; alert names, labels, and PromQL expressions remain identical.

Example diff for the CPU alert:

- alert: 物理节点cpu使用率
  expr: (100 - avg(irate(node_cpu_seconds_total{mode='idle'}[5m])) by(instance)*100)
    > 65
  for: 1m
# previously: > 20 and for: 2s

The write procedure:

Stage candidate content to rules.yml.candidate.

If promtool exists in the same directory, run promtool check rules <candidate>; on failure delete candidate and abort.

Backup original: cp -a rules.yml rules.yml.bak.<YYYYMMDDHHMMSS>.

Atomically replace: mv -f rules.yml.candidate rules.yml.

Shell snippet implementing the safe replace:

promtool = remote_parent(path).rstrip("/") + "/promtool"
check_cmd = (
    f"if [ -x {shlex.quote(promtool)} ]; then "
    f"{shlex.quote(promtool)} check rules {shlex.quote(staged)}; "
    "else echo PROMTOOL_MISSING; fi"
)
# On check failure: delete candidate, do not overwrite rules.yml
stamp = datetime.now(CST).strftime("%Y%m%d%H%M%S")
backup = f"{path}.bak.{stamp}"
replace_cmd = (
    f"if [ -f {shlex.quote(path)} ]; then cp -a {shlex.quote(path)} {shlex.quote(backup)}; "
    f"else echo NO_ORIGINAL; fi && mv -f {shlex.quote(staged)} {shlex.quote(path)}"
)

After write, the UI can call Prometheus /-/reload . If the new rules cause issues, the operator can copy a rules.yml.bak.* back over rules.yml and reload again.

Additional Metrics and Observability

The same rule set also monitors: Nginx 2xx request rate Instance liveness ( up == 0 ) – observed but not modified Disk I/O performance ("lower_is_worse") Inbound/outbound network traffic TCP current connection count Custom PromQL can be added to visualize curves, but they do not create new alerts. Optionally, the latest value and 10-minute prediction for each series can be pushed to Pushgateway under job deepseek_prediction with metrics deepseek_metric_last and deepseek_metric_predict_10min , enabling Grafana dashboards that show the exact water levels the model used for decision-making.

Operational Workflow and Threshold Expiry

The author summarizes the troubleshooting sequence when an alert fires: check historical data, run intelligent analysis, deploy updated rules. The tool is packaged as a Docker image (deployment manual in the same directory). A final note: thresholds expire; before they do, compare the past day's P95 and the 10-minute prediction to decide whether the old value (e.g., 20) still belongs in the rule.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

OperationsAlertingPrometheusDeepSeekAIOpsPromQLRollbackDynamic Thresholds

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion