Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
27 Nov 2026 · 18 min read ·Article 98 / 208
Go

Golang Observability: Prometheus Metrics, Grafana Dashboard, OpenTelemetry Tracing

The complete observability setup for Santekno Shop. Prometheus metrics, Grafana dashboard, OpenTelemetry distributed tracing, structured logging, and alerting rules for a production baseline.

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Golang observability is the foundation that must exist before load testing and before deploying to production. Its three pillars: Metrics (Prometheus), Traces (OpenTelemetry), and Logs (structured JSON). In this article we set all of them up for Santekno Shop with code you can use directly.


18.01 The Three Pillars of Observability

Before writing instrumentation code, it’s important to understand which question each pillar answers. The summary below maps metrics, traces, and logs to their respective roles, plus the Golden Signals from Google SRE.

text
 1METRICS (Prometheus + Grafana):
 2  "What is happening in aggregate?"
 3  → QPS, latency percentile, error rate, DB pool size
 4  → Alert when a value crosses a threshold
 5
 6TRACES (OpenTelemetry + Jaeger/Tempo):
 7  "Why is this request slow?"
 8  → Distributed trace from HTTP request down to DB query
 9  → Identify bottleneck: handler vs usecase vs DB
10
11LOGS (structured JSON + Loki):
12  "What happened on this request?"
13  → Correlation via request ID + trace ID
14  → Error detail with stack context
15
16Golden Signals (Google SRE):
17  1. Latency    → histogram p50/p95/p99
18  2. Traffic    → requests per second
19  3. Errors     → error rate %
20  4. Saturation → CPU, memory, connection pool, queue depth

The three pillars complement each other: metrics tell you a problem exists, traces show where, and logs explain what exactly happened.


18.02 Prometheus Metrics Setup

The first step is defining the metrics we want to observe. The file below declares counters, histograms, and gauges for HTTP, business, and infrastructure with the santekno namespace.

go
 1// internal/infrastructure/metrics/metrics.go
 2
 3package metrics
 4
 5import (
 6    "github.com/prometheus/client_golang/prometheus"
 7    "github.com/prometheus/client_golang/prometheus/promauto"
 8)
 9
10var (
11    // HTTP metrics
12    HTTPRequestsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
13        Namespace: "santekno",
14        Subsystem: "http",
15        Name:      "requests_total",
16        Help:      "Total HTTP requests",
17    }, []string{"method", "path", "status"})
18
19    HTTPRequestDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
20        Namespace: "santekno",
21        Subsystem: "http",
22        Name:      "request_duration_seconds",
23        Help:      "HTTP request duration",
24        Buckets:   []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5},
25    }, []string{"method", "path"})
26
27    // Business metrics
28    OrdersCreatedTotal = promauto.NewCounterVec(prometheus.CounterOpts{
29        Namespace: "santekno",
30        Subsystem: "business",
31        Name:      "orders_created_total",
32        Help:      "Total orders created",
33    }, []string{"status", "payment_method"})
34
35    OrderCancellationsTotal = promauto.NewCounter(prometheus.CounterOpts{
36        Namespace: "santekno",
37        Subsystem: "business",
38        Name:      "order_cancellations_total",
39        Help:      "Total orders cancelled",
40    })
41
42    RevenueTotal = promauto.NewCounterVec(prometheus.CounterOpts{
43        Namespace: "santekno",
44        Subsystem: "business",
45        Name:      "revenue_total_idr_cents",
46        Help:      "Total revenue in IDR cents",
47    }, []string{"payment_method"})
48
49    // Infrastructure metrics
50    DBPoolAcquireTotal = promauto.NewCounter(prometheus.CounterOpts{
51        Namespace: "santekno",
52        Subsystem: "db",
53        Name:      "pool_acquire_total",
54        Help:      "Total DB pool acquisitions",
55    })
56
57    DBPoolSize = promauto.NewGauge(prometheus.GaugeOpts{
58        Namespace: "santekno",
59        Subsystem: "db",
60        Name:      "pool_size",
61        Help:      "Current DB pool size",
62    })
63
64    CacheHitsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
65        Namespace: "santekno",
66        Subsystem: "cache",
67        Name:      "hits_total",
68        Help:      "Total cache hits",
69    }, []string{"cache", "result"}) // result: hit/miss
70
71    OutboxPendingCount = promauto.NewGauge(prometheus.GaugeOpts{
72        Namespace: "santekno",
73        Subsystem: "outbox",
74        Name:      "pending_events",
75        Help:      "Number of unpublished outbox events",
76    })
77
78    KafkaConsumerLag = promauto.NewGaugeVec(prometheus.GaugeOpts{
79        Namespace: "santekno",
80        Subsystem: "kafka",
81        Name:      "consumer_lag",
82        Help:      "Kafka consumer group lag",
83    }, []string{"topic", "partition"})
84)

Notice the choice of types: counters for values that only increase (total requests, revenue), histograms for latency distributions, and gauges for values that can go up and down (pool size, outbox lag).


18.03 HTTP Metrics Middleware

HTTP metrics are most practically collected via middleware that wraps every request. The middleware below records the total request count and its duration for each combination of method, path, and status.

go
 1// delivery/http/middleware/metrics.go
 2
 3package middleware
 4
 5import (
 6    "strconv"
 7    "time"
 8
 9    "github.com/labstack/echo/v4"
10    "github.com/santekno/santekno-shop/internal/infrastructure/metrics"
11)
12
13func Metrics() echo.MiddlewareFunc {
14    return func(next echo.HandlerFunc) echo.HandlerFunc {
15        return func(c echo.Context) error {
16            start := time.Now()
17
18            err := next(c)
19
20            duration := time.Since(start).Seconds()
21            status := strconv.Itoa(c.Response().Status)
22
23            // Normalize path to avoid cardinality explosion
24            // /api/v1/orders/some-uuid → /api/v1/orders/:id
25            path := c.Path()
26
27            metrics.HTTPRequestsTotal.WithLabelValues(
28                c.Request().Method,
29                path,
30                status,
31            ).Inc()
32
33            metrics.HTTPRequestDuration.WithLabelValues(
34                c.Request().Method,
35                path,
36            ).Observe(duration)
37
38            return err
39        }
40    }
41}

The key here is c.Path(), which returns the route template (/api/v1/orders/:id) rather than the actual path with the UUID — this prevents a label cardinality explosion that could overwhelm Prometheus.


18.04 Business Metrics Integration

Beyond technical metrics, we want to track numbers that matter to the business. The example below records order count and revenue in the usecase after the operation succeeds.

go
 1// Record business metrics in the usecase after the operation succeeds
 2
 3// internal/usecase/order/place_order.go
 4func (uc *PlaceOrderUseCase) Execute(ctx context.Context, input PlaceOrderInput) (*domainOrder.Order, error) {
 5    // ... normal implementation ...
 6
 7    if err := uc.orderRepo.Create(ctx, o); err != nil {
 8        return nil, fmt.Errorf("placeOrder.Execute: %w", err)
 9    }
10
11    // Record business metrics
12    metrics.OrdersCreatedTotal.WithLabelValues(
13        string(o.Status),
14        string(o.PaymentMethod),
15    ).Inc()
16
17    metrics.RevenueTotal.WithLabelValues(
18        string(o.PaymentMethod),
19    ).Add(float64(o.TotalAmountIDR))
20
21    return o, nil
22}

Notice that the metrics are recorded after Create succeeds — so revenue and order counts are never tallied for a transaction that failed or was rolled back.


18.05 Prometheus Endpoint

Prometheus needs an endpoint to scrape metrics, plus health checks for the orchestrator. The code below registers /metrics, /health, and /ready on the server.

go
 1// cmd/server/main.go
 2
 3import (
 4    "github.com/prometheus/client_golang/prometheus/promhttp"
 5)
 6
 7func setupRoutes(e *echo.Echo, c *Container) {
 8    // Metrics endpoint (no auth needed — scraped from internal network)
 9    e.GET("/metrics", echo.WrapHandler(promhttp.Handler()))
10
11    // Health endpoint
12    e.GET("/health", healthHandler(c))
13    e.GET("/ready", readinessHandler(c))
14
15    // API routes
16    api := e.Group("/api/v1")
17    // ... routes ...
18}
19
20// Health handler
21func healthHandler(c *Container) echo.HandlerFunc {
22    return func(ctx echo.Context) error {
23        return ctx.JSON(200, map[string]string{
24            "status": "ok",
25            "version": version,
26        })
27    }
28}
29
30// Readiness: check DB + Redis
31func readinessHandler(c *Container) echo.HandlerFunc {
32    return func(ctx echo.Context) error {
33        if err := c.DB.Ping(ctx.Request().Context()); err != nil {
34            return ctx.JSON(503, map[string]string{"status": "db_unavailable"})
35        }
36        if err := c.Redis.Ping(ctx.Request().Context()).Err(); err != nil {
37            return ctx.JSON(503, map[string]string{"status": "redis_unavailable"})
38        }
39        return ctx.JSON(200, map[string]string{"status": "ready"})
40    }
41}

The difference between /health and /ready matters: health merely proves the process is alive, whereas readiness checks the dependencies (DB, Redis) so the orchestrator doesn’t route traffic to a pod that isn’t ready yet.


18.06 Structured Logging

Logs that are useful in production must be structured and machine-parseable. The Zap configuration below produces JSON with standard fields like timestamp and severity.

go
 1// pkg/logger/logger.go
 2
 3package logger
 4
 5import (
 6    "os"
 7    "go.uber.org/zap"
 8    "go.uber.org/zap/zapcore"
 9)
10
11var global *zap.Logger
12
13func Init(env string) {
14    var cfg zap.Config
15    if env == "production" {
16        cfg = zap.NewProductionConfig()
17    } else {
18        cfg = zap.NewDevelopmentConfig()
19    }
20
21    // Always JSON in production (for Loki/Datadog parsing)
22    cfg.Encoding = "json"
23    cfg.EncoderConfig.TimeKey = "timestamp"
24    cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
25    cfg.EncoderConfig.MessageKey = "message"
26    cfg.EncoderConfig.LevelKey = "severity"
27
28    var err error
29    global, err = cfg.Build()
30    if err != nil {
31        panic(err)
32    }
33}
34
35func Get() *zap.Logger {
36    if global == nil { Init("development") }
37    return global
38}
39
40// Helper for a request-scoped logger with request_id
41func WithRequestID(requestID string) *zap.Logger {
42    return Get().With(zap.String("request_id", requestID))
43}

The field naming like severity and timestamp is deliberately aligned with the Loki/Datadog conventions, so logs can be filtered and queried directly without extra transformation.


18.07 Request Logging Middleware

Every request ideally produces one structured log line with a request ID. The middleware below creates or forwards X-Request-ID and then records the request details after it completes.

go
 1// delivery/http/middleware/logging.go
 2
 3package middleware
 4
 5import (
 6    "time"
 7
 8    "github.com/labstack/echo/v4"
 9    "go.uber.org/zap"
10    "github.com/santekno/santekno-shop/pkg/logger"
11)
12
13func RequestLogger() echo.MiddlewareFunc {
14    return func(next echo.HandlerFunc) echo.HandlerFunc {
15        return func(c echo.Context) error {
16            start := time.Now()
17            req := c.Request()
18
19            // Get or generate a request ID
20            requestID := req.Header.Get("X-Request-ID")
21            if requestID == "" {
22                requestID = generateRequestID()
23            }
24            c.Set("request_id", requestID)
25            c.Response().Header().Set("X-Request-ID", requestID)
26
27            err := next(c)
28
29            duration := time.Since(start)
30            status := c.Response().Status
31
32            logger.Get().Info("request",
33                zap.String("request_id", requestID),
34                zap.String("method", req.Method),
35                zap.String("path", req.URL.Path),
36                zap.Int("status", status),
37                zap.Duration("duration", duration),
38                zap.String("user_agent", req.UserAgent()),
39                zap.String("ip", c.RealIP()),
40                zap.Error(err),
41            )
42
43            return err
44        }
45    }
46}

With X-Request-ID written back into the response header, both the client and downstream services can cite the same ID — making it easy to trace a single request across multiple services.


18.08 OpenTelemetry Tracing Setup

To understand why a request is slow, we need distributed tracing. The code below initializes OpenTelemetry with the OTLP exporter and 10% sampling for production.

go
 1// internal/infrastructure/tracing/tracing.go
 2
 3package tracing
 4
 5import (
 6    "context"
 7    "fmt"
 8
 9    "go.opentelemetry.io/otel"
10    "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
11    "go.opentelemetry.io/otel/sdk/resource"
12    sdktrace "go.opentelemetry.io/otel/sdk/trace"
13    semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
14)
15
16func Init(ctx context.Context, serviceName, otlpEndpoint string) (func(context.Context) error, error) {
17    exporter, err := otlptracegrpc.New(ctx,
18        otlptracegrpc.WithEndpoint(otlpEndpoint),
19        otlptracegrpc.WithInsecure(), // TLS in production
20    )
21    if err != nil {
22        return nil, fmt.Errorf("tracing.Init: create exporter: %w", err)
23    }
24
25    res, _ := resource.New(ctx,
26        resource.WithAttributes(
27            semconv.ServiceName(serviceName),
28            semconv.ServiceVersion("1.0.0"),
29            semconv.DeploymentEnvironment("production"),
30        ),
31    )
32
33    tp := sdktrace.NewTracerProvider(
34        sdktrace.WithBatcher(exporter),
35        sdktrace.WithResource(res),
36        sdktrace.WithSampler(sdktrace.TraceIDRatioBased(0.1)), // 10% sampling
37    )
38
39    otel.SetTracerProvider(tp)
40
41    return tp.Shutdown, nil
42}

The 10% sampling (TraceIDRatioBased(0.1)) is a production compromise: enough samples to diagnose slow patterns without flooding the trace backend and adding overhead to every request.


18.09 Instrumented Handler

A trace is only useful if spans are created at important points in the request flow. The handler below starts a span at the beginning, records errors, and adds result attributes at the end.

go
 1// Example handler with tracing
 2
 3import (
 4    "go.opentelemetry.io/otel"
 5    "go.opentelemetry.io/otel/attribute"
 6    "go.opentelemetry.io/otel/trace"
 7)
 8
 9var tracer = otel.Tracer("santekno-shop")
10
11func (h *OrderHandler) PlaceOrder(c echo.Context) error {
12    ctx, span := tracer.Start(c.Request().Context(), "PlaceOrder",
13        trace.WithAttributes(
14            attribute.String("user.id", getUserIDFromContext(c)),
15        ))
16    defer span.End()
17
18    var req placeOrderRequest
19    if err := c.Bind(&req); err != nil {
20        span.RecordError(err)
21        return c.JSON(400, apierror.Response{Error: "INVALID_REQUEST"})
22    }
23
24    // Context propagates trace to usecase + repository
25    order, err := h.placeOrderUC.Execute(ctx, placeOrderInput(req))
26    if err != nil {
27        span.RecordError(err)
28        span.SetStatus(codes.Error, err.Error())
29        return apierror.Handle(c, err)
30    }
31
32    span.SetAttributes(attribute.String("order.id", order.ID.String()))
33    return c.JSON(201, toOrderResponse(order))
34}

The key here is passing ctx (not the original context) into the usecase — this is what makes the trace flow automatically from handler to usecase down to repository as one complete span tree.


18.10 pgx Instrumentation

Database queries are often the main bottleneck, so every query deserves its own span. The wrapper below wraps pgx queries with a span and records the sanitized SQL statement.

go
 1// internal/repository/postgres/traced_pool.go
 2// Wrap pgxpool with tracing for every DB query
 3
 4package postgres
 5
 6import (
 7    "context"
 8    "go.opentelemetry.io/otel"
 9    "go.opentelemetry.io/otel/attribute"
10)
11
12var dbTracer = otel.Tracer("santekno-shop.db")
13
14// tracedQuery: wrap a query with a span
15func tracedQuery(ctx context.Context, name, sql string, fn func() error) error {
16    ctx, span := dbTracer.Start(ctx, "db."+name,
17        trace.WithAttributes(
18            attribute.String("db.system", "postgresql"),
19            attribute.String("db.statement", sanitizeSQL(sql)), // strip sensitive values
20        ))
21    defer span.End()
22
23    if err := fn(); err != nil {
24        span.RecordError(err)
25        return err
26    }
27    return nil
28}
29
30// Usage in the repository:
31func (r *OrderRepository) GetByID(ctx context.Context, id uuid.UUID) (*domainOrder.Order, error) {
32    var o domainOrder.Order
33    err := tracedQuery(ctx, "orders.GetByID",
34        "SELECT * FROM orders WHERE id = $1",
35        func() error {
36            return r.db.QueryRow(ctx, "SELECT ...", id).Scan(...)
37        })
38    if err != nil { return nil, err }
39    return &o, nil
40}

Notice sanitizeSQL, which strips sensitive values before they enter the span attribute — a SQL trace is useful for debugging, but customer data must never leak into the tracing system.


18.11 Prometheus Scrape Config

Prometheus needs to know which targets to scrape and how often. The configuration below registers the application and the exporters for PostgreSQL, Redis, and Kafka.

yaml
 1# monitoring/prometheus/prometheus.yml
 2
 3global:
 4  scrape_interval: 15s
 5  evaluation_interval: 15s
 6
 7rule_files:
 8  - "alerts/*.yml"
 9
10scrape_configs:
11  - job_name: santekno-shop
12    static_configs:
13      - targets: ['santekno-shop:8080']
14    metrics_path: /metrics
15    scrape_interval: 10s
16
17  - job_name: postgres-exporter
18    static_configs:
19      - targets: ['postgres-exporter:9187']
20
21  - job_name: redis-exporter
22    static_configs:
23      - targets: ['redis-exporter:9121']
24
25  - job_name: kafka-exporter
26    static_configs:
27      - targets: ['kafka-exporter:9308']
28
29alerting:
30  alertmanagers:
31    - static_configs:
32      - targets: ['alertmanager:9093']

The main application is scraped more frequently (10s) than the exporters (15s) because its golden signal metrics are more dynamic and more critical for early problem detection.


18.12 Alerting Rules

Metrics without alerts are only useful when someone happens to be staring at a dashboard. The alert rules below trigger automatic notifications when error rate, outbox lag, or latency crosses a threshold.

yaml
 1# monitoring/prometheus/alerts/business.yml
 2
 3groups:
 4  - name: santekno-business
 5    rules:
 6      - alert: HighOrderFailureRate
 7        expr: |
 8          rate(santekno_http_requests_total{path="/api/v1/orders",status=~"4..|5.."}[5m])
 9          /
10          rate(santekno_http_requests_total{path="/api/v1/orders"}[5m]) > 0.1
11        for: 2m
12        labels:
13          severity: critical
14        annotations:
15          summary: "Order failure rate > 10%"
16          runbook: "https://wiki.santekno.com/runbooks/high-order-failure"
17
18      - alert: OutboxEventLag
19        expr: santekno_outbox_pending_events > 1000
20        for: 5m
21        labels:
22          severity: warning
23        annotations:
24          summary: "Outbox has {{ $value }} pending events"
25
26      - alert: KafkaConsumerLag
27        expr: santekno_kafka_consumer_lag > 500
28        for: 5m
29        labels:
30          severity: warning
31        annotations:
32          summary: "Kafka consumer lag {{ $value }} on {{ $labels.topic }}"
33
34  - name: santekno-infrastructure
35    rules:
36      - alert: HighP99Latency
37        expr: |
38          histogram_quantile(0.99,
39            rate(santekno_http_request_duration_seconds_bucket[5m])
40          ) > 2
41        for: 3m
42        labels:
43          severity: warning
44        annotations:
45          summary: "P99 latency > 2s on {{ $labels.path }}"
46
47      - alert: DBConnectionPoolExhausted
48        expr: santekno_db_pool_size / 25 > 0.9  # 25 = max pool size
49        for: 1m
50        labels:
51          severity: critical
52        annotations:
53          summary: "DB connection pool {{ $value | humanizePercentage }} full"

Notice the for clause on each alert — for example for: 2m — which prevents false-positive alerts from momentary spikes; an alert only fires if the condition persists long enough.


18.13 Grafana Dashboard

Metrics are easiest to understand when visualized. The Grafana dashboard definition below displays panels for QPS, error rate, latency percentiles, and revenue.

json
 1// monitoring/grafana/dashboards/santekno-shop.json (excerpt)
 2
 3{
 4  "title": "Santekno Shop",
 5  "panels": [
 6    {
 7      "title": "Request Rate (QPS)",
 8      "type": "graph",
 9      "targets": [{
10        "expr": "sum(rate(santekno_http_requests_total[1m]))",
11        "legendFormat": "Total QPS"
12      }]
13    },
14    {
15      "title": "Error Rate",
16      "type": "graph",
17      "targets": [{
18        "expr": "sum(rate(santekno_http_requests_total{status=~\"5..\"}[1m])) / sum(rate(santekno_http_requests_total[1m]))",
19        "legendFormat": "Error Rate %"
20      }]
21    },
22    {
23      "title": "P50/P95/P99 Latency",
24      "type": "graph",
25      "targets": [
26        {"expr": "histogram_quantile(0.5, rate(santekno_http_request_duration_seconds_bucket[5m]))", "legendFormat": "P50"},
27        {"expr": "histogram_quantile(0.95, rate(santekno_http_request_duration_seconds_bucket[5m]))", "legendFormat": "P95"},
28        {"expr": "histogram_quantile(0.99, rate(santekno_http_request_duration_seconds_bucket[5m]))", "legendFormat": "P99"}
29      ]
30    },
31    {
32      "title": "Orders per Minute",
33      "type": "stat",
34      "targets": [{
35        "expr": "sum(rate(santekno_business_orders_created_total[1m])) * 60",
36        "legendFormat": "Orders/min"
37      }]
38    },
39    {
40      "title": "Revenue (Last 24h)",
41      "type": "stat",
42      "targets": [{
43        "expr": "increase(santekno_business_revenue_total_idr_cents[24h]) / 100",
44        "legendFormat": "IDR"
45      }]
46    }
47  ]
48}

Business panels like “Orders per Minute” and “Revenue” are deliberately placed alongside the technical panels, so when a technical metric drops, its impact on the business is immediately visible on the same screen.


18.14 docker-compose Monitoring Stack

To run the entire observability stack locally, we use docker-compose. The configuration below brings together Prometheus, Grafana, Jaeger, Alertmanager, and Loki.

yaml
 1# docker-compose.monitoring.yml
 2
 3services:
 4  prometheus:
 5    image: prom/prometheus:v2.51
 6    volumes:
 7      - ./monitoring/prometheus:/etc/prometheus
 8      - prometheus_data:/prometheus
 9    command:
10      - --config.file=/etc/prometheus/prometheus.yml
11      - --storage.tsdb.retention.time=15d
12    ports:
13      - "9090:9090"
14
15  grafana:
16    image: grafana/grafana:10.4
17    volumes:
18      - ./monitoring/grafana/dashboards:/var/lib/grafana/dashboards
19      - grafana_data:/var/lib/grafana
20    environment:
21      - GF_SECURITY_ADMIN_PASSWORD=admin123
22      - GF_AUTH_ANONYMOUS_ENABLED=true
23      - GF_DASHBOARDS_DEFAULT_HOME_DASHBOARD_PATH=/var/lib/grafana/dashboards/santekno-shop.json
24    ports:
25      - "3000:3000"
26
27  jaeger:
28    image: jaegertracing/all-in-one:1.56
29    environment:
30      - COLLECTOR_OTLP_ENABLED=true
31    ports:
32      - "16686:16686"  # Jaeger UI
33      - "4317:4317"    # OTLP gRPC
34
35  alertmanager:
36    image: prom/alertmanager:v0.27
37    volumes:
38      - ./monitoring/alertmanager:/etc/alertmanager
39    ports:
40      - "9093:9093"
41
42  loki:
43    image: grafana/loki:2.9
44    ports:
45      - "3100:3100"
46
47  promtail:
48    image: grafana/promtail:2.9
49    volumes:
50      - /var/log:/var/log
51      - ./monitoring/promtail:/etc/promtail
52    command: -config.file=/etc/promtail/config.yml
53
54volumes:
55  prometheus_data:
56  grafana_data:

With a single docker-compose up command, a developer gets the entire observability stack identical to production — allowing them to test dashboards and alerts before they’re actually needed during an incident.


18.15 SLO Definition

Mature observability measures reliability against explicit targets, not just “feels fast.” The SLO definition below sets targets for availability, latency, and order completion.

yaml
 1# monitoring/slo.yml — Service Level Objectives
 2
 3slos:
 4  # Availability SLO
 5  - name: api-availability
 6    description: "API endpoint availability"
 7    target: 99.9%  # 8.7 hours downtime/year
 8    measurement:
 9      metric: |
10        1 - (
11          rate(santekno_http_requests_total{status=~"5.."}[28d])
12          /
13          rate(santekno_http_requests_total[28d])
14        )
15    alert_burn_rate: [14.4, 6]  # 1h and 6h burn rate alerts
16
17  # Latency SLO
18  - name: api-latency-p95
19    description: "95th percentile API latency"
20    target: 95%  # 95% requests under 500ms
21    measurement:
22      metric: |
23        histogram_quantile(0.95,
24          rate(santekno_http_request_duration_seconds_bucket[28d])
25        ) < 0.5
26
27  # Order completion SLO
28  - name: order-completion
29    description: "Orders successfully created within 2s"
30    target: 99%
31    measurement:
32      metric: |
33        histogram_quantile(0.99,
34          rate(santekno_http_request_duration_seconds_bucket{path="/api/v1/orders",method="POST"}[28d])
35        ) < 2

The alert_burn_rate concept enables early warning: instead of waiting until the SLO is actually breached, the team is notified when the error budget is burning too fast and there’s still time to act.


18.16 Correlation: Logs + Traces + Metrics

The true power of observability emerges when all three pillars can be linked together. The middleware below injects trace_id into every log so a single request can be traced across Loki, Jaeger, and Grafana.

go
 1// Request arrives: inject trace ID into the log context
 2
 3func RequestLogger() echo.MiddlewareFunc {
 4    return func(next echo.HandlerFunc) echo.HandlerFunc {
 5        return func(c echo.Context) error {
 6            // Get trace from context (if present from upstream)
 7            span := trace.SpanFromContext(c.Request().Context())
 8            traceID := span.SpanContext().TraceID().String()
 9
10            requestID := c.Request().Header.Get("X-Request-ID")
11            c.Set("request_id", requestID)
12            c.Set("trace_id", traceID)
13
14            err := next(c)
15
16            // Log with trace_id for cross-correlation
17            logger.Get().Info("request",
18                zap.String("request_id", requestID),
19                zap.String("trace_id", traceID),   // ← link to Jaeger
20                zap.String("path", c.Path()),
21                zap.Int("status", c.Response().Status),
22            )
23
24            return err
25        }
26    }
27}
28
29// In Grafana: Explore panel
30// Loki → filter trace_id=abc123 → see all logs from this request
31// Click "Open in Jaeger" → see the distributed trace
32// Click "Open in Grafana" → see the metrics spike at the same time

With trace_id as the common thread, debugging changes from hopping between tools into one smooth flow: from the error log, to the trace that caused it, to the metric graph at the very same second.


18.17 Go Runtime Metrics

Beyond application metrics, the Go runtime itself holds important signals like goroutine count and GC duration. The code below registers the runtime and process collectors with the Prometheus registry.

go
 1// Go runtime metrics are already included in the default prometheus registry
 2// Enable with an import:
 3
 4import (
 5    _ "net/http/pprof"
 6    "github.com/prometheus/client_golang/prometheus/collectors"
 7)
 8
 9func init() {
10    // Go runtime metrics: GC, goroutines, memory
11    prometheus.MustRegister(collectors.NewGoCollector(
12        collectors.WithGoCollectorRuntimeMetrics(
13            collectors.GoRuntimeMetricsRule{Matcher: regexp.MustCompile(`/.*`)},
14        ),
15    ))
16    prometheus.MustRegister(collectors.NewProcessCollector(
17        collectors.ProcessCollectorOpts{},
18    ))
19}
20
21// Metrics that become available:
22// go_goroutines                → goroutine count
23// go_gc_duration_seconds       → GC pause duration
24// go_memstats_alloc_bytes      → heap allocation
25// process_resident_memory_bytes → RSS memory

The go_goroutines metric is especially valuable for detecting a goroutine leak — a count that keeps rising without falling is an early signal of a leak that could end in running out of memory.


18.18 pprof Profiling Endpoint

When you need to dissect CPU or memory in depth, pprof is the go-to tool. The code below runs a pprof server on a separate port that may only be accessed from the internal network.

go
 1// Enable pprof for on-demand profiling (never on a public endpoint)
 2
 3// cmd/server/main.go
 4import _ "net/http/pprof"
 5
 6func startPprofServer() {
 7    go func() {
 8        log.Printf("pprof server on :6060")
 9        http.ListenAndServe(":6060", nil)
10    }()
11}
12
13// Access only from internal network / kubectl port-forward
14
15// Commands:
16// go tool pprof http://localhost:6060/debug/pprof/heap
17// go tool pprof http://localhost:6060/debug/pprof/goroutine
18// go tool pprof -http=:8081 http://localhost:6060/debug/pprof/profile?seconds=30

pprof runs on port 6060, separated from public traffic, and must be restricted via a NetworkPolicy — a profiling endpoint exposed to the internet is a serious security hole.


18.19 Outbox Monitoring Goroutine

Some metrics don’t arise from a request, but must be sampled periodically. The goroutine below monitors the number of unpublished outbox events every 30 seconds and updates the Prometheus gauge.

go
 1// Monitor outbox lag every 30 seconds
 2// Update the Prometheus metric
 3
 4func (w *Worker) startMonitoring(ctx context.Context) {
 5    ticker := time.NewTicker(30 * time.Second)
 6    defer ticker.Stop()
 7
 8    for {
 9        select {
10        case <-ctx.Done():
11            return
12        case <-ticker.C:
13            var count int
14            w.db.QueryRow(ctx,
15                `SELECT COUNT(*) FROM outbox_events WHERE published = false`,
16            ).Scan(&count)
17
18            metrics.OutboxPendingCount.Set(float64(count))
19
20            if count > 1000 {
21                logger.Get().Warn("outbox lag high",
22                    zap.Int("pending_events", count))
23            }
24        }
25    }
26}

A periodic sampling pattern like this fits a gauge that describes the “current condition” — and the select with ctx.Done() ensures the goroutine stops cleanly when the application shuts down.


18.20 Summary: The Observability Baseline Is Ready

Santekno Shop now has a full observability stack ready for a production baseline.

Metrics (Prometheus): HTTP golden signals, business metrics (orders, revenue), infrastructure metrics (DB pool, cache hit rate, outbox lag), and Go runtime metrics.

Traces (OpenTelemetry + Jaeger): distributed trace from HTTP request down to DB query, with 10% sampling for production.

Logs (Zap + Loki): structured JSON with request_id and trace_id for cross-correlation.

Alerting: business alerts (order failure rate, outbox lag) and infrastructure alerts (high latency, DB pool exhaustion).

SLOs: availability 99.9%, P95 latency < 500ms, order completion P99 < 2s. With this foundation, we’re ready for the next stage: measuring how far the system can be pushed before it crosses those SLO thresholds.

Related Articles

💬 Comments