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.
The bookstore API from Module 12 runs — on Lena's laptop. Now "Kant & Curves" wants to go live for real: three developers, an operations team, releases every two weeks. This is precisely the phase where projects die — not from missing features, but from decisions someone made months ago that nobody can explain anymore. Why Gin and not chi? Why sqlc and not GORM? If the answer lives only in someone's head or in a Slack thread, you lose weeks.
The tool for this is deliberately plain: ADRs (Architecture Decision Records) — numbered markdown files in the repo, each exactly one page, with context, decision, and consequences. And the second half of the lesson: a layer plan that states which Go package may import whom. Together they are the difference between "hexagonal sounds nice" and hexagonal that still holds in two years — the architectural styles in depth are covered in Module 3 of the architecture course.
An ADR Is a Contract with Your Future Self
ADRs are intentionally boring: short context (which problem was pressing?), one clear decision in the indicative mood ("we use Gin for the API layer"), and the honest consequences including the downsides. ADRs are never edited, only superseded: if you believe a decision is wrong, you write a new ADR that replaces the old one. That keeps the decision history readable — like git log for architecture.
First the layer plan — a standard layout for Go services that you will recognize almost everywhere:
bookstore/
├── cmd/bookstore/main.go # composition root: wiring happens here and nowhere else
├── internal/
│ ├── catalog/ # domain: entities, ports (interfaces) — imports NO framework
│ ├── api/ # adapter: Gin handlers, middleware, JSON
│ ├── store/ # adapter: sqlc-generated queries, pgx pool
│ └── obs/ # logging, metrics, tracing (lesson 73)
└── docs/adr/ # 0001-adr-process.md, 0007-router-is-gin.md, …
And an ADR from the bookshop's everyday life — number 7, because the first six decisions (Postgres, Go, CI, migrations with github.com/golang-migrate/migrate/v4, deployment, monitoring) were already made:
# ADR 0007: Gin as the HTTP router for the API layer
## Context
About thirty routes, an admin group with auth, JSON binding. net/http has
handled method patterns and wildcards itself since Go 1.22 (lesson 46) —
pure route matching is not an argument for a framework.
## Decision
We use github.com/gin-gonic/gin for the API layer. The domain
(internal/catalog) stays router-free.
## Consequences
- Binding, validation middleware, and groups save time across 30 routes.
- The largest middleware ecosystem of the candidates.
− Its own handler signature (*gin.Context): a later router switch touches
every handler line — accepted because it is unlikely.
But a plan only holds if it cannot be argued away. Go has no classpath magic — yet there is a trick many teams have never seen: the dependency rule as a test. An ordinary go test that inspects a package's imports via go list and goes red the moment the domain imports a framework:
// internal/arch/arch_test.go — the layer rule as an executable test
package arch
import (
"os/exec"
"strings"
"testing"
)
func TestCatalogImportsNoFramework(t *testing.T) {
out, err := exec.Command("go", "list",
"-deps", "bookstore/internal/catalog").CombinedOutput()
if err != nil {
t.Fatal(err)
}
for _, imp := range strings.Fields(string(out)) {
switch {
case strings.HasPrefix(imp, "github.com/gin-gonic/gin"),
strings.HasPrefix(imp, "github.com/jackc/pgx"),
strings.HasPrefix(imp, "github.com/spf13/cobra"):
t.Errorf("domain imports infrastructure: %s", imp)
}
}
}
// Terminal: go test ./internal/arch/
// → ok bookstore/internal/arch 0.412s
//
// Terminal: after a "quick fix" that drags gin.Context into the domain
// → --- FAIL: TestCatalogImportsNoFramework
// → arch_test.go:20: domain imports infrastructure: github.com/gin-gonic/gin
And the other direction of the rule — the domain defines its own ports, as plain Go interfaces. That is the core of the hexagonal idea in Go: no implements keyword, no factories, just the fact that implementations satisfy interfaces implicitly:
// internal/catalog/ports.go — the domain states the WHAT, the adapter delivers the HOW
package catalog
import "context"
type Book struct {
ISBN, Title, Author string
PriceCents int64
}
// Repository is a port: named from the domain's point of view, not the database's.
type Repository interface {
ByISBN(ctx context.Context, isbn string) (Book, error)
Store(ctx context.Context, b Book) error
}
// Terminal: go build ./internal/catalog
// → (no output — the domain compiles without a single framework)
⚠ Common mistake: The layer rule lives only in a wiki — or as a comment above the package tree. Three months later the first "quick fix" carries a
*gin.Contextinto the domain, and nobody notices, because everything still compiles. A rule no CI enforces is not a rule, it is a wish. Thego listtest above costs twenty lines and runs with everygo test ./...— there is no excuse to leave it out.
Check: Where does the repository interface belong in the layer plan — and why?
Answer: In the domain — Go interfaces are satisfied implicitly by the implementer, so internal/catalog stays import-free
The Java reflex puts interfaces next to implementations. In Go it is the other way around: interfaces belong to the consumer. The domain states what it needs (ByISBN, Store), and every adapter — sqlc, an in-memory fake for tests, whatever comes later — satisfies the interface without the domain ever knowing it. A central shared/types package instead couples every layer to one place, which collects unrelated dependencies like a basement collects boxes.
Takeaways:
cmd/ as the composition root, internal/catalog as the router-free domain, internal/api and internal/store as adapters.go list test in CI makes the rule unavoidable instead of voluntary.implements, no import.The plan exists (lesson 71); now it becomes concrete: a service skeleton that has every property of a production system from day one — even while the domain is still small. Hexagonal here does not mean folder religion, but a single statement: the core knows only its ports, and everything technical is an adapter you can swap without touching the core. That pays off immediately: the service tests in Module 13 ran against an in-memory implementation, with no Docker container required.
The build order matters: domain and ports first, then the adapters, and main dead last. Whoever starts with main.go and the router drags framework types through everything that follows.
The core — pure Go, testable in nanoseconds:
// internal/catalog/service.go — the domain: no gin, no pgx, just logic
package catalog
import (
"context"
"fmt"
)
type Service struct {
repo Repository // the port from ports.go — whoever fills it
}
func NewService(repo Repository) *Service { return &Service{repo: repo} }
var ErrNotFound = fmt.Errorf("catalog: book not found")
func (s *Service) Book(ctx context.Context, isbn string) (Book, error) {
b, err := s.repo.ByISBN(ctx, isbn)
if err != nil {
return Book{}, fmt.Errorf("isbn %s: %w", isbn, err)
}
return b, nil
}
// Terminal: go test ./internal/catalog -run TestBook
// → ok bookstore/internal/catalog 0.003s (0.003 s — no network, no DB)
The HTTP adapter — Gin at the edge, thin handlers, error mapping in exactly one place. Which status code belongs to which error is an API-design decision, not a Go decision; Module 5 of the architecture course has the table for that:
// internal/api/books.go — the adapter: parse, call the domain, respond
package api
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"bookstore/internal/catalog"
)
func Book(svc *catalog.Service) gin.HandlerFunc {
return func(c *gin.Context) {
b, err := svc.Book(c.Request.Context(), c.Param("isbn"))
switch {
case err == nil:
c.JSON(http.StatusOK, b)
case errors.Is(err, catalog.ErrNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "book not found"})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
// details go to the log only (lesson 73) — never into the response
}
}
}
// Terminal: curl -s -i localhost:8080/api/v1/books/000-0-0000-0000-0
// → HTTP/1.1 404 Not Found
// → {"error":"book not found"}
The storage adapter — sqlc generates the types, the adapter merely implements the port. The queries live in internal/store/queries/books.sql (lesson 58), and sqlc.yaml says sql_package: "pgx/v5":
// internal/store/catalog.go — hide the sqlc output behind the port
package store
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"bookstore/internal/catalog"
)
type Repository struct{ q *Queries } // Queries: generated by sqlc
func NewRepository(q *Queries) *Repository { return &Repository{q: q} }
func (r *Repository) ByISBN(ctx context.Context, isbn string) (catalog.Book, error) {
row, err := r.q.GetBookByISBN(ctx, isbn)
switch {
case errors.Is(err, pgx.ErrNoRows):
return catalog.Book{}, catalog.ErrNotFound // adapter translates, domain stays DB-free
case err != nil:
return catalog.Book{}, err
}
return catalog.Book{ISBN: row.Isbn, Title: row.Title,
Author: row.Author, PriceCents: row.PriceCents}, nil
}
// Terminal: go vet ./...
// → (no output — clean)
And the composition root — the only file that sees every layer. Migrations run with github.com/golang-migrate/migrate/v4 before the first request arrives:
// cmd/bookstore/main.go — wire, do not think
package main
import (
"context"
"log/slog"
"net/http"
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgxpool"
"bookstore/internal/api"
"bookstore/internal/catalog"
"bookstore/internal/store"
)
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
slog.Error("pool", "err", err)
os.Exit(1)
}
defer pool.Close() // ONE pool per process — lesson 60
if err := migrateDB(ctx, os.Getenv("DATABASE_URL")); err != nil { // golang-migrate/v4, files in db/migrations
slog.Error("migration", "err", err)
os.Exit(1)
}
svc := catalog.NewService(store.NewRepository(pool)) // ports meet adapters — right here
r := gin.Default()
r.GET("/api/v1/books/:isbn", api.Book(svc))
srv := &http.Server{
Addr: ":8080",
Handler: r,
ReadHeaderTimeout: 5 * time.Second, // Slowloris protection, lesson 49
WriteTimeout: 15 * time.Second,
}
slog.Info("listening on :8080")
if err := srv.ListenAndServe(); err != nil {
slog.Error("server", "err", err)
}
}
// Terminal: DATABASE_URL=postgres://book@localhost/kurve go run ./cmd/bookstore
// → {"time":"2026-11-05T20:11:48+01:00","level":"INFO","msg":"listening on :8080"}
Thin Handlers Are Not a Matter of Taste
A handler has exactly three jobs: parse the request, call the domain, write the response. Anything beyond that — business rules, SQL, pricing logic — moves into the core and thereby becomes testable without HTTP, router, or network. The litmus test: could the domain run as a CLI program without changing a single line in internal/catalog? If yes, the skeleton is hexagonal. If no, the handler is too fat.
⚠ Common mistake: The first handler passes
*gin.Contextas a parameter into the service method — "saves all that double context ceremony." From that moment the domain is coupled to Gin: tests need a Gin engine stub, and because the context becomes invalid after the request, you grow leak-like bugs whenever the domain keeps using it in a goroutine. The only context that enters the domain iscontext.Context— in the handler that isc.Request.Context(), in tests and CLIs it iscontext.Background().
Check: The handler calls svc.Book. Which context does it pass into the domain — and what is the actual point?
Answer: c.Request.Context() — cancellation, deadline, and later the trace span (lesson 73) travel all the way to the database
The worry behind option 1 is even correctly observed, but it draws the wrong conclusion: yes, the request context gets canceled — and that is exactly the intended effect. When the user navigates away or the budget expires, the DB query aborts instead of burning resources on an answer nobody will read. context.Background() prevents precisely that and produces ghost work; 30-second default timeouts burn the caller's budget. You set timeouts where the budget is known (lesson 74), not wholesale in the handler.
Takeaways:
main last — whoever starts with the router drags framework types through everything.context.Context and its ports; handlers stay thin (parse, call, respond).pgx.ErrNoRows) into domain errors (catalog.ErrNotFound) — the domain stays DB-free.main.go is the only file that imports every layer; migrations run before the first request with github.com/golang-migrate/migrate/v4.The scenario everyone knows: the bookshop's latency spikes, the ticket queue fills up, and the chat holds three hypotheses and zero data. Is it the database? The recommendation service from Module 14? The pod on the wrong node? Without observability, seven people guess; with it, one person reads three graphs and knows. The three tools answer different questions: logs answer "what exactly happened?", metrics answer "how many and how fast?", traces answer "where did the time go?".
For all three the rule is: not bolted on afterwards, but middleware installed from day one. And the extra work is small, because Go ships structured logging as log/slog (in the standard library since Go 1.21) and Prometheus and OpenTelemetry provide ready-made libraries.
The Trace ID Is the Hinge Between the Three Worlds
Running logs, metrics, and traces separately is half-finished. The trick is correlation: every request gets a trace ID, every log entry carries it, every span belongs to it. Then you jump from the Prometheus graph ("P99 jumped to 800 ms at 16:12") into a trace from that minute ("800 ms in the pg span") and from there into the log lines with the same trace_id ("lock timeout on books"). Three systems, one thread.
Level one: structured logs with slog — plus the bridge to OpenTelemetry that automatically writes trace and span IDs into every entry whenever a span is active:
// internal/obs/logging.go — slog JSON plus trace correlation, built once, used everywhere
package obs
import (
"context"
"log/slog"
"os"
"go.opentelemetry.io/otel/trace"
)
// TraceHandler wraps any slog.Handler and appends trace/span IDs.
type TraceHandler struct{ slog.Handler }
func (h TraceHandler) Handle(ctx context.Context, r slog.Record) error {
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
r.AddAttrs(slog.String("trace_id", sc.TraceID().String()),
slog.String("span_id", sc.SpanID().String()))
}
return h.Handler.Handle(ctx, r)
}
func NewLogger() *slog.Logger {
return slog.New(TraceHandler{slog.NewJSONHandler(os.Stdout, nil)})
}
// Terminal: curl -s localhost:8080/api/v1/books/978-3-423-2089-8
// → {"time":"2026-11-05T21:14:02+01:00","level":"INFO","msg":"book served","isbn":"978-3-423-2089-8","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"00f067aa0ba902b7"}
Level two: metrics. For an HTTP service the RED set is enough — rate, errors, duration — as a histogram with the two labels that matter: route and status code. github.com/prometheus/client_golang provides everything, and promhttp.Handler() exposes /metrics:
// internal/obs/metrics.go — RED metrics as Gin middleware
package obs
import (
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
)
var httpDur = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request duration by route and status code.",
Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5},
}, []string{"route", "code"})
func init() { prometheus.MustRegister(httpDur) }
// Metrics uses c.FullPath() — the ROUTE, not the concrete path (see mistake below).
func Metrics() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
httpDur.WithLabelValues(c.FullPath(), strconv.Itoa(c.Writer.Status())).
Observe(time.Since(start).Seconds())
}
}
// Terminal: curl -s localhost:8080/metrics | grep http_request_duration_seconds_bucket
// → http_request_duration_seconds_bucket{code="200",route="/api/v1/books/:isbn",le="0.01"} 14
Level three: traces with OpenTelemetry. Build the provider once in main, ship spans via OTLP/HTTP, and honor the batch flush on shutdown — otherwise every deploy loses the last spans:
// cmd/bookstore/otel.go — OpenTelemetry: provider, exporter, clean shutdown
package main
import (
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)
func newTracerProvider(ctx context.Context, otlpURL string) (*sdktrace.TracerProvider, error) {
exp, err := otlptracehttp.New(ctx, otlptracehttp.WithEndpointURL(otlpURL))
if err != nil {
return nil, err
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp), // collect spans, ship them in batches
sdktrace.WithResource(resource.NewWithAttributes(
semconv.SchemaURL, semconv.ServiceName("bookstore"))),
)
otel.SetTracerProvider(tp) // library instrumentation hooks in here
return tp, nil
}
// in runServe: build tp, then defer tp.Shutdown(graceCtx) AFTER httpSrv.Shutdown —
// first stop new requests, then flush the remaining spans.
//
// Terminal: the request from above in a trace view (Jaeger/Tempo)
// → bookstore GET /api/v1/books/:isbn 41 ms
// → bookstore SELECT books WHERE isbn = $1 12 ms (db.system: postgresql)
The 4:12 p.m. incident now reads like this: the graph shows the P99 jump to 800 ms at 16:12, the span shows 780 ms waiting on a lock, the logs show the lock timeouts with the same trace IDs. Diagnosis done before the coffee goes cold — and this time the culprit was a forgotten migration from lesson 72, which now gets its own line in the release checklist of lesson 75.
⚠ Common mistake: Using the concrete path as the route label —
c.Request.URL.Pathinstead ofc.FullPath(). Prometheus labels mean one time series per value combination:/api/v1/books/978-3-423-2089-8,/api/v1/books/978-3-453-2007-3, ten thousand ISBNs later the server holds ten thousand series for the same route, Prometheus memory grows, and queries become useless (cardinality explosion).FullPath()returns the registered pattern (/api/v1/books/:isbn) — finitely many series no matter how many books the shop carries.
Check: What is the actual purpose of the trace ID inside log entries — not of the traces themselves?
Answer: It interlocks logs and traces for searching: from the metric anomaly into the trace, and from there into the individual log lines of the same request
The common misconception sees the trace ID as yet another identifier for the logs themselves. Its value is the bridge: an anomaly in the metrics (WHEN, HOW BAD) leads to a trace (WHERE in the call path), and that carries the same ID into the logs (WHAT exactly, with which parameters). Without that hinge you are left with three data silos connected only by timestamp guessing — exactly the Friday-afternoon game observability exists to prevent.
Takeaways:
log/slog (since Go 1.21) plus a thin TraceHandler write structured JSON logs that automatically carry trace_id and span_id.route and code — route always via c.FullPath(), never the concrete path.go.opentelemetry.io/otel and an OTLP exporter in main; flush the batch on shutdown, or every deploy loses its last spans.The recommendation service from Module 14 — pgvector embeddings, all fine — suddenly answers in eight seconds instead of forty milliseconds. Without protection this escalates predictably: every book request waits for recommendations, goroutines pile up, the pgx pool clogs with waiting requests, and five minutes later the whole shop is down — because of a service that was only nice-to-have. A production-ready service handles this like a power grid: every line has a fuse. How timeouts, circuit breakers, and bulkheads work as patterns is covered in Module 8: Resilience of the architecture course — in this lesson you build them in Go.
The fuses stack from the outside in, and each has a different job:
| Fuse | Tool | Job |
|---|---|---|
| Timeout per call | context.WithTimeout | no request waits longer than its budget |
| Client cap | http.Client{Timeout: …} | reserve parachute if a context is forgotten |
| Circuit breaker | github.com/sony/gobreaker/v2 | after repeated failures, do not even ask |
| Rate limit | golang.org/x/time/rate | one client cannot flood the service |
| Server timeouts | http.Server fields | Slowloris and stuck writers (lesson 49) |
Level one: the budget. The caller knows how much time it wants to grant the dependency — here 1.5 seconds — and the http.Client gets a hard cap on top:
// internal/recommend/client.go — budgets: context first, then the client cap
package recommend
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
type Client struct {
svc string
http *http.Client
}
func New(svc string) *Client {
return &Client{svc: svc,
http: &http.Client{Timeout: 2 * time.Second}} // cap for ALL calls
}
func (c *Client) For(ctx context.Context, userID string) ([]string, error) {
ctx, cancel := context.WithTimeout(ctx, 1500*time.Millisecond) // the caller's budget
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
c.svc+"/v1/recommend?user="+userID, nil)
if err != nil {
return nil, err
}
resp, err := c.http.Do(req)
if err != nil {
return nil, fmt.Errorf("recommend: %w", err) // context.DeadlineExceeded stays visible
}
defer resp.Body.Close()
var recs []string
return recs, json.NewDecoder(resp.Body).Decode(&recs)
}
// Terminal: the service takes 8 s today — the request still does not
// → 2026/11/05 21:30:00 GET /api/v1/books 200 in 1501 ms (timeout, fallback active)
Level two: the circuit breaker. github.com/sony/gobreaker/v2 counts failures per state: after five consecutive failures the circuit trips, and the next calls fail in microseconds — without touching the dead service at all. After thirty seconds it lets probe requests through (half-open):
// internal/recommend/breaker.go — gobreaker/v2 with a fallback instead of an error
package recommend
import (
"context"
"time"
"github.com/sony/gobreaker/v2"
)
var cb = gobreaker.NewCircuitBreaker[[]string](gobreaker.Settings{
Name: "recommend",
MaxRequests: 3, // half-open: allow exactly 3 probe requests
Timeout: 30 * time.Second, // how long the circuit stays open
ReadyToTrip: func(c gobreaker.Counts) bool {
return c.ConsecutiveFailures >= 5 // trip after 5 failures in a row
},
})
func SafeFor(c *Client) func(ctx context.Context, uid string) ([]string, error) {
return func(ctx context.Context, uid string) ([]string, error) {
recs, err := cb.Execute(func() ([]string, error) {
return c.For(ctx, uid)
})
if err != nil {
return []string{"978-3-423-2089-8"}, nil // fallback: the bestseller list
}
return recs, nil
}
}
// Terminal: log lines every second while the recommendation service hangs
// → 21:30:05 recommend err=context deadline exceeded (cb consecutive_failures=4)
// → 21:30:06 recommend err=context deadline exceeded (cb consecutive_failures=5)
// → 21:30:07 recommend err=exec refused request (circuit open — 0.04 ms instead of 1,500 ms)
Level three: rate limits. Not because users are evil — but because one buggy client or script can be. golang.org/x/time/rate (the extended-standard-library package under golang.org/x, not std) hands each client IP a token bucket — and the middleware keeps even the crudest attacker in check:
// internal/api/ratelimit.go — one rate.Limiter per client IP
package api
import (
"net"
"sync"
"github.com/gin-gonic/gin"
"golang.org/x/time/rate"
)
var (
mu sync.Mutex
limiters = make(map[string]*rate.Limiter)
)
func limiterFor(ip string) *rate.Limiter {
mu.Lock()
defer mu.Unlock()
lim, ok := limiters[ip]
if !ok {
lim = rate.NewLimiter(5, 10) // 5 requests/s per IP, bursts up to 10
limiters[ip] = lim
}
return lim
}
func RateLimit() gin.HandlerFunc {
return func(c *gin.Context) {
host, _, err := net.SplitHostPort(c.Request.RemoteAddr)
if err != nil {
host = c.Request.RemoteAddr
}
if !limiterFor(host).Allow() {
c.AbortWithStatus(429) // Too Many Requests — no body; attackers deserve no hints
return
}
c.Next()
}
}
// Terminal: eleven requests in one second from the same IP
// → HTTP/1.1 200 OK (x10)
// → HTTP/1.1 429 Too Many Requests
Fuses Stack — Each for a Different Failure Mode
Timeouts end individual waiting calls, but they are expensive: even an aborted request already burdened the downstream. The breaker prevents the call entirely and gives the sick service room to breathe. Rate limits protect against the other extreme: too much success or too much hostility. None replaces the others — with only timeouts you keep hammering a dead service; with only a breaker you die on the first slow request before the breaker even starts counting.
⚠ Common mistake: On timeout, simply retrying the same request three times — "maybe it works now." If the downstream is overloaded, the retry logic triples exactly the load that killed it, and the outage becomes self-reinforcing (retry storm). If you retry at all: exponential backoff plus jitter, idempotent operations only, and a total budget that counts the retries — the circuit breaker is almost always the better first answer.
Check: The circuit is open. What is the purpose of that state — who wins what?
Answer: The caller fails fast instead of waiting, and the sick service gets quiet time to recover — both win
The breaker heals nothing and routes nothing — fallbacks are yours to write (in the example: the bestseller list). Its purpose is failing fast: the caller burns no 1.5 seconds on a request doomed anyway, and the overloaded service gets no new requests queued while it tries to recover. Timeouts remain necessary regardless: the breaker only learns it should trip from failures — including timeout failures — in the first place.
Takeaways:
http.Client.Timeout as the cap, a circuit breaker for total outages, rate limits against floods, http.Server timeouts against Slowloris.github.com/sony/gobreaker/v2 encapsulates open/half-open/closed; cb.Execute plus a fallback makes the outage invisible to the user.golang.org/x/time/rate per client IP; 429 without a body — the protection is for the service, not for the attacker.Release day. The build runs, the image moves to the registry, the pod starts — and the first question operations asks is: "Which version is this — and how do we roll back?" If the only honest answer is "the latest tag from a minute ago," you have missed the point of this module. The final lesson wires everything into a repeatable process: a binary that knows its own version, an image that contains nothing extra, and a checklist nobody has to recall from memory.
Level one: version embedding. Go has an old, reliable mechanism for this: the linker sets package variables at build time — -ldflags "-X main.version=1.4.0". And since Go 1.18, debug.ReadBuildInfo() even carries the commit revision when you build inside a git repo, without any flag:
// cmd/bookstore/version.go — embed the version at build time
package main
import (
"fmt"
"runtime/debug"
)
// -ldflags "-X main.version=1.4.0" sets exactly this variable at link time.
var version = "dev"
func buildVersion() string {
if version != "dev" {
return version
}
if bi, ok := debug.ReadBuildInfo(); ok { // go build in a git repo: vcs info since Go 1.18
if rev, ok := bi.Settings["vcs.revision"]; ok && len(rev.Value) >= 7 {
return fmt.Sprintf("dev-%s", rev.Value[:7])
}
}
return "dev"
}
// Terminal: go run ./cmd/bookstore version
// → bookstore dev-8f3c2ab
Plus the two endpoints operations actually needs — /healthz (is the process alive?) and /readyz (can it work, i.e. can it reach the database?):
// internal/api/health.go — liveness and readiness are different questions
package api
import (
"context"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgxpool"
)
func Healthz() gin.HandlerFunc {
return func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true}) }
}
func Readyz(pool *pgxpool.Pool) gin.HandlerFunc {
return func(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 500*time.Millisecond)
defer cancel()
if err := pool.Ping(ctx); err != nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"ready": false, "db": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"ready": true, "version": buildVersion()})
}
}
// Terminal: curl -s localhost:8080/readyz
// → {"ready":true,"version":"1.4.0"}
//
// Terminal: while the database restarts
// → {"ready":false,"db":"failed to connect"}
Level two: the image. Multi-stage build — the compiler exists only in the first stage; the second stage holds a static binary in a distroless image with no shell, no package manager, no attack surface:
# Dockerfile — multi-stage: build, then take only the binary
FROM golang:1.25 AS build
ARG VERSION=dev
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download # own layer: code changes re-download no dependencies
COPY . .
RUN CGO_ENABLED=0 go build -trimpath \
-ldflags "-s -w -X main.version=${VERSION}" \
-o /out/bookstore ./cmd/bookstore
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/bookstore /bookstore
USER nonroot
ENTRYPOINT ["/bookstore"]
# Terminal: build, run, push — with the fixed version as the tag
# → docker build -t registry.curves.shop/bookstore:1.4.0 --build-arg VERSION=1.4.0 .
# → docker run --rm -p 8080:8080 registry.curves.shop/bookstore:1.4.0
# → {"time":"2026-11-05T21:52:03+01:00","level":"INFO","msg":"listening on :8080","version":"1.4.0"}
Level three: the checklist. Deliberately short — one box per line, and a deploy without a full set of boxes stops right there:
go test ./... -race green — including the architecture tests from lesson 71.go vet and staticcheck (honnef.co/go/tools) quiet — static analysis without findings.golang-migrate up AND down (lesson 72).latest (see mistake below)./healthz and /readyz of the new version checked — including the version in the response./readyz.Production-Readiness Is a Property of the Process, Not the Code
No single line in this module is hard. Production readiness comes from things always happening the same way: the version comes from the build, never from memory; deploys follow the checklist, never the mood of the day; the rollback is a rehearsed move, not an adventure. The capstone of your Go journey is therefore not a framework but this discipline — the code from Modules 11 through 14 is already inside.
⚠ Common mistake: Deploying
:latest— and, as a crowning touch, forgetting to pass-X main.version. In production/readyzthen reportsdev-whatever, three pods laterdev-somethingelse, and during the 11 p.m. incident nobody knows which code is actually running. The rollback is alsolatest— in other words, hoping. Immutable version tags are the cheapest insurance in the world: build once, one tag, the same binary everywhere.
Check: What exactly does the linker flag -ldflags -X main.version=1.4.0 do — and what does it not do?
Answer: At link time it sets the package variable main.version — it only works for string variables declared at package level
The linker replaces the symbol main.version at link time — once, at build time, final. That requires two things option 4 ignores: the variable must be declared at package level and be of type string; local variables do not even exist as symbols for the linker. Nor does -X read git tags — ReadBuildInfo at least yields the commit revision (vcs.revision, since Go 1.18), but the flag is the way to get real version numbers from your pipeline into the binary.
Takeaways:
-ldflags "-X main.version=…" sets package string variables at link time; debug.ReadBuildInfo() additionally yields the commit revision from the git repo since Go 1.18./healthz (process alive) and /readyz (including DB ping and version) answer different questions — orchestrators and operators ask both.golang:1.25, run in gcr.io/distroless/static-debian12:nonroot — no shell, no attack surface, static binary.-race tests, migrations rehearsed both ways, fixed version tags, rehearsed rollback — never latest.Course navigation: ← Module 14 · All 20 modules · Module 16 →