> ## 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.

# In Code Metric Instrumentation

> Guidance on instrumenting applications to expose Prometheus metrics, defining counters gauges histograms, exposing endpoints, avoiding high cardinality, and using client libraries or OpenTelemetry.

Previously, examples assumed metrics already existed: Prometheus scrapes them, Grafana visualizes them, and queries use PromQL. But where do those metrics originate?

Often exporters provide many system-level metrics: `node_exporter` for host metrics, `kube-state-metrics` for Kubernetes object state, and application exporters for app-specific metrics. This article (and the next) demystifies how to go from zero metrics to instrumenting an application so it exposes multiple metrics directly to Prometheus.

When you instrument an application you do two things:

1. Compute metrics in your application and keep the current value for each time series in memory.
2. Expose an HTTP metrics endpoint that Prometheus scrapes to read those values.

![A diagram titled "Demystifying the Metric Instrumentation Process" showing the Prometheus monitoring stack. It depicts client libraries and exporters feeding metrics into a Prometheus server (with local storage and service discovery), Grafana for visualization, and Alertmanager sending notifications to services like OpsGenie and PagerDuty.](https://mintcdn.com/kodekloud-c4ac6d9a/qM9vA-hQoWNCxcKa/images/Grafana-Prometheus-for-Metrics-Driven-Observability/Metric-Instrumentation/In-Code-Metric-Instrumentation/prometheus-metric-instrumentation-grafana-alerts.jpg?fit=max\&auto=format\&n=qM9vA-hQoWNCxcKa\&q=85\&s=31424a1cf5292c7280f989ea726129ad)

Example of the Prometheus exposition (text) format returned by a metrics endpoint:

```text theme={null}
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{le="0.05"} 1847
http_request_duration_seconds_bucket{le="0.1"} 2903
http_request_duration_seconds_bucket{le="0.25"} 3187
http_request_duration_seconds_bucket{le="0.5"} 3298
http_request_duration_seconds_bucket{le="+Inf"} 3345
http_request_duration_seconds_sum 412.83
http_request_duration_seconds_count 3345
```

For security, serve metric endpoints on a separate port or behind internal network controls so they are not publicly exposed.

Prometheus client libraries that both calculate metrics and expose them via an HTTP endpoint are available for most major languages: Python, Go, Java, Node.js, Ruby, and more. The instrumentation pattern is consistent between languages; examples here use the Python Prometheus client library.

![A slide titled "Prometheus Clients for Multiple Languages" showing the logos and labels for Python, Go, Java, Node.js, and Ruby.](https://mintcdn.com/kodekloud-c4ac6d9a/qM9vA-hQoWNCxcKa/images/Grafana-Prometheus-for-Metrics-Driven-Observability/Metric-Instrumentation/In-Code-Metric-Instrumentation/prometheus-python-go-java-nodejs-ruby.jpg?fit=max\&auto=format\&n=qM9vA-hQoWNCxcKa\&q=85\&s=2c4f3661ed390e1427f87bc6296d882b)

General pattern

1. Define your metric at module scope (outside request handlers or event loops). Provide a stable metric name, a `help`/description string, and optional label keys. For histograms you can predefine bucket boundaries.
2. Update the metric from application logic when relevant events occur (requests, errors, queue lengths, business events).
3. Expose a metrics HTTP endpoint so Prometheus can scrape the current values.

Example metric declarations (module scope) in Python:

```python theme={null}
from prometheus_client import Counter, Gauge, Histogram

http_requests = Counter(
    "http_requests_total",
    "Total HTTP requests to service",
    ["http_path", "response_code"],
)

active_connections = Gauge(
    "app_active_connections",
    "Number of currently active connections",
    ["service", "endpoint"],
)

order_value = Histogram(
    "order_value_dollars",
    "USD Order Value Distribution",
    ["product_category", "payment_method"],
    buckets=(10, 25, 50, 100, 250, 500, 1000, 2500, 5000),
)
```

Update metrics inside application logic when events occur:

```python theme={null}
# Increment counters (defaults to +1 or pass a custom amount)
http_requests.labels(http_path="/orders", response_code="200").inc()
http_requests.labels(http_path="/orders", response_code="200").inc(12)

# For gauges you can inc, dec, or set an absolute value
active_connections.labels(service="checkout", endpoint="orders").inc()
active_connections.labels(service="checkout", endpoint="orders").dec()
active_connections.labels(service="checkout", endpoint="orders").set(42)

# For histograms, observe the measurement (e.g., latency or value)
order_value.labels(product_category="electronics", payment_method="card").observe(199.99)
```

Metric types at a glance

| Metric Type | Purpose | Common Methods / Usage |
| - | - | - |
| Counter | Monotonically increasing count (e.g., requests, errors) | `inc()` — increment by 1 or a value |
| Gauge | Arbitrary value that can go up and down (e.g., concurrent connections) | `inc()`, `dec()`, `set(value)` |
| Histogram | Distribution of values (e.g., request latency, order amount) | `observe(value)`, plus bucketed counts and sum |

Conceptually, counters, gauges, and histograms differ; in code, the difference is which methods you call. Client libraries manage the time series and format the endpoint output into the OpenMetrics/Prometheus exposition format, but they do not prevent cardinality explosions caused by high-cardinality labels — design labels carefully.

Label cardinality is a common pitfall. Avoid using unbounded values (e.g., user IDs, UUIDs, or timestamps) as label values. Prefer aggregations or buckets for high-cardinality attributes to keep the number of time series manageable.

Many client libraries provide decorators or context managers to simplify timing or counting around a block of code; for example, Python’s `Histogram.time()` can measure function or request latency automatically.

Security and deployment tips

* Expose metrics on a separate port or an internal-only endpoint to prevent public access.
* Scrape metrics with appropriate authentication or network policies in production.
* Monitor the cardinality and churn of time series — high cardinality increases memory use and query cost.

If you accidentally use high-cardinality labels (like user IDs or request UUIDs), Prometheus storage and query performance can degrade rapidly. Audit label usage before deploying instrumentation to production.

Why this matters to DevOps and SRE

This lesson is intended to give DevOps and SRE practitioners enough context to collaborate effectively with developers about what metrics to expose and where to look when something important isn’t being tracked. Instrumentation decisions affect alerting, dashboards, and query performance.

OpenTelemetry and auto-instrumentation

OpenTelemetry can auto-instrument common frameworks to provide metrics such as HTTP request counts and latencies without writing manual instrumentation for every handler. Compare manual instrumentation and auto-instrumentation in a running lab to see which metrics each approach provides and to determine which metrics you can rely on versus which require explicit code changes.

Further reading and references

* Prometheus exposition formats: [https://prometheus.io/docs/instrumenting/exposition\_formats/](https://prometheus.io/docs/instrumenting/exposition_formats/)
* Prometheus documentation: [https://prometheus.io/docs/](https://prometheus.io/docs/)
* OpenTelemetry project: [https://opentelemetry.io/](https://opentelemetry.io/)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/grafana-prometheus-for-metrics-driven-observability/module/f101faec-1de6-4831-b109-d9edcafb246c/lesson/f86c613a-a1f9-4a52-87af-3632f1a5bed6)


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