Prometheus metric registration

You can register bounded Prometheus counters, gauges, and histograms so the next exercise can expose service behaviour without creating a series for every URL.

Learning outcomes

  • Explain how Prometheus scrapes metrics from the API and worker through HTTP endpoints.
  • Choose histograms, counters and gauges for request duration, order creation, cache activity and connection counts.
  • Use bounded metric labels and chi route patterns to avoid unbounded time-series cardinality.
  • Interpret latency, traffic, errors and saturation using Prometheus queries and Kafka consumer lag.

A restaurant menu request can return HTTP 200 and still take two seconds. Your order API can slow down while the Kafka worker falls behind processing events. Without measurements, you cannot tell whether the problem comes from MySQL, Redis, HTTP handling or background processing.

You need metrics that describe what each process is doing. The API and worker will expose their own measurements so you can inspect request latency, business activity and processing backlog.

Prometheus scraping

Prometheus uses a pull model. Your application exposes its current metrics through an HTTP endpoint, usually /metrics. A separate Prometheus server periodically requests that endpoint and stores the returned measurements as time series.

The application does not need to know where Prometheus is running. It only needs to expose its metrics endpoint. Prometheus controls which services to scrape and how frequently to collect their measurements.

This differs from a push model, where an application sends measurements directly to a monitoring server whenever an event occurs. Pull-based collection also lets your monitoring system detect whether a service is reachable.

For the Go backend, you use github.com/prometheus/client_golang. Three packages provide the main functionality:

  • prometheus defines metric types, descriptors and registries.
  • promauto creates and registers metrics.
  • promhttp exposes registered metrics through HTTP handlers.

A registry holds the metrics belonging to a service. You can create a dedicated registry rather than placing every metric in the default global registry.

backend/internal/metrics/metrics.go
var registry = prometheus.NewRegistry()

var requestDuration = promauto.With(registry).NewHistogramVec(
    prometheus.HistogramOpts{
        Name: "http_request_duration_seconds",
        Help: "HTTP request duration in seconds.",
    },
    []string{"method", "route", "status"},
)

The HistogramVec declaration creates a histogram with three labels. promauto.With(registry) registers it with the selected registry.

You expose that registry through an HTTP handler:

backend/internal/metrics/metrics.go
func Handler() http.Handler {
    return promhttp.HandlerFor(
        registry,
        promhttp.HandlerOpts{},
    )
}

The API mounts this handler at GET /metrics through its existing chi router. The worker exposes its own /metrics endpoint through a separate HTTP server.

The two processes have independent registries and independent metrics endpoints. This matters because the worker handles Kafka events outside the API request lifecycle.

pprof complements Prometheus but serves a different purpose. Metrics help you identify a problem, while pprof helps you investigate resource consumption inside a Go process. For example, a latency increase might lead you to inspect CPU usage, heap allocations or goroutine activity.

Metric types

Prometheus provides different metric types because different measurements describe different kinds of behaviour. Choosing the wrong type can make dashboards misleading.

Histograms

A histogram records observations and groups them into configured buckets. It also maintains the sum and count of all observations.

Request duration is a natural use case. Most requests to the restaurant listing endpoint might complete quickly, while a few take several seconds because of a slow database query.

An average alone can hide those slow requests. A histogram gives you the distribution needed to estimate latency percentiles.

A histogram declaration specifies its measurement unit and bucket boundaries:

backend/internal/metrics/metrics.go
var requestDuration = promauto.With(registry).NewHistogramVec(
    prometheus.HistogramOpts{
        Name:    "http_request_duration_seconds",
        Help:    "HTTP request duration in seconds.",
        Buckets: []float64{
            0.005, 0.01, 0.025, 0.05,
            0.1, 0.25, 0.5, 1, 2.5, 5,
        },
    },
    []string{"method", "route", "status"},
)

The bucket boundaries are measured in seconds. For example, 0.1 represents 100 milliseconds.

Each observation contributes to the applicable cumulative buckets, the total sum and the observation count. These measurements let Prometheus estimate latency percentiles across multiple application instances.

Consider the following PromQL query:

promql
histogram_quantile(
  0.99,
  sum by (le, route) (
    rate(http_request_duration_seconds_bucket[5m])
  )
)

This estimates p99 request duration for each route over a five-minute window.

The rate() function calculates the per-second increase in bucket counts. sum by (le, route) combines measurements across instances while retaining the bucket boundary and route. histogram_quantile() estimates the requested percentile from those bucket rates.

The result is an estimate, not an exact measurement. Bucket boundaries limit percentile precision. If most requests fall between 100 and 500 milliseconds but your buckets are widely spaced in that range, the estimate will be less precise.

Averages also hide tail latency. A service with a 50-millisecond average can still have requests taking several seconds. p95 and p99 help reveal these slow requests.

Counters

A counter is a metric whose value only increases during a process lifetime. It resets when the process restarts.

Counters are appropriate for events such as successfully placed orders, cache lookups and failed authentication attempts.

Your backend needs an order counter:

backend/internal/metrics/metrics.go
var OrdersPlaced = promauto.With(registry).NewCounter(
    prometheus.CounterOpts{
        Name: "orders_placed_total",
        Help: "Total number of orders placed.",
    },
)

Increment it when a new order has been successfully created.

go
metrics.OrdersPlaced.Inc()

The important distinction is that the counter represents an event, not the number of orders currently stored in MySQL.

Your order API supports an Idempotency-Key. A customer can retry the same request and receive the existing order rather than creating another one. That replay must not increment orders_placed_total.

Increment the counter only when the operation creates a new order successfully. Otherwise, retries inflate your business metrics even though the number of orders has not changed.

Prometheus commonly uses rate() to calculate how quickly a counter increases:

promql
rate(orders_placed_total[5m])

This gives the average number of newly placed orders per second over the previous five minutes. Prometheus also accounts for counter resets when calculating rates across process restarts.

A counter can have labels too. A CounterVec creates separate counter series for different label values.

Your cache needs to distinguish a cache hit from a cache miss:

go
var CacheRequests = promauto.With(registry).NewCounterVec(
    prometheus.CounterOpts{
        Name: "cache_requests_total",
        Help: "Total number of cache lookups.",
    },
    []string{"result"},
)

The result label identifies the lookup outcome.

go
metrics.CacheRequests.WithLabelValues("hit").Inc()
metrics.CacheRequests.WithLabelValues("miss").Inc()

Count every cache lookup, not only successful cache reads. A valid cached value is a hit. A missing or unusable cached value is a miss, even when the application subsequently loads the data successfully.

This distinction lets you calculate the cache hit rate and see whether caching is reducing database work.

Gauges

A gauge represents a value that can increase or decrease. It is appropriate for measurements describing the current state of a system.

Consider WebSocket connections. When a customer opens an order-tracking connection, the number of active connections increases. When the connection closes, the number decreases.

go
var WSConnections = promauto.With(registry).NewGauge(
    prometheus.GaugeOpts{
        Name: "ws_connections",
        Help: "Number of active WebSocket connections.",
    },
)

The metric must follow the actual connection lifecycle.

go
metrics.WSConnections.Inc()
defer metrics.WSConnections.Dec()

The increment belongs where the hub registers a connection. The decrement belongs where that connection closes. Pairing the updates with the lifecycle prevents disconnected clients from leaving incorrect counts.

Kafka consumer lag is another gauge. It measures how far a consumer group is behind the messages available in its topic.

Suppose a worker has 120 messages of lag. After processing some messages, the lag falls to 75. A counter would be the wrong choice because its value cannot decrease.

Represent lag as a gauge with group and topic labels:

go
var consumerLag = promauto.With(registry).NewGaugeVec(
    prometheus.GaugeOpts{
        Name: "kafka_consumer_lag",
        Help: "Current Kafka consumer lag.",
    },
    []string{"group", "topic"},
)

When the worker measures the latest lag, update the corresponding series:

go
consumerLag.WithLabelValues(
    group,
    topic,
).Set(float64(lag))

Use Set() because lag represents a current measurement. The same series must be updated when the lag reaches zero. Otherwise, monitoring dashboards can continue displaying an outdated backlog.

Consumer lag belongs to the worker because the worker owns the Kafka consumers. It should export lag for each group and topic it consumes.

Labels and cardinality

Labels let you divide one metric into meaningful groups. The request duration histogram uses three labels:

  • method: HTTP method, such as GET or POST.
  • route: the matched route pattern.
  • status: HTTP response status code.

These labels let you compare request durations across different endpoints and response statuses without creating a separate metric definition for every endpoint.

However, labels introduce an important resource consideration called Label cardinality. Cardinality is the number of distinct combinations of label values. Each unique combination creates a separate time series in Prometheus.

Consider two possible route labels:

/v1/restaurants/{id}/menu
/v1/restaurants/42/menu

The first is a route pattern. The second is a raw request path.

If you use raw paths, every restaurant ID can create a separate time series. An attacker can also generate random URLs and cause the application to create a large number of series.

Every series consumes memory in the application and monitoring infrastructure. High cardinality can make the monitoring system expensive and difficult to operate.

Use stable route patterns. Never use raw paths, request IDs, email addresses or user IDs as request metric labels.

Measuring HTTP request duration

HTTP middleware is a suitable place to measure request duration because it wraps the entire downstream handler execution. It captures the request before the handler runs and observes elapsed time after the handler returns.

The API uses the Chi router for route matching. Chi stores the matched route pattern in the request's routing context.

A common mistake is reading that pattern before the handler runs. At that point, chi may not have completed route matching.

go
next.ServeHTTP(w, r)

route := chi.RouteContext(r.Context()).RoutePattern()
if route == "" {
    route = "unmatched"
}

Read the pattern after next.ServeHTTP returns. This ensures that the routing context contains the final pattern.

For example, these two requests:

GET /v1/restaurants/1/menu
GET /v1/restaurants/2/menu

Both produce this route label:

/v1/restaurants/{id}/menu

Unknown paths use the single label unmatched. That keeps random URLs from creating new time series.

The middleware also needs the response status. The HTTP handler receives an http.ResponseWriter, so you can wrap it to record calls to WriteHeader.

go
type statusWriter struct {
    http.ResponseWriter
    status int
}

func (w *statusWriter) WriteHeader(code int) {
    if w.status != 0 {
        return
    }
    w.status = code
    w.ResponseWriter.WriteHeader(code)
}

The net/http constants name the HTTP status codes handlers write. For example, http.StatusOK is 200 and http.StatusTeapot is 418.

There is one more detail: handlers do not always explicitly call WriteHeader. Writing a response body implicitly sends HTTP 200. Your instrumentation must account for that default status when no explicit status was recorded.

A response writer wrapper also needs to preserve optional interfaces. The WebSocket implementation relies on http.Hijacker, and streaming responses can rely on http.Flusher. A wrapper that hides these interfaces can break otherwise working handlers.

There is another registry detail to watch. If you register metrics in a custom registry but expose the default registry through your HTTP handler, your metrics will not appear in the scrape. Create and register metrics against the same registry that your handler exposes.

The four golden signals

The four golden signals are latency, traffic, errors and saturation. Together, they provide a practical starting point for understanding service health.

Latency

Latency measures how long requests or operations take. The request duration histogram provides measurements for percentiles such as p50, p95 and p99.

A rising p99 can indicate slow database queries, Redis delays, excessive middleware work or overloaded application instances.

Traffic

Traffic measures how much work a service receives. For an HTTP API, request rate is a useful starting point.

The request histogram also exposes an observation count. You can calculate Requests per second (RPS) using rate():

promql
sum(rate(http_request_duration_seconds_count[5m]))

This calculates the total HTTP requests per second over a five-minute window.

You can also group the result by route or method when investigating a specific endpoint.

Errors

Errors measure failed operations. The HTTP status label lets you distinguish successful responses from client and server errors.

For example, calculate the rate of HTTP 5xx responses:

promql
sum(
  rate(http_request_duration_seconds_count{status=~"5.."}[5m])
)

This helps identify whether the service is returning more server errors as traffic increases.

HTTP status codes do not capture every application-level failure. Important background operations should expose their own error counters too.

Saturation

Saturation measures how close a resource is to its capacity. Examples include Kafka consumer lag, open WebSocket connections and database connection pool usage.

Growing Kafka consumer lag suggests that messages are arriving faster than the worker can process them. Increasing open connections can indicate that a service is approaching its connection-handling capacity.

Look at the signals together. If traffic increases, p99 latency rises and consumer lag grows, the service may be receiving more work than its current processing capacity can handle.

API and worker metrics

The next exercise, API and worker metrics, connects these ideas to the existing Go API and worker.

You will put request instrumentation around HTTP handler execution, while order and cache metrics belong close to the operations they measure. The WebSocket gauge belongs at connection registration and closure. Kafka consumer lag belongs to the worker that consumes the messages.

The API will expose its registered metrics through GET /metrics. The worker will expose its own metrics endpoint, including consumer lag. Separate private pprof listeners provide profiling access without exposing profiling handlers through the public API router.

Keep the measurements focused on events and resource states that the system actually owns. A route pattern describes a request category. A counter describes an event. A gauge describes a changing value. A histogram describes a distribution.

Check your understanding

Question 1 of 4

Your API exposes /metrics, and a Prometheus server periodically requests it. Which monitoring model is being used?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (Go, Prometheus client_golang).

Finished Lesson 6.3?