Lesson 11 / 15 · Production & Operations

Monitoring & observability

Monitor a Go database in production: Prometheus metrics, structured logging with zap, profiling, health checks and the four golden signals.

2-3 hours advanced Not completed

On this page · 6 sections
  1. Prometheus Metrics
  2. Structured Logging
  3. Performance Profiling
  4. Health Checks
  5. Lab: Monitoring System
  6. Quiz

You cannot fix what you cannot see. Here you will expose Prometheus metrics (request rate, latency histograms, errors), switch to structured logs, add health and readiness endpoints, and wire pprof in so you can profile the live server.

Prometheus Metrics

What are Metrics?

Metrics are measurements that help you understand system behavior:

Counter

Only increases

requests_total
errors_total
bytes_written_total

Gauge

Can go up or down

current_connections
memory_usage_bytes
queue_length

Histogram

Distribution of values

latency_seconds with buckets
request_size_bytes
response_time

Summary

Percentiles computed on client side

quantile="0.5" value="0.1"
quantile="0.95" value="0.5"
quantile="0.99" value="1.0"

Four Golden Signals

Start with these four signals (latency, traffic, errors, saturation); most incidents show up in one of them first:

1. Latency - How long requests take
   Metric: request_duration_seconds
   Target: p99 < 100ms

2. Traffic - How much work happening
   Metric: requests_per_second
   Target: 10,000+ ops/sec

3. Errors - How many requests fail
   Metric: error_rate_percent
   Target: < 1%

4. Saturation - How utilized is system
   Metric: cpu_percent, memory_percent
   Target: < 70%

Implementing Prometheus Metrics

package metrics

import (
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promauto"
)

type Metrics struct {
    // Counters - always increase
    RequestsTotal prometheus.Counter
    ErrorsTotal   prometheus.Counter
    
    // Gauges - can go up/down
    ConnectionCount prometheus.Gauge
    MemoryBytes     prometheus.Gauge
    
    // Histograms - distribution with buckets
    RequestLatency  prometheus.Histogram
}

// NewMetrics creates all metrics
func NewMetrics() *Metrics {
    return &Metrics{
        RequestsTotal: promauto.NewCounter(prometheus.CounterOpts{
            Name: "kvdb_requests_total",
            Help: "Total number of requests",
        }),
        
        ErrorsTotal: promauto.NewCounter(prometheus.CounterOpts{
            Name: "kvdb_errors_total",
            Help: "Total number of errors",
        }),
        
        ConnectionCount: promauto.NewGauge(prometheus.GaugeOpts{
            Name: "kvdb_connections",
            Help: "Current number of connections",
        }),
        
        MemoryBytes: promauto.NewGauge(prometheus.GaugeOpts{
            Name: "kvdb_memory_bytes",
            Help: "Memory usage in bytes",
        }),
        
        RequestLatency: promauto.NewHistogram(prometheus.HistogramOpts{
            Name: "kvdb_request_latency_seconds",
            Help: "Request latency",
            Buckets: []float64{0.001, 0.01, 0.1, 1},
        }),
    }
}

// RecordRequest records a request
func (m *Metrics) RecordRequest(duration float64, hasError bool) {
    m.RequestsTotal.Inc()
    m.RequestLatency.Observe(duration)
    
    if hasError {
        m.ErrorsTotal.Inc()
    }
}

// UpdateConnections updates connection gauge
func (m *Metrics) UpdateConnections(count int64) {
    m.ConnectionCount.Set(float64(count))
}

// UpdateMemory updates memory gauge
func (m *Metrics) UpdateMemory(bytes int64) {
    m.MemoryBytes.Set(float64(bytes))
}

Using Metrics in Server

import (
    "net/http"
    "time"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

type Server struct {
    metrics *Metrics
}

// HandleRequest records metrics for each request
func (s *Server) HandleRequest(operation string) error {
    start := time.Now()
    
    // Do work
    err := s.doWork()
    
    // Record metrics
    duration := time.Since(start).Seconds()
    s.metrics.RecordRequest(duration, err != nil)
    
    return err
}

// ExposeMetrics starts Prometheus endpoint
func (s *Server) ExposeMetrics(addr string) {
    http.Handle("/metrics", promhttp.Handler())
    go http.ListenAndServe(addr, nil)
}

Structured Logging

Problem: Unstructured Logs

Bad

2025-01-16 10:15:23 Request from 192.168.1.1 with key user:100 took 50ms

Problems:
- Hard to parse
- Inconsistent format
- Can't filter/search easily

Solution: Structured Logging

Better

{
  "timestamp": "2025-01-16T10:15:23Z",
  "level": "error",
  "message": "request failed",
  "client_ip": "192.168.1.1",
  "key": "user:100",
  "duration_ms": 50,
  "error": "timeout"
}

Benefits:
- Easy to parse
- Consistent format
- Can filter/search
- Can aggregate

Using zap Logger

import "go.uber.org/zap"

// Create logger
logger, _ := zap.NewProduction()
defer logger.Sync()

// Log with fields
logger.Info("operation completed",
    zap.String("operation", "GET"),
    zap.String("key", "user:100"),
    zap.Duration("latency", 50*time.Millisecond),
    zap.Int("status_code", 200),
)

// Log errors
logger.Error("operation failed",
    zap.String("operation", "PUT"),
    zap.Error(err),
    zap.Duration("latency", 100*time.Millisecond),
)

// Log levels
logger.Debug("debug info")
logger.Info("informational")
logger.Warn("warning")
logger.Error("error")

Performance Profiling

CPU Profiling

import (
    "runtime/pprof"
    "os"
)

// Start profiling
f, _ := os.Create("cpu.prof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
defer f.Close()

// Run operations
for i := 0; i < 1000000; i++ {
    store.Get([]byte("key"))
}

// Analyze: go tool pprof cpu.prof

Memory Profiling

import "runtime/pprof"

// Capture heap
f, _ := os.Create("heap.prof")
pprof.WriteHeapProfile(f)
f.Close()

// Analyze: go tool pprof heap.prof

HTTP Profiling Endpoint

import _ "net/http/pprof"

// Available endpoints:
// /debug/pprof/profile?seconds=30  - CPU profile
// /debug/pprof/heap                - Memory profile
// /debug/pprof/goroutine           - Goroutine profile

Health Checks

Liveness Probe (Is server alive?)

func (s *Server) Liveness() bool {
    // Simple check - is process running?
    return s.db != nil
}

// HTTP endpoint
func (s *Server) handleLiveness(w http.ResponseWriter, r *http.Request) {
    if s.Liveness() {
        w.WriteHeader(200)
        w.Write([]byte("alive"))
    } else {
        w.WriteHeader(500)
    }
}

// Usage: GET /healthz

Readiness Probe (Can serve requests?)

func (s *Server) Readiness() (bool, string) {
    // Database check
    _, err := s.db.Get(context.Background(), []byte("health"))
    if err != nil {
        return false, "database down"
    }
    
    // Replication check
    lag := s.replication.GetLag()
    if lag > 5*time.Second {
        return false, "replication lag too high"
    }
    
    // Disk check
    if s.getDiskUsagePercent() > 90 {
        return false, "disk full"
    }
    
    return true, "ready"
}

// HTTP endpoint
func (s *Server) handleReadiness(w http.ResponseWriter, r *http.Request) {
    ready, reason := s.Readiness()
    if ready {
        w.WriteHeader(200)
        w.Write([]byte("ready"))
    } else {
        w.WriteHeader(503)
        w.Write([]byte(reason))
    }
}

// Usage: GET /readyz

Lab: Monitoring System

Objective

Add metrics, structured logging, profiling and health checks to the server.

Requirements

  • Prometheus Metrics: Counters, gauges, histograms for all operations

  • Structured Logging: JSON logs with zap for all events

  • Performance Profiling: CPU and memory profiling endpoints

  • Health Checks: Liveness and readiness probes

  • Monitoring Dashboard: Grafana dashboard with key metrics

  • Alerting: Alert rules for critical metrics

Starter code

Fill in every TODO. The hints and a tested reference solution are further down.

type MonitoringSystem struct {
    metrics *Metrics
    logger  *zap.Logger
}

func NewMonitoringSystem() *MonitoringSystem {
    metrics := NewMetrics()
    logger, _ := zap.NewProduction()
    return &MonitoringSystem{metrics, logger}
}

func (ms *MonitoringSystem) RecordOperation(op string, duration time.Duration, err error) {
    ms.metrics.RecordRequest(duration.Seconds(), err != nil)
    
    if err != nil {
        ms.logger.Error("operation failed",
            zap.String("operation", op),
            zap.Duration("latency", duration),
            zap.Error(err),
        )
    } else {
        ms.logger.Info("operation succeeded",
            zap.String("operation", op),
            zap.Duration("latency", duration),
        )
    }
}

// TODO: Implement health checks
func (ms *MonitoringSystem) Liveness() bool {
    return true
}

func (ms *MonitoringSystem) Readiness() (bool, string) {
    return true, "ready"
}

// TODO: Implement profiling endpoints
func (ms *MonitoringSystem) SetupProfiling() {
    // Add /debug/pprof endpoints
}

Test Template

func TestMetrics(t *testing.T) {
    metrics := NewMetrics()
    
    // Record some operations
    metrics.RecordRequest(0.1, false)
    metrics.RecordRequest(0.2, true)
    metrics.UpdateConnections(100)
    
    // Verify metrics were recorded
    // (In real test, you'd check Prometheus registry)
}

func TestHealthChecks(t *testing.T) {
    ms := NewMonitoringSystem()
    
    // Test liveness
    assert.True(t, ms.Liveness())
    
    // Test readiness
    ready, reason := ms.Readiness()
    assert.True(t, ready)
    assert.Equal(t, "ready", reason)
}

func TestLogging(t *testing.T) {
    logger, _ := zap.NewDevelopment()
    
    logger.Info("test message",
        zap.String("key", "value"),
        zap.Int("count", 42),
    )
    
    // In real test, you'd capture log output
}

Acceptance Criteria

  • All operations record metrics

  • Structured JSON logs for all events

  • CPU and memory profiling working

  • Liveness probe responds correctly

  • Readiness probe checks all dependencies

  • Grafana dashboard shows key metrics

  • Alert rules trigger on critical conditions

  • > 90% code coverage

  • All tests pass

Hints

  • Create metrics on your own prometheus.Registry instead of the global one, so tests and multiple servers in one process do not collide.
  • Label requests by operation and status (ok, not_found, error). A cache miss is not an error and should not page anyone.
  • Keep liveness trivial (is the process responsive?) and put real checks in readiness (started, storage reachable, replication lag, not draining).
  • Log every error, but log successes only when they are slow; logging each request at high QPS costs more than the request.
  • Serve /debug/pprof only on an internal port.

Reference solution

Try the lab on your own first, then compare. It uses Prometheus and zap as in the lesson, with labelled metrics, liveness and readiness probes and pprof endpoints. It compiles and passes its tests with go test -race (Go 1.22 or newer).

Reference solution: monitoring.go
package monitoring

import (
    "context"
    "errors"
    "net/http"
    "net/http/pprof"
    "runtime"
    "sync/atomic"
    "time"

    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
    "go.uber.org/zap"
)

var ErrNotFound = errors.New("not found")

// Store is the part of the database the readiness probe touches.
type Store interface {
    Get(ctx context.Context, key []byte) ([]byte, error)
}

// Metrics uses its own registry so tests (and several servers in one process) don't collide.
type Metrics struct {
    Registry        *prometheus.Registry
    Requests        *prometheus.CounterVec   // by operation and status
    RequestLatency  *prometheus.HistogramVec // by operation
    ConnectionCount prometheus.Gauge
    MemoryBytes     prometheus.Gauge
    ReplicationLag  prometheus.Gauge
}

func NewMetrics() *Metrics {
    m := &Metrics{
        Registry: prometheus.NewRegistry(),
        Requests: prometheus.NewCounterVec(prometheus.CounterOpts{
            Name: "kvdb_requests_total", Help: "Requests by operation and status.",
        }, []string{"op", "status"}),
        RequestLatency: prometheus.NewHistogramVec(prometheus.HistogramOpts{
            Name: "kvdb_request_duration_seconds", Help: "Request latency.",
            Buckets: []float64{.0001, .0005, .001, .005, .01, .05, .1, .5, 1},
        }, []string{"op"}),
        ConnectionCount: prometheus.NewGauge(prometheus.GaugeOpts{Name: "kvdb_connections", Help: "Open client connections."}),
        MemoryBytes:     prometheus.NewGauge(prometheus.GaugeOpts{Name: "kvdb_memory_bytes", Help: "Heap in use."}),
        ReplicationLag:  prometheus.NewGauge(prometheus.GaugeOpts{Name: "kvdb_replication_lag_seconds", Help: "Follower lag."}),
    }
    m.Registry.MustRegister(m.Requests, m.RequestLatency, m.ConnectionCount, m.MemoryBytes, m.ReplicationLag,
        prometheus.NewGoCollector(), prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
    return m
}

// MonitoringSystem bundles metrics, logs, health checks and profiling for the server.
type MonitoringSystem struct {
    metrics   *Metrics
    logger    *zap.Logger
    store     Store
    lag       func() time.Duration // nil if this node is not a follower
    started   atomic.Bool          // set once startup (WAL replay etc.) has finished
    draining  atomic.Bool          // set during graceful shutdown
    MaxLag    time.Duration
    SlowQuery time.Duration
}

func NewMonitoringSystem(store Store, logger *zap.Logger, lag func() time.Duration) *MonitoringSystem {
    if logger == nil {
        logger = zap.NewNop()
    }
    return &MonitoringSystem{metrics: NewMetrics(), logger: logger, store: store, lag: lag,
        MaxLag: 5 * time.Second, SlowQuery: 100 * time.Millisecond}
}

func (ms *MonitoringSystem) Metrics() *Metrics { return ms.metrics }
func (ms *MonitoringSystem) MarkStarted()      { ms.started.Store(true) }
func (ms *MonitoringSystem) MarkDraining()     { ms.draining.Store(true) }

// RecordOperation counts and times one operation. Successes are logged only when slow,
// so logs stay useful at high request rates.
func (ms *MonitoringSystem) RecordOperation(op string, d time.Duration, err error) {
    status := "ok"
    if errors.Is(err, ErrNotFound) {
        status = "not_found" // a miss is not a server error
    } else if err != nil {
        status = "error"
    }
    ms.metrics.Requests.WithLabelValues(op, status).Inc()
    ms.metrics.RequestLatency.WithLabelValues(op).Observe(d.Seconds())
    switch {
    case status == "error":
        ms.logger.Error("operation failed", zap.String("op", op), zap.Duration("latency", d), zap.Error(err))
    case d > ms.SlowQuery:
        ms.logger.Warn("slow operation", zap.String("op", op), zap.Duration("latency", d))
    }
}

// Liveness: is the process able to respond at all? Keep it trivial so a busy
// server is not restarted by Kubernetes.
func (ms *MonitoringSystem) Liveness() bool { return true }

// Readiness: should the load balancer send traffic here?
func (ms *MonitoringSystem) Readiness() (bool, string) {
    if !ms.started.Load() {
        return false, "starting"
    }
    if ms.draining.Load() {
        return false, "shutting down"
    }
    ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
    defer cancel()
    if _, err := ms.store.Get(ctx, []byte("__health__")); err != nil && !errors.Is(err, ErrNotFound) {
        return false, "storage unavailable: " + err.Error()
    }
    if ms.lag != nil {
        lag := ms.lag()
        ms.metrics.ReplicationLag.Set(lag.Seconds())
        if lag > ms.MaxLag {
            return false, "replication lag " + lag.String()
        }
    }
    return true, "ready"
}

// Handler serves /metrics, /healthz, /readyz and /debug/pprof/*. Bind it to an
// internal-only address: pprof must never be public.
func (ms *MonitoringSystem) Handler() http.Handler {
    mux := http.NewServeMux()
    mux.Handle("/metrics", promhttp.HandlerFor(ms.metrics.Registry, promhttp.HandlerOpts{}))
    mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
        if ms.Liveness() {
            w.Write([]byte("alive"))
            return
        }
        http.Error(w, "dead", http.StatusInternalServerError)
    })
    mux.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) {
        if ok, reason := ms.Readiness(); !ok {
            http.Error(w, reason, http.StatusServiceUnavailable)
            return
        }
        w.Write([]byte("ready"))
    })
    ms.SetupProfiling(mux)
    return mux
}

// SetupProfiling registers the pprof endpoints on mux.
func (ms *MonitoringSystem) SetupProfiling(mux *http.ServeMux) {
    mux.HandleFunc("/debug/pprof/", pprof.Index)
    mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
    mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
    mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
    mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
}

// SampleRuntime updates the memory gauge every interval until ctx ends.
func (ms *MonitoringSystem) SampleRuntime(ctx context.Context, every time.Duration) {
    t := time.NewTicker(every)
    defer t.Stop()
    var m runtime.MemStats
    for {
        runtime.ReadMemStats(&m)
        ms.metrics.MemoryBytes.Set(float64(m.HeapInuse))
        select {
        case <-ctx.Done():
            return
        case <-t.C:
        }
    }
}
Tests: monitoring_test.go
package monitoring

import (
    "context"
    "errors"
    "io"
    "net/http/httptest"
    "strings"
    "testing"
    "time"
)

type store struct{ err error }

func (s store) Get(context.Context, []byte) ([]byte, error) { return nil, s.err }

func TestProbesAndMetrics(t *testing.T) {
    lag := time.Duration(0)
    ms := NewMonitoringSystem(store{err: ErrNotFound}, nil, func() time.Duration { return lag })
    srv := httptest.NewServer(ms.Handler())
    defer srv.Close()
    get := func(p string) (int, string) {
        r, err := srv.Client().Get(srv.URL + p)
        if err != nil {
            t.Fatal(err)
        }
        b, _ := io.ReadAll(r.Body)
        r.Body.Close()
        return r.StatusCode, string(b)
    }
    if c, _ := get("/readyz"); c != 503 {
        t.Fatal("ready before start", c)
    }
    ms.MarkStarted()
    if c, b := get("/readyz"); c != 200 {
        t.Fatal(c, b)
    }
    lag = 10 * time.Second
    if c, _ := get("/readyz"); c != 503 {
        t.Fatal("lag ignored")
    }
    if c, _ := get("/healthz"); c != 200 {
        t.Fatal("liveness")
    }
    ms.RecordOperation("get", 2*time.Millisecond, nil)
    ms.RecordOperation("set", time.Millisecond, errors.New("disk full"))
    _, body := get("/metrics")
    if !strings.Contains(body, `kvdb_requests_total{op="set",status="error"} 1`) {
        t.Fatal(body[:300])
    }
    if c, _ := get("/debug/pprof/"); c != 200 {
        t.Fatal("pprof")
    }
}

Quiz

  1. Name the four golden signals.
  2. Why structured logs instead of free-form text?
  3. What’s the difference between a liveness and a readiness probe?
Show answers
  1. Latency, traffic, errors and saturation.
  2. Fields such as key, latency_ms and error can be filtered, aggregated and alerted on without fragile text parsing.
  3. Liveness asks whether the process should be restarted; readiness asks whether it should receive traffic right now (for example after recovery finishes).

Done with this lesson?

Marking it complete updates the sidebar, the course page and the Continue button.