---
title: "How the knowledge graph discovers services in Kubernetes and Istio | Grafana Cloud documentation"
description: "Learn how the knowledge graph discovers Kubernetes services, pods, and the calls between them, including Istio service mesh traffic, from the metrics you already send"
---

> For a curated documentation index, see [llms.txt](/llms.txt). For the complete documentation index, see [llms-full.txt](/llms-full.txt).

# How the knowledge graph discovers services in Kubernetes and Istio

The knowledge graph finds your services, the pods that run them, and the calls between them using only the metrics you already send, such as kube-state-metrics, Istio, OpenTelemetry `target_info`, and cAdvisor metrics. This topic follows one Kubernetes workload through the three sets of rules that turn its metrics into a Service entity, using excerpts of the rules that ship with the knowledge graph.

> Note
> 
> The rule excerpts in this topic are here to help you understand the concepts. They’re simplified, and the shipped rules can change. If discovery doesn’t work as expected, contact Support.

For an overview of all processing stages, refer to [How the knowledge graph processes data](https://grafana.com/docs/grafana-cloud/knowledge-graph/reference/how-knowledge-graph-processes-data/).

## How discovery works

Three sets of rules run in sequence:

Expand table

| Stage                             | Where it runs                                           | What it does                                                                                                                                     |
|-----------------------------------|---------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------|
| 1\. Ingest relabel rules          | In Grafana Cloud Metrics, as each sample is written     | Adds `asserts_env` and `asserts_site` from labels you choose, and copies framework-specific labels into common names. Doesn’t create new series. |
| 2\. Recording rules               | In the Grafana Cloud Metrics ruler, on every evaluation | Joins raw metrics into compact `asserts:*` series, for example to resolve which workload a Pod belongs to.                                       |
| 3\. Entity and relationship rules | In the knowledge graph, on a recurring schedule         | Runs PromQL queries. Each result series becomes an entity or a relationship.                                                                     |

## Example workload

The example in this topic is a Deployment named `message-router` in the `messaging` namespace, running on the `prod-use1-01` cluster. The environment is identified by an `env` label and the site by a `deployment_site` label. All names and values are fictional.

kube-state-metrics sends series like the following:

![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```none
kube_pod_owner{env="prod", deployment_site="us-east-1/eks/prod-use1-01",
  cluster="prod-use1-01", namespace="messaging", pod="message-router-6c9d7-x2k4q",
  owner_kind="ReplicaSet", owner_name="message-router-6c9d7", ...}

kube_replicaset_owner{env="prod", namespace="messaging",
  replicaset="message-router-6c9d7", owner_kind="Deployment", owner_name="message-router", ...}
```

No single series says that Pod `message-router-6c9d7-x2k4q` belongs to Deployment `message-router`. That fact is spread across two series.

## Stage 1: Ingest relabel rules

Relabel rules run as each sample is written, before it reaches storage. They change labels on the series you send. They never create new series, so they don’t add to your active series count.

### Environment and site labels

The most important relabel rules set `asserts_env` and `asserts_site`. The knowledge graph generates them from the environment settings you choose when you set it up. In the example, they copy `env` into `asserts_env` and `deployment_site` into `asserts_site`.

Together, these two labels form the scope of every entity. That’s why the same workload running on two clusters becomes two Service entities, not one.

A series gets an `asserts_env` label only when both of the following are true:

- It’s a metric that a knowledge graph dataset covers, such as `kube_*` or `istio_*` metrics.
- It matches your environment settings: an environment value you selected, and any filters you added, such as excluding test namespaces.

Series without `asserts_env` are ignored by every recording rule and entity rule in the next two stages.

The following excerpt shows the shape of the generated rules:

YAML ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```yaml
# env → asserts_env
- selector: '{__name__=~"apiserver_request_total|container_.*|coredns_.*|kube.*|…",
    env=~"dev|prod|stage", namespace!~"<optional exclusion filter>"}'
  join_labels: [env]
  target_label: asserts_env

# deployment_site → asserts_site, after env is set
- selector: '{__name__=~"apiserver_request_total|container_.*|coredns_.*|kube.*|…",
    asserts_env!="", asserts_site=""}'
  join_labels: [deployment_site]
  target_label: asserts_site
```

To view the generated rules for your stack, run `gcx kg relabel-rules get`.

### Framework label mapping

Vendor rule sets copy framework-specific labels into the common names that later rules expect. For example, Istio reports `destination_workload`, and the Istio rule set copies it into `workload` and `service`:

YAML ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```yaml
name: istio
selector: '{asserts_env!=""}'
metric_regex:
  - 'istio_request.*'
rules:
  - join_labels: [destination_workload]
    selector: '{__name__=~"istio_request(s_total|_duration_.+)", reporter="destination"}'
    target_label: workload
  - join_labels: [source_workload]
    selector: '{__name__=~"istio_request(s_total|_duration_.+)", reporter="source"}'
    target_label: workload
  - join_labels: [destination_workload]
    selector: '{__name__=~"istio_request(s_total|_duration_.+)", reporter="destination", service=""}'
    target_label: service
  # … namespace, asserts_request_context, status …
```

For custom cases, Grafana can add a relabel rule that maps a custom label into a standard label. For example, the following rule copies the Micrometer `service_name` label into `service`:

YAML ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```yaml
- selector: '{__name__="http_server_requests_seconds_count"}'
  join_labels: [service_name]
  target_label: service
```

Custom relabel rules are an advanced capability. Grafana enables them on request, and you use them with help from Grafana. To request them, contact Support. You can view relabel rules with gcx, but you can’t create them.

After stage 1, the example series carries the scope labels:

![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```none
kube_pod_owner{asserts_env="prod", asserts_site="us-east-1/eks/prod-use1-01",
  env="prod", namespace="messaging", pod="message-router-6c9d7-x2k4q", ...}
```

## Stage 2: Recording rules

Entity rules could query raw metrics directly, with every join written into each query. However, several rules need the same joins, and each would repeat them every time the graph is built. Recording rules do the shared work once per evaluation and write the result as compact `asserts:*` series. Entity rules, dashboards, and insights all read those series instead of the raw metrics.

Three groups of recording rules feed Service discovery.

### Pod to workload: `asserts:mixin_pod_workload`

Kubernetes doesn’t label a Pod with its Deployment. The Pod points to a ReplicaSet, and the ReplicaSet points to the Deployment. Resolving that takes two joins, plus a third join to `kube_pod_info` to find the node.

`asserts:mixin_pod_workload` does those joins once per evaluation and records one series per Pod with the `workload`, `workload_type`, `pod`, `node`, and scope labels. Seven rules build it, one for each ownership pattern: Deployments, StatefulSets, DaemonSets, standalone ReplicaSets, other controllers such as Argo Rollouts, and two special cases.

For the example Pod, the recorded series is:

![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```none
asserts:mixin_pod_workload{workload="message-router", workload_type="deployment",
  pod="message-router-6c9d7-x2k4q", node="ip-10-42-7-19.ec2.internal",
  namespace="messaging", cluster="prod-use1-01",
  asserts_env="prod", asserts_site="us-east-1/eks/prod-use1-01"}
```

The following excerpt shows the rule for Deployments:

YAML ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```yaml
- record: asserts:mixin_pod_workload
  labels:
    workload_type: deployment
  expr: |
    max by (cluster, namespace, workload, pod, node, asserts_env, asserts_site) (
      label_replace(
        label_replace(
          # 1. pod → its ReplicaSet (owner_name)
          group without() (kube_pod_owner{asserts_env!="", namespace!~"kube-.*",
            owner_kind="ReplicaSet", exported_pod="", pod!="<aggregated>"}),
          "replicaset", "$1", "owner_name", "(.*)"
        )
        # 2. ReplicaSet → the Deployment that owns it
        * on(replicaset, namespace, asserts_env, asserts_site) group_left(owner_name, owner_kind)
          topk by(replicaset, namespace, asserts_env, asserts_site) (1,
            max by (replicaset, namespace, owner_name, owner_kind, asserts_env, asserts_site) (
              kube_replicaset_owner{asserts_env!="", namespace!~"kube-.*",
                owner_name!="", owner_name!="<none>", owner_kind="Deployment"}
            )
          ),
        "workload", "$1", "owner_name", "(.*)"
      )
      # 3. attach the node the pod runs on
      * on (cluster, namespace, pod, asserts_env, asserts_site) group_left(node)
        topk by (cluster, namespace, pod, asserts_env, asserts_site) (1,
          group by(cluster, namespace, pod, asserts_env, asserts_site, node)(
            kube_pod_info{asserts_env!="", pod!="<aggregated>"}))
    )
```

The rules skip Pods in `kube-*` namespaces, with Karpenter as an exception.

### Workload names: `asserts:mixin_workload_job`

One workload often has several names. Prometheus scrapes it under a `job`, a Kubernetes Service gives it a `service` name, and OpenTelemetry reports its `service.name`. Without a way to know these names refer to the same workload, the graph would show one Service for each name.

`asserts:mixin_workload_job` records every known name for each workload. It joins `up`, OpenTelemetry `target_info`, Istio, and Kubernetes Service metrics to `asserts:mixin_pod_workload` on the Pod. Entity rules use it to avoid duplicate Services: the Kubernetes rules skip a workload that OpenTelemetry already names, and the knowledge graph never creates a Service from service graph data for a name already on the list.

![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```none
asserts:mixin_workload_job{workload="message-router", job="message-router/message-router",
  service="message-router", namespace="messaging",
  asserts_env="prod", asserts_site="us-east-1/eks/prod-use1-01"}
```

### Service-to-service calls: `asserts:relation:calls`

Call metrics come in many shapes. Istio reports `source_workload` and `destination_workload`, and Tempo service graphs report `client` and `server`. Each source has a recording rule that maps these labels onto one series, `asserts:relation:calls`:

- The caller goes in `workload` or `service`, plus `namespace`.
- The called service goes in `dst_workload` or `dst_service`, plus `dst_namespace`.

Sources include Istio, Application Observability service graphs, Spring Boot client metrics, and NGINX Ingress. Some sources skip this step: Beyla network flows and the Tempo `traces_service_graph_connection_info` metric already name both ends, so a relationship rule reads them directly.

![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```none
asserts:relation:calls{workload="sms-gateway", namespace="messaging",
  dst_workload="message-router", dst_namespace="messaging",
  asserts_env="prod", asserts_site="us-east-1/eks/prod-use1-01", asserts_source="istio"}
```

The Istio rule records a series only when there’s traffic between the two workloads:

YAML ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```yaml
- record: asserts:relation:calls
  expr: >
    sum by (workload, dst_workload, namespace, dst_namespace, asserts_env, asserts_site) (
      label_replace(label_replace(label_replace(label_replace(
        sum by (source_workload, destination_workload, source_workload_namespace,
                destination_workload_namespace, asserts_env, asserts_site, reporter) (
          rate(istio_requests_total{asserts_env!="", source_workload!~"unknown|",
            destination_workload!~"unknown|istio-telemetry|", reporter="source"}[5m])) > 0
        or ignoring(reporter)
        sum by (source_workload, destination_workload, source_workload_namespace,
                destination_workload_namespace, asserts_env, asserts_site, reporter) (
          rate(istio_requests_total{asserts_env!="", source_workload!~"unknown|",
            destination_workload!~"unknown|istio-telemetry|", reporter="destination"}[5m])) > 0,
      "workload", "$1", "source_workload", "(.*)"),
      "dst_workload", "$1", "destination_workload", "(.*)"),
      "namespace", "$1", "source_workload_namespace", "(.*)"),
      "dst_namespace", "$1", "destination_workload_namespace", "(.*)")
    )
  labels:
    asserts_source: istio
```

## Stage 3: Entity rules

The knowledge graph builds the graph on a recurring schedule. On each run, it queries your stack’s metrics with every entity rule’s PromQL query. Each returned series creates or refreshes one entity. An entity that stops being returned eventually expires.

Three fields in an entity rule determine the entity:

- `name` uses the first non-empty label in a list. For Service entities, the list is `otel_service | workload | service | job`, so the example workload is named `message-router`.
- `scope` (`env`, `site`, and `namespace`) is the boundary within which the name is unique.
- `labelValues` copies labels onto the entity as properties.

The following excerpt shows the rule that finds Kubernetes workloads that nothing scrapes, which is the case for the example. It reads `asserts:mixin_pod_workload` and keeps every workload except Jobs and CronJobs, workloads that OpenTelemetry already names, and pods covered by a scraped `up` series. Other rules handle those cases.

YAML ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```yaml
- type: Service
  name: otel_service | workload | service | job
  scope:
    namespace: namespace
    env: asserts_env
    site: asserts_site
  definedBy:
    # … other Service discovery rules …
    - query: >
        group by (cluster, namespace, workload, workload_type, asserts_env, asserts_site) (
          group by (cluster, pod, workload, workload_type, namespace, asserts_env, asserts_site) (
            asserts:mixin_pod_workload{workload_type!~"job|cronjob"}
          )
          unless on (workload, namespace, asserts_env, asserts_site)
            group by (workload, namespace, asserts_env, asserts_site) (
              asserts:mixin_workload_job{otel_service!=""})
          unless on (pod, namespace, asserts_env, asserts_site)
            group by (pod, namespace, asserts_env, asserts_site) (
              up{pod!="", service!="", container!="istio-proxy"})
        )
      labelValues:
        workload: workload
        workload_type: workload_type
        cluster: cluster
```

The result is one entity:

Expand table

| Field      | Value                                                                         |
|------------|-------------------------------------------------------------------------------|
| Type       | Service                                                                       |
| Name       | `message-router`                                                              |
| Scope      | `env=prod`, `site=us-east-1/eks/prod-use1-01`, `namespace=messaging`          |
| Properties | `workload=message-router`, `workload_type=deployment`, `cluster=prod-use1-01` |

### Service discovery sources

The Service entity type has several `definedBy` queries. When two queries return the same name and scope, they describe the same Service, and the knowledge graph merges their properties.

Expand table

| Source                         | Built from                                                         | Finds                                                                                                                                              |
|--------------------------------|--------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|
| Scraped Kubernetes pods        | `up{pod!="", service!=""}` joined to `asserts:mixin_pod_workload`  | Kubernetes workloads that Prometheus scrapes                                                                                                       |
| Unscraped Kubernetes workloads | `asserts:mixin_pod_workload` unless `up`                           | Kubernetes workloads that nothing scrapes                                                                                                          |
| Targets outside Kubernetes     | `up{pod=""}`                                                       | VMs, bare-metal hosts, and other targets outside pods. OS-level exporters, such as `node_exporter`, are excluded and become Node entities instead. |
| Standalone containers          | cAdvisor `container_last_seen{pod=""}` seen in the last 60 seconds | Docker or Swarm containers outside Kubernetes                                                                                                      |
| OpenTelemetry services         | `target_info` or `traces_target_info`                              | Instrumented services, named by `service.name`                                                                                                     |

### Enrichment

`enrichedBy` rules add properties to Service entities that already exist. They never create an entity. The knowledge graph matches each series from an enrichment query to a Service by name and scope, and adds the series labels as properties.

For example, a built-in enrichment rule joins `kube_pod_labels` through `asserts:mixin_pod_workload` and sets the `app`, `component`, and `managed_by` properties from your pods’ Kubernetes labels, using the first label that’s present:

YAML ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```yaml
enrichedBy:
  - query: |-
      group without (pod) (
        group by (pod, namespace, label_app, label_app_kubernetes_io_name, label_k8s_app,
          label_component, label_app_kubernetes_io_component, label_eks_amazonaws_com_component,
          label_app_kubernetes_io_managed_by, asserts_env, asserts_site) (
          kube_pod_labels{asserts_env!=""}
        )
        * on (pod, namespace, asserts_env, asserts_site) group_left(workload)
          group by (pod, namespace, asserts_env, asserts_site, workload) (
            asserts:mixin_pod_workload{workload!="", workload_type!~"job|cronjob"})
      )
    labelValues:
      app: label_app | label_app_kubernetes_io_name | label_k8s_app
      component: label_component | label_app_kubernetes_io_component | label_eks_amazonaws_com_component
      managed_by: label_app_kubernetes_io_managed_by
```

For the example, this adds `app=message-router`, `component=api`, and `managed_by=Helm`.

## Stage 3: Relationship rules

After the entities are written, relationship rules add the connections between them. There are two kinds:

- **`PROPERTY_MATCH`** connects two existing entities whose properties are equal. No query runs. For example, Pod entities get their `workload` property from `asserts:mixin_pod_workload`, so Service `message-router` `CONTROLS` every Pod with `workload="message-router"` in the same scope.
- **`METRICS`** runs a query and draws one relationship for each result series, finding the start and end entities from the series labels. For example, each `asserts:relation:calls` series becomes a `CALLS` relationship, but only when both ends exist as Service entities in the matching environment, site, and namespace.

YAML ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```yaml
- type: CONTROLS
  startEntityType: Service
  endEntityType: Pod
  definedBy:
    source: PROPERTY_MATCH
    startEntityProperties: [workload, namespace, env, site]
    endEntityProperties: [workload, namespace, env, site]

- type: CALLS
  startEntityType: Service
  endEntityType: Service
  definedBy:
    source: METRICS
    pattern: sum by (workload, dst_workload, namespace, dst_namespace, asserts_env, asserts_site)
      (asserts:relation:calls{workload != "", dst_workload != ""})
    startEntityMatchers:
      name: workload
      namespace: namespace
      env: asserts_env
      site: asserts_site
    endEntityMatchers:
      name: dst_workload
      namespace: dst_namespace
      env: asserts_env
      site: asserts_site
```

The service map draws `CALLS` and `ROUTES` relationships as connections between services. The knowledge graph uses `CALLS` when request metrics exist for the connection and `ROUTES` when they don’t. Both show the same topology. Other relationship types, such as `CONTROLS` and `HOSTS`, build the hierarchy you navigate from a Namespace down to a Pod.

For the example, the resulting graph is:

![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```none
Namespace messaging ─CONTROLS→ Service message-router ─CONTROLS→ Pod message-router-6c9d7-x2k4q
                                                       ─CONTROLS→ Pod message-router-6c9d7-p8m2z
Service sms-gateway ─CALLS→ Service message-router ─CALLS→ Service carrier-connector
```

## Add your own rules

You can add custom entity and relationship rules in the same format. A custom rule can define a new entity type, add a `definedBy` or `enrichedBy` query to an existing type, or add relationships between entities.

Custom rules merge with the built-in rules. An entity that a custom rule returns with the same type, name, and scope is the same entity, not a copy.

For example, the following rule creates a `Component` entity from a service catalog metric and connects it to the Service with the same name:

YAML ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```yaml
entities:
  - type: Component
    name: service
    definedBy:
      - query: group by (service, team) (service_catalog_info)
        labelValues:
          team: team
relations:
  - type: CONTROLS
    startEntityType: Component
    endEntityType: Service
    definedBy:
      source: PROPERTY_MATCH
      startEntityProperties: [name]
      endEntityProperties: [name]
```

To add custom rules, refer to [Manage entities and relations](https://grafana.com/docs/grafana-cloud/knowledge-graph/configure/manage-entities-relations/) or [Add a custom metric to the knowledge graph](https://grafana.com/docs/grafana-cloud/knowledge-graph/configure/add-custom-metric/).

## Check each stage

If a Service is missing or looks wrong, run the following queries in order in Explore against your Grafana Cloud Prometheus data source. The first query that returns nothing tells you which stage to investigate. Replace `messaging` and `message-router` with your namespace and workload, and `env` with your environment label.

1. Check that the environment label is set (stage 1). A row with an empty `asserts_env` isn’t included. Compare its labels with your environment settings and filters.
   
   promql ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy
   
   ```promql
   count by (env, asserts_env, asserts_site) (kube_pod_owner{namespace="messaging"})
   ```
2. Check that each Pod maps to a workload (stage 2). An empty result means stage 1 failed, or the owner chain of the Pod isn’t one of the seven supported patterns.
   
   promql ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy
   
   ```promql
   count by (workload, workload_type, asserts_site) (asserts:mixin_pod_workload{namespace="messaging"})
   ```
3. Check whether OpenTelemetry names the Service (stage 3). If this query returns a row, the Service is named by its OpenTelemetry `service.name` instead of its workload name.
   
   promql ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy
   
   ```promql
   asserts:mixin_workload_job{namespace="messaging", otel_service!=""}
   ```
4. Check that there are calls to draw (stage 3). Each series becomes a `CALLS` relationship if both ends exist as Services in the same scope.
   
   promql ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy
   
   ```promql
   asserts:relation:calls{workload="message-router"} or asserts:relation:calls{dst_workload="message-router"}
   ```

For common causes and fixes, refer to [Troubleshoot entity discovery by stage](https://grafana.com/docs/grafana-cloud/knowledge-graph/get-started/troubleshooting/#troubleshoot-entity-discovery-by-stage). If the checks don’t explain the problem, contact Support.
