Metrics are numerical measurements sampled and aggregated over time: trends, rates, and distributions. They answer questions the other signals can’t:
- Is p99 latency rising or falling over the last hour?
- What is the current request rate, and is it spiking?
- How many connections are open right now?
Where logs capture individual events and traces capture individual requests, metrics capture the shape of the system over time. They are the first signal you look at: cheap to store, fast to query, and alert-friendly. Metrics tell you that something is wrong before you reach for logs or traces to find out why.
OpenTelemetry defines metrics as one of the three core
observability signals. The OTEL SDK (go.opentelemetry.io/otel/metric) provides a
vendor-neutral API that can export to Prometheus, OTLP, or any other backend from a
single instrumentation. The Prometheus client library is a practical alternative when
Prometheus is the only target.
The patterns here use Go for examples but the concepts (metric types, naming conventions, and PromQL) are the same regardless of language.
Metric types
Prometheus has four types. Three of them are useful.
Counter
A value that only ever goes up. Resets to zero on process restart.
Use for: requests served, errors encountered, bytes sent, tasks completed.
http_requests_total{method="POST", status="201", handler="/accounts"} 1Never subtract from a counter or use one for a value that can decrease. Query
counters with rate() to get a per-second rate over a window.
Gauge
A value that goes up and down. Represents a snapshot of current state.
Use for: active connections, queue depth, memory usage, cache size, items in flight.
http_requests_in_flight{method="POST"} 3Histogram
Samples observations and counts them in configurable buckets. Exposes _count,
_sum, and one _bucket series per boundary. Use for distributions: request
durations, payload sizes, queue wait times.
http_request_duration_seconds_bucket{handler="/accounts", le="0.1"} 953
http_request_duration_seconds_bucket{handler="/accounts", le="0.5"} 1201
http_request_duration_seconds_sum{handler="/accounts"} 84.2
http_request_duration_seconds_count{handler="/accounts"} 1204Histograms from multiple instances can be aggregated in Prometheus queries, which is why they are preferred over summaries.
Summary
Naming
Prometheus metric names are permanent API surface. Once a dashboard, alert, or recording rule references a name, renaming it breaks everything downstream.
{namespace}_{subsystem}_{name}_{unit}| Segment | Purpose | Example |
|---|---|---|
namespace |
Application or team prefix | payments, myapp |
subsystem |
Component within the app | http, db, cache |
name |
What is being measured | requests, duration, errors |
unit |
Base unit (see below) | seconds, bytes, total |
All lowercase snake_case. No hyphens.
# Good
payments_http_request_duration_seconds
myapp_db_connections_open
myapp_cache_evictions_total
# Bad
HTTPRequestDuration # not snake_case
request-duration-ms # hyphens, scaled unit
db_query_time # no unitBase units
Always use base units. Never scale.
| Measure | Unit | Not |
|---|---|---|
| Time | seconds |
milliseconds, minutes |
| Size | bytes |
kilobytes, megabytes |
| Ratios | ratio (0–1) |
percent |
| Counts | total |
(no unit suffix) |
// Good: record in seconds
duration.Observe(time.Since(start).Seconds())
// Bad: record in milliseconds
duration.Observe(float64(time.Since(start).Milliseconds()))Required suffixes
| Type | Required suffix | Example |
|---|---|---|
| Counter | _total |
http_requests_total |
| Histogram | _seconds, _bytes, etc. |
http_request_duration_seconds |
| Gauge | unit suffix or none | http_requests_in_flight |
Counters must end in _total; rate(metric_total[5m]) is the standard PromQL
pattern and some tools warn if the suffix is missing.
Labels and cardinality
Every unique combination of label values creates a separate time series. Cardinality is the total number of those series, and it’s the most common way to accidentally destroy a Prometheus instance.
5 methods × 10 status codes × 50 handlers = 2,500 series ← fine
5 methods × 10 status codes × 50 handlers × 10,000 user IDs → 25,000,000 series ← catastrophicThe single most common mistake: using the raw request path as a label.
# One series per unique URL: infinite cardinality
http_requests_total{handler="/users/f47ac10b-58cc-4372-a567-0e02b2c3d479"}
# One series per route template: bounded
http_requests_total{handler="/users/{id}"}Use the route template your router matched, not the actual path. In Go’s net/http
(1.22+): r.Pattern gives you the matched pattern.
HTTP metrics
Three metrics cover the essentials for any HTTP service: request rate, error rate, latency distribution, and concurrency.
# HELP http_requests_total The total number of HTTP requests.
# TYPE http_requests_total counter
http_requests_total{method="POST",status="201",handler="/accounts"} 1
# HELP http_request_duration_seconds A histogram of the request duration.
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{method="POST",status="201",handler="/accounts",le="0.1"} 1
http_request_duration_seconds_sum{method="POST",status="201",handler="/accounts"} 0.054
http_request_duration_seconds_count{method="POST",status="201",handler="/accounts"} 1
# HELP http_requests_in_flight Current number of HTTP requests being processed.
# TYPE http_requests_in_flight gauge
http_requests_in_flight{method="POST"} 3Go implementation
Define metrics once at package level with a custom registry; this keeps tests deterministic and avoids collisions with metrics from imported packages:
var (
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests.",
},
[]string{"method", "status", "handler"},
)
httpRequestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request duration in seconds.",
Buckets: prometheus.DefBuckets,
},
[]string{"method", "status", "handler"},
)
httpRequestsInFlight = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "http_requests_in_flight",
Help: "Current number of HTTP requests being processed.",
},
[]string{"method"},
)
)
func NewRegistry() *prometheus.Registry {
reg := prometheus.NewRegistry()
reg.MustRegister(httpRequestsTotal, httpRequestDuration, httpRequestsInFlight)
return reg
}Wire them up in middleware so every handler is instrumented without touching handler code:
func instrumentHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
method := r.Method
handler := routePattern(r)
httpRequestsInFlight.WithLabelValues(method).Inc()
defer httpRequestsInFlight.WithLabelValues(method).Dec()
start := time.Now()
rw := &responseWriter{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rw, r)
status := strconv.Itoa(rw.status)
elapsed := time.Since(start).Seconds()
httpRequestsTotal.WithLabelValues(method, status, handler).Inc()
httpRequestDuration.WithLabelValues(method, status, handler).Observe(elapsed)
})
}
// routePattern strips the method prefix from r.Pattern.
// "GET /users/{id}" → "/users/{id}"
func routePattern(r *http.Request) string {
p := r.Pattern
if i := strings.IndexByte(p, ' '); i >= 0 {
return p[i+1:]
}
return p
}Histogram buckets
prometheus.DefBuckets ([.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10]
seconds) suit general-purpose HTTP APIs. Tune them to your service’s latency profile:
// Fast internal service
Buckets: []float64{.001, .005, .01, .025, .05, .1, .25, .5, 1}
// Long-running export or batch endpoint
Buckets: []float64{.1, .5, 1, 2.5, 5, 10, 30, 60}Use the exact status code, not a grouped class like "2xx"; HTTP status codes are
a small finite set and not a cardinality risk.
Essential PromQL
# Request rate over the last 5 minutes
rate(http_requests_total[5m])
# Error rate (5xx only)
rate(http_requests_total{status=~"5.."}[5m])
# Error ratio
rate(http_requests_total{status=~"5.."}[5m])
/ rate(http_requests_total[5m])
# p99 latency
histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m]))
# p99 latency per handler
histogram_quantile(0.99,
sum by (handler, le) (rate(http_request_duration_seconds_bucket[5m]))
)