TExcelTAD

Instrumenting a Go Service

Exporters cover software you don't own (databases, the OS). For your own services, you instrument the code with a client library, which keeps the metrics in memory and serves /metrics. linkly is written in Go and uses the official prometheus/client_golang. Libraries with the same model exist for Python (prometheus_client), Java (simpleclient/Micrometer), Node.js (prom-client), .NET and Rust.

The client_golang way

go
package main

import (
	"log"
	"net/http"
	"strconv"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
	requests = promauto.NewCounterVec(prometheus.CounterOpts{
		Name: "http_requests_total",
		Help: "HTTP requests handled, by route and status code.",
	}, []string{"route", "code"})

	duration = promauto.NewHistogramVec(prometheus.HistogramOpts{
		Name:    "http_request_duration_seconds",
		Help:    "Time to handle a request.",
		Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5},
	}, []string{"route"})

	linksStored = promauto.NewGauge(prometheus.GaugeOpts{
		Name: "linkly_links_stored",
		Help: "Short links in the database.",
	})
)

// instrument wraps a handler; route is the template ("/{code}"), never the raw path.
func instrument(route string, next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		next(rec, r)
		requests.WithLabelValues(route, strconv.Itoa(rec.status)).Inc()
		duration.WithLabelValues(route).Observe(time.Since(start).Seconds())
	}
}

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) { s.status = code; s.ResponseWriter.WriteHeader(code) }

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /{code}", instrument("/{code}", redirect))
	mux.HandleFunc("POST /links", instrument("/links", createLink))
	mux.Handle("GET /metrics", promhttp.Handler())
	log.Fatal(http.ListenAndServe(":8080", mux))
}

Notes on this code:

  • promauto registers each metric with the default registry, which also includes Go runtime metrics (go_goroutines, go_memstats_*, go_gc_duration_seconds) and process metrics (process_cpu_seconds_total, process_resident_memory_bytes, process_open_fds) for free.
  • code is the numeric status as a string ("302"). Agree on that format across services (some teams use classes like 3xx), or cross-service dashboards break.
  • promhttp.InstrumentHandlerCounter and InstrumentHandlerDuration exist in client_golang and do what instrument does; writing it once by hand shows the moving parts.
  • Go 1.22+ ServeMux patterns (GET /{code}) give you the route template; with other routers, ask the router for the matched pattern.

The same idea, runnable

The real library needs module downloads, so here is a standard-library model of it: a registry of counters and a histogram, a middleware that records the route template and status, and a /metrics handler printing the text format. A fake clock makes the durations repeatable; httptest drives the handlers without a network:

go · try it yourself
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"sort"
	"strings"
	"time"
)

type registry struct {
	requests map[string]float64 // key: route|code
	buckets  []float64
	hist     map[string][]float64 // route -> cumulative counts per bucket (+Inf last)
	sum      map[string]float64
}

func newRegistry() *registry {
	return &registry{requests: map[string]float64{}, buckets: []float64{0.01, 0.05, 0.25},
		hist: map[string][]float64{}, sum: map[string]float64{}}
}

func (r *registry) observe(route string, code int, secs float64) {
	r.requests[fmt.Sprintf("%s|%d", route, code)]++
	h, ok := r.hist[route]
	if !ok {
		h = make([]float64, len(r.buckets)+1)
		r.hist[route] = h
	}
	for i, b := range r.buckets {
		if secs <= b {
			h[i]++
		}
	}
	h[len(r.buckets)]++
	r.sum[route] += secs
}

func (r *registry) write(w io.Writer) {
	fmt.Fprintln(w, "# TYPE http_requests_total counter")
	keys := make([]string, 0, len(r.requests))
	for k := range r.requests {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		p := strings.Split(k, "|")
		fmt.Fprintf(w, "http_requests_total{route=%q,code=%q} %g\n", p[0], p[1], r.requests[k])
	}
	fmt.Fprintln(w, "# TYPE http_request_duration_seconds histogram")
	routes := make([]string, 0, len(r.hist))
	for k := range r.hist {
		routes = append(routes, k)
	}
	sort.Strings(routes)
	for _, route := range routes {
		h := r.hist[route]
		for i, b := range r.buckets {
			fmt.Fprintf(w, "http_request_duration_seconds_bucket{route=%q,le=\"%g\"} %g\n", route, b, h[i])
		}
		fmt.Fprintf(w, "http_request_duration_seconds_bucket{route=%q,le=\"+Inf\"} %g\n", route, h[len(r.buckets)])
		fmt.Fprintf(w, "http_request_duration_seconds_sum{route=%q} %g\n", route, r.sum[route])
		fmt.Fprintf(w, "http_request_duration_seconds_count{route=%q} %g\n", route, h[len(r.buckets)])
	}
}

// fakeClock advances by a scripted duration on each call, so the output is repeatable.
type fakeClock struct {
	t     time.Time
	steps []time.Duration
}

func (c *fakeClock) now() time.Time {
	if len(c.steps) > 0 {
		c.t = c.t.Add(c.steps[0])
		c.steps = c.steps[1:]
	}
	return c.t
}

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) { s.status = code; s.ResponseWriter.WriteHeader(code) }

func instrument(reg *registry, clk *fakeClock, route string, next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		start := clk.now()
		rec := &statusRecorder{ResponseWriter: w, status: 200}
		next(rec, req)
		reg.observe(route, rec.status, clk.now().Sub(start).Seconds())
	}
}

func main() {
	reg := newRegistry()
	clk := &fakeClock{steps: []time.Duration{
		0, 4 * time.Millisecond, 0, 30 * time.Millisecond, 0, 3 * time.Millisecond, 0, 120 * time.Millisecond}}
	links := map[string]string{"abc": "https://example.com"}

	mux := http.NewServeMux()
	mux.HandleFunc("GET /{code}", instrument(reg, clk, "/{code}", func(w http.ResponseWriter, r *http.Request) {
		if url, ok := links[r.PathValue("code")]; ok {
			http.Redirect(w, r, url, http.StatusFound)
			return
		}
		http.NotFound(w, r)
	}))
	mux.HandleFunc("POST /links", instrument(reg, clk, "/links", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusCreated)
	}))
	mux.HandleFunc("GET /metrics", func(w http.ResponseWriter, r *http.Request) { reg.write(w) })

	for _, req := range []*http.Request{
		httptest.NewRequest("GET", "/abc", nil),
		httptest.NewRequest("GET", "/zzz", nil),
		httptest.NewRequest("GET", "/abc", nil),
		httptest.NewRequest("POST", "/links", nil),
	} {
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, req)
		fmt.Println(req.Method, req.URL.Path, "->", rec.Code)
	}
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest("GET", "/metrics", nil))
	fmt.Print(rec.Body.String())
}
GET /abc -> 302
GET /zzz -> 404
GET /abc -> 302
POST /links -> 201
# TYPE http_requests_total counter
http_requests_total{route="/links",code="201"} 1
http_requests_total{route="/{code}",code="302"} 2
http_requests_total{route="/{code}",code="404"} 1
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{route="/links",le="0.01"} 0
http_request_duration_seconds_bucket{route="/links",le="0.05"} 0
http_request_duration_seconds_bucket{route="/links",le="0.25"} 1
http_request_duration_seconds_bucket{route="/links",le="+Inf"} 1
http_request_duration_seconds_sum{route="/links"} 0.12
http_request_duration_seconds_count{route="/links"} 1
http_request_duration_seconds_bucket{route="/{code}",le="0.01"} 2
http_request_duration_seconds_bucket{route="/{code}",le="0.05"} 3
http_request_duration_seconds_bucket{route="/{code}",le="0.25"} 3
http_request_duration_seconds_bucket{route="/{code}",le="+Inf"} 3
http_request_duration_seconds_sum{route="/{code}"} 0.037000000000000005
http_request_duration_seconds_count{route="/{code}"} 3

Three requests to two different short codes produced one route="/{code}" label value, not two paths: the cardinality rule from the previous lesson, enforced in the middleware.

What to instrument

Layer Metrics
inbound HTTP/gRPC requests by route and code (counter), duration by route (histogram), in-flight (gauge)
outbound calls (PostgreSQL, Redis, other APIs) the same three per dependency: linkly_db_query_duration_seconds{op="insert_link"}
pools and queues size, in use, waiters (gauges); wait time (histogram)
business events linkly_links_created_total, `linkly_redirects_total{cache="hit
build info linkly_build_info{version, revision, goversion} 1

The first two rows give you RED for the service and for each dependency (RED & USE). Business counters are what product people actually look at, and they make great sanity checks ("redirects dropped to zero, but error rate is fine?").

OpenTelemetry metrics

The OpenTelemetry SDK also has a metrics API (counters, up-down counters, histograms, gauges), exported over OTLP to a Collector or straight into Prometheus (--web.enable-otlp-receiver), or exposed on /metrics through a Prometheus exporter. Teams that already use OTel for traces often use it for metrics too, to have one SDK. Prometheus-native client libraries remain simpler for a pure Prometheus setup. Either way the naming and cardinality rules are the same; the OpenTelemetry SDKs lesson shows the metrics API next to tracing.

Test yourself

What should the route label hold for a request to /abc123?

  1. /abc123
  2. The route template, e.g. /{code}
  3. The short code abc123
  4. Nothing; don't label by route

Which metrics do you get from client_golang's default registry without writing any code?

  1. None
  2. Go runtime and process metrics such as go_goroutines and process_resident_memory_bytes
  3. HTTP request metrics for every handler
  4. Database metrics

Why does the runnable model use a fake clock?

  1. Go has no clock on Compiler Explorer
  2. Real durations differ on every run; scripted ones make the histogram output repeatable
  3. Prometheus requires it
  4. To make it faster