Every vSphere admin has had this ticket: “the app is slow, is it the storage?” The app team has a trace showing a database call taking half a second. You have a datastore that looks fine at the five-minute rollup. Both of you are probably right, and nobody can prove it, because the trace stops at the pod and your charts start at the VM. This post closes that gap. Using the stack from parts 2 to 5, it follows one slow API request from a span in Tempo to the pod, the node VM, the ESXi host and the datastore, with the exact query at each hop, and it is honest about which hops are automatic and which are a join you have to build.

Level: advanced  ·  Stack: everything from parts 2 to 5 (vcenter receiver, ESXi syslog, Tempo, Mimir or Prometheus, Loki, Grafana, in-cluster agents with the k8s.node.name join), a Kubernetes cluster on vSphere with the vSphere CSI driver, PostgreSQL 16, Python 3.12  ·  Build time: about 90 minutes, plus 15 minutes of deliberately broken storage


Contents

  1. The scenario
  2. What the stack from parts 2 to 5 gives you
  3. The drill-down path
  4. The demo app
  5. Grafana correlation setup
  6. End-to-end workflow: build the lab and break it
  7. The investigation, hop by hop
  8. Timeline of the incident
  9. Where correlation is a join you configure
  10. Runbook: slow app on vSphere, layer by layer
  11. Troubleshooting

01. The scenario

A small service, orders-api, accepts POST /orders and writes each order to PostgreSQL. PostgreSQL runs as a StatefulSet in the same Kubernetes cluster, on a PersistentVolume that the vSphere CSI driver created as a CNS volume on a shared datastore. Every request does one INSERT and one COMMIT, and with synchronous_commit on, the COMMIT does not return until the write-ahead log has been flushed to disk. That makes commit time a direct, per-request measurement of write latency on the datastore underneath, which is exactly the property you want in a demo about storage.

Then a different workload, on a different node VM, starts hammering the same datastore with random writes. Nothing on the database’s node VM changes. Its CPU is idle, its memory is fine, Kubernetes sees nothing wrong. Requests just get slow. The question is how quickly you can get from “POST /orders p95 is up” to “the fio job in namespace noise is saturating ds-01″, and how much of that path is evidence rather than intuition.

Lab only. The noisy neighbour in this post exists to degrade a datastore. Run it only on a datastore that carries nothing you care about. On shared production storage it is an outage generator, and your storage team will be right to be annoyed.

02. What the stack from parts 2 to 5 gives you

Correlation only works if the labels line up, so here is the contract this post relies on. If your names differ, change the queries, not the idea.

SignalSource (part)Where it landsLabels this post relies on
Traces from orders-apiOTel Python SDK through the node agent (5)Temporesource.service.name, resource.k8s.pod.name, resource.k8s.node.name, span.http.route
Container logsfile_log in the node agent (5)LokiIndex labels k8s_namespace_name, k8s_pod_name, k8s_deployment_name; trace_id= in the line
Pod and node metricskubelet_stats (5)Mimir or Prometheusk8s_node_name, k8s_namespace_name, k8s_pod_name
Guest OS disk countershost_metrics (5)Mimir or Prometheusk8s_node_name, device, direction
Node VM metricsvcenter receiver plus transform/k8s_join (2, 5)Mimir or Prometheusk8s_node_name, vcenter_vm_name, vcenter_host_name, object, direction, disk_type
ESXi host metricsvcenter receiver (2)Mimir or Prometheusvcenter_host_name, object (device), direction
ESXi logssyslog pipeline (3)LokiYour part 3 stream selector; this post uses {service_name="esxi"} with the host in host_name
Span metricsTempo metrics-generator (4)Mimir or Prometheustraces_spanmetrics_latency_bucket with service, span_name, span_kind, status_code

Metric names assume the default OTLP to Prometheus translation: dots to underscores, unit suffixes added (ms becomes _milliseconds, % becomes _percent, s on a counter becomes _seconds_total), and units in braces such as {KiBy/s} adding nothing. So vcenter.vm.disk.latency.avg is vcenter_vm_disk_latency_avg_milliseconds and vcenter.vm.disk.throughput is vcenter_vm_disk_throughput.

One number you must understand before you start

The vcenter receiver asks vCenter for the real-time (20 second) interval with MaxSample: 1. Each collection therefore returns one 20 second sample per counter, not an average of everything since the last collection. At the default collection_interval of 2 minutes you see one sixth of the time; at 1 minute, one third. A 30 second latency spike between collections never shows up. Traces see every request, and host_metrics disk counters are cumulative, so rate() over them covers every second. That is why the investigation below uses the guest counters as the dense signal and vCenter as the authoritative but sampled one. For this lab, set the vcenter receiver to collection_interval: 1m.

03. The drill-down path

1. Request / traceTempo, TraceQLWhat to look fororders.commit span dominates POST /orderstrace_idautomatic (log correlation)2. Pod and logsLoki, LogQLWhat to look forslow commit lines, same trace_idk8s.node.nameautomatic (k8s_attributes)3. Node guest OSPrometheus, PromQLWhat to look fordata disk write await up, CPU mostly idlek8s.node.name = vcenter.vm.nameconfigured (transform rule)4. Node VMvcenter receiverWhat to look forvirtual disk write latency up, CPU ready flatvcenter.host.nameautomatic (VM resource attr)5. ESXi hostvcenter receiverWhat to look fordevice latency up on every host using itPV to CNS volume to datastoremanual (kubectl + govc)6. Datastore / arraygovc, ESXi logs, arrayWhat to look forneighbour PVC on same datastore, heavy writes
Figure 1. Six layers, five hops. Green hops are joins the data already carries. Amber hops are a rule you configured in part 5 or a lookup you do by hand.

The path is deliberately ordered from the user’s experience downward. Each hop answers one question and hands a key to the next: a trace ID, a pod name, a node name, a host name, a volume ID. If a hop’s answer is “normal”, you have learned something too: the problem is above it.

04. The demo app

About eighty lines of Flask. The only deliberate design choice is the manual span around conn.commit(). The psycopg instrumentation creates spans for execute(), not for commit(), so without that span the fsync time would show up as unexplained gap inside the request span. One extra span turns “the request was slow” into “the commit was slow”, and that distinction is the first fork in the investigation.

app.py

# app.py: orders-api, a deliberately small Flask service that writes to PostgreSQL.
# Every POST /orders is one INSERT plus one COMMIT. With synchronous_commit on,
# the COMMIT waits for the WAL fsync, so its duration tracks the write latency of
# the datastore under the PVC. That is the whole point of the demo.
import json
import logging
import os
import time
import uuid

import psycopg
from flask import Flask, jsonify, request
from opentelemetry import trace

DSN = (
    f"host={os.environ['DB_HOST']} dbname={os.environ['DB_NAME']} "
    f"user={os.environ['DB_USER']} password={os.environ['DB_PASSWORD']} connect_timeout=5"
)
SLOW_COMMIT_MS = float(os.environ.get("SLOW_COMMIT_MS", "200"))

app = Flask(__name__)
log = logging.getLogger("orders")
tracer = trace.get_tracer("orders-api")


def init_schema() -> None:
    for attempt in range(30):  # PostgreSQL may still be initialising its PVC
        try:
            with psycopg.connect(DSN) as conn:
                conn.execute(
                    "CREATE TABLE IF NOT EXISTS orders ("
                    " id uuid PRIMARY KEY, created timestamptz DEFAULT now(), body jsonb NOT NULL)"
                )
            return
        except psycopg.OperationalError as exc:
            log.warning("database not ready (attempt %d): %s", attempt + 1, exc)
            time.sleep(2)
    raise SystemExit("database never became ready")


@app.get("/healthz")
def healthz():
    return "ok"


@app.post("/orders")
def create_order():
    order = request.get_json(force=True, silent=True) or {}
    order_id = str(uuid.uuid4())
    payload = json.dumps({**order, "pad": "x" * 2048})  # ~2 KiB row, enough WAL per commit

    # psycopg instrumentation traces execute(); it does not trace commit(),
    # so wrap the commit in our own span to make fsync time visible.
    with psycopg.connect(DSN) as conn:
        conn.execute("INSERT INTO orders (id, body) VALUES (%s, %s)", (order_id, payload))
        with tracer.start_as_current_span("orders.commit") as span:
            t0 = time.perf_counter()
            conn.commit()
            commit_ms = (time.perf_counter() - t0) * 1000
            span.set_attribute("orders.commit_ms", round(commit_ms, 1))

    if commit_ms > SLOW_COMMIT_MS:
        log.warning("slow commit order_id=%s commit_ms=%.1f", order_id, commit_ms)
    return jsonify(id=order_id, commit_ms=round(commit_ms, 1)), 201


@app.get("/orders/<order_id>")
def get_order(order_id):
    with psycopg.connect(DSN) as conn:
        row = conn.execute("SELECT id, created FROM orders WHERE id = %s", (order_id,)).fetchone()
    if row is None:
        return jsonify(error="not found"), 404
    return jsonify(id=str(row[0]), created=row[1].isoformat())


init_schema()

requirements.txt and Dockerfile

flask==3.1.*
gunicorn==27.*
psycopg[binary]==3.3.*
# Distro + OTLP exporters. Keep the contrib (0.xxbN) and SDK (1.xx) lines in step;
# 0.66b2 pairs with SDK 1.45.x. Bump both together.
opentelemetry-distro[otlp]==0.66b2
opentelemetry-instrumentation-logging==0.66b2   # trace_id/span_id in log lines
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt \
 && opentelemetry-bootstrap -a install     # adds flask, psycopg, logging instrumentations
COPY app.py .
RUN useradd -u 10001 -m app
USER 10001
EXPOSE 8080
# opentelemetry-instrument wires the SDK from OTEL_* env vars before gunicorn imports app.py.
# One worker with threads keeps the demo free of pre-fork SDK caveats.
CMD ["opentelemetry-instrument", "gunicorn", "-b", "0.0.0.0:8080", "-w", "1", "--threads", "8", "app:app"]

opentelemetry-instrument configures the SDK from OTEL_* environment variables and loads the Flask, psycopg and logging instrumentations that opentelemetry-bootstrap installed. With OTEL_PYTHON_LOG_CORRELATION=true, the logging instrumentation rewrites the log format to include trace_id= and span_id=, which is what lets Loki link back to Tempo. Logs go to stdout and reach Loki through the node agent’s file_log receiver, the same path every other pod uses.

Manifests: database, API, load

Vanilla clusters with the vSphere CSI driver can pin the lab to one datastore with a StorageClass. On VKS, use a StorageClass published from a vSphere storage policy instead, and confirm placement with the govc check in step 7.

# Vanilla/RKE2/kubeadm clusters with the vSphere CSI driver only.
# On VKS, use a StorageClass the Supervisor publishes from a vSphere storage policy
# (kubectl get storageclass) and skip this file.
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: demo-ds01
provisioner: csi.vsphere.vmware.com
parameters:
  # Pin the lab to one datastore so the noisy neighbour lands on the same one.
  # Datastore URL from: govc datastore.info <DATASTORE> | awk '/URL:/{print $2}'
  datastoreurl: "<DATASTORE_URL>"      # e.g. ds:///vmfs/volumes/<uuid>/
  csi.storage.k8s.io/fstype: ext4
reclaimPolicy: Delete
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true
# orders-demo.yaml: PostgreSQL on a vSphere-backed PVC, the orders-api, and a load generator.
# kubectl create secret generic orders-db -n shop --from-literal=password="$(openssl rand -hex 16)"
# kubectl apply -f orders-demo.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: shop
  labels:
    pod-security.kubernetes.io/enforce: restricted
---
apiVersion: v1
kind: Service
metadata: { name: orders-db, namespace: shop }
spec:
  clusterIP: None
  selector: { app: orders-db }
  ports: [{ name: pg, port: 5432 }]
---
apiVersion: apps/v1
kind: StatefulSet
metadata: { name: orders-db, namespace: shop }
spec:
  serviceName: orders-db
  replicas: 1
  selector: { matchLabels: { app: orders-db } }
  template:
    metadata: { labels: { app: orders-db } }
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 999          # the postgres user in the official image
        fsGroup: 999
        seccompProfile: { type: RuntimeDefault }
      containers:
        - name: postgres
          image: postgres:16
          args: ["-c", "synchronous_commit=on", "-c", "shared_buffers=256MB"]
          env:
            - { name: POSTGRES_DB, value: orders }
            - { name: POSTGRES_USER, value: orders }
            - name: POSTGRES_PASSWORD
              valueFrom: { secretKeyRef: { name: orders-db, key: password } }
            - { name: PGDATA, value: /var/lib/postgresql/data/pgdata }
          ports: [{ containerPort: 5432, name: pg }]
          securityContext:
            allowPrivilegeEscalation: false
            capabilities: { drop: ["ALL"] }
          readinessProbe:
            exec: { command: ["pg_isready", "-U", "orders", "-d", "orders"] }
            periodSeconds: 5
          resources:
            requests: { cpu: 250m, memory: 512Mi }
            limits:   { memory: 1Gi }
          volumeMounts:
            - { name: data, mountPath: /var/lib/postgresql/data }
  volumeClaimTemplates:
    - metadata: { name: data }
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: <STORAGE_CLASS>   # demo-ds01, or the VKS policy-backed class
        resources: { requests: { storage: 20Gi } }
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: orders-api, namespace: shop }
spec:
  replicas: 2
  selector: { matchLabels: { app: orders-api } }
  template:
    metadata: { labels: { app: orders-api } }
    spec:
      securityContext:
        runAsNonRoot: true
        seccompProfile: { type: RuntimeDefault }
      containers:
        - name: orders-api
          image: <REGISTRY>/orders-api:1.0
          ports: [{ containerPort: 8080, name: http }]
          env:
            - { name: DB_HOST, value: orders-db-0.orders-db.shop.svc.cluster.local }
            - { name: DB_NAME, value: orders }
            - { name: DB_USER, value: orders }
            - name: DB_PASSWORD
              valueFrom: { secretKeyRef: { name: orders-db, key: password } }
            # OpenTelemetry SDK configuration
            - { name: OTEL_SERVICE_NAME, value: orders-api }
            - { name: OTEL_EXPORTER_OTLP_ENDPOINT, value: "http://otel-agent.observability.svc.cluster.local:4318" }
            - { name: OTEL_EXPORTER_OTLP_PROTOCOL, value: http/protobuf }
            - { name: OTEL_TRACES_EXPORTER, value: otlp }
            - { name: OTEL_METRICS_EXPORTER, value: none }   # span metrics come from Tempo
            - { name: OTEL_LOGS_EXPORTER, value: none }      # logs go via stdout + file_log
            - { name: OTEL_PYTHON_LOG_CORRELATION, value: "true" }
            - name: K8S_POD_IP
              valueFrom: { fieldRef: { fieldPath: status.podIP } }
            - name: K8S_POD_UID
              valueFrom: { fieldRef: { fieldPath: metadata.uid } }
            - name: K8S_NODE_NAME
              valueFrom: { fieldRef: { fieldPath: spec.nodeName } }
            # Belt and braces: the agent's k8s_attributes can always associate by pod UID/IP,
            # even if a CNI or hostPort path rewrites the source address.
            - name: OTEL_RESOURCE_ATTRIBUTES
              value: "k8s.pod.ip=$(K8S_POD_IP),k8s.pod.uid=$(K8S_POD_UID),k8s.node.name=$(K8S_NODE_NAME)"
          securityContext:
            allowPrivilegeEscalation: false
            capabilities: { drop: ["ALL"] }
          readinessProbe:
            httpGet: { path: /healthz, port: http }
          resources:
            requests: { cpu: 100m, memory: 128Mi }
            limits:   { memory: 256Mi }
---
apiVersion: v1
kind: Service
metadata: { name: orders-api, namespace: shop }
spec:
  selector: { app: orders-api }
  ports: [{ name: http, port: 80, targetPort: http }]
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: orders-load, namespace: shop }
spec:
  replicas: 1
  selector: { matchLabels: { app: orders-load } }
  template:
    metadata: { labels: { app: orders-load } }
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 10002
        seccompProfile: { type: RuntimeDefault }
      containers:
        - name: load
          image: curlimages/curl:8.11.1
          command: ["/bin/sh", "-c"]
          args:
            - |
              while true; do
                curl -s -o /dev/null -w '%{http_code} %{time_total}\n' \
                  -X POST http://orders-api.shop.svc.cluster.local/orders \
                  -H 'content-type: application/json' -d '{"item":"widget","qty":1}'
                sleep 0.2
              done
          securityContext:
            allowPrivilegeEscalation: false
            capabilities: { drop: ["ALL"] }
          resources:
            requests: { cpu: 20m, memory: 16Mi }

The noisy neighbour

# noisy-neighbour.yaml: a fio job that saturates the SAME datastore from a DIFFERENT node.
# LAB ONLY. Never point this at a datastore that carries anything you care about.
# kubectl apply -f noisy-neighbour.yaml ; kubectl delete -f noisy-neighbour.yaml to stop
apiVersion: v1
kind: Namespace
metadata:
  name: noise
  labels:
    pod-security.kubernetes.io/enforce: baseline   # the job installs fio at start, so it runs as root
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: fio-scratch, namespace: noise }
spec:
  accessModes: ["ReadWriteOnce"]
  storageClassName: <STORAGE_CLASS>   # same class (and so same datastore) as orders-db
  resources: { requests: { storage: 40Gi } }
---
apiVersion: batch/v1
kind: Job
metadata: { name: fio-noise, namespace: noise }
spec:
  backoffLimit: 0
  template:
    metadata: { labels: { app: fio-noise } }
    spec:
      restartPolicy: Never
      affinity:
        # Run on a different node VM from the database, so the only shared thing is the datastore.
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - topologyKey: kubernetes.io/hostname
              namespaceSelector: {}
              labelSelector: { matchLabels: { app: orders-db } }
      containers:
        - name: fio
          image: alpine:3.20        # air-gapped? mirror an image with fio preinstalled instead
          command: ["/bin/sh", "-c"]
          args:
            - |
              apk add --no-cache fio >/dev/null && \
              fio --name=noise --filename=/scratch/fio.bin --size=30G \
                  --rw=randwrite --bs=64k --ioengine=libaio --direct=1 \
                  --iodepth=32 --numjobs=4 --time_based --runtime=900 \
                  --group_reporting
          resources:
            requests: { cpu: 500m, memory: 256Mi }
          volumeMounts:
            - { name: scratch, mountPath: /scratch }
      volumes:
        - name: scratch
          persistentVolumeClaim: { claimName: fio-scratch }

The anti-affinity rule matters. It puts fio on a different node VM from PostgreSQL, so the only thing the two share is the datastore. If they shared a node VM, the guest’s own block queue would muddy the result and you would learn less.

05. Grafana correlation setup

Grafana does not discover relationships between signals. Every link you click in this investigation exists because a data source was configured to build it. This provisioning file creates all of them in one place: trace to logs, trace to metrics (including the node VM and its ESXi host), log line to trace, and metric exemplar to trace.

# /etc/grafana/provisioning/datasources/vsphere-correlation.yaml
# Grafana provisioning expands $VAR, so every literal $ in a query is written $$.
apiVersion: 1

datasources:
  - name: Tempo
    type: tempo
    uid: tempo
    url: http://<TEMPO_QUERY_HOST>:3200
    access: proxy
    jsonData:
      serviceMap:
        datasourceUid: prometheus
      nodeGraph:
        enabled: true
      tracesToLogsV2:
        datasourceUid: loki
        spanStartTimeShift: "-2m"
        spanEndTimeShift: "2m"
        filterByTraceID: true        # appends |= "<traceId>" to the generated LogQL
        filterBySpanID: false
        tags:
          # span/resource attribute -> Loki label (both are Loki index labels by default)
          - { key: k8s.namespace.name, value: k8s_namespace_name }
          - { key: k8s.deployment.name, value: k8s_deployment_name }
      tracesToMetrics:
        datasourceUid: prometheus
        spanStartTimeShift: "-10m"   # vCenter samples are sparse; give the panel context
        spanEndTimeShift: "10m"
        tags:
          - { key: k8s.node.name, value: k8s_node_name }
        queries:
          - name: "Guest disk await, ms (node)"
            query: >-
              1000 * sum by (device) (rate(system_disk_operation_time_seconds_total{$$__tags, direction="write"}[2m]))
              / sum by (device) (rate(system_disk_operations_total{$$__tags, direction="write"}[2m]))
          - name: "Node VM virtual disk latency, ms (vCenter)"
            query: >-
              max by (vcenter_vm_name, vcenter_host_name, object, direction)
              (vcenter_vm_disk_latency_avg_milliseconds{$$__tags, disk_type="virtual"})
          - name: "Node VM CPU ready, % (vCenter)"
            query: vcenter_vm_cpu_readiness_percent{$$__tags}
          - name: "ESXi host device latency, ms (host running this node VM)"
            query: >-
              max by (vcenter_host_name, object, direction) (
                vcenter_host_disk_latency_avg_milliseconds
                * on (vcenter_host_name) group_left
                (0 * max by (vcenter_host_name) (vcenter_vm_cpu_readiness_percent{$$__tags}) + 1)
              )

  - name: Loki
    type: loki
    uid: loki
    url: http://<LOKI_QUERY_HOST>:3100
    access: proxy
    jsonData:
      derivedFields:
        # Python log correlation writes "trace_id=<32 hex>" into the log line.
        - name: TraceID
          matcherType: regex
          matcherRegex: "trace_id=(\\w{32})"
          datasourceUid: tempo
          url: "$${__value.raw}"
          urlDisplayLabel: "Open trace"
        # Logs that arrive over OTLP carry trace_id as structured metadata instead.
        - name: trace_id
          matcherType: label
          matcherRegex: "trace_id"
          datasourceUid: tempo
          url: "$${__value.raw}"
          urlDisplayLabel: "Open trace"

  - name: Prometheus
    type: prometheus
    uid: prometheus
    url: <PROMETHEUS_OR_MIMIR_QUERY_URL>
    access: proxy
    jsonData:
      exemplarTraceIdDestinations:
        # Tempo's metrics-generator labels exemplars traceID unless you changed trace_id_label_name.
        - name: traceID
          datasourceUid: tempo

A few details that are easy to get wrong:

  • Escaping. Grafana expands $VAR in provisioning files, so every literal dollar sign in a query is written $$. In the UI you write a single $.
  • Tag mapping. In tracesToMetrics, the tag k8s.node.name is mapped to the Prometheus label k8s_node_name, and $__tags expands to k8s_node_name="<value from the span>". Grafana looks the tag up in both span and resource attributes, so the resource attribute the agent added is found.
  • The host query is a join, not a lookup. The span does not know which ESXi host ran the node VM. The fourth query multiplies host device latency by a one-valued vector derived from the node VM’s own metric, which keeps only the host currently carrying vcenter_host_name for that node. That is the part 5 label doing its job.
  • Logs. k8s_namespace_name and k8s_deployment_name are among the resource attributes Loki indexes by default for OTLP logs. k8s_node_name is not; it is stored as structured metadata, so filter on it after the stream selector, not inside it.

A dashboard panel with data links

For the other direction, from a pod list to vSphere dashboards, add this table panel to the Kubernetes dashboard from part 4. Each row is a pod with its node VM’s worst virtual disk latency, and the row links open the vSphere VM and host dashboards with the time range preserved.

{
  "type": "table",
  "title": "Pods by node VM disk latency (vCenter, worst virtual disk)",
  "datasource": { "type": "prometheus", "uid": "prometheus" },
  "targets": [
    {
      "refId": "A",
      "instant": true,
      "format": "table",
      "expr": "max by (k8s_node_name, vcenter_host_name) (vcenter_vm_disk_latency_avg_milliseconds{disk_type=\"virtual\"})\n* on (k8s_node_name) group_right (vcenter_host_name)\n(max by (k8s_node_name, k8s_namespace_name, k8s_pod_name) (k8s_pod_memory_working_set_bytes{k8s_namespace_name=~\"$namespace\"}) * 0 + 1)"
    }
  ],
  "fieldConfig": {
    "defaults": {
      "unit": "ms",
      "thresholds": {
        "mode": "absolute",
        "steps": [
          { "color": "green", "value": null },
          { "color": "orange", "value": 20 },
          { "color": "red", "value": 50 }
        ]
      },
      "links": [
        {
          "title": "Node VM in the vSphere VM dashboard",
          "url": "/d/<VSPHERE_VM_DASHBOARD_UID>/vsphere-vm?var-node=${__data.fields.k8s_node_name}&${__url_time_range}"
        },
        {
          "title": "ESXi host in the vSphere host dashboard",
          "url": "/d/<VSPHERE_HOST_DASHBOARD_UID>/vsphere-host?var-host=${__data.fields.vcenter_host_name}&${__url_time_range}"
        }
      ]
    },
    "overrides": []
  },
  "options": { "sortBy": [{ "displayName": "Value", "desc": true }] }
}

06. End-to-end workflow: build the lab and break it

Step 1. Confirm part 5 is working.

count by (k8s_node_name, vcenter_host_name) (vcenter_vm_cpu_readiness_percent{k8s_node_name!=""})

Expected: One row per node VM. If this is empty, stop and fix section 06 of part 5; nothing below the pod layer will join without it.

Step 2. Build and push the image.

docker build -t <REGISTRY>/orders-api:1.0 .
docker push <REGISTRY>/orders-api:1.0

Expected: A pushed image. On an air-gapped VKS cluster, push to the registry your clusters trust (for example Harbor).

Step 3. Pick the StorageClass.

kubectl get storageclass
# vanilla only: edit storageclass.yaml, then
kubectl apply -f storageclass.yaml

Expected: The class you will put in <STORAGE_CLASS> in both manifests.

Step 4. Deploy the database, API and load generator.

kubectl create namespace shop --dry-run=client -o yaml | kubectl apply -f -
kubectl -n shop create secret generic orders-db --from-literal=password="$(openssl rand -hex 16)"
kubectl apply -f orders-demo.yaml
kubectl -n shop rollout status statefulset/orders-db
kubectl -n shop rollout status deploy/orders-api
kubectl -n shop logs deploy/orders-load --tail=5

Expected: Load generator lines such as 201 0.031: HTTP 201 and a total time in seconds.

Step 5. Check that traces carry Kubernetes and node identity (TraceQL in Grafana Explore).

{ resource.service.name = "orders-api" && span.http.route = "/orders" }
  | select(resource.k8s.pod.name, resource.k8s.node.name, span.orders.commit_ms)

Expected: Server spans with pod and node names filled in, each with a child orders.commit span.

Step 6. Load the Grafana correlation file and restart Grafana.

sudo cp grafana-correlation-datasources.yaml /etc/grafana/provisioning/datasources/
sudo systemctl restart grafana-server
curl -s -u "admin:${GRAFANA_ADMIN_PASSWORD}" http://<GRAFANA_HOST>:3000/api/datasources/uid/tempo \
  | jq -r '.jsonData.tracesToMetrics.queries[].name'

Expected: The four query names from the file. In Kubernetes-hosted Grafana, put the same YAML in the chart’s datasource provisioning values instead.

Step 7. Record a baseline, and confirm both PVCs will land on the same datastore.

kubectl -n shop get pvc data-orders-db-0 -o jsonpath='{.spec.volumeName}{"\n"}'
govc volume.ls -ds <DATASTORE>

Expected: The orders-db PV name appears in the CNS volume list for that datastore. Note the p95 of POST /orders and typical orders.commit_ms.

Step 8. Start the noisy neighbour.

kubectl apply -f noisy-neighbour.yaml
kubectl get pods -A -o wide -l 'app in (orders-db,fio-noise)'
govc volume.ls -ds <DATASTORE>

Expected: fio running on a different NODE from orders-db-0, and a second PV in the datastore’s volume list.

Step 9. Investigate, using section 07.

# follow section 07 hop by hop

Expected: You reach the fio PVC from the trace without guessing.

Step 10. Stop the noise and watch recovery.

kubectl delete -f noisy-neighbour.yaml
kubectl -n shop logs deploy/orders-load --tail=5

Expected: Request times back to baseline within a minute or two; the vCenter samples follow at the next collection.

07. The investigation, hop by hop

What follows is what you should see if the lab behaves as designed. The absolute numbers depend entirely on your array, network and datastore type, so I describe shapes and relationships rather than promising milliseconds. The shapes are what the runbook relies on.

Hop 0. Something is slow

The signal that starts the investigation is user-facing latency, ideally from Tempo’s span metrics so it alerts without anyone opening a trace:

histogram_quantile(0.95,
  sum by (le) (rate(traces_spanmetrics_latency_bucket{service="orders-api", span_kind="SPAN_KIND_SERVER"}[5m])))

If you have TraceQL metrics enabled in Tempo, the same question can be asked of the traces directly, and split by node immediately:

{ resource.service.name = "orders-api" && kind = server } | quantile_over_time(duration, .95) by (resource.k8s.node.name)

What you see: p95 climbs within seconds of fio starting. Because the database is the bottleneck, every orders-api replica is slow, whichever node it runs on. Latency that rises on every node at once is already a hint that the cause is shared, not node-local.

Hop 1. The trace: where inside the request is the time?

{ resource.service.name = "orders-api" && span.http.route = "/orders" && kind = server && duration > 300ms }
  >> { name = "orders.commit" && duration > 200ms }

This structural query returns slow requests whose descendant orders.commit span was itself slow, which separates storage-bound requests from requests that were slow for other reasons. Open one.

What you see: the server span is long, the INSERT span from psycopg is short, and orders.commit takes almost all of the time. The request is waiting for a WAL flush. The resource attributes on the span show k8s.pod.name of the API pod and its k8s.node.name. Note that this is the API pod’s node. The node you care about is the one running PostgreSQL, because that is where the flush happens. That is the first place where knowing the architecture beats following links blindly.

Find the database’s node. The commit span is measured by the client, but the flush happens wherever PostgreSQL runs. Look it up with kubectl -n shop get pod orders-db-0 -o jsonpath='{.spec.nodeName}' and call the result <DB_NODE>. If you trace the database tier itself (through a proxy or a sidecar), its spans carry their own k8s.node.name and this lookup disappears.

Hop 2. Logs for the same request

From the span, Logs for this span runs a query built from the provisioning file. Written by hand, it is:

{k8s_namespace_name="shop", k8s_deployment_name="orders-api"} |= "<TRACE_ID>"

And to see how widespread the problem is, count slow-commit warnings per pod:

sum by (k8s_pod_name) (count_over_time({k8s_namespace_name="shop", k8s_deployment_name="orders-api"} |= "slow commit" [1m]))

What you see: slow commit order_id=... commit_ms=... lines with the same trace_id, and the derived field link takes you back to the trace. The count is non-zero on every replica. Check the PostgreSQL logs too: {k8s_namespace_name="shop", k8s_pod_name="orders-db-0"}. A database that is merely slow to flush usually logs nothing at default settings, which is itself useful: no errors, no restarts, just waiting.

Hop 3. The node guest: is the VM itself busy?

Now the database’s node VM, from inside. Two questions: is the guest short of CPU, and what does the guest kernel think disk latency is?

# CPU by state on the database node (look at user, system, wait, steal)
sum by (state) (rate(system_cpu_time_seconds_total{k8s_node_name="<DB_NODE>"}[2m]))

# Guest write await per device, milliseconds
1000 * sum by (device) (rate(system_disk_operation_time_seconds_total{k8s_node_name="<DB_NODE>", direction="write"}[2m]))
  / sum by (device) (rate(system_disk_operations_total{k8s_node_name="<DB_NODE>", direction="write"}[2m]))

# The pod itself, from the kubelet
k8s_pod_cpu_usage{k8s_namespace_name="shop", k8s_pod_name="orders-db-0"}

What you see: CPU mostly idle with some wait; steal flat. The write await on one device, the one holding the PV, rises sharply while the OS disk stays flat. The pod’s CPU usage drops slightly, because it spends its time waiting. The guest is telling you the I/O is slow below it. It cannot tell you why.

Hop 4. The node VM in vCenter

This is the hop the part 5 join exists for. Same node name, vSphere’s view:

# Virtual disk latency per disk and direction, ms
max by (vcenter_vm_name, vcenter_host_name, object, direction)
  (vcenter_vm_disk_latency_avg_milliseconds{k8s_node_name="<DB_NODE>", disk_type="virtual"})

# Rule out CPU contention at the hypervisor
vcenter_vm_cpu_readiness_percent{k8s_node_name="<DB_NODE>"}

# Rule out memory pressure at the hypervisor
vcenter_vm_memory_ballooned_mebibytes{k8s_node_name="<DB_NODE>"}
vcenter_vm_memory_swapped_mebibytes{k8s_node_name="<DB_NODE>"}

What you see: write latency on one virtual disk (an object such as scsi0:1 or a later controller slot; CNS volumes attach as additional disks) rises, broadly in line with the guest await. CPU ready stays low, ballooning and swapping stay at zero. You now know two things: the guest and the hypervisor agree on the latency, so it is not a guest queueing problem, and the VM is not starved, so it is not a host CPU or memory problem. The label vcenter_host_name on the result tells you which ESXi host to look at next.

Hop 5. The ESXi host: one host or all of them?

# Device latency on the host running the database node VM
max by (object, direction) (vcenter_host_disk_latency_avg_milliseconds{vcenter_host_name="<ESXI_HOST>"})

# The same devices across every host in the cluster
max by (vcenter_host_name, object) (vcenter_host_disk_latency_avg_milliseconds{direction="write"})

What you see on a block datastore (VMFS over FC or iSCSI): the device backing the datastore (an naa. identifier) shows raised write latency on every host that mounts it, not just the one running the database. That is the most important fork in the whole investigation. Latency on one host only points at that host’s path: HBA, queue depth, a bad link. Latency on all hosts for one device points at the datastore and the array behind it.

What you see on an NFS datastore: nothing here. The host disk counters the receiver collects cover block devices, and an NFS datastore is not one. The vcenter receiver does not collect the host datastore counter group either. For NFS you go to the ESXi host’s own per-datastore counters, which govc can sample directly:

# Real-time per-datastore latency as ESXi sees it (instances are datastore identifiers, not names)
govc metric.sample -n 6 -instance '*' <HOST_INVENTORY_PATH> datastore.totalWriteLatency.average datastore.totalReadLatency.average
# e.g. <HOST_INVENTORY_PATH> = /<DATACENTER>/host/<CLUSTER>/esx02.lab.local
govc datastore.info <DATASTORE> | grep URL   # match the identifier in the URL

For VMFS, the ESXi logs from part 3 often say it out loud. The kernel reports when a device’s latency jumps well above its running average:

{service_name="esxi"} |= "performance has deteriorated"

Those vmkernel messages name the naa. device and the before and after latency in microseconds. They are a VMFS and block-device signal; NFS problems surface differently, as covered in catching NFS APD before vCenter.

Hop 6. The datastore, and who else is on it

This hop has no automatic join. Nothing in the vcenter receiver’s resource attributes connects a VM or a host device to a datastore name, and Kubernetes knows nothing about datastores at all. You walk it with kubectl and govc:

# 1. Which PV backs the database?
PV=$(kubectl -n shop get pvc data-orders-db-0 -o jsonpath='{.spec.volumeName}')
kubectl get pv "$PV" -o jsonpath='{.spec.csi.driver}{"  "}{.spec.csi.volumeHandle}{"\n"}'

# 2. Vanilla vSphere CSI: the volumeHandle is the CNS volume ID; -b prints the backing path,
#    which starts with the datastore name in square brackets
govc volume.ls -b <VOLUME_HANDLE>

# 2b. VKS: the guest volumeHandle is the name of a PVC in the Supervisor namespace.
#     Log in to the Supervisor, then follow that PVC to its PV and CNS volume:
#     kubectl -n <VSPHERE_NAMESPACE> get pvc <VOLUME_HANDLE> -o jsonpath='{.spec.volumeName}'

# 3. Every CNS volume on that datastore (CNS volume names are PV names)
govc volume.ls -ds <DATASTORE>

Then find the heaviest writers among the VMs that can reach it. This query ranks every VM’s write throughput, which on a busy cluster you will want to narrow to the hosts from hop 5:

topk(10, sum by (vcenter_vm_name, vcenter_host_name, k8s_node_name) (vcenter_vm_disk_throughput{direction="write"}))

What you see: the fio PV in the datastore’s volume list, and the node VM running the fio pod at or near the top of write throughput, with its k8s_node_name filled in because it is a cluster node. One more kubectl turns the PV into a workload: kubectl get pv <PV> -o jsonpath='{.spec.claimRef.namespace}/{.spec.claimRef.name}' returns noise/fio-scratch. The chain is complete: slow request, slow commit, slow virtual disk, slow device on every host, one neighbour writing hard to the same datastore.

The last layer, the array, belongs to the array’s own telemetry. If you collect it (the NFS datastore latency post does this for NFS), put its latency on the same time axis as the vCenter numbers; when array-side latency is low while ESXi-side latency is high, the problem is between them, in the fabric or the host’s queueing.

08. Timeline of the incident

fio noisy neighbourp95 POST /ordersVM disk latency (vCenter)Grafana alertInvestigation10:0010:0210:0410:0610:0810:1010:1210:1410:1610:1810:2010:2210:24fio randwrite 64k, iodepth 32 x 4 jobscommit time dominates every requestone 20 s sample per 1 min collectionpending (for: 5m)firingtracelogsguestVMhostdatastorefio stopped
Figure 2. The incident as each signal sees it. Traces react within seconds. vCenter reports one 20 second sample per collection, so its view is accurate but sparse. The alert waits for its pending period. Investigation runs top-down, then the noise is stopped.

The timeline makes one practical point. If the noisy neighbour had run for 40 seconds instead of 15 minutes, traces and guest counters would show it clearly and vCenter might not show it at all, depending on where the samples fell. For short storage events, trust the dense signals (traces, guest disk counters) for when, and vCenter and the array for where.

The alert in the figure is a plain Grafana rule on the span metrics p95 from hop 0, for example above 250 ms for 5 minutes. Use whatever threshold matches your service’s objective; the point is that it fires on what the user feels, not on datastore latency, which is often high for reasons nobody notices.

09. Where correlation is a join you configure

Vendors like to call this kind of investigation automatic. It is not. Some hops are carried by the data, some are rules you wrote, and one is a manual lookup. Knowing which is which tells you what will break silently.

HopMechanismConfigured whereBreaks when
Trace to logstrace_id in the log line; Grafana tracesToLogsV2 and Loki derived fieldApp (log correlation), Grafana provisioningThe app logs without trace context, or logs arrive unparsed and the regex misses
Trace to pod and nodeResource attributes from k8s_attributes and the downward APINode agent (part 5)Pod association fails (rewritten source IP and no k8s.pod.uid)
Node to node VMk8s.node.name copied from vcenter.vm.nametransform/k8s_join in the vCenter collectorNode names stop matching VM names, the regex is too narrow, or new nodes appear without regenerated rules (Option B)
Node VM to ESXi hostvcenter.host.name on VM metricsNothing; the receiver does itBriefly after vMotion, joins see two host series
Host to datastoreNone in the telemetryYou, with kubectl and govcAlways manual. Automating it means collecting CNS volume to datastore mappings yourself
Datastore to arrayTime alignment onlyArray exporter (separate post)Clocks drift, or array data is at coarser resolution than ESXi

If you take one thing from this table: the most fragile link is node to node VM, because it depends on naming. Put the count by (k8s_node_name, vcenter_host_name) (vcenter_vm_cpu_readiness_percent{k8s_node_name!=""}) query from step 1 on a dashboard and alert when its row count is lower than the cluster’s node count. When the join breaks, you find out on a quiet afternoon rather than during an incident.

10. Runbook: slow app on vSphere, layer by layer

Copy this into your team’s runbook. Work top to bottom; each row either clears a layer or tells you where to go next.

#LayerQuestionWhere to lookHealthySuspiciousNext
1RequestIs latency real, and which span holds it?Span metrics p95; TraceQL with >> to the slow child spanp95 at baselineOne child span (DB, commit, external call) dominatesDB or I/O span: row 2. CPU-bound app span: profile the app
2PodIs the workload healthy?k8s_cluster restarts and phase; pod CPU against its limit; logs with the trace IDNo restarts, CPU below limit, no errorsThrottling, restarts, error burstsFix app or limits. If clean but slow: row 3 on the node that does the I/O
3Node guestIs the VM busy, or waiting?system_cpu_time_seconds_total by state; guest write await per deviceLow wait and steal, await flatHigh await on the data disk, or high stealAwait high: row 4. Steal high: row 4, CPU ready
4Node VMDoes vSphere agree, and is the VM starved?vcenter_vm_disk_latency_avg_milliseconds, vcenter_vm_cpu_readiness_percent, ballooned and swapped memoryVirtual disk latency low, CPU ready low, no balloon or swapDisk latency matches guest await; or CPU ready highDisk: row 5. CPU ready: host or cluster CPU contention, DRS
5ESXi hostOne host or every host?vcenter_host_disk_latency_avg_milliseconds by host and device; ESXi logs; for NFS, govc metric.sample datastore countersDevice latency low on all hostsHigh on one host only, or high on all hosts for one deviceOne host: host path (HBA, NIC, queue depth). All hosts: row 6
6DatastoreWhat else is on it, and who is writing?govc volume.ls -ds; top VM write throughput; datastore utilizationNo unusual neighbour, utilization normalOne neighbour dominating writes; datastore nearly fullMove or throttle the neighbour (Storage I/O Control, storage policy, separate datastore); then row 7
7ArrayIs the array itself slow?Array telemetry on the same time axisArray latency lowArray latency highStorage team. If array is fast but ESXi slow: the fabric between them

11. Troubleshooting

SymptomLikely causeCheckFix
No orders.commit spans, only server spansImage built without the SDK, or opentelemetry-instrument not in the commandkubectl -n shop exec deploy/orders-api -- pip list | grep opentelemetryRebuild with the Dockerfile as given; check OTEL_TRACES_EXPORTER=otlp.
Traces present but no k8s.node.nameAgent association failed and downward API env missingSpan resource attributes in TempoKeep the OTEL_RESOURCE_ATTRIBUTES env from the manifest; verify agent k8s_attributes config.
Logs for this span returns nothingTag mapping mismatch, or log lines lack trace_id=Run the LogQL by hand; look at a raw log lineCheck OTEL_PYTHON_LOG_CORRELATION; make the Loki labels in tags match your streams exactly.
Trace-to-metrics VM query is emptyk8s_node_name not on vCenter metrics, or the span came from a different node than expectedStep 1 queryFix transform/k8s_join; remember the API pod and database pod can be on different nodes.
Guest await rises but vCenter shows nothingSpike fell between vCenter samplesCompare with a 1 minute vcenter collection intervalLower collection_interval for the lab; rely on guest counters for timing.
No host device latency rowsNFS datastore (not a block device), or statistics level too lowDatastore type in vCenterUse govc metric.sample on datastore.* counters; for VMFS, check the statistics level (part 2).
fio lands on another datastoreStorage policy matched more than one datastoregovc volume.ls -ds <DATASTORE>Pin with datastoreurl (vanilla) or a policy that matches one datastore.
fio barely moves latencyArray absorbs the load (cache, all-flash)fio output bandwidth and IOPSIncrease numjobs or iodepth, or run two fio jobs on two nodes. A fast array is a good problem.
PostgreSQL pod fails Pod SecurityRestricted standard and image defaultsEvents in shopKeep the runAsUser: 999 and fsGroup: 999 settings from the manifest.
many-to-many matching not allowed in the panelNode VM vMotioned; two host series in the lookbackRun each side separatelyDrop vcenter_host_name from the left-hand by clause.

What’s next

That is the series payoff: one trace, six layers, and an honest map of which links are data and which are your configuration. From here the posts go deeper on single layers. NFS datastore latency with OpenTelemetry fills in the hop this post had to do by hand for NFS, and catching NFS APD before vCenter does the same with logs. Sizing the OTel collector for vSphere covers the collection interval trade-off that limits how dense the vCenter view can be. If you want the previous building blocks: part 5 for the in-cluster agents and the node identity join, part 4 for Tempo, Loki and Grafana, and part 3 for ESXi logs. For background on the storage side, see NFSv3 and NFSv4.1 in vSphere and the ESXi log analyser.

Written against OpenTelemetry Collector 0.166, OpenTelemetry Python SDK 1.45 with contrib 0.66b2, Grafana’s Tempo, Loki and Prometheus data source provisioning as documented in December 2026, vSphere 8 and VCF 9. The investigation describes the expected shape of each signal, not measured values; your numbers depend on your array. Run the noisy neighbour only on a lab datastore.

Leave a Reply