TExcelTAD
Home › Observability: Prometheus, Grafana, Loki & OpenTelemetry › Metric Types: Counter, Gauge, Histogram, Summary

Metric Types: Counter, Gauge, Histogram, Summary

Prometheus stores every series the same way (timestamps and float values), but client libraries offer four types with different meanings. Picking the right one decides which queries make sense later.

Type Goes Example Query it with
Counter only up (resets to 0 on restart) http_requests_total, linkly_cache_misses_total rate(), increase()
Gauge up and down linkly_db_connections_in_use, process_resident_memory_bytes the value itself, avg_over_time(), max()
Histogram counts observations into buckets http_request_duration_seconds histogram_quantile(), rate(_sum)/rate(_count)
Summary computes quantiles in the client go_gc_duration_seconds the quantile series directly, no aggregation

Counter

A counter counts events since the process started: requests, errors, bytes sent. Its absolute value is almost meaningless (it depends on uptime); its rate of increase is what you want. When the process restarts, the counter drops to 0, and PromQL's rate() detects that drop and treats it as a reset (rate(), irate() & increase()).

Rule: if you are tempted to Set() a counter, or decrement it, it's a gauge.

Gauge

A gauge is a snapshot: current queue length, memory in use, temperature, the number of links stored. You can read it directly, and take its max, min or avg_over_time. Never rate() a gauge (the result is meaningless when it goes down), but deriv() gives its slope.

Histogram

A histogram answers "how are these values distributed?", typically latencies or sizes. The client keeps a set of cumulative buckets with upper bounds (le, "less than or equal") and exposes three kinds of series:

text
http_request_duration_seconds_bucket{le="0.05"}  930    # requests that took ≤ 50 ms
http_request_duration_seconds_bucket{le="0.1"}   975
http_request_duration_seconds_bucket{le="0.5"}   998
http_request_duration_seconds_bucket{le="+Inf"} 1000    # = all requests
http_request_duration_seconds_sum   37.2                # total seconds observed
http_request_duration_seconds_count 1000                # number of observations

Every bucket and _sum/_count is a counter, so histograms aggregate cleanly: sum the buckets of ten pods and you have the fleet's distribution. The quantile is estimated on the server with histogram_quantile() (Histograms & Quantiles).

Prometheus 3 also has native histograms: one series with exponential buckets chosen automatically, far cheaper and more accurate. They are stable and widely supported now, but many dashboards and exporters still use classic buckets, so this course teaches both.

Summary

A summary also tracks a distribution, but the client computes quantiles (say p50, p90, p99) over a sliding time window and exposes them directly:

text
rpc_duration_seconds{quantile="0.5"}  0.012
rpc_duration_seconds{quantile="0.99"} 0.31
rpc_duration_seconds_sum   812.4
rpc_duration_seconds_count 52011

The catch: quantiles cannot be aggregated. The average of ten pods' p99 is not the fleet's p99. Prefer histograms for anything you will aggregate across instances, which is almost everything in a service. Summaries are fine for single-process internals such as Go's GC pauses.

The four types as code

This model implements the four types the way client libraries do, then prints what a /metrics scrape would show:

python · try it yourself
import bisect

class Counter:
    def __init__(self): self.value = 0.0
    def inc(self, n=1.0):
        if n < 0: raise ValueError("counters can only go up")
        self.value += n

class Gauge:
    def __init__(self): self.value = 0.0
    def set(self, v): self.value = v
    def inc(self, n=1.0): self.value += n
    def dec(self, n=1.0): self.value -= n

class Histogram:
    def __init__(self, buckets):
        self.bounds = sorted(buckets) + [float("inf")]
        self.counts = [0] * len(self.bounds)          # per bucket, not cumulative
        self.sum = 0.0
    def observe(self, v):
        self.counts[bisect.bisect_left(self.bounds, v)] += 1
        self.sum += v
    def expose(self, name):
        total = 0
        for bound, c in zip(self.bounds, self.counts):
            total += c                                   # exposed buckets are cumulative
            le = "+Inf" if bound == float("inf") else repr(bound)
            print(f'{name}_bucket{{le="{le}"}} {total}')
        print(f"{name}_sum {round(self.sum, 3)}")
        print(f"{name}_count {total}")

requests = Counter()
in_flight = Gauge()
latency = Histogram([0.05, 0.1, 0.5])

durations = [0.012, 0.031, 0.044, 0.07, 0.093, 0.2, 0.61, 0.021]
for d in durations:
    in_flight.inc()
    requests.inc()
    latency.observe(d)
    in_flight.dec()

print(f"http_requests_total {requests.value}")
print(f"http_requests_in_flight {in_flight.value}")
latency.expose("http_request_duration_seconds")
try:
    requests.inc(-1)
except ValueError as e:
    print("error:", e)
http_requests_total 8.0
http_requests_in_flight 0.0
http_request_duration_seconds_bucket{le="0.05"} 4
http_request_duration_seconds_bucket{le="0.1"} 6
http_request_duration_seconds_bucket{le="0.5"} 7
http_request_duration_seconds_bucket{le="+Inf"} 8
http_request_duration_seconds_sum 1.081
http_request_duration_seconds_count 8
error: counters can only go up

The histogram keeps six numbers (four buckets, the sum and the count) no matter how many requests it sees: that's why histograms are cheap. The price is precision: you know 7 of 8 requests took at most 0.5 s, not their exact values.

Choosing

Question you will ask Type
How many per second? What fraction failed? counter (one per outcome, or a label)
How many right now? How full? gauge
How slow is the 99th percentile across the fleet? histogram
What's the latency distribution of this one process, and I'll never aggregate it? summary (or still a histogram)

Test yourself

Which type fits "number of open database connections"?

  1. Counter
  2. Gauge
  3. Histogram
  4. Summary

Why are histograms usually preferred over summaries for request latency?

  1. They are more precise
  2. Their buckets are counters that can be summed across instances, so fleet-wide quantiles can be computed
  3. Summaries need native histograms
  4. Histograms don't need labels

A histogram has buckets le=0.1 → 40 and le=0.5 → 55 and +Inf → 60. How many observations were between 0.1 and 0.5?

  1. 55
  2. 15
  3. 40
  4. 5