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-writerpermission. 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_envisn’t empty. The knowledge graph setsasserts_envandasserts_siteduring 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.
Create a file called
dispatch-model-rules.yamlwith the following contents: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: dispatchThe
nameandscopefields together identify one entity. Each value inlabelValuesbecomes a property of the entity, and each value inliteralsbecomes 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 alookupfield, 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 thelookuplabels instead. For example, it can match an alert’sinstancelabel against the entity’sipproperty. Keeping the two separate keeps discovery precise and alert correlation flexible. This example doesn’t uselookup.
Define a relationship
The same metric carries both service and dispatch_zone, so one query can define a relationship between them.
Add the following
relationssection todispatch-model-rules.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_siteThe knowledge graph draws one
SERVESrelationship for each result series. It only draws the relationship when both the Service and the DispatchZone exist in the same environment, site, and namespace.Validate the file. The
--dry-runflag checks the file against your stack and shows a diff without changing anything:gcx kg model-rules upsert -f dispatch-model-rules.yaml --dry-runApply the file:
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.
Sign in to Grafana Cloud and click Observability > Configuration.
Click RED mapping.
Click Add new mapping and choose to map all KPIs using a histogram.
Enter the following values:
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.
Create a file called
dispatch-prom-rules.yamlwith the following contents: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_dispatchValidate the file:
gcx kg prom-rules upsert -f dispatch-prom-rules.yaml --dry-runApply the file:
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.
Check the result
Confirm that the new entities exist:
gcx kg entities list --type DispatchZone --env prodFind the services that serve a zone, and the services they call:
gcx kg graph query "MATCH (s:Service)-[:SERVES]->(z:DispatchZone {name:'midtown'}) OPTIONAL MATCH (s)-[:CALLS]->(d:Service) RETURN s, z, d LIMIT 50"Look for the new insight on a service:
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
upsertcommands 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 schemaorgcx kg prom-rules schemato get the JSON Schema for each file type.
Related commands
For all flags, refer to the gcx CLI reference.


