Below is a practical “reference implementation” for observability you can apply to most services (HTTP, gRPC, async workers). It covers logging patterns, metrics, tracing, RED/USE & SRE golden signals, instrumentation with OpenTelemetry, sampling, dashboards, and alerting—with concrete examples.
1) What to observe (frameworks)
SRE Golden Signals (service-level)
Latency (p50/p95/p99, broken down by route/dependency)
Traffic (RPS/QPS, throughput)
Errors (error rate, failed requests, exception rate)
Saturation (resource utilization: CPU, memory, threads, queue depth, connection pools)
RED method (request-driven services)
R ate: requests/sec
E rrors: errors/sec or %
D uration: request latency distributions
USE method (infrastructure/resources)
U tilization: how busy (CPU%, disk busy%)
S aturation: backlog/queueing (run queue, IO wait, pool exhaustion)
E rrors: hardware/network errors
Rule of thumb:
Use RED for endpoints and dependencies.
Use USE for hosts/containers/DBs/queues.
Tie them together with traces and correlation IDs .
2) Logging: patterns that scale
2.1 Structured logging (JSON) with consistent fields
Prefer one log event per line, machine-parsable. Include:
timestamp, level, message
service.name, service.version, env
trace_id, span_id (for correlation)
request context: http.method, http.route, status_code, duration_ms
business identifiers (careful): tenant_id, user_id (hashed), order_id
Example log event (JSON):
json Copy code
{
"ts": "2025-12-13T08:15:30.123Z",
"level": "INFO",
"service": "checkout-api",
"env": "prod",
"msg": "request completed",
"http.method": "POST",
"http.route": "/v1/checkout",
"status_code": 200,
"duration_ms": 143,
"tenant_id": "t_123",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"span_id": "00f067aa0ba902b7"
}
2.2 Log levels & intent
DEBUG: diagnostic details (guard with sampling/feature flags in prod)
INFO: lifecycle events, request summaries (often sampled)
WARN: unexpected but handled (retries, degraded behavior)
ERROR: request failed, dependency failed, invariant violated
FATAL: process must exit (rare)
2.3 Patterns to avoid
Logging full request/response bodies (PII + cost + cardinality)
High-cardinality values as keys (e.g., user_email, raw order_id in every line)
Multi-line stack traces without structured fields (better: structured exception fields + single-line)
2.4 Correlation rules
Emit a trace_id in every log line that occurs during a request/job.
Propagate inbound IDs via W3C traceparent (or generate if missing).
3) Metrics: what to measure (and how)
3.1 Metric types
Counters : monotonically increasing (requests_total)
Histograms : latency distributions (request_duration_seconds)
Gauges : current values (inflight_requests, queue_depth)
3.2 Naming & labels (cardinality discipline)
Use stable labels: service, env, route, method, status_class (2xx/4xx/5xx)
Avoid: user_id, order_id, raw URL, exception messages as labels
3.3 RED metrics examples (Prometheus style)
Counters
http_server_requests_total{route="/v1/checkout", method="POST", status_class="2xx"}
Histogram
http_server_request_duration_seconds_bucket{route="/v1/checkout", ...}
Gauge
http_server_inflight_requests{route="/v1/checkout"}
3.4 PromQL examples (RED)
Rate (RPS):
promql Copy code
sum by (route, method) (rate(http_server_requests_total[5m]))
Error rate (%):
promql Copy code
100 *
sum(rate(http_server_requests_total{status_class=~"4xx|5xx"}[5m]))
/
sum(rate(http_server_requests_total[5m]))
p95 latency:
promql Copy code
histogram_quantile(
0.95,
sum by (le, route) (rate(http_server_request_duration_seconds_bucket[5m]))
)
3.5 USE metrics examples (infra)
CPU: rate(container_cpu_usage_seconds_total[5m])
Memory: container_memory_working_set_bytes
Saturation: queue depth, thread pool queue, DB connection pool usage
Errors: node_network_receive_errs_total, disk IO errors, etc.
4) Tracing: distributed request visibility
4.1 What to trace
Every inbound request/job message creates a root span
Each dependency call: DB query, external HTTP call, cache, message publish
Include semantic attributes:
HTTP: http.method, http.route, http.status_code
DB: db.system, db.statement (sanitized), db.operation
Messaging: messaging.system, messaging.destination
4.2 Propagation
Adopt W3C Trace Context:
inbound: read traceparent / tracestate
outbound: inject into headers (HTTP) / message headers (Kafka/SQS/etc.)
4.3 Exemplars (link metrics ↔ traces)
Many stacks allow histogram exemplars so a latency spike point links to a trace.
5) Instrumentation: OpenTelemetry reference setup (with examples)
5.1 Architecture (common)
App → OpenTelemetry SDK → OTLP → OpenTelemetry Collector → backends
Logs: Loki/Elastic
Metrics: Prometheus/Mimir
Traces: Tempo/Jaeger
5.2 Example: Python FastAPI (metrics + tracing + log correlation)
Install:
bash Copy code
pip install fastapi uvicorn opentelemetry-sdk opentelemetry-exporter-otlp \
opentelemetry-instrumentation-fastapi opentelemetry-instrumentation-requests \
structlog
Tracing + metrics (simplified):
python Copy code
from fastapi import FastAPI
import time
import structlog
from opentelemetry import trace, metrics
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.requests import RequestsInstrumentor
resource = Resource.create({
"service.name": "checkout-api",
"service.version": "1.2.3",
"deployment.environment": "prod"
})
trace.set_tracer_provider(TracerProvider(resource=resource))
tracer_provider = trace.get_tracer_provider()
tracer_provider.add_span_processor(
BatchSpanProcessor(OTLPSpanExporter(endpoint="http://otel-collector:4318/v1/traces"))
)
metrics.set_meter_provider(MeterProvider(resource=resource))
meter = metrics.get_meter("checkout-api")
request_counter = meter.create_counter(
"http_server_requests_total",
description="Total HTTP requests"
)
latency_hist = meter.create_histogram(
"http_server_request_duration_ms",
description="Request latency in ms"
)
log = structlog.get_logger()
app = FastAPI()
FastAPIInstrumentor.instrument_app(app)
RequestsInstrumentor().instrument()
@app.middleware("http")
async def observe_requests(request, call_next):
start = time.time()
response = await call_next(request)
dur_ms = (time.time() - start) * 1000
route = request.url.path
method = request.method
status = response.status_code
status_class = f"{status//100}xx"
# Metrics
request_counter.add(1, {"route": route, "method": method, "status_class": status_class})
latency_hist.record(dur_ms, {"route": route, "method": method, "status_class": status_class})
# Log correlation (trace_id/span_id)
span = trace.get_current_span()
ctx = span.get_span_context()
log.info("request completed",
route=route, method=method, status=status, duration_ms=dur_ms,
trace_id=format(ctx.trace_id, "032x"),
span_id=format(ctx.span_id, "016x"))
return response
@app.get("/healthz")
def healthz():
return {"ok": True}
5.3 Example: OpenTelemetry Collector config (minimal)
yaml Copy code
receivers:
otlp:
protocols:
http:
grpc:
processors:
batch:
exporters:
otlp/tempo:
endpoint: tempo:4317
tls:
insecure: true
prometheus:
endpoint: "0.0.0.0:9464" # scrape collector for metrics
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [otlp/tempo]
metrics:
receivers: [otlp]
processors: [batch]
exporters: [prometheus]
6) Sampling strategies (cost control without blindness)
6.1 Trace sampling options
Head-based sampling (decide at start):
Pros: cheap, simple
Cons: can miss rare errors unless configured carefully
Tail-based sampling (decide after seeing full trace, usually in collector):
Pros: keep slow/error traces reliably
Cons: more memory/CPU in collector
6.2 Practical sampling policy (recommended)
Default: 1–10% head sampling for normal traffic
Always sample:
traces with http.status_code >= 500
high latency (duration > 1s, route-specific)
specific tenants/endpoints during incidents (dynamic rules)
Tail-sampling policy sketch (collector):
keep 100% of error traces
keep 100% of traces above latency threshold
keep 1% of everything else
6.3 Log sampling
Keep all WARN/ERROR
Sample high-volume INFO logs (e.g., 1:100) if metrics cover request summaries
Never sample audit/security logs unless you have an explicit compliance design
7) Dashboards: what to build (Grafana examples)
7.1 Service overview dashboard (Golden Signals)
Panels:
Traffic : RPS by route/method
Error rate : total and by route (4xx vs 5xx)
Latency : p50/p95/p99 by route + heatmap
Saturation : CPU, memory, thread pool/queue depth, DB pool usage
Suggested PromQL panels:
RPS:
promql Copy code
sum(rate(http_server_requests_total[5m]))
Error rate:
promql Copy code
sum(rate(http_server_requests_total{status_class="5xx"}[5m]))
/
sum(rate(http_server_requests_total[5m]))
p95 latency:
promql Copy code
histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket[5m])))
7.2 Dependency dashboard
Outbound HTTP latency/error by dependency host/service
DB query latency (by operation/table if safe)
Cache hit ratio
Queue publish/consume rate + lag
7.3 Tracing dashboard
Top slow endpoints
Trace search shortcuts:
service.name="checkout-api" AND http.route="/v1/checkout" AND duration>1s
status_code>=500
8) Alerting: actionable, SLO-based, low-noise
8.1 Alert types
Symptoms (user impact) : SLO burn, high error rate, elevated latency
Causes (resource failures) : CPU throttling, OOM kills, DB down
Prefer paging on symptoms , ticket on causes (unless the cause is clearly imminent impact).
8.2 SLO + burn-rate alerts (best practice)
Example SLO: 99.9% successful requests over 30 days.
Define error ratio:
promql Copy code
error_ratio =
sum(rate(http_server_requests_total{status_class="5xx"}[5m]))
/
sum(rate(http_server_requests_total[5m]))
Burn-rate alerting typically uses multi-window / multi-burn to reduce noise:
Page if fast burn (e.g., 5m + 1h)
Ticket if slow burn (e.g., 6h + 3d)
Example (conceptual):
Page: error budget consumed too fast over short window
Ticket: persistent moderate burn
8.3 Concrete Prometheus alert examples
High 5xx error rate (page):
yaml Copy code
- alert: High5xxErrorRate
expr: |
(
sum(rate(http_server_requests_total{status_class="5xx"}[5m]))
/
sum(rate(http_server_requests_total[5m]))
) > 0.02
for: 10m
labels:
severity: page
annotations:
summary: "High 5xx error rate"
description: "5xx error ratio > 2% for 10m"
p95 latency regression (ticket):
yaml Copy code
- alert: P95LatencyHigh
expr: |
histogram_quantile(
0.95,
sum by (le) (rate(http_server_request_duration_seconds_bucket[10m]))
) > 0.5
for: 20m
labels:
severity: ticket
annotations:
summary: "p95 latency high"
description: "p95 > 500ms for 20m"
Saturation example: too many inflight requests (ticket):
yaml Copy code
- alert: HighInflightRequests
expr: |
sum(http_server_inflight_requests) > 500
for: 15m
labels:
severity: ticket
8.4 Alert hygiene rules
Every page must have:
clear user impact statement
owner/runbook link
immediate mitigation steps
dashboard + trace search link
Avoid alerts on raw CPU% unless it correlates with latency/errors (use saturation + symptoms)
9) Putting it together: minimal “done” checklist
Logging
Metrics
Tracing
Dashboards
Alerting
If you tell me your stack (language/framework, Kubernetes or not, Prometheus/Grafana vs Datadog/New Relic, messaging/DB choices), I can tailor:
the exact OpenTelemetry SDK setup,
collector config,
recommended metrics (names/labels),
a starter Grafana dashboard JSON,
and alert rules aligned to your SLOs.