> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo Prometheus Metric Instrumentation

> A hands-on lab demonstrating Prometheus and OpenTelemetry instrumentation in a FastAPI Cat API, covering system and business metrics, deployment, and validation with Grafana.

In this lesson we'll extend instrumentation concepts with hands-on practice using both manual Prometheus instrumentation and OpenTelemetry auto-instrumentation. The sample application is a small FastAPI "Cat API" that demonstrates:

* OpenTelemetry auto-instrumentation for HTTP and system metrics (configured inside the application).
* Prometheus manual instrumentation to capture cat-specific business metrics.

Welcome banner (environment):

```bash theme={null}
Welcome to the KodeKloud Hands-On lab

K O D E K L O U D

All rights reserved

controlplane ~ »
```

The monitoring stack (Prometheus + Grafana) is already deployed in the `monitoring` namespace for this lab. Use `kubectl get po -n monitoring` to confirm pods are running before continuing.

Verification: check the monitoring pods

```bash theme={null}
kubectl get po -n monitoring
```

Example output:

```bash theme={null}
NAME                                                   READY   STATUS    RESTARTS   AGE
prometheus-prometheus-stack-kube-prom-prometheus-0     2/2     Running   0          5m
prometheus-stack-grafana-86cf754f4f-zm7dm              2/2     Running   0          5m
prometheus-stack-kube-prom-operator-6fd9d6bf6f-mhxjq   1/1     Running   0          5m
```

Deploy the Cat API into the `default` namespace

```bash theme={null}
kubectl apply -f app/k8s/deployment.yaml
kubectl apply -f app/k8s/service.yaml
```

Wait for the Cat API pod to become Ready:

```bash theme={null}
kubectl get po -w
```

Example pod lifecycle:

```bash theme={null}
NAME                            READY   STATUS    RESTARTS   AGE
cat-api-6566c5b99f-mxt6x        0/1     Running   0          7s
cat-api-6566c5b99f-mxt6x        1/1     Running   0          14s
```

Deployment manifest (app/k8s/deployment.yaml)

```yaml theme={null}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cat-api
  namespace: default
  labels:
    app: cat-api
spec:
  replicas: 1
  selector:
    matchLabels:
      app: cat-api
  template:
    metadata:
      labels:
        app: cat-api
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8000"
        prometheus.io/path: "/metrics"
    spec:
      containers:
      - name: cat-api
        image: kodekloud/cat-api:latest
        imagePullPolicy: IfNotPresent
        ports:
        - name: http
          containerPort: 8000
          protocol: TCP
        livenessProbe:
          httpGet:
            path: /
            port: http
          initialDelaySeconds: 20
          periodSeconds: 20
        readinessProbe:
          httpGet:
            path: /
            port: http
          initialDelaySeconds: 20
          periodSeconds: 20
```

The deployment includes Prometheus scrape annotations so the cluster Prometheus can automatically discover and scrape the application on port 8000 at `/metrics`. This avoids needing a separate ServiceMonitor for the simple lab setup.

Accessing the Cat API UI

* The Cat API UI exposes endpoints to:
  * View current cat mood metrics (JSON).
  * Retrieve Prometheus metrics text at `/metrics`.
  * Generate a random cat GIF and get JSON metadata.
  * Make the cat "chase" a laser pointer (returns JSON metadata).

Example JSON returned for "collective cat mood":

```json theme={null}
{
  "advice": "More treats recommended \ud83d\udc1f",
  "current_moods": {
    "grumpy": 0.5000035167267555,
    "happy": 5.417823941239602,
    "hungry": 7.461537478765501,
    "playful": 7.50489689069805,
    "sleepy": 3.8884124368218203
  },
  "dominant_mood": "playful"
}
```

Example JSON returned when generating a random GIF:

```json theme={null}
{
  "caption": "\u2328\ufe0f\ud83d\udc31 Cat on keyboard typing",
  "timestamp": 1787024797.4863682,
  "type": "keyboard",
  "url": "/static/gifs/keyboard-cat.gif"
}
```

OpenTelemetry auto-instrumentation setup

Open the application file at `app/catapi.py` (or `catapi.py` at the app root). The section titled "OpenTelemetry auto-instrumentation setup" is located around lines 24–89 in this repository. In that section you will typically see the following imports and initialization patterns:

```python theme={null}
from opentelemetry.exporter.prometheus import PrometheusMetricReader
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.instrumentation.system_metrics import SystemMetricsInstrumentor
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
```

What each piece does

* PrometheusMetricReader: exposes a Prometheus-compatible metrics endpoint so Prometheus can scrape metrics produced by OpenTelemetry.
* MeterProvider + set\_meter\_provider: configures the OpenTelemetry metrics SDK so code and instrumentations can create and record metrics.
* SystemMetricsInstrumentor: automatically collects system-level metrics (CPU, memory, etc.) without manual metric definitions.
* FastAPIInstrumentor: auto-instruments FastAPI to capture HTTP request metrics/traces (latency, status codes, etc.)

Summary table: OpenTelemetry components used

| Component | Purpose | Example import |
| - | - | - |
| Metric exporter | Exposes metrics in a Prometheus format | `from opentelemetry.exporter.prometheus import PrometheusMetricReader` |
| Meter provider | Registers the metrics SDK | `from opentelemetry.sdk.metrics import MeterProvider` |
| System metrics instrumentation | Auto-collects system CPU/memory/disk metrics | `from opentelemetry.instrumentation.system_metrics import SystemMetricsInstrumentor` |
| HTTP/FastAPI instrumentation | Auto-instruments web framework requests and internals | `from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor` |

Typical initialization sequence in `catapi.py`

1. Create a `PrometheusMetricReader` and configure it with the `MeterProvider`.
2. Call `set_meter_provider` to wire the SDK into the application.
3. Initialize `SystemMetricsInstrumentor()` to gather system metrics.
4. Instrument the FastAPI app with `FastAPIInstrumentor()` to capture HTTP metrics.

This order ensures system and HTTP metrics are registered with the same MeterProvider and that the Prometheus-compatible reader exposes them at the app's metrics endpoint for scraping.

Manual Prometheus instrumentation (business metrics)

* In addition to auto-instrumentation, the application may include manual Prometheus metrics for domain-specific data (e.g., counters, histograms for cat actions). These are typically created using the Prometheus client library (e.g., `prometheus_client`) and exposed on `/metrics`, or via OpenTelemetry metrics translated for Prometheus via `PrometheusMetricReader`.

How to validate metrics are scrapped

1. Open the application `/metrics` endpoint (port 8000) using port-forwarding or from inside the cluster.
2. Confirm you see both Prometheus-style metrics and OpenTelemetry-provided metrics (system and HTTP metrics).
3. In Grafana, open dashboards (if provided) or create panels that query Prometheus for the app metrics.

Example: port-forward to test locally

```bash theme={null}
kubectl port-forward svc/cat-api 8000:8000
# then visit http://localhost:8000/metrics
```

If the `/metrics` endpoint is not reachable, verify: (1) the pod is Ready, (2) the service is created and targets the correct port, and (3) no network policies block access.

References and links

* Prometheus: [https://prometheus.io/](https://prometheus.io/)
* OpenTelemetry: [https://opentelemetry.io/](https://opentelemetry.io/)
* FastAPI: [https://fastapi.tiangolo.com/](https://fastapi.tiangolo.com/)
* Grafana: [https://grafana.com/](https://grafana.com/)
* Kubernetes docs: [https://kubernetes.io/docs/](https://kubernetes.io/docs/)

Question: In the OpenTelemetry auto-instrumentation section of `catapi.py`, which two instrumentors are initialized to collect system and HTTP metrics?

Answer: SystemMetricsInstrumentor and FastAPIInstrumentor.

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/grafana-prometheus-for-metrics-driven-observability/module/f101faec-1de6-4831-b109-d9edcafb246c/lesson/aaf3a402-efae-4852-a57c-72bfb3fe5301)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.