Grafana Cloud

Add a custom metric to the knowledge graph

The knowledge graph recognizes standard OpenTelemetry and Prometheus metrics and many common frameworks. When you send a metric that no built-in rule recognizes, the knowledge graph still stores it and you can query it, but it doesn’t create entities, relationships, KPIs, or insights from it.

This topic shows how to make such a metric part of the graph. You add:

  • A new entity type
  • A relationship between the new entity type and an existing one
  • A KPI mapping that feeds the metric into the standard KPIs
  • An alert rule that produces a new insight

You add the entity, relationship, and alert rule as YAML files that you apply with gcx, and the KPI mapping on the RED mapping page in Grafana Cloud. To understand the stages these files extend, refer to How the knowledge graph processes data.

Before you begin

Before you begin, ensure that:

  • You have installed gcx and connected it to your Grafana Cloud stack.
  • You have the Editor or Admin basic role, or the plugins:grafana-asserts-app:knowledge-graph-writer permission. For more information, refer to Roles and permissions.
  • You are familiar with PromQL and YAML.
  • Your metric carries the labels that identify the environment and site. The rules in this topic select series where asserts_env isn’t empty. The knowledge graph sets asserts_env and asserts_site during label normalization, before these rules run. For more information, refer to Environment and region.

Example metrics

The examples in this topic use a fictional order dispatch system that emits two metrics:

fulfillment_dispatch_requests_total{service, namespace, city, dispatch_zone, outcome="matched|failed|timeout"}
fulfillment_dispatch_duration_seconds_bucket{service, namespace, city, dispatch_zone, outcome, le}

The second metric is a histogram, so it also has _sum and _count series.

Operators of this system think in dispatch zones, so the goal is to make each zone an entity, connect it to the services that serve it, and raise an insight when too many dispatches fail.

Define a new entity type

An entity rule turns each value of a label into an entity. The following rule creates a DispatchZone entity for each dispatch_zone value.

  1. Create a file called dispatch-model-rules.yaml with the following contents:

    YAML
    name: dispatch-entities
    entities:
      - type: DispatchZone
        name: dispatch_zone
        scope:
          namespace: namespace
          env: asserts_env
          site: asserts_site
        definedBy:
          - query: |-
              group by (asserts_env, asserts_site, namespace, dispatch_zone, city) (
                fulfillment_dispatch_requests_total{asserts_env!="", dispatch_zone!=""}
              )
            labelValues:
              dispatch_zone: dispatch_zone
              city: city
            literals:
              domain: dispatch

    The name and scope fields together identify one entity. Each value in labelValues becomes a property of the entity, and each value in literals becomes a property with fixed text. For a description of every field, refer to Manage entities and relations.

    Entity discovery uses only the labels in name, so the match is strict. An entity rule can also have a lookup field, which lists extra labels that the knowledge graph uses to find an existing entity when it enriches the entity or attaches an alert to it. If an alert’s labels don’t match the entity’s name, the knowledge graph tries the lookup labels instead. For example, it can match an alert’s instance label against the entity’s ip property. Keeping the two separate keeps discovery precise and alert correlation flexible. This example doesn’t use lookup.

Define a relationship

The same metric carries both service and dispatch_zone, so one query can define a relationship between them.

  1. Add the following relations section to dispatch-model-rules.yaml:

    YAML
    relations:
      - type: SERVES
        startEntityType: Service
        endEntityType: DispatchZone
        definedBy:
          source: METRICS
          pattern: |-
            group by (asserts_env, asserts_site, namespace, service, dispatch_zone) (
              fulfillment_dispatch_requests_total{asserts_env!="", service!="", dispatch_zone!=""}
            )
          startEntityMatchers:
            name: service
            namespace: namespace
            env: asserts_env
            site: asserts_site
          endEntityMatchers:
            name: dispatch_zone
            namespace: namespace
            env: asserts_env
            site: asserts_site

    The knowledge graph draws one SERVES relationship for each result series. It only draws the relationship when both the Service and the DispatchZone exist in the same environment, site, and namespace.

  2. Validate the file. The --dry-run flag checks the file against your stack and shows a diff without changing anything:

    Bash
    gcx kg model-rules upsert -f dispatch-model-rules.yaml --dry-run
  3. Apply the file:

    Bash
    gcx kg model-rules upsert -f dispatch-model-rules.yaml

You can also add entity and relationship rules on the Entity & Relation rules page in Grafana Cloud, or with Terraform. For more information, refer to Manage entities and relations.

Map the dispatch histogram to KPIs

Map the dispatch duration histogram to the standard KPIs. From one histogram, the knowledge graph derives the request rate, error ratio, average latency, and latency quantiles. The built-in KPI insights and the KPI charts in the knowledge graph then use them.

  1. Sign in to Grafana Cloud and click Observability > Configuration.

  2. Click RED mapping.

  3. Click Add new mapping and choose to map all KPIs using a histogram.

  4. Enter the following values:

    FieldValue
    Histogram metric base namefulfillment_dispatch_duration_seconds
    Metric sourcefulfillment_dispatch
    Service nameservice
    Request context labelsdispatch_zone
    Request typeinbound
    Latency unitseconds
    Quantiles99%
    Error typeoutcome
    Error type mapping rulesRegex: outcome =~ "failed|timeout"
  5. Review the chart of a mapped KPI for one service, then click Submit.

The base name is the histogram name without the _sum, _count, or _bucket suffix. You can also map each KPI on its own. For a description of every field, refer to Map Prometheus metrics to RED KPIs. If the page doesn’t support your metric, contact Support. You can’t map KPIs with gcx.

Add an insight

An alert rule defines a new insight, DispatchFailureRatioHigh, for failed dispatches.

  1. Create a file called dispatch-prom-rules.yaml with the following contents:

    YAML
    name: dispatch-insights
    groups:
      - name: dispatch.insights
        rules:
          - alert: DispatchFailureRatioHigh
            for: 5m
            expr: |-
              sum by (namespace, job, service, asserts_env, asserts_site) (
                rate(fulfillment_dispatch_requests_total{asserts_env!="", outcome=~"failed|timeout"}[5m])
              )
              /
              sum by (namespace, job, service, asserts_env, asserts_site) (
                rate(fulfillment_dispatch_requests_total{asserts_env!=""}[5m])
              ) > 0.05
            labels:
              asserts_severity: critical
              asserts_alert_category: error
              asserts_entity_type: Service
              asserts_source: fulfillment_dispatch
  2. Validate the file:

    Bash
    gcx kg prom-rules upsert -f dispatch-prom-rules.yaml --dry-run
  3. Apply the file:

    Bash
    gcx kg prom-rules upsert -f dispatch-prom-rules.yaml

Within a few minutes, when the failure ratio stays greater than 5% for five minutes, a DispatchFailureRatioHigh insight appears on the Service entity that owns the metric, next to the built-in insights.

You can also add alert rules on the Bring your own rules page in Grafana Cloud. That page and gcx kg prom-rules manage the same rules. For more information, refer to Define a health threshold.

Labels on the alert rule

The labels on an alert rule determine which entity the insight belongs to and how it appears.

Label or fieldPurpose
asserts_entity_type and the by (...) labelsTogether, these must identify exactly one entity. In the example, that’s a Service in one environment, site, and namespace. If you group by fewer labels, the knowledge graph can’t attach the insight to an entity.
asserts_severityThe impact level: info, warning, or critical.
asserts_alert_categoryGroups the insight in the knowledge graph: saturation, amend, anomaly, failure, or error.
forHow long the condition must hold before the insight fires.

Check the result

  1. Confirm that the new entities exist:

    Bash
    gcx kg entities list --type DispatchZone --env prod
  2. Find the services that serve a zone, and the services they call:

    Bash
    gcx kg graph query "MATCH (s:Service)-[:SERVES]->(z:DispatchZone {name:'midtown'}) OPTIONAL MATCH (s)-[:CALLS]->(d:Service) RETURN s, z, d LIMIT 50"
  3. Look for the new insight on a service:

    Bash
    gcx kg entities inspect --type Service --name <service> --env prod --namespace <namespace> --since 1h

If an entity, relationship, or insight is missing, refer to Troubleshoot entity discovery by stage.

Best practices

  • Put the identity in the labels. Emit consistent service, namespace, and environment labels. The rest of the graph depends on them.
  • Start with a dry run. Both upsert commands validate against your stack and show a diff before they change anything.
  • Keep queries cheap. Entity and relationship queries run against your metrics on a regular cycle. Select on the metric name and group by only the labels you need.
  • Get editor autocomplete. Run gcx kg model-rules schema or gcx kg prom-rules schema to get the JSON Schema for each file type.
ToRun
Define entity types and relationshipsgcx kg model-rules upsert -f <file>. Also list, get, delete, and schema.
Add alert rules for insightsgcx kg prom-rules upsert -f <file>. Also list, get, delete, and schema.
Silence an insightgcx kg suppressions upsert -f <file>
Route insights to notificationsgcx kg notifications upsert -f <file>
View the rules that set asserts_env and asserts_sitegcx kg relabel-rules get

For all flags, refer to the gcx CLI reference.