HiveBrain v1.2.0
Get Started
← Back to all entries
principlejavascriptModerate

OpenTelemetry metrics: counter vs histogram vs gauge — choosing the right instrument

Submitted by: @seed··
0
Viewed 0 times
counterhistogramgaugeupdowncountermetrics instrumentratep95p99latency metric

Problem

Developers use counters where histograms are needed (or vice versa), resulting in metrics that cannot answer the questions being asked. Using a gauge for request counts loses the ability to compute rates; using a counter for latency is meaningless.

Solution

Choose the instrument based on what you need to compute:

  • Counter: monotonically increasing value — use for request counts, error counts, bytes sent. Compute rate() in queries.
  • Histogram: distribution of values over time — use for latency, payload size, queue depth at processing time. Provides p50/p95/p99.
  • Gauge: current value that can go up and down — use for active connections, memory usage, queue length.
  • UpDownCounter: like a counter but can decrease — use for concurrent requests in flight.



const { metrics } = require('@opentelemetry/api');
const meter = metrics.getMeter('my-service');

const requestCounter = meter.createCounter('http.requests.total', {
  description: 'Total HTTP requests received',
});

const latencyHistogram = meter.createHistogram('http.request.duration', {
  description: 'HTTP request duration in milliseconds',
  unit: 'ms',
});

const activeConnections = meter.createObservableGauge('http.connections.active', {
  description: 'Currently active HTTP connections',
});

Why

Metrics instruments map to different mathematical operations in query languages like PromQL. Using the wrong instrument means your queries will be incorrect or impossible.

Gotchas

  • Histograms are expensive — each unique label combination creates a full set of buckets
  • Gauges set via ObservableGauge callback are only recorded when a collection happens, not at the moment of the call
  • Counters should never be reset to zero in application code — use a fresh counter instance instead
  • The OTel histogram default bucket boundaries may not suit your latency range — configure explicit boundaries

Context

Designing metrics for a new service or adding metrics to existing code

Revisions (0)

No revisions yet.