Running Go natively in the cloud: multi-stage Dockerfiles with distroless images, 12-factor configuration with clean liveness and readiness endpoints, Kubernetes automation with client-go, operators built on controller-runtime and kubebuilder, and sidecars, webhooks & CRDs as extension patterns.
if got != want Becomes BoilerplateThe tasksrv from module 10 keeps growing: the worker reads from a queue, notifies other services, and the test files fill up with the same three-line ritual — if err != nil { t.Fatalf(...) }, if got != want { t.Errorf(...) }, over and over. In lesson 41 you wrote table-driven tests with the standard library, in lesson 43 hand-rolled fakes. Both still stand — but past a certain test volume, the Go ecosystem's standard answer pays off: github.com/stretchr/testify.
Testify is the most widely used testing library for Go — not because the standard library can't do it, but because assert and require make checks readable and print diffs on failure automatically. On top comes mockery, a code generator that turns the interfaces from lesson 43 into complete mocks — including strict expectation checking that hand-written fakes often lack.
assert documents, require protects
assert.Equal(t, want, got) marks the test as failed and keeps going — good for several independent checks. require.Equal(t, want, got) calls t.FailNow() internally and stops immediately — mandatory whenever everything else depends on the result: first require.NoError(t, err), then touch the result. Exactly this distinction is missing in many suites, and it decides whether a test yields a clean, readable failure or a masked nil-pointer panic.
One test using both families — compact, with a diff instead of hand-rolled messages:
// tasks/priority_test.go
package tasks
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParsePriority(t *testing.T) {
got, err := ParsePriority("P1")
require.NoError(t, err) // no error, no usable got — stop right here
assert.Equal(t, Priority(1), got)
assert.NotEmpty(t, got.Label())
_, err = ParsePriority("whatever")
assert.ErrorIs(t, err, ErrInvalidPriority) // independent check: keep going
}
// Terminal: go test -run TestParsePriority -v
// → === RUN TestParsePriority
// → --- PASS: TestParsePriority (0.00s)
//
// Terminal (with a failure): go test -run TestParsePriority
// → Error Trace: priority_test.go:14
// → Error: Not equal: expected: 1, actual: 2
The store test needs a fresh state before every test. With plain testing you put setup into each test function (or into TestMain, lesson 42); with a Testify suite it becomes one method. SetupTest runs fresh before every test in the suite, SetupSuite exactly once for all of them — and the assertions arrive as methods on s: s.Equal, s.Require().NoError.
// tasks/store_suite_test.go
package tasks
import (
"testing"
"github.com/stretchr/testify/suite"
)
type StoreSuite struct {
suite.Suite
store *Store
}
// SetupTest runs before every single test — each one starts with an empty store.
func (s *StoreSuite) SetupTest() {
s.store = NewStore()
}
func (s *StoreSuite) TestAddAssignsIDs() {
t1 := s.store.Add("prepare deploy")
t2 := s.store.Add("test rollback")
s.Equal(1, t1.ID)
s.Equal(2, t2.ID)
}
func TestStoreSuite(t *testing.T) {
suite.Run(t, new(StoreSuite))
}
// Terminal: go test -v
// → === RUN TestStoreSuite
// → === RUN TestStoreSuite/TestAddAssignsIDs
// → --- PASS: TestStoreSuite (0.00s)
The worker notifies through a Notifier interface (the seam from lesson 43). The hand-written fake works — but when the interface grows, you must keep the fake in sync manually. mockery (v2, github.com/vektra/mockery/v2) reads the interface and generates a complete mock with expectations, call counting, and AssertExpectations. Configured via a .mockery.yaml at the repo root, a bare mockery invocation is all you need.
// notify/notify.go — the interface the worker consumes
package notify
//go:generate mockery --name Notifier --output ./mocks
type Notifier interface {
Send(taskID int, msg string) error
}
// worker_test.go — the generated mock in action
package worker
import (
"testing"
"github.com/team/tasksrv/notify/mocks"
)
func TestFinishNotifies(t *testing.T) {
n := mocks.NewMockNotifier(t)
n.On("Send", 42, "deploy finished").Return(nil).Once()
NewWorker(n).Finish(42)
n.AssertExpectations(t) // fails if Send did not run (exactly once)
}
// Terminal: go test -run TestFinishNotifies -v
// → === RUN TestFinishNotifies
// → --- PASS: TestFinishNotifies (0.00s)
⚠ Common mistake: Using
assert.NoError(t, err)for the error everything else depends on. The test keeps running, dereferences an empty result, and dies withinvalid memory address or nil pointer dereference— the actual cause (the parse error) is buried inside the panic, and the stack trace points at the consumer line, not the problem. Rule of thumb:requirefor preconditions (errors, setup, length),assertfor peer-level follow-up checks. Same idea in suites withs.Require().
Check: A Testify suite has SetupTest with a log line and two test functions. How often does the log line appear in the go test output?
Answer: Twice — SetupTest runs fresh before each individual test in the suite
SetupTest is the per-test fixture hook, not a per-suite one — otherwise tests would share state, which is exactly what breaks test isolation. For one-time expensive setup there is SetupSuite (and analogously TearDownTest/TearDownSuite). Answering »once« here confuses the suite with a TestMain from lesson 42.
Takeaways:
github.com/stretchr/testify provides assert (keeps going after failure) and require (stops via t.FailNow) — first require.NoError, then work with the result.suite.Suite with SetupTest/TearDownTest) attach fixtures to every single test instead of the suite; assertions become s.Equal, s.Require().mockery generates a mock from an interface (//go:generate mockery --name Notifier) with On(...).Return(...).Once() and AssertExpectations(t) — no more hand-maintained fakes.Since module 10 the tasksrv writes to a real Postgres — but the repo is tested against … nothing. Unit tests with a fake store prove logic, not that the SQL is right: whether ON CONFLICT fires, whether the migration actually adds the column, whether the index exists. That is exactly where github.com/testcontainers/testcontainers-go shines: the library starts a real Docker container for the test — same image, same version as production — and tears it down afterwards.
This settles an old dispute. SQLite as a Postgres stand-in is out, and so is the mocked DB layer: the test runs against the real engine, just ephemeral and on a randomly chosen free host port. The prerequisite is a running Docker environment (a local daemon or a remote one via DOCKER_HOST) — Testcontainers orchestrates, it does not virtualize itself.
The Container IS the Environment
An integration test with Testcontainers starts the same artifact as production — say postgres:17-alpine — waits for readiness, and hands you a connection string. Test setup and production environment can no longer drift apart, because there is only one definition of the database: the image. The price is startup time: a few seconds per container, which is why you share one across many tests.
The first integration test — start container, migrate, insert, read. The Postgres module (github.com/testcontainers/testcontainers-go/modules/postgres) ships a sensible default wait: it waits for the »database system is ready to accept connections« log line before Run returns:
// integration/repo_test.go
//go:build integration
package integration
import (
"context"
"errors"
"testing"
"github.com/golang-migrate/migrate/v2"
_ "github.com/golang-migrate/migrate/v2/database/postgres"
_ "github.com/golang-migrate/migrate/v2/source/file"
"github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/team/tasksrv/tasks"
)
func TestRepoAddAndGet(t *testing.T) {
ctx := context.Background()
pg, err := postgres.Run(ctx, "postgres:17-alpine",
postgres.WithDatabase("tasks"),
postgres.WithUsername("app"),
postgres.WithPassword("test"),
)
if err != nil {
t.Fatalf("container start: %v", err)
}
t.Cleanup(func() { _ = pg.Terminate(ctx) }) // disposal is mandatory, lesson 42
m, err := migrate.New("file://../../migrations",
pg.ConnectionString(ctx, "sslmode=disable"))
if err != nil {
t.Fatalf("migrate init: %v", err)
}
if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
t.Fatalf("migration: %v", err)
}
repo := tasks.NewRepo(pg.ConnectionString(ctx, "sslmode=disable"))
id, err := repo.Add(ctx, "run a real migration once")
if err != nil {
t.Fatalf("add: %v", err)
}
got, err := repo.Get(ctx, id)
if err != nil || got.Title != "run a real migration once" {
t.Fatalf("get: %v / %+v", err, got)
}
}
// Terminal: go test -tags=integration -v
// → === RUN TestRepoAddAndGet
// → --- PASS: TestRepoAddAndGet (3.8s) — a real Postgres 17, started in a container and cleaned up
The integration build tag keeps the fast unit tests clean of this: go test ./... runs without Docker, go test -tags=integration ./... in the pipeline runs against the real engine.
Two seconds of startup per test is fine — for 40 repo tests it becomes two minutes of nothing. The established pattern: one shared container in TestMain, each test gets its own database or table. You pay startup once per package instead of once per test function:
// integration/main_test.go
//go:build integration
package integration
import (
"context"
"log"
"os"
"testing"
"github.com/testcontainers/testcontainers-go/modules/postgres"
)
var dsn string
func TestMain(m *testing.M) {
ctx := context.Background()
pg, err := postgres.Run(ctx, "postgres:17-alpine",
postgres.WithDatabase("tasks"),
postgres.WithUsername("app"),
postgres.WithPassword("test"),
)
if err != nil {
log.Fatalf("container start: %v", err)
}
dsn = pg.ConnectionString(ctx, "sslmode=disable")
code := m.Run() // all tests, one shared server
_ = pg.Terminate(ctx) // exactly once, even after a panic in a test
os.Exit(code)
}
// Terminal: go test -tags=integration ./integration/
// → ok github.com/team/tasksrv/integration 9.4s — 41 tests, 1 container, 1 startup
⚠ Common mistake: Starting the container and forgetting
Terminate— say,t.Cleanupwas omitted, or an earlyt.Fatalffired before registration. Everygo testrun then leaves a running Postgres container behind; after a day of CI that's hundreds of them, the Docker host runs out of memory and ports, and the pipeline fails with something that looks like a network issue. RegisterTerminateimmediately after a successfulRun(via Cleanup orTestMain), and at least log the error from stopping.
Check: The test connects to postgres://app:test@localhost:55432/tasks — yet Postgres is not installed on the host at all. How is the connection possible?
Answer: Docker maps a randomly chosen free host port to port 5432 inside the container — ConnectionString returns exactly that
The Postgres inside the container listens on 5432 — but only within the container network. Docker publishes the service through a mapped host port (a fixed port would be a bottleneck for parallel tests, so Testcontainers picks a free one). That is exactly why pg.ConnectionString exists: it knows the host and mapped port of this concrete container instance. Hardcoding 5432 collides with the next parallel test run.
Takeaways:
github.com/testcontainers/testcontainers-go starts real containers (e.g. postgres:17-alpine) via the Docker API for tests — same engine as production, torn down afterwards.pg.ConnectionString(ctx, "sslmode=disable") returns the DSN including the randomly mapped host port.//go:build integration) separate slow integration tests from go test ./... — the pipeline invokes them with -tags=integration.TestMain pays startup once per suite instead of once per test; register Terminate right after Run.github.com/golang-migrate/migrate/v2) also verifies the schema — not just the repo code.The tasksrv runs, but the nightly job has failed since Tuesday. The logs consist of lines like »starting import«, »done«, »something failed« — set with log.Printf, parked in text files. Which queue? Which task? How long did it take? None of that is in the line, so the team digs by hand. Structured logging flips the approach: every line is a record with fields — filterable, aggregatable, alarmable.
Go has shipped log/slog in the standard library since version 1.21 — the reference point every third-party library is measured against. The two best known: go.uber.org/zap (Uber, type-safe fields, very fast) and github.com/rs/zerolog (zero-allocation, chain-style API). All three write JSON instead of prose — the prerequisite for logs, metrics, and traces to work together as an architecture discipline instead of forming three separate silos.
Fields, Not Formats
logger.Info("task created", "task_id", 42, "queue", "ingest") writes the values as dedicated keys in the line — not into a composed sentence. That is the whole difference: queue="ingest" can be filtered and counted in the log platform; »created task 42 for queue ingest« is full text only. Formatting values into the message discards them as data — no matter how nicely the message reads.
slog since Go 1.21: handlers decide the format, With attaches contextual fields to every descendant:
// tasksrv/main.go
package main
import (
"context"
"log/slog"
"os"
"time"
)
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
slog.SetDefault(logger) // net/http internals now log structured too
// Context for everything downstream in this branch:
ingest := logger.With("queue", "ingest", "region", "eu-central")
ingest.Info("task created",
slog.Int("task_id", 42),
slog.Duration("enqueue_wait", 3*time.Millisecond),
)
ingest.Error("queue stuck", slog.Duration("since_last", 90*time.Second))
}
// → {"time":"2026-11-05T10:14:03Z","level":"INFO","msg":"task created","queue":"ingest","region":"eu-central","task_id":42,"enqueue_wait":"3ms"}
// → {"time":"2026-11-05T10:15:33Z","level":"ERROR","msg":"queue stuck","queue":"ingest","region":"eu-central","since_last":"1m30s"}
One logger per request (with logger.With("trace_id", ...) from lesson 65) ties every line to one call — the basis for correlation across service boundaries.
Why a third-party library at all when slog is standard? Both libraries predate slog and shine in the delicate spot: hot paths, millions of lines per minute. zerolog writes without allocations, zap uses typed fields that avoid reflection — and since Go 1.21 both can be plugged in as slog handlers, so the rest of the code stays on slog:
// worker/log.go — zerolog on the worker hot path
package worker
import (
"os"
"time"
"github.com/rs/zerolog"
)
var log = zerolog.New(os.Stdout).With().Timestamp().Caller().Logger()
func Handle(taskID int, wait time.Duration) {
log.Info().
Int("task_id", taskID).
Str("queue", "ingest").
Dur("wait", wait).
Msg("task picked up")
}
// → {"level":"info","caller":"/worker/log.go:14","task_id":42,"queue":"ingest","wait":"3ms","time":"2026-11-05T10:14:06.120Z","message":"task picked up"}
// notifier/log.go — zap with typed fields
logger, _ := zap.NewProduction()
defer logger.Sync()
logger.Info("notification sent",
zap.Int("task_id", 42),
zap.String("channel", "matrix"),
zap.Int64("bytes", 312),
)
// → {"level":"info","ts":1762331646.120,"caller":"notifier/log.go:9","msg":"notification sent","task_id":42,"channel":"matrix","bytes":312}
The honest recommendation for a service like tasksrv: start with slog — standard library, no dependency, good enough. Only when profiles from lesson 44 show that logging measurably costs in the hottest path, drop zap or zerolog in there specifically; via a handler, the API everywhere else stays slog.
⚠ Common mistake: Writing credentials and personal data as log fields —
"api_key","password","Authorization","email"land in the line withslogorzerologwithout mercy — and structured lines, unlike prose, get machine-indexed, shipped, and retained for months. Alogger.Info("login", "password", pw)is a credentials leak with a search index. Validate field contents at trust boundaries (lesson 8) and never log sensitive values — at most hashed or truncated.
Check: What does slog.Info(»starting import for %s«, queue) actually output — with queue being the string »ingest«?
Answer: The message stays verbatim and the value appears as a field with the key !BADKEY — slog does not format
slog.Info(msg, args...) interprets args alternately as key and value — there are no printf verbs. »starting import for %s« becomes the message verbatim, followed by a value without a key, which slog marks with the !BADKEY placeholder. Correct: slog.Info(»import started«, »queue«, queue). You can format yourself, of course — but then you lose the searchable field.
Takeaways:
task_id, queue, duration) instead of formatted prose — filterable, countable, alarmable.log/slog is part of the standard library since Go 1.21: handlers (JSONHandler) pick the format, With(...) attaches context fields to all descendants, slog.SetDefault switches the whole process.go.uber.org/zap (type-safe fields) and github.com/rs/zerolog (zero-allocation, chain-style) shine on hot paths — and plug in as slog handlers.slog for the whole service, zap/zerolog only where measurements (lesson 44) prove the need.Friday morning the product owner asks: »How many tasks per minute come in, and how fast are we?« — and nobody can answer without digging through logs. Logs from lesson 63 tell you why one specific task failed; for the aggregate state of the system you need metrics: numbers the service continuously publishes about itself. The de facto standard for that is Prometheus — and github.com/prometheus/client_golang ships everything a Go service needs.
The model is deliberately small: a counter only ever increases (number of tasks), a gauge holds a current value (queue length), a histogram distributes observations into buckets (request duration). The service exports these time series on a /metrics endpoint in text format; the Prometheus server scrapes it every 15 seconds. No agent, no sidecar — just an HTTP handler.
Labels Are Dimensions, Not Data
A label like queue="ingest" turns one counter into a family of time series — one per queue. That is the strength (»show the rate per queue«) and the trap: every new label value creates a new time series. Five queues: fine. Fifty thousand user IDs: a storage and query disaster (cardinality explosion). Rule of thumb: labels only for small, known-in-advance value sets; anything identifying (task ID, user, path parameters) belongs in traces and logs of the neighboring lessons — classified as a discipline in the architecture course's observability module.
Two metrics for the tasksrv — counter and histogram, registered via promauto at package import:
// metrics/metrics.go
package metrics
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
var (
TasksCreated = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "tasksrv_tasks_created_total",
Help: "Tasks accepted in total, by queue.",
}, []string{"queue"})
HandlerDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "tasksrv_handler_duration_seconds",
Help: "HTTP handler duration in seconds.",
Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1},
}, []string{"route", "method"})
)
// Terminal (right after startup): curl -s localhost:8080/metrics | grep _count
// → tasksrv_handler_duration_seconds_count{method="POST",route="/tasks"} 0
The instrumentation in the handler — two lines of code, a complete RED dashboard in the ops view — plus the endpoint itself, wired into the mux from lesson 46 like any other handler:
// main.go
mux := http.NewServeMux()
mux.HandleFunc("POST /tasks", func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// ... validation and store logic from lesson 47 ...
metrics.TasksCreated.WithLabelValues("api").Inc()
metrics.HandlerDuration.WithLabelValues("/tasks", "POST").
Observe(time.Since(start).Seconds())
})
mux.Handle("GET /metrics", promhttp.Handler())
// Terminal: curl -s localhost:8080/metrics | grep tasksrv_tasks_created
// → # HELP tasksrv_tasks_created_total Tasks accepted in total, by queue.
// → # TYPE tasksrv_tasks_created_total counter
// → tasksrv_tasks_created_total{queue="api"} 128
Why a histogram instead of a gauge with the average? Because averages hide tail latency: a p95 of 800 ms at a mean of 40 ms looks perfectly healthy on an average line. The histogram keeps the distribution in buckets, Prometheus computes quantiles from it (histogram_quantile) — correctly across instances, because buckets are additive while averages of averages are not.
⚠ Common mistake: Unbounded values as labels — classically
pathincluding path parameters (/tasks/4291/...) or plainuser_id. Every new ID creates a new time series; after a week the/metricsoutput carries millions of series, the Prometheus server runs into memory and timeout limits, and the service's metrics become unusable. Restrict labels to fixed sets (route="/tasks"instead of the real path) and leave per-item detail to logs and traces.
Check: You want the dashboard to show the p95 latency of POST /tasks. Which instrumentation approach yields that correctly across three service instances?
Answer: A histogram with fixed buckets: each instance observes, PromQL computes histogram_quantile over the summed buckets
Only histogram buckets are additive across instances — that is why histogram_quantile computes a correct global p95 from buckets. Averaging per-instance quantiles (summary) or per-instance averages (gauge) blurs exactly the outliers p95 asks about; a latency-sum counter loses the distribution entirely. The bucket boundaries should cover the SLO-relevant range — hence 0.005 to 1 second in the example.
Takeaways:
github.com/prometheus/client_golang exports Go metrics in Prometheus format: promhttp.Handler() mounts them as an ordinary handler at GET /metrics.tasks_created_total), gauge (current value, e.g. queue length), histogram (distribution in buckets, e.g. handler duration).queue, route, method); IDs and free-form strings belong in logs/traces, or the cardinality explodes.histogram_quantile over additive buckets), not averaged means — averages hide exactly the outliers that matter.A task vanishes: the client sent it to tasksrv, the monitor shows it as »created« — but the notification never arrives, and nobody knows where the chain broke. Laying the two services' logs side by side is guesswork: timestamps roughly match, but which worker log line belongs to exactly this request? Distributed systems need a common thread — and that is precisely tracing. A trace is the single ID connecting all steps of one request across all services; the individual steps are called spans.
go.opentelemetry.io/otel is the vendor-neutral standard library for this (CNCF, no backend-vendor lock-in). The flow is the same everywhere: set up a TracerProvider with an exporter, pass span information through the context — context.Context from lesson 38 is the transport — and carry it across service boundaries via propagation in HTTP headers. The wire format for that is the W3C standard traceparent.
The Trace Context Travels in the Header
A span is never born in a void: tracer.Start(ctx, ...) attaches it to the span in the context — and only in the context. When a call crosses a service boundary, the client injects the current trace ID into the traceparent header, and the server extracts it again. Only then do two spans in two processes become one tree. This does not happen automatically, because net/http knows nothing about OpenTelemetry — otelhttp.NewHandler does the injecting/extracting for you, but it is itself just middleware in the lesson 48 sense.
Step one: provider and exporter. For development the stdout exporter (go.opentelemetry.io/otel/exporters/stdout/stdouttrace) is enough — span after span onto the console; in production the same code points at an OTLP collector:
// telemetry/tracer.go
package telemetry
import (
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
// InitTracer sets the global provider and returns a shutdown function.
func InitTracer(ctx context.Context) (func(context.Context) error, error) {
exp, err := stdouttrace.New(stdouttrace.WithPrettyPrint())
if err != nil {
return nil, err
}
tp := sdktrace.NewTracerProvider(sdktrace.WithBatcher(exp))
otel.SetTracerProvider(tp)
return tp.Shutdown, nil // flushes pending spans on shutdown
}
// main.go
shutdown, err := telemetry.InitTracer(ctx)
if err != nil {
log.Fatal(err)
}
defer shutdown(context.Background()) // without shutdown, batched spans are lost
// Terminal (on exit): shutdown flushes the spans still sitting in the batch
// → {"Name":"POST /api/tasks","TraceID":"4bf92f3577b34da6a3ce929d0e0e4736", ...} — right now, not when the span ended
Step two: span transport. The server wraps its handlers with otelhttp — that creates a span per request, extracts incoming traceparent headers, and injects them on the worker's outgoing call. Inner spans come from your own code, always from the request's context:
// tasksrv: handler boundary and inner span
mux.Handle("/api/", otelhttp.NewHandler(apiMux, "api"))
func (s *Store) AddTask(ctx context.Context, title string) (Task, error) {
ctx, span := otel.Tracer("tasksrv/store").Start(ctx, "AddTask")
defer span.End()
span.SetAttributes(
attribute.String("task.title", title),
attribute.Int("task.queue_len", s.Len()),
)
task, err := s.insert(ctx, title)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
return task, err
}
// Terminal: curl -s -X POST localhost:8080/api/tasks — trace debug on both services
// → {"Name":"POST /api/tasks","TraceID":"4bf92f3577b34da6a3ce929d0e0e4736","SpanID":"00f067aa0ba902b7", ...}
// → {"Name":"AddTask","TraceID":"4bf92f3577b34da6a3ce929d0e0e4736","ParentSpanID":"00f067aa0ba902b7", ...}
// → {"Name":"send notification","TraceID":"4bf92f3577b34da6a3ce929d0e0e4736", ...}
Same TraceID, three spans, two processes — the vanished-task problem from above becomes a matter of seconds: take the trace ID from the request log (lesson 63 prepared trace_id as a field), paste it into the trace backend, and the gap shows up exactly where the worker stopped answering. That completes the triad: metrics say whether, logs say why, traces say where — brought together in the architecture course's observability module. This is the foundation module 14 builds on, wiring AI frameworks into the Go service.
⚠ Common mistake: Starting inner spans with
context.Background()instead of the request context —tracer.Start(context.Background(), "AddTask"). The span then has no parent information, starts its own isolated trace, and in the trace view it sits as an orphaned one-off next to the actual request tree instead of inside it. Always pass thectxthe handler received (r.Context(), or the context returned bytracer.Startfor its children).
Check: Two services, both instrumented with otelhttp — yet the backend shows their spans as two separate traces. What is the most typical cause?
Answer: The outgoing client call bypasses otelhttp — the traceparent header is never injected, and the server starts a fresh trace without context
Connections only exist through propagation: the client must send the active trace ID as a traceparent header, and the server must extract it. otelhttp does both — but only for calls that actually go through an instrumented transport or handler (or where you propagate manually). A bare http.Post skips the middleware, and the server starts a fresh trace. Only looking at the TraceID in the log reveals the split.
Takeaways:
go.opentelemetry.io/otel is the vendor-neutral standard (CNCF), and spans travel via context.Context.TracerProvider with an exporter (stdout locally, OTLP in production) and never skip defer shutdown(...) — otherwise batched spans are lost on exit.otelhttp.NewHandler creates server spans and carries the W3C traceparent header across service boundaries; the outgoing call must also run through an instrumented transport, or the trace breaks.tracer.Start(ctx, ...)), and make failures visible with span.RecordError and SetStatus(codes.Error, ...).trace_id log field couples logs and traces directly.Course navigation: ← Module 12 · All 20 modules · Module 14 →