Victoriametrics Cardinality Analysis logo

Victoriametrics Cardinality Analysis

Organization
VictoriaMetrics
victoriametrics-cardinality-analysis

Analyze VictoriaMetrics time series cardinality to find optimization opportunities — unused metrics, high-cardinality labels, problematic label values, histogram bloat. Produces actionable report with relabeling and stream aggregation recommendations. Use whenever the user mentions cardinality analysis, series reduction, unused metrics, high cardinality labels, TSDB optimization, storage cost reduction, metric cleanup, too many time series, or wants to reduce cardinality. Also trigger when discussing relabeling strategies, streaming aggregation opportunities, or "which metrics can we drop".

Overview

PublisherVictoriaMetrics
Repositoryskills
Skill namevictoriametrics-cardinality-analysis
Stars
62
Forks
9
Bundled files
Instructions only
LicenseApache-2.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by VictoriaMetrics on GitHub. Read the source before you install it.

Installation

Install the Victoriametrics Cardinality Analysis AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/VictoriaMetrics/skills/tree/main/plugins/diagnostics/skills/victoriametrics-cardinality-analysis
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/VictoriaMetrics/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/plugins/diagnostics/skills/victoriametrics-cardinality-analysis .claude/skills/victoriametrics-cardinality-analysis
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Victoriametrics Cardinality Analysis in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Victoriametrics Cardinality Analysis on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Victoriametrics Cardinality Analysis is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

VictoriaMetrics Cardinality Analysis

Systematic cardinality analysis for VictoriaMetrics. Collects TSDB status, metric usage stats, and label value patterns, then produces a structured report with specific relabeling and stream aggregation configs the user can apply directly.

The goal is to find the highest-impact optimization opportunities — metrics nobody queries, labels that explode cardinality for no monitoring value, and patterns that indicate data hygiene problems (error messages as labels, SQL text as labels, UUIDs as labels).

Environment

Uses the same env vars as the victoriametrics-query skill:

bash
# $VM_METRICS_URL - base URL
#   cluster: export VM_METRICS_URL="https://vmselect.example.com/select/0/prometheus"
#   single: export VM_METRICS_URL="http://localhost:8428"
# $VM_CURL_CONFIG - curl config file with auth header (unset if no auth is required)
#   Remote: export VM_CURL_CONFIG="$HOME/.config/victoriametrics/curl.conf"
#   Local:  leave unset (defaults to /dev/null - no auth)

Workflow

Phase 1: Data Collection

Spawn 3 subagents in a single response to collect data in parallel. Each subagent prompt must include the curl auth pattern and environment variable references above.

If the user specified a scope (job, namespace, metric prefix), pass it as match[] parameter to TSDB status queries and as series selectors to label queries.


Subagent 1: TSDB Overview

Agent name: cardinality-tsdb | Description: "Collect TSDB cardinality stats"

Query 1 — Yesterday's series (captures recently churned series):

bash
curl -q --config "${VM_CURL_CONFIG:-/dev/null}" -s \
  "$VM_METRICS_URL/api/v1/status/tsdb?topN=50&date=$(date -d 'yesterday' +%Y-%m-%d)" | jq '.data'

Queries yesterday's stats — broader than today (includes series that may have already churned) without scanning the entire TSDB.

Query 2 — Today's active series:

bash
curl -q --config "${VM_CURL_CONFIG:-/dev/null}" -s \
  "$VM_METRICS_URL/api/v1/status/tsdb?topN=50" | jq '.data'

Query 3 — Focus on known high-cardinality labels:

bash
for label in pod instance container path url user_id request_id session_id trace_id le name; do
  echo "=== focusLabel=$label ===" && \
  curl -q --config "${VM_CURL_CONFIG:-/dev/null}" -s \
    "$VM_METRICS_URL/api/v1/status/tsdb?topN=20&focusLabel=$label" | \
    jq --arg l "$label" '{label: $l, focus: .data.seriesCountByFocusLabelValue}'
done

Return: All raw JSON preserving structure. Include totalSeries, totalLabelValuePairs, seriesCountByMetricName, seriesCountByLabelName, seriesCountByLabelValuePair from each query.


Subagent 2: Metric Usage Stats

Agent name: cardinality-usage | Description: "Find unused and rarely-queried metrics"

Query 1 — Never-queried metrics:

bash
curl -q --config "${VM_CURL_CONFIG:-/dev/null}" -s \
  "$VM_METRICS_URL/api/v1/status/metric_names_stats?le=0&limit=500" | jq '.'

Query 2 — Rarely-queried metrics (≤5 total queries):

bash
curl -q --config "${VM_CURL_CONFIG:-/dev/null}" -s \
  "$VM_METRICS_URL/api/v1/status/metric_names_stats?le=5&limit=500" | jq '.'

Query 3 — Stats overview (tracking period):

bash
curl -q --config "${VM_CURL_CONFIG:-/dev/null}" -s \
  "$VM_METRICS_URL/api/v1/status/metric_names_stats?limit=1" | \
  jq '{statsCollectedSince: .statsCollectedSince, statsCollectedRecordsTotal: .statsCollectedRecordsTotal}'

If the endpoint returns an error, storage.trackMetricNamesStats may not be enabled on vmstorage. Note this in the return and proceed — the analysis can still work with TSDB status data alone.

Query 4 — Cross-check: are "unused" metrics referenced in alerting rules?

bash
curl -q --config "${VM_CURL_CONFIG:-/dev/null}" -s \
  "$VM_METRICS_URL/api/v1/rules" | jq '[.data.groups[].rules[].query]'

Extract metric names from rule queries. Any "unused" metric that appears in an alert/recording rule is NOT safe to drop — it's queried indirectly.

Return: Unused metrics with cross-reference against alert rules. Flag each as:

  • safe to drop: never queried AND not in any rule
  • used by rules only: never queried by dashboards but referenced in rules — verify intent
  • rarely used: low query count, may be accessed infrequently (e.g., monthly reports)

Subagent 3: Label Pattern Inspection

Agent name: cardinality-labels | Description: "Inspect label values for problematic patterns"

All data comes from the TSDB status endpoint — do NOT use /api/v1/labels or /api/v1/label/.../values.

Query 1 — Label cardinality overview (unique value counts + series counts):

bash
curl -q --config "${VM_CURL_CONFIG:-/dev/null}" -s \
  "$VM_METRICS_URL/api/v1/status/tsdb?topN=50" | \
  jq '{labelValueCountByLabelName: .data.labelValueCountByLabelName, seriesCountByLabelName: .data.seriesCountByLabelName}'

labelValueCountByLabelName returns labels sorted by unique value count (replaces per-label /values counting). seriesCountByLabelName shows how many series each label appears in.

Query 2 — Sample values for high-cardinality labels via focusLabel: For each label with >100 unique values from Query 1, fetch sample values:

bash
for label in <top labels from Query 1>; do
  echo "=== focusLabel=$label ===" && \
  curl -q --config "${VM_CURL_CONFIG:-/dev/null}" -s \
    "$VM_METRICS_URL/api/v1/status/tsdb?topN=20&focusLabel=$label" | \
    jq --arg l "$label" '{label: $l, topValues: .data.seriesCountByFocusLabelValue}'
done

seriesCountByFocusLabelValue returns label values sorted by series count — use the value names to detect problematic patterns.

Query 3 — High-cardinality label-value pairs:

bash
curl -q --config "${VM_CURL_CONFIG:-/dev/null}" -s \
  "$VM_METRICS_URL/api/v1/status/tsdb?topN=50" | \
  jq '.data.seriesCountByLabelValuePair'

Shows which specific label=value pairs contribute the most series.

Pattern detection — classify label values from focusLabel samples:

PatternRegex hintIndicates
UUIDs[0-9a-f]{8}-[0-9a-f]{4}-Request/session/trace IDs as labels
IP addresses\d+\.\d+\.\d+\.\d+Per-client or per-pod IP tracking
Long strings (>50 chars)length checkError messages, SQL, stack traces
SQL keywordsSELECT|INSERT|UPDATE|DELETE|FROM|WHEREQuery text stored as label
URL paths with IDs/api/.*/[0-9a-f]+Unsanitized HTTP paths
Timestampsepoch or ISO8601Time values as labels (unbounded)
Stack tracesat .*\.(java|go|py):Error details as labels

Return: Table of labels sorted by unique value count, with detected pattern, sample values from focusLabel, and series impact.


Phase 2: Analysis

After all subagents return, compile and classify findings. This is the analytical core — apply judgment, not mechanical filtering.

Category 1: Unused Metrics (Quick Wins)

Cross-reference metric usage stats with TSDB series counts:

  • Drop candidates: queryRequestsCount=0, not in any alert/recording rule, >100 series
  • Verify candidates: queryRequestsCount=0 but referenced in rules — check if rule is still needed
  • Low-priority: queryRequestsCount≤5 with few series — not worth the config churn

Sort by series count descending — the biggest unused metrics are the biggest wins.

Category 2: High-Cardinality Labels

Labels with excessive unique values that drive series explosion:

Label patternAssessmentTypical remedy
user_id, customer_id, account_idShould NEVER be metric labels — belongs in logs/tracesDrop label
request_id, session_id, trace_id, span_idCorrelation IDs — never metric labelsDrop label
error, error_message, reason, status_messageUnbounded stringsDrop label or replace with error code
sql, query, command, statementQuery text in labels — unboundedDrop label
path, url, uri, endpointUnbounded if not sanitizedRelabel to normalize, or stream aggregate without
pod, containerNormal for k8s but high churnStream aggregate without, if per-pod not needed
instanceNormal for node metrics, wasteful for app metricsStream aggregate without for app-level metrics
le (histogram buckets)Fine-grained buckets multiply every label combinationReduce bucket count

For each finding, estimate impact: (series with this label) - (series without) ≈ series saved.

Category 3: Histogram Bloat

Check metrics ending in _bucket:

  • How many unique le values?
  • Each additional bucket multiplies series by (number of label combinations)
  • Look for histograms where most buckets are empty or redundant
Category 4: Series Churn

Compare yesterday's stats vs today:

  • Ratio >3:1 suggests significant churn from pod restarts, deployments, short-lived jobs
  • Not directly fixable via relabeling, but indicates opportunity for dedup_interval or -search.maxStalenessInterval tuning

Phase 3: Report

Compile into a structured report. Every finding must include impact estimate and specific remedy config.

Use this template:

markdown
## VictoriaMetrics Cardinality Report — <date>

### Overview
| Metric | Value |
|--------|-------|
| Total active series (today) | X |
| Total series (yesterday) | X |
| Churn ratio (yesterday / today) | X:1 |
| Unique metric names | X |
| Stats tracking since | <date> |

### 1. Unused Metrics
**Potential savings: ~X series (Y% of total)**

| Metric | Series | Last Queried | In Alert Rules | Action |
|--------|--------|-------------|----------------|--------|
| ... | ... | never | no | Drop |
| ... | ... | never | yes — verify | Check rule |

<details>
<summary>Relabeling config to drop unused metrics</summary>

```yaml
# Add to vmagent metric_relabel_configs (VMServiceScrape or global)
metric_relabel_configs:
  - source_labels: [__name__]
    regex: "metric1|metric2|metric3"
    action: drop

2. High-Cardinality Labels

Potential savings: ~X series (Y%)

LabelUnique ValuesTop Affected MetricsPatternAction
user_id50,000http_requests_totalUUIDDrop
path10,000http_request_durationURL pathsAggregate
error_message5,000app_errors_totalLong stringsDrop
yaml
metric_relabel_configs:
  - regex: "user_id|request_id|session_id|trace_id|error_message|sql_query"
    action: labeldrop
yaml
# vmagent stream aggregation config
- match: '{__name__=~"http_request.*"}'
  interval: 1m
  without: [path, instance, pod]
  outputs: [total]
  # drop_input: true  # enable after verifying aggregated output

- match: '{__name__=~"http_request_duration.*_bucket"}'
  interval: 1m
  without: [pod, instance]
  outputs: [total]
  keep_metric_names: true
yaml
metric_relabel_configs:
  - source_labels: [path]
    regex: "/api/v1/users/[^/]+"
    target_label: path
    replacement: "/api/v1/users/:id"
  - source_labels: [path]
    regex: "/api/v1/orders/[^/]+"
    target_label: path
    replacement: "/api/v1/orders/:id"

3. Histogram Optimization

Potential savings: ~X series (Y%)

MetricBucket CountRecommendation
...30Reduce to standard 11 buckets

4. Series Churn

ObservationValue
Yesterday / today ratioX:1
Primary driverPod restarts / short-lived jobs

Summary

CategoryEst. Series Saved% of TotalEffort
Drop unused metricsXY%Low — relabeling only
Drop bad labelsXY%Low — labeldrop
Stream aggregationXY%Medium — new config
Histogram reductionXY%Low — bucket filtering
TotalXY%

Implementation Priority

  1. [Low effort] Drop unused metrics — pure relabeling, no data loss risk
  2. [Low effort] Drop labels that should never be in metrics (IDs, messages, SQL)
  3. [Medium effort] Stream aggregation for high-cardinality HTTP/app metrics
  4. [Medium effort] Histogram bucket reduction

Adapt the template to actual findings — omit sections with no findings, expand sections
with significant findings.

---

## Remediation Reference

### Relabeling (metric_relabel_configs)

Applied at scrape time or remote write. Changes affect new data immediately.

**Drop entire metrics:**

```yaml
metric_relabel_configs:
  - source_labels: [__name__]
    regex: "metric_to_drop|another_metric"
    action: drop

Drop labels:

yaml
metric_relabel_configs:
  - regex: "label_to_drop|another_label"
    action: labeldrop

Normalize label values (reduce unique values):

yaml
metric_relabel_configs:
  - source_labels: [path]
    regex: "/api/v1/users/[^/]+"
    target_label: path
    replacement: "/api/v1/users/:id"

Stream Aggregation

Applied at vmagent level. Aggregates in-flight before writing to storage. Docs: https://docs.victoriametrics.com/victoriametrics/stream-aggregation/

Remove labels while preserving metric semantics:

yaml
- match: '{__name__=~"http_.*"}'
  interval: 1m
  without: [instance, pod]
  outputs: [total]

Aggregate counters (drop high-cardinality dimension):

yaml
- match: 'http_requests_total'
  interval: 30s
  without: [path, user_id]
  outputs: [total]

Aggregate histograms:

yaml
- match: '{__name__=~".*_bucket"}'
  interval: 1m
  without: [pod, instance]
  outputs: [quantiles(0.5, 0.9, 0.99)]
  keep_metric_names: true

Common output functions:

FunctionUse forExample
totalCounters (running sum)request counts
sum_samplesGauge sumsmemory usage across pods
count_samplesSample countsnumber of reporting instances
lastLatest gauge valuecurrent temperature
min, maxExtremespeak latency
avgAveragesmean CPU usage
quantiles(0.5, 0.9, 0.99)Distribution estimationlatency percentiles
histogram_bucketRe-bucket histogramsreduce bucket granularity

Important: use total for counters, last/avg/sum_samples for gauges. Using total on gauges produces nonsensical running sums.

Where to Apply in Kubernetes

MethodCRD / ConfigScope
metric_relabel_configsVMServiceScrape / VMPodScrape .spec.metricRelabelConfigsPer scrape target
Global relabelingVMAgent -remoteWrite.relabelConfigAll metrics
Stream aggregationVMAgent -remoteWrite.streamAggr.configAll remote-written metrics
Per-remote-write SAVMAgent .spec.remoteWrite[].streamAggrConfigPer destination

Common Mistakes

MistakeFix
Dropping a metric used by alertsAlways cross-check /api/v1/rules before dropping
drop_input: true without testingVerify aggregation output matches expectations first
Stream aggregating gauges with totalUse last, avg, or sum_samples for gauges
Forgetting keep_metric_names: trueWithout it, output gets long auto-generated suffix
Dropping le label entirely from histogramsOnly drop specific le values, never the label itself
Not considering recording rule dependenciesCheck both alerting AND recording rules
Applying relabeling without testingUse -dryRun flag or test on a single scrape target first

Frequently asked questions

What does the Victoriametrics Cardinality Analysis AI skill do?

Analyze VictoriaMetrics time series cardinality to find optimization opportunities — unused metrics, high-cardinality labels, problematic label values, histogram bloat. Produces actionable report with relabeling and stream aggregation recommendations. Use whenever the user mentions cardinality analysis, series reduction, unused metrics, high cardinality labels, TSDB optimization, storage cost reduction, metric cleanup, too many time series, or wants to reduce cardinality. Also trigger when discussing relabeling strategies, streaming aggregation opportunities, or "which metrics can we drop".

Why use Victoriametrics Cardinality Analysis on TypingMind?

Because you install it once and use it with any model. Victoriametrics Cardinality Analysis is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Victoriametrics Cardinality Analysis in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/VictoriaMetrics/skills/tree/main/plugins/diagnostics/skills/victoriametrics-cardinality-analysis. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Victoriametrics Cardinality Analysis?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Victoriametrics Cardinality Analysis?

As many as you like. As long as a model supports skills, you can use Victoriametrics Cardinality Analysis with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Victoriametrics Cardinality Analysis AI skill free?

Yes. It is published on GitHub by VictoriaMetrics under the Apache-2.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇