sre

Build a Loki Log Volume Agent: Find the Noisiest Streams, Prove Nobody Queries Them, and Ship Alloy Drop, Sampling, and Retention Rules as PRs Without Losing an Error Line

Build a Loki log volume agent: find the noisiest streams, prove nobody queries them, and ship Alloy drop and sampling rules as PRs without losing errors.

November 27, 2026·13 min read·
#ai#sre#observability#grafana#cost-optimization#finops#automation#kubernetes#devops

What This Agent Does

A Loki log volume agent answers three questions about your log bill. Which streams produce the bytes? Which lines inside those streams repeat? Does anyone ever read them? It pulls per-stream volume from Loki's index, samples the top streams and groups lines into templates, then checks 30 days of Loki's own query log, the ruler's alert rules, and Grafana dashboards for anything that reads those lines. For what is left it opens a pull request against the collector config: an Alloy stage.match drop for health-check lines, a sampling stage for debug floods, a shorter retention_stream for dev namespaces. It never calls Loki's delete API and never edits a running collector.

The reason to build it: log volume is rarely spread evenly. In most clusters a few containers produce most of the bytes, and a large share of those bytes is one repeated line. Finding that line by hand takes an afternoon per service, so nobody does it until the invoice or the S3 bucket forces the question.

The Five Findings

FindingEvidenceFixSaves
Repeated line nobody readsOne template is over 20% of a stream, zero queries match itPR: stage.match with action = "drop"Ingestion and storage
Debug or trace floodLevel share from the sample, queried only now and thenPR: stage.sampling inside a matchIngestion and storage
Dev or CI namespace on full retentionNamespace label, no query older than 3 daysPR: retention_stream entryStorage only
High-cardinality labelStream count per label valueReport: move it to structured metadataIndex size, query speed
Big and actively queriedQuery log shows regular readsReport onlyNothing, and that is correct

The last row is the one to say out loud. A noisy stream that on-call searches every week is not waste. The agent's job is to separate "large" from "large and unread", and only the second gets a PR.

Step 1: Rank Streams by Bytes

Loki keeps per-stream byte statistics in its TSDB index and exposes them at /loki/api/v1/index/volume. It answers from the index, so it is cheap even over a week. It needs volume_enabled: true under limits_config; check that before anything else.

curl -sG "$LOKI/loki/api/v1/index/volume" \
  -H "X-Scope-OrgID: prod" \
  --data-urlencode 'query={cluster="prod"}' \
  --data-urlencode "start=$(date -d '24 hours ago' +%s)000000000" \
  --data-urlencode "end=$(date +%s)000000000" \
  --data-urlencode 'targetLabels=namespace,container' \
  --data-urlencode 'limit=50' | jq -r '.data.result[] | [.value[1], .metric.namespace, .metric.container] | @tsv'

If the volume endpoint is off, the same ranking comes from a metric query, at a much higher cost because Loki has to read the chunks:

topk(50, sum by (namespace, container) (bytes_over_time({cluster="prod"}[24h])))

Run that fallback over 1 hour first. A 24-hour bytes_over_time across the whole cluster is exactly the kind of query that gets a tenant rate-limited.

# logvol/volume.py
import time, requests

LOKI = "http://loki-query-frontend.loki.svc:3100"
HEADERS = {"X-Scope-OrgID": "prod", "X-Query-Tags": "Source=logvol-agent"}

def top_streams(hours: int = 24, limit: int = 50) -> list[dict]:
    end = time.time_ns()
    start = end - hours * 3600 * 10**9
    r = requests.get(f"{LOKI}/loki/api/v1/index/volume", headers=HEADERS, params={
        "query": '{cluster="prod"}', "start": start, "end": end,
        "targetLabels": "namespace,container", "limit": limit}, timeout=60)
    r.raise_for_status()
    return [{"namespace": s["metric"].get("namespace", ""),
             "container": s["metric"].get("container", ""),
             "bytes": int(s["value"][1])} for s in r.json()["data"]["result"]]

The X-Query-Tags header matters later. This agent reads every large stream in the cluster, so if its own queries are not tagged, Step 3 will conclude that every stream is actively queried.

Step 2: Find the Repeated Lines

For each of the top streams, pull a bounded sample from several windows across the day, not just the last five minutes. A cron job that floods at 02:00 is invisible in an afternoon sample. Then collapse each line to a template by masking the parts that vary.

# logvol/templates.py
import re
from collections import Counter

MASKS = [
    (re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b"), "<uuid>"),
    (re.compile(r"\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}\S*"), "<ts>"),
    (re.compile(r"\b\d{1,3}(\.\d{1,3}){3}(:\d+)?\b"), "<ip>"),
    (re.compile(r"\b[0-9a-f]{16,}\b"), "<hex>"),
    (re.compile(r"\b\d+(\.\d+)?(ms|s|µs|ns)?\b"), "<n>"),
]

def template(line: str) -> str:
    for rx, token in MASKS:
        line = rx.sub(token, line)
    return line[:300]

def top_templates(lines: list[str], n: int = 5) -> list[dict]:
    total = sum(len(l) for l in lines) or 1
    by_bytes: Counter = Counter()
    example: dict[str, str] = {}
    for l in lines:
        t = template(l)
        by_bytes[t] += len(l)
        example.setdefault(t, l)
    return [{"template": t, "byte_share": round(b / total, 3), "example": example[t]}
            for t, b in by_bytes.most_common(n)]

Rank templates by bytes, not line count. A stack trace that appears 40 times can outweigh 10,000 one-line access logs.

Newer Loki versions have a pattern ingester (pattern_ingester.enabled, served at /loki/api/v1/patterns) that does this server-side. If you run it, use it and skip the sampling. The masking code above works on any version and is good enough to find a line that is 40% of a stream.

While you are here, check label cardinality. logcli series '{namespace="payments"}' --analyze-labels prints how many unique values each label has. A label like pod_template_hash, request_id, or path with thousands of values splits one stream into thousands of tiny chunks. That is an index and query-speed problem more than a byte problem, so the agent reports it and does not try to fix it in the same PR.

Step 3: Prove Nobody Reads It

A stream counts as read if anything matches it in three places.

Loki's own query log. The query frontend writes one caller=metrics.go line per query, with the full LogQL in a query field plus bytes scanned and duration. If Loki's logs are shipped to Loki, the last 30 days of real usage is one query away:

{namespace="loki", container="query-frontend"} |= "caller=metrics.go" | logfmt | query != "" | line_format "{{.query}}"

The label names depend on how you deploy Loki, and the query-tag field name has varied between releases, so look at one raw line from your version before writing the filter. Exclude the agent's own tag and anything that is a label-values lookup from Grafana's Explore dropdowns.

Ruler rules. GET /loki/api/v1/rules returns every alerting and recording rule as YAML. Any stream selector in there is in use by definition, and its line filters matter in Step 4.

Grafana dashboards. Walk /api/search?type=dash-db and each dashboard's panels for targets whose datasource type is loki. The Grafana MCP server post covers a read-only service account for this.

Matching is done on parsed selectors, not strings. Extract the label matchers from each query and test them against the stream's labels:

# logvol/usage.py
import re

MATCHER = re.compile(r'(\w+)\s*(=~|!~|!=|=)\s*"((?:[^"\\]|\\.)*)"')

def selector_matches(query: str, labels: dict[str, str]) -> bool:
    sel = query[query.find("{") + 1: query.find("}")]
    matchers = MATCHER.findall(sel)
    if not matchers:
        return False
    for name, op, value in matchers:
        actual = labels.get(name, "")
        if op == "=" and actual != value: return False
        if op == "!=" and actual == value: return False
        if op == "=~" and not re.fullmatch(value, actual): return False
        if op == "!~" and re.fullmatch(value, actual): return False
    return True

That tells you a stream is read. For a drop rule you need the narrower fact: is this specific template read? Take each query that matches the stream, pull out its line filters (the strings after |= and the regexes after |~), and test them against the template's example lines. A query for |= "error" on the payments gateway does not read GET /healthz 200 lines. A query with no line filter at all reads everything, and that template is then marked read.

Step 4: The Model Picks From a Closed List

Code produces the evidence. The model gets one finding at a time, with the template, its byte share, the sample lines, and the list of queries and rules that touch the stream, and must return this:

{
  "name": "propose_log_action",
  "input_schema": {
    "type": "object",
    "required": ["action", "line_filter", "rationale", "risk"],
    "properties": {
      "action": {"enum": [
        "drop_lines",
        "sample_lines",
        "shorten_retention",
        "report_label_cardinality",
        "report_only"
      ]},
      "line_filter": {"type": "string", "maxLength": 120},
      "sample_rate": {"type": "number", "minimum": 0.01, "maximum": 0.5},
      "retention_hours": {"type": "integer", "minimum": 72},
      "rationale": {"type": "string", "maxLength": 600},
      "risk": {"enum": ["low", "medium", "high"]}
    }
  }
}

The system prompt carries the judgment rules:

You propose one action for one log template in one Loki stream.
- drop_lines is only for lines with no diagnostic value on their own:
  health checks, readiness probes, keepalives, "nothing to do" poll loops.
- For debug or trace level floods, prefer sample_lines. Never drop a whole level.
- Never propose an action for lines at warn, error, or fatal level.
- line_filter must be a literal substring taken from the example lines.
  No regex. It must be specific enough not to match unrelated lines.
- If any listed query or alert rule could match the template, return report_only.
- Audit, auth, and payment event logs are report_only regardless of volume.

After the model answers, code tests the proposal against Loki itself. This is the step that keeps an over-broad filter from shipping:

# logvol/validate.py
def validate_drop(stream: str, line_filter: str, query_scalar) -> str | None:
    needle = line_filter.replace('"', '\\"')
    base = f'{stream} |= "{needle}"'
    errors = query_scalar(
        f'sum(count_over_time({base} |~ "(?i)(error|fatal|panic|exception)" [24h]))')
    if errors > 0:
        return f"filter also matches {int(errors)} error-looking lines in 24h"
    matched = query_scalar(f"sum(bytes_over_time({base} [24h]))")
    total = query_scalar(f"sum(bytes_over_time({stream} [24h]))")
    if total == 0 or matched / total < 0.05:
        return "filter matches under 5% of the stream, not worth a rule"
    return None

If the proposed substring healthz also matches healthz check failed: connection refused, the first query returns a non-zero count and the finding is downgraded to report_only with the reason attached. Namespaces on a denylist (kube-system audit logs, anything labeled as compliance scope) never reach the model at all.

Step 5: Ship the Rule as a PR

Following the pull requests, not kubectl pattern, the fix lands in the Alloy config in Git, one rule per PR:

loki.process "volume_rules" {
  forward_to = [loki.write.default.receiver]

  // logvol-agent: 41% of payments/gateway bytes, 0 matching queries in 30d
  stage.match {
    selector            = "{namespace=\"payments\", container=\"gateway\"} |= \"GET /healthz\""
    action              = "drop"
    drop_counter_reason = "logvol_healthz_payments_gateway"
  }

  // logvol-agent: debug lines are 63% of search/indexer bytes, queried twice in 30d
  stage.match {
    selector = "{namespace=\"search\", container=\"indexer\"} |= \"level=debug\""

    stage.sampling {
      rate = 0.05
    }
  }
}

drop_counter_reason is the part reviewers skip and should not. Every dropped line increments loki_process_dropped_lines_total with that reason as a label, so after the merge you can confirm the rule is doing what the PR claimed, and nothing more:

sum by (reason) (rate(loki_process_dropped_lines_total[5m]))

The agent re-checks this a day after merge. If the dropped rate is far above the estimate in the PR, the filter is matching something the sample never showed, and the agent opens a revert PR and says so.

Retention changes go to the Loki config, and only work when the compactor has retention_enabled: true:

limits_config:
  retention_period: 720h
  retention_stream:
    - selector: '{namespace=~"dev-.*|ci"}'
      priority: 1
      period: 72h

Know which lever saves what. On a hosted plan billed per ingested GB, only drops and sampling reduce the bill; shorter retention on a slice of streams usually changes nothing. On self-hosted Loki, drops cut ingester and distributor load plus object storage, and retention cuts object storage only. The PR description states which one applies, with the measured bytes per day, so nobody approves a retention change expecting an ingestion saving. The same split shows up in the CloudWatch Logs cost agent, where ingestion and storage are separate line items.

Guardrails

RuleEnforced where
Read-only Loki and Grafana credentials, no delete APIToken scopes
Agent queries tagged and excluded from usage evidenceX-Query-Tags plus Step 3 filter
No action on warn, error, or fatal linesPrompt, then validate_drop error check
Any matching alert rule or dashboard forces report_onlyPost-model validation
Literal substring filters only, no regex dropsSchema plus validator
At most 3 PRs per run, one rule per PRPR opener
Denylisted namespaces never reach the modelCollector
Post-merge drop rate compared with the estimateFollow-up run

Give the agent its own key on the LiteLLM gateway. Sample lines are the one thing here that can balloon a prompt, so cap each finding at 20 example lines of 300 characters and redact before sending. Log lines carry emails, tokens, and customer IDs far more often than anyone admits; the masking from Step 2 runs on the examples too, and the prompt injection defenses apply because log content is attacker-influenced text.

What the Report Looks Like

An illustrative weekly run:

Loki log volume (prod tenant, 24h window, top 50 streams = 81% of bytes)

payments/gateway     118 GB/d   41% "GET /healthz <n>"         0 queries/30d  -> PR: drop
search/indexer        74 GB/d   63% level=debug                2 queries/30d  -> PR: sample 5%
ingress-nginx/ctrl    66 GB/d   access log, 14 dashboards                     -> report only (read)
dev-*/ (9 namespaces) 52 GB/d   newest query age: 31h                         -> PR: retention 72h
batch/etl-worker      39 GB/d   label "job_run_id": 18,400 values             -> report: cardinality
auth/session-svc      22 GB/d   denylisted                                    -> skipped

Estimated ingestion reduction if merged: 95 GB/d (17% of tenant)

The estimate is the measured bytes matching each filter over the last 24 hours. It moves with traffic, so treat it as an order of magnitude.

Honest Limits

  • "Not queried in 30 days" is weak evidence for incident logs. Some lines exist for the outage that happens twice a year. That is why warn and above are untouchable, why debug is sampled and not dropped, and why the query-log check alone never justifies a rule.
  • The query log only sees queries that went through the frontend you scraped. Direct querier access, a second Grafana pointing at another gateway, or logcli from a laptop through a different path will not show up. If Loki's own logs are not in Loki, this evidence does not exist and the agent should be report-only.
  • Sampling misses rare templates. A line that appears once an hour will not be in a 5,000-line sample, and the validator's error check is the only thing standing between it and a broad filter. Keep filters long and literal.
  • Dropping at the collector is the second-best fix. The best one is the service not emitting the line: a log level change or an access-log exclusion for the probe path. The PR description says this and tags the owning team, found through the Backstage MCP server if you have one.
  • Metrics do not replace dropped logs automatically. If someone was counting health-check lines to infer uptime, that signal is gone. Move it to a real metric first; the Prometheus cardinality agent is the mirror image of this agent on the metrics side.

Run it report-only for two weeks before enabling PRs. The first report usually contains one line that everyone recognizes and nobody defends, and that single drop rule tends to be worth more than everything else on the list combined.

#ai#sre#observability#grafana#cost-optimization#finops#automation#kubernetes#devops
D
DevToCashAuthor

Senior DevOps/SRE Engineer · 10+ years · Professional Trader (IDX, Crypto, US Equities)

I write about real infrastructure patterns and trading strategies I use in production and in live markets. No courses, no affiliate hype — just documentation of what actually works.

More about me →