Pidoku

Archive

This learning material is in the archive. It is not currently maintained and has not been updated with the latest information, so tool versions, prices and dates may be out of date.

Golden Signals, RED and USE

Module 3 Lesson 3.a 45 min Difficulty 2/5

Prerequisites 2.a

The idea in one minute#

Three short checklists cover almost everything worth monitoring:

  • The four golden signals (Google SRE book), for any user-facing system: latency, traffic, errors, saturation.
  • RED (Tom Wilkie), for every service: rate, errors, duration.
  • USE (Brendan Gregg), for every resource — CPU, memory, disk, network, connection pool, queue: utilisation, saturation, errors.

RED tells you a service is unhealthy; USE tells you which resource is why. If every service and every resource exposes these, most incidents can be located in minutes.

An analogy#

A doctor’s first check: pulse (traffic), blood pressure (latency), temperature (errors), and “how out of breath are you?” (saturation). It does not diagnose the disease, but it tells you very quickly whether something is wrong and roughly where to look next.

A picture#

flowchart TB
  subgraph SVC["Services — RED"]
    direction LR
    R1["<b>Rate</b><br/><small>requests/s</small>"]
    E1["<b>Errors</b><br/><small>failed/s</small>"]
    D1["<b>Duration</b><br/><small>latency histogram</small>"]
  end
  subgraph RES["Resources — USE"]
    direction LR
    U2["<b>Utilisation</b><br/><small>% busy</small>"]
    S2["<b>Saturation</b><br/><small>queued work</small>"]
    E2["<b>Errors</b><br/><small>device/driver errors</small>"]
  end
  USER[":i-users: Users"] --> SVC
  SVC -->|"which resource is the bottleneck?"| RES
  RES --> CPU[":i-cpu: CPU"]
  RES --> MEM[":i-memory-stick: Memory"]
  RES --> DSK[":i-hard-drive: Disk"]
  RES --> NET[":i-network: Network"]
  RES --> POOL[":i-database: Connection pool"]
  class USER neutral
  class R1,E1,D1 compute
  class U2,S2,E2 queue
  class CPU,MEM,DSK,NET,POOL memory

How it really works#

The four golden signals#

SignalMeasureWatch out for
LatencyHistogram of request duration, separately for successes and errorsA fast error (instant 500) lowers average latency; split them
TrafficRequests per second, by route; or sessions, transactions, bytesSudden drops are as alarming as spikes — traffic falling to zero is an outage
ErrorsFailed requests per second: explicit (5xx), implicit (200 with wrong content), policy (too slow)Errors hidden by retries or by a proxy returning a friendly page
SaturationHow “full” the service is: the most constrained resource — queue length, thread pool, memory, CPUSaturation usually rises before latency does; it is the early warning

RED for every service#

Expose three things for every endpoint, ideally from a shared middleware so no team forgets:

http_requests_total{route, method, code}                 counter   → rate and errors
http_request_duration_seconds_bucket{route, method, le}  histogram → duration percentiles
http_requests_in_flight{route}                           gauge     → a saturation hint

Typical queries:

# rate
sum by (route) (rate(http_requests_total[5m]))
# error ratio
sum by (route) (rate(http_requests_total{code=~"5.."}[5m])) / sum by (route) (rate(http_requests_total[5m]))
# p99 duration
histogram_quantile(0.99, sum by (route, le) (rate(http_request_duration_seconds_bucket[5m])))

Keep labels low-cardinality: route is the template (/users/{id}), never the raw path, and never a user ID.

USE for every resource#

ResourceUtilisationSaturationErrors
CPU% busy per coreRun-queue length (load above core count), throttling in containers—
Memory% used (excluding reclaimable cache)Swapping, page faults, OOM killsAllocation failures
Disk% time busyI/O queue depth, await timeDevice errors
Disk space% full— (full is the failure)Write errors (ENOSPC)
NetworkBytes/s vs link speedDrops, retransmits, socket backlog overflowsInterface errors
Connection poolConnections in use / maxGoroutines/threads waiting for a connectionConnection failures, timeouts
Work queueWorkers busy / workersItems waiting, oldest item ageFailed items, dead-lettered items
Go runtimeGoroutines, GC CPU fractionScheduler latencyPanics

The software resources at the bottom of the table cause more outages than the hardware ones. A connection pool of 10 in front of a database that can serve 200 is a bottleneck no CPU graph will show.

Saturation is the early warning#

Latency stays flat while a resource fills — until it is nearly full, then rises sharply (Module 7.e explains why with queueing theory). An alert or dashboard that shows queue length and the age of the oldest item sees trouble coming several minutes before an SLO alert does.

Where each one belongs#

UseSignals
PagesSLO burn-rate alerts (golden-signal errors and latency, measured at the edge)
TicketsSaturation trending towards full (disk at 85% and growing), certificate expiring
DashboardsEverything here, organised top-down: SLO → RED per service → USE per resource
DebuggingTraces, logs, profiles — the observability tools

A worked example#

Checkout’s p99 latency jumps from 300 ms to 4 s. Walking the checklists:

  1. RED on checkout: rate is normal, errors are slightly up (timeouts), duration is way up — for every route, not one. Something shared.
  2. RED on dependencies: payments and inventory APIs are fast. So the time is spent inside checkout, or waiting before calling anything.
  3. USE on checkout’s resources: CPU 35%, memory fine. DB connection pool: 20 of 20 in use, 140 goroutines waiting for a connection. Saturation found.
  4. Why? A new report query deployed an hour ago holds connections for 2 seconds each.

Four steps, about three minutes, and nobody had to guess. The program below builds exactly that instrumentation: RED middleware and a connection-pool gauge, served in Prometheus text format.

Code#

This program serves HTTP, so gocheck -run skips it. It sends itself requests with httptest and prints the metrics page, so you can run it without opening a browser.

Go
// red.go — RED middleware plus a pool-saturation gauge, exposed in Prometheus text format.
package main

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

var buckets = []float64{0.05, 0.1, 0.25, 0.5, 1, 2.5, 5}

type metrics struct {
	mu       sync.Mutex
	requests map[string]int     // route|code → count
	hist     map[string][]int   // route → cumulative bucket counts (+Inf last)
	sum      map[string]float64 // route → total seconds
	inFlight int
}

func newMetrics() *metrics {
	return &metrics{requests: map[string]int{}, hist: map[string][]int{}, sum: map[string]float64{}}
}

type statusWriter struct {
	http.ResponseWriter
	code int
}

func (w *statusWriter) WriteHeader(c int) { w.code = c; w.ResponseWriter.WriteHeader(c) }

// red wraps a handler for one route template (never the raw path: it would explode cardinality).
func (m *metrics) red(route string, h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		m.mu.Lock()
		m.inFlight++
		m.mu.Unlock()
		start := time.Now()
		sw := &statusWriter{ResponseWriter: w, code: 200}
		h(sw, r)
		d := time.Since(start).Seconds()

		m.mu.Lock()
		defer m.mu.Unlock()
		m.inFlight--
		m.requests[fmt.Sprintf("%s|%d", route, sw.code)]++
		if m.hist[route] == nil {
			m.hist[route] = make([]int, len(buckets)+1)
		}
		for i, b := range buckets {
			if d <= b {
				m.hist[route][i]++
			}
		}
		m.hist[route][len(buckets)]++
		m.sum[route] += d
	}
}

// pool is a tiny connection pool whose saturation we expose (USE for a software resource).
type pool struct {
	slots   chan struct{}
	waiting int
	mu      sync.Mutex
}

func (p *pool) acquire() {
	p.mu.Lock()
	p.waiting++
	p.mu.Unlock()
	p.slots <- struct{}{}
	p.mu.Lock()
	p.waiting--
	p.mu.Unlock()
}
func (p *pool) release() { <-p.slots }

func (m *metrics) expose(p *pool) http.HandlerFunc {
	return func(w http.ResponseWriter, _ *http.Request) {
		m.mu.Lock()
		defer m.mu.Unlock()
		var b strings.Builder
		b.WriteString("# TYPE http_requests_total counter\n")
		keys := make([]string, 0, len(m.requests))
		for k := range m.requests {
			keys = append(keys, k)
		}
		sort.Strings(keys)
		for _, k := range keys {
			parts := strings.Split(k, "|")
			fmt.Fprintf(&b, "http_requests_total{route=%q,code=%q} %d\n", parts[0], parts[1], m.requests[k])
		}
		b.WriteString("# TYPE http_request_duration_seconds histogram\n")
		for route, counts := range m.hist {
			for i, le := range buckets {
				fmt.Fprintf(&b, "http_request_duration_seconds_bucket{route=%q,le=\"%g\"} %d\n", route, le, counts[i])
			}
			fmt.Fprintf(&b, "http_request_duration_seconds_bucket{route=%q,le=\"+Inf\"} %d\n", route, counts[len(buckets)])
			fmt.Fprintf(&b, "http_request_duration_seconds_sum{route=%q} %.3f\n", route, m.sum[route])
			fmt.Fprintf(&b, "http_request_duration_seconds_count{route=%q} %d\n", route, counts[len(buckets)])
		}
		p.mu.Lock()
		fmt.Fprintf(&b, "# TYPE db_pool_in_use gauge\ndb_pool_in_use %d\n", len(p.slots))
		fmt.Fprintf(&b, "db_pool_max %d\n", cap(p.slots))
		fmt.Fprintf(&b, "# TYPE db_pool_waiting gauge\ndb_pool_waiting %d\n", p.waiting)
		p.mu.Unlock()
		fmt.Fprintf(&b, "http_requests_in_flight %d\n", m.inFlight)
		w.Write([]byte(b.String()))
	}
}

func main() {
	m := newMetrics()
	db := &pool{slots: make(chan struct{}, 4)} // a deliberately small pool
	mux := http.NewServeMux()
	mux.HandleFunc("/checkout", m.red("/checkout", func(w http.ResponseWriter, r *http.Request) {
		db.acquire()
		defer db.release()
		time.Sleep(time.Duration(20+rand.Intn(80)) * time.Millisecond) // the query
		if rand.Intn(50) == 0 {
			w.WriteHeader(http.StatusInternalServerError)
		}
	}))
	mux.HandleFunc("/metrics", m.expose(db))
	srv := httptest.NewServer(mux)
	defer srv.Close()

	// 40 concurrent shoppers against a pool of 4: watch db_pool_waiting.
	var wg sync.WaitGroup
	for i := 0; i < 40; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 5; j++ {
				if resp, err := http.Post(srv.URL+"/checkout", "application/json", nil); err == nil {
					resp.Body.Close()
				}
			}
		}()
	}
	time.Sleep(150 * time.Millisecond)
	var page []byte
	if snap, err := http.Get(srv.URL + "/metrics"); err == nil { // mid-load: the pool is saturated
		page, _ = io.ReadAll(snap.Body)
		snap.Body.Close()
	}
	wg.Wait()
	fmt.Println("── /metrics during the load ──")
	fmt.Print(string(page))
}

Notice that db_pool_waiting is large while CPU (not shown) would be nearly idle: the service is saturated on a software resource. Raise the pool size to 40 and run again — the p99 bucket counts move left.

Remember this#

  • Golden signals: latency, traffic, errors, saturation. RED for services, USE for resources.
  • Split latency of successes and errors; treat a traffic drop as seriously as an error spike.
  • Software resources — pools, queues, worker counts — need USE metrics too, and cause many outages.
  • Saturation is the early warning; SLO burn is what pages.

Try it#

  1. Run red.go (go run red.go). Change the pool size to 40. What happens to db_pool_waiting and to the duration histogram?
  2. Pick a service you know and write its RED queries and the USE table for its three most constrained resources.
  3. Find one software resource in your system (a pool, a semaphore, a queue) that has no metric.

Check yourself#

  1. Why should latency of successful and failed requests be measured separately?
  2. Which checklist would find an exhausted database connection pool, and under which letter?
  3. Why is route="/users/{id}" a good label and path="/users/8812" a bad one?
  4. Why is traffic dropping to zero an alertable symptom?

Sources#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in