Gin in production · 5 MIN READ

Health and metrics in Gin: simple liveness, budgeted readiness, counters keyed by route template

Separate liveness from readiness, check dependencies within a short budget, and count requests by route template and status class.

Health endpoints and request counters are how the platform and the on-call engineer see a service from outside. Each answers a narrow question: should this process be restarted, should it receive traffic right now, and how is each route behaving. Mixing up the first two causes restart storms. Labeling counters with raw paths makes the metrics system the next thing to fall over.

gin · A MAP OF THE IDEA

  1. Liveness: process only
  2. Readiness: deps + budget
  3. Count by route template
  4. Bound every label

Useful when

  • Probes tell the platform exactly what to do: restart or reroute.
  • Route-template labels keep metric cardinality fixed.

Watch out

  • Dependency checks in liveness turn outages into restart storms.
  • Raw paths or client-chosen methods as labels grow without bound.

Implementation & operation cost: Two small endpoints, one middleware and a bounded map; a real metrics stack adds a client library and storage for every series you create.

01

Liveness and readiness answer different questions

An orchestrator such as Kubernetes restarts a container whose liveness probe fails, and stops routing traffic to one whose readiness probe fails without restarting it. If liveness checks the database, a database outage makes every replica fail liveness at once. The platform restarts all of them, the restarts add a reconnect storm to a struggling database, and the outage lasts longer. So liveness checks only what a restart can fix: the process is serving HTTP and is not wedged. Readiness checks what traffic needs: required dependencies are reachable, startup work is finished, and the replica is not draining. During shutdown, readiness turns false first so the load balancer stops sending new requests before the server drains, as the server-lifecycle lesson describes. Kubernetes HTTP probes treat any status from 200 to 399 as success, so return a 5xx code to mean not ready.

02

A budgeted readiness check and route-keyed counters

readiness runs every check concurrently under one 25 ms context, so a hung dependency costs one budget rather than one per check and cannot starve the others. countRequests records the normalized method, route template and status class after c.Next. The traffic includes three user IDs, two scanner paths and a nonsense method, followed by probes before and after a simulated database outage and during a drain.

go
package main

import (
	"cmp"
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"slices"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/gin-gonic/gin"
)

type series struct{ method, route, class string }

// Counters is a tiny concurrency-safe stand-in for a metrics client.
type Counters struct {
	mu sync.Mutex
	m  map[series]uint64
}

func (c *Counters) Inc(s series) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.m[s]++
}

func (c *Counters) WriteText(b *strings.Builder) {
	type row struct {
		s series
		n uint64
	}
	c.mu.Lock()
	rows := make([]row, 0, len(c.m))
	for s, n := range c.m {
		rows = append(rows, row{s, n})
	}
	c.mu.Unlock()
	slices.SortFunc(rows, func(a, b row) int { // map order is random; sort for stable output
		return cmp.Or(cmp.Compare(a.s.route, b.s.route), cmp.Compare(a.s.method, b.s.method), cmp.Compare(a.s.class, b.s.class))
	})
	for _, r := range rows {
		fmt.Fprintf(b, "http_requests_total{method=%q,route=%q,class=%q} %d\n", r.s.method, r.s.route, r.s.class, r.n)
	}
}

func normMethod(m string) string {
	switch m {
	case "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS":
		return m
	}
	return "OTHER" // the method string is client-controlled too
}

func countRequests(cnt *Counters) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()
		route := c.FullPath() // the route template, never the raw path
		if route == "" {
			route = "unmatched"
		}
		cnt.Inc(series{normMethod(c.Request.Method), route, fmt.Sprintf("%dxx", c.Writer.Status()/100)})
	}
}

type Check struct {
	Name string
	Run  func(context.Context) error
}

func readiness(checks []Check, budget time.Duration, draining *atomic.Bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		if draining.Load() {
			c.JSON(http.StatusServiceUnavailable, gin.H{"status": "draining"})
			return
		}
		ctx, cancel := context.WithTimeout(c.Request.Context(), budget)
		defer cancel()
		errs := make([]error, len(checks))
		var wg sync.WaitGroup
		for i, ch := range checks {
			wg.Go(func() { errs[i] = ch.Run(ctx) }) // concurrent: one slow check cannot starve the others
		}
		wg.Wait()
		var failed []string
		for i, err := range errs {
			if err != nil {
				failed = append(failed, checks[i].Name)
			}
		}
		if len(failed) > 0 {
			c.JSON(http.StatusServiceUnavailable, gin.H{"status": "not ready", "failed": failed})
			return
		}
		c.JSON(http.StatusOK, gin.H{"status": "ready"})
	}
}

func main() {
	gin.SetMode(gin.TestMode)
	var dbUp, draining atomic.Bool
	dbUp.Store(true)
	pingDB := func(ctx context.Context) error {
		if dbUp.Load() {
			return nil
		}
		<-ctx.Done() // a hung database answers nothing; the budget decides
		return ctx.Err()
	}
	pingCache := func(ctx context.Context) error { return nil }

	cnt := &Counters{m: map[series]uint64{}}
	r := gin.New()
	r.Use(countRequests(cnt))
	r.GET("/livez", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
	r.GET("/readyz", readiness([]Check{{"db", pingDB}, {"cache", pingCache}}, 25*time.Millisecond, &draining))
	r.GET("/users/:id", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"id": c.Param("id")}) })
	r.GET("/metrics", func(c *gin.Context) {
		var b strings.Builder
		cnt.WriteText(&b)
		c.String(http.StatusOK, b.String())
	})

	call := func(method, path string) string {
		w := httptest.NewRecorder()
		r.ServeHTTP(w, httptest.NewRequest(method, path, nil))
		return fmt.Sprint(w.Code, " ", w.Body.String())
	}
	raw := map[string]bool{}
	for _, p := range []string{"/users/1", "/users/2", "/users/3", "/wp-login.php", "/.env"} {
		raw[p] = true
		call("GET", p)
	}
	call("BREW", "/users/1")
	fmt.Println("livez:", call("GET", "/livez"), "| readyz:", call("GET", "/readyz"))
	dbUp.Store(false)
	fmt.Println("livez:", call("GET", "/livez"), "| readyz:", call("GET", "/readyz"))
	draining.Store(true)
	fmt.Println("readyz while draining:", call("GET", "/readyz"))
	fmt.Println(len(raw), "distinct raw paths, but only these series:")
	w := httptest.NewRecorder()
	r.ServeHTTP(w, httptest.NewRequest("GET", "/metrics", nil))
	fmt.Print(w.Body.String())
}
Read the code

wg.Go, available since Go 1.25, starts each check, and each check writes only its own slot in errs, so no mutex is needed and the failed list keeps the configured order. The hung database blocks until the budget expires and is reported by name. The body leaves out the error text, because probe responses are often reachable from outside and internal hostnames do not belong there. Liveness answers 200 throughout, and draining short-circuits readiness before any check runs. countRequests labels by c.FullPath, so /users/1, /users/2 and /users/3 collapse into one series, the scanner paths become unmatched, and BREW becomes OTHER because the method string is client-controlled too. WriteText copies the map under the lock and sorts it, because map iteration order is random.

03

Why raw paths explode metric cardinality

Every distinct combination of label values is a separate time series that the metrics backend must store, index and query. Label by raw path, and every user ID, order number and scanner probe mints a new series. A crawler or a hostile client can create millions of them in an hour, which shows up as memory growth in your process, where the counter map lives, and again in the backend, where dashboards slow to a crawl. Prometheus's naming guidance is explicit: do not use labels for unbounded values such as user IDs or email addresses. Keep labels to bounded sets: the route template, a normalized method and the status class, or a short list of exact codes you actually alert on. Put the specifics in logs and traces, keyed by request ID, where high cardinality is expected and affordable. Status classes are enough for error-rate alerts; add exact codes when a dashboard has to tell 404 apart from 429.

04

Give readiness checks a budget and restraint

A readiness probe runs every few seconds on every replica, so keep it cheap: a ping with a short timeout, not a real query against a large table. One shared budget, set below the probe's own timeout, guarantees the endpoint answers in time. A probe that times out is still a failure, but it tells you nothing about which dependency caused it. Consider caching the result for a second or two, or running the checks in a background goroutine and letting /readyz read the latest result, so a burst of probes cannot add load to a struggling dependency. Include only dependencies without which the replica cannot serve anything. If a recommendations service is optional, degrade that feature instead of going unready; otherwise one optional outage removes the whole fleet from rotation, which is the liveness cascade again in a different form. Serve probes on an internal port where you can, and keep their bodies minimal.

05

From the model counter to a real metrics stack

Counters models what a metrics client does: a concurrency-safe map from a bounded label set to a number, exported in a text format. A real client adds latency histograms, which count observations per bucket, process metrics and the exact exposition format with label escaping. The standard library's expvar package is an option for simple counters, but importing it registers /debug/vars on http.DefaultServeMux and publishes the command line and memory statistics, so serve it only on an internal listener. Whichever you choose, keep the metrics endpoint off the public router. Tests should check that requests for different IDs share one series, that unmatched paths and unknown methods are bucketed, that readiness fails within its budget when a dependency hangs, that liveness stays 200 throughout, and that the counter survives parallel requests under the race detector.

TAKE THIS WITH YOU

Keep liveness free of dependency checks. Let readiness check required dependencies concurrently within a short budget and report draining. Label request counters only with bounded values: route template, normalized method and status class.

Check your understanding

Should a service's liveness probe fail when its database is unreachable?

Go to the source

Progress stays in this browser. No account needed.