Self-study deck · Go · AWS SDK v2 · client-go · controller-runtime

Go for
Platform Engineers

Build useful CLIs, safe cloud automation, and a Kubernetes operator. From your first Go module to production behavior, with a lab in every chapter.

← → / Space: navigate · I: contents · O: overview · T: theme · F: fullscreen

Go for Platform Engineers

Contents

Select a chapter · press I anywhere to return here

Chapter 00 · Go for Platform Engineers

Orientation and setup

← Contents
Chapter 0 · Section 00

Why Go in platform engineering

Concepts to understand and explain before the lab.

Point 1

Platform use cases: CLIs, API adapters, inventory and diagnostic tools, and Kubernetes controllers.

Point 2

The trade-off: a compiled binary and strong standard library versus a scripting language; choose Go when distribution, concurrency, or long-running services justify it.

Point 3

Map the two projects used throughout: platformctl (read-only CLI) and PlatformEnvironment (local Kubernetes operator).

Chapter 0 · Section 00 · Applied

Pick the right tool

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

One-time text transform → Bash/Python
Portable team CLI → Go
Continuous desired-state loop → Go controller

Why it matters

Use Go for a durable product boundary, not just because a task is technical.

Chapter 0 · Section 01

Environment

Concepts to understand and explain before the lab.

Point 1

Install Go, verify go version and go env; configure editor support with gopls.

Point 2

Create a module with go mod init; run a program with go run; build with go build.

Point 3

Use a local kind cluster for Kubernetes labs; reserve AWS labs for a sandbox or recorded fixtures.

Chapter 0 · Section 01 · Applied

First module

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

mkdir platformctl && cd platformctl
go mod init example.com/platformctl
cat > main.go <<'EOF'
package main
import "fmt"
func main() { fmt.Println("hello platform") }
EOF
go run . && go build .

Why it matters

The module path identifies imports; it does not need a public repository for a local lab.

Chapter 0 · Section 02

How to learn from this deck

Concepts to understand and explain before the lab.

Point 1

For each concept: read a small example, predict its behavior, run it, change one input, then explain the result.

Point 2

Track an error log of compiler errors, failed tests, and their fixes; use the Go docs before relying on snippets.

Point 3

Lab 0: create the repository skeleton and a hello platform command; verify a clean build and test run.

Chapter 0 · Section 02 · Applied

Practice loop

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

Predict → Run → Change one input → Explain
go test ./...
go doc context.Context
go help mod

Why it matters

Type examples yourself, then compare the actual output with your prediction.

Chapter 0 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

When is Go preferable to a script?

When a portable, tested, long-lived tool or controller justifies a compiled binary.

What identifies a module?

Its module path in go.mod.

Where do labs run?

Locally; AWS reads use fixtures or a sandbox, Kubernetes writes use a separate kind cluster.

Lab 0

Bootstrap the module

Complete this before starting the next chapter.

Step 1

Install Go and confirm go version and go env.

Step 2

Create platformctl with go mod init and a cmd/platformctl entry point.

Step 3

Print hello platform; run, build, format, and test it.

Done when: go build ./... and go test ./... pass.
Chapter 01 · Go for Platform Engineers

Go language foundations

← Contents
Chapter 1 · Section 03

Program structure and values

Concepts to understand and explain before the lab.

Point 1

package main, imports, exported names, main, comments, and the Go formatting convention.

Point 2

Variables, const, zero values, short declarations, basic numeric and string types, explicit conversions.

Point 3

Value semantics, pointers, nil, addressability, and when a pointer is needed.

Chapter 1 · Section 03 · Applied

Zero value and pointers

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

type Health struct { Ready bool; Restarts int }
var h Health  // false, 0
func markReady(h *Health) { h.Ready = true }

Why it matters

Use a pointer when mutation or absence matters; do not use one merely to avoid a tiny copy.

Chapter 1 · Section 04

Control flow

Concepts to understand and explain before the lab.

Point 1

if, switch, for, range, defer, and early returns; no exception-based control flow.

Point 2

Go 1.22 per-iteration loop variables (when the module's language version is at least 1.22) and range over integers; Go 1.23 range over iterator functions and the iter package.

Point 3

Scope and shadowing, including accidental err shadowing; labeled loops only when justified.

Point 4

Time and duration values for retries and timeouts.

Chapter 1 · Section 04 · Applied

Loop variables are versioned

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

for i := range 3 { fmt.Println(i) } // 0, 1, 2
for _, name := range names { go func() { use(name) }() }
for name := range slices.Values(names) { fmt.Println(name) } // Go 1.23

Why it matters

Per-iteration variables require a module language version of Go 1.22 or newer; review old modules carefully.

Chapter 1 · Section 05

Collections and aliasing

Concepts to understand and explain before the lab.

Point 1

Arrays versus slices; length, capacity, append, shared backing arrays, copying, and mutation hazards.

Point 2

Maps: lookup with the ok idiom, missing keys, iteration order, and safe initialization.

Point 3

Strings as UTF-8 bytes; runes versus bytes; safe traversal and normalization boundaries.

Chapter 1 · Section 05 · Applied

Slice aliasing

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

a := []string{"dev", "prod"}
b := a[:1]
b[0] = "test" // a[0] is now test
c := append([]string(nil), a...) // independent copy

Why it matters

Slices are descriptors over backing arrays. Use a copy when ownership must be independent.

Chapter 1 · Section 06

First platform program

Concepts to understand and explain before the lab.

Point 1

Parse a line-oriented list of service names, validate names, deduplicate, and print sorted results.

Point 2

Compare stdout output with stderr diagnostics and use a nonzero exit on invalid input.

Point 3

Lab 1: implement platformctl services list using only the standard library.

Chapter 1 · Section 06 · Applied

Deterministic list

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

seen := map[string]struct{}{}
for _, name := range input { seen[name] = struct{}{} }
for name := range seen { names = append(names, name) }
slices.Sort(names)

Why it matters

Map iteration order is unspecified. Sort before producing human or machine-readable output.

Chapter 1 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

What is a zero value?

The initialized value of a variable without an explicit assignment.

Why sort map keys before output?

Go map iteration order is unspecified.

What changed in Go 1.22 loops?

New loop variables are created per iteration for modules using the Go 1.22 language version.

Lab 1

List services

Complete this before starting the next chapter.

Step 1

Read service names from a fixture file with bounded input.

Step 2

Reject empty or malformed names, deduplicate, then sort.

Step 3

Print results on stdout and diagnostics on stderr.

Done when: Sorted output; invalid input returns a nonzero exit code.
Chapter 02 · Go for Platform Engineers

Data, types, and serialization

← Contents
Chapter 2 · Section 07

Structs and composition

Concepts to understand and explain before the lab.

Point 1

Define structs for cluster, service, and health data; fields, tags, embedded structs, and methods.

Point 2

Pointer versus value receivers; copying structs with slices/maps; keep state ownership explicit.

Point 3

Separate input, domain, and output types instead of using one struct everywhere.

Chapter 2 · Section 07 · Applied

Transport versus domain

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

type Service struct { Name string; Ready bool }
type ServiceJSON struct { Name string `json:"name"`; Ready bool `json:"ready"` }

Why it matters

Do not let an external API shape every internal type; translate at the boundary.

Chapter 2 · Section 08

JSON and API contracts

Concepts to understand and explain before the lab.

Point 1

encoding/json: exported fields, tags, omitempty versus Go 1.24 omitzero, decoding, encoding, and unknown fields.

Point 2

Distinguish absent, zero, and null when config or API contracts require it.

Point 3

Bound input size; validate parsed data; never treat successful decoding as validation.

Chapter 2 · Section 08 · Applied

Absent, empty, zero

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

type Request struct { Replicas *int `json:"replicas,omitempty"` }
// nil = omitted; pointer to 0 = explicitly zero
type Report struct { SeenAt time.Time `json:"seenAt,omitzero"` }

Why it matters

Use a pointer or explicit optional type when zero and missing mean different things.

Chapter 2 · Section 09

Text and YAML boundaries

Concepts to understand and explain before the lab.

Point 1

Read line-oriented files with bufio; handle scanner limits and malformed records.

Point 2

Go has no YAML package in the standard library; use sigs.k8s.io/yaml for the Kubernetes/config use case, with validation after conversion.

Point 3

Use typed Kubernetes objects or validated schemas instead of editing YAML as strings.

Chapter 2 · Section 09 · Applied

YAML boundary

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

raw, err := os.ReadFile(path)
if err != nil { return err }
jsonBytes, err := yaml.YAMLToJSONStrict(raw)
if err != nil { return fmt.Errorf("invalid YAML: %w", err) }

Why it matters

Convert only at the boundary, then decode into a typed schema and validate semantics.

Chapter 2 · Section 10

Data modeling exercise

Concepts to understand and explain before the lab.

Point 1

Define a stable JSON schema for a service inventory report; preserve field names and predictable ordering.

Point 2

Lab 2: load fixture data and emit both human-readable text and machine-readable JSON; add invalid-input cases.

Chapter 2 · Section 10 · Applied

Stable output contract

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

{"account":"111122223333","region":"us-east-1","services":[...]}

Why it matters

Document field names and ordering before scripts depend on the output.

Chapter 2 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

When is a pointer useful in JSON?

When absent and explicitly zero have different meanings.

Does decoding imply validity?

No; validate domain constraints after parsing.

Why avoid editing YAML as strings?

It bypasses structure and schema validation.

Lab 2

Produce an inventory report

Complete this before starting the next chapter.

Step 1

Define typed input and output structs with JSON tags.

Step 2

Parse valid and invalid fixtures; validate semantics after decoding.

Step 3

Emit stable text and JSON representations.

Done when: JSON parses, fields are documented, malformed input is rejected.
Chapter 03 · Go for Platform Engineers

Functions, errors, interfaces, and packages

← Contents
Chapter 3 · Section 11

Functions and API design

Concepts to understand and explain before the lab.

Point 1

Multiple return values, variadic functions, closures, defer, and small functions with one clear job.

Point 2

Pass dependencies explicitly; avoid package globals and hidden initialization.

Point 3

Design package APIs around a caller's task, not a large generic framework.

Chapter 3 · Section 11 · Applied

Dependency injection

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

type Store interface { List(context.Context) ([]Service, error) }
func Report(ctx context.Context, store Store) error {
    services, err := store.List(ctx)
    if err != nil { return err }; return render(services)
}

Why it matters

Pass a narrow dependency from main into the operation; avoid package globals.

Chapter 3 · Section 12

Error handling

Concepts to understand and explain before the lab.

Point 1

Return errors with context using %w; distinguish errors.Is, errors.As, errors.Join, and direct comparison.

Point 2

Sentinel versus typed errors; translate low-level errors at boundaries without losing the cause.

Point 3

Decide when to retry, report, or terminate; avoid logging and returning the same error at every layer.

Chapter 3 · Section 12 · Applied

Error chain

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

if err != nil { return fmt.Errorf("list services in %s: %w", region, err) }
if errors.Is(err, context.DeadlineExceeded) { /* timeout */ }
var apiErr *smithy.GenericAPIError
if errors.As(err, &apiErr) { /* inspect code */ }
return errors.Join(collectErr, writeErr) // independent failures

Why it matters

A useful error says what failed while preserving the cause for callers.

Chapter 3 · Section 13

Interfaces and generics

Concepts to understand and explain before the lab.

Point 1

Implicit interface implementation; small consumer-owned interfaces for test seams.

Point 2

Type assertions and type switches; any only where a real boundary requires it.

Point 3

Basic type parameters and constraints; use generics for repeated algorithms, not to hide concrete domain types.

Chapter 3 · Section 13 · Applied

Small interfaces

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

type Clock interface { Now() time.Time }
// Better: define the interface where the caller needs it.
func Expired(now time.Time, deadline time.Time) bool { return !now.Before(deadline) }

Why it matters

Prefer a plain value or function when an interface adds no useful substitution.

Chapter 3 · Section 14

Package layout

Concepts to understand and explain before the lab.

Point 1

cmd/ for entry points and task-oriented internal packages; when internal/ helps.

Point 2

Avoid circular imports and the utils dumping ground; document exported APIs.

Point 3

Lab 3: refactor the inventory command into a loader, domain model, formatter, and CLI; verify errors preserve causes.

Chapter 3 · Section 14 · Applied

Package boundaries

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

cmd/platformctl/main.go
internal/inventory/collect.go
internal/report/format.go
internal/config/load.go

Why it matters

Packages should follow tasks and ownership, not a generic utils bucket.

Chapter 3 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

Why wrap with %w?

It adds context while preserving the underlying error for Is/As.

Who should define a small interface?

Usually the consumer that needs the dependency boundary.

When use errors.Join?

When multiple independent errors must be reported together.

Lab 3

Refactor into packages

Complete this before starting the next chapter.

Step 1

Move loading, domain rules, and formatting into task-oriented packages.

Step 2

Inject the loader into the report operation through a small interface.

Step 3

Wrap errors with %w and assert errors.Is or errors.As.

Done when: Tests pass and the original error cause remains discoverable.
Chapter 04 · Go for Platform Engineers

Modules and developer tooling

← Contents
Chapter 4 · Section 15

Modules and dependencies

Concepts to understand and explain before the lab.

Point 1

go.mod, go.sum, semantic versions, go get, go mod tidy, and reproducible dependency review.

Point 2

Module path and major-version suffixes; use go work for local multi-module development only when needed.

Point 3

Go 1.24 tool directives and go tool for executable dependencies such as controller-gen; GOPRIVATE/GOPROXY for internal modules.

Point 4

Dependency risk: direct versus transitive dependencies, updates, licenses, and vulnerability checks.

Chapter 4 · Section 15 · Applied

Reproducible dependency review

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

go mod tidy
go list -m all
go mod graph
go get example.com/dependency@v1.2.3

Why it matters

Review why a dependency entered the graph before accepting a major update.

Chapter 4 · Section 16

Daily tooling

Concepts to understand and explain before the lab.

Point 1

gofmt, go vet, go test, go doc, gopls, and a linter such as Staticcheck or golangci-lint as feedback rather than ritual.

Point 2

Install govulncheck separately; it is not bundled with the Go toolchain.

Point 3

Read compiler and vet output; use go list and go env to troubleshoot the build environment.

Chapter 4 · Section 16 · Applied

A local quality gate

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

go fmt ./...
go vet ./...
go test ./...
govulncheck ./...

Why it matters

Install govulncheck separately; pin it as a tool dependency where reproducibility matters.

Chapter 4 · Section 17

Build behavior

Concepts to understand and explain before the lab.

Point 1

go build versus go install; GOOS/GOARCH, build tags, and CGO trade-offs. Use CGO_ENABLED=0 for a static build only when dependencies permit; verify the binary.

Point 2

Binary version information, reproducible build inputs, and why a container image should carry the binary's provenance.

Chapter 4 · Section 17 · Applied

Cross-build carefully

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o dist/platformctl ./cmd/platformctl
file dist/platformctl

Why it matters

A static build depends on your packages and linker choices; inspect the artifact instead of assuming.

Chapter 4 · Section 18

Dependency exercise

Concepts to understand and explain before the lab.

Point 1

Add a small dependency, update it, inspect the module graph, and remove it cleanly.

Point 2

Lab 4: add format/test/vet/vulnerability checks to a local build script; explain each failure before fixing it.

Chapter 4 · Section 18 · Applied

Tool directive

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

go get -tool sigs.k8s.io/controller-tools/cmd/controller-gen@<version>
go tool controller-gen --help

Why it matters

The Go 1.24 tool directive tracks an executable dependency in go.mod.

Chapter 4 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

Is govulncheck bundled with Go?

No; install and track it separately.

What does go mod tidy do?

Aligns module requirements and checksums with imported packages.

Does CGO_ENABLED=0 guarantee a static artifact?

Not unconditionally; dependencies and linker choices still require verification.

Lab 4

Create a local quality gate

Complete this before starting the next chapter.

Step 1

Track required tools with go.mod tool directives when supported.

Step 2

Run format, vet, tests, a linter, and govulncheck.

Step 3

Add a dependency, inspect the module graph, then remove it cleanly.

Done when: All checks run; an intentionally broken example fails the right gate.
Chapter 05 · Go for Platform Engineers

Files, processes, and configuration

← Contents
Chapter 5 · Section 19

Filesystem and streams

Concepts to understand and explain before the lab.

Point 1

os, io, bufio, and filepath; readers and writers; safe file permissions.

Point 2

Atomic output: write a temporary file, sync where appropriate, then rename; avoid partially written reports.

Point 3

Bound reads and close resources; treat file paths as untrusted input. Use Go 1.24 os.Root/os.OpenRoot for directory-confined access when accepting relative paths.

Chapter 5 · Section 19 · Applied

Atomic file write

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

f, err := os.CreateTemp(dir, "report-*")
// write, Sync, Close, then os.Rename to destination
// remove temp file on every error path

Why it matters

A report should be old or new, never half written. Consider filesystem sync requirements.

Chapter 5 · Section 20

Process execution

Concepts to understand and explain before the lab.

Point 1

os/exec with argument arrays, context cancellation, exit status, and bounded output.

Point 2

Why passing unsanitized input through a shell is dangerous; prefer APIs over shelling out when available.

Point 3

Distinguish a child-process timeout from an application error.

Chapter 5 · Section 20 · Applied

No shell interpolation

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

cmd := exec.CommandContext(ctx, "kubectl", "get", "pods", "-n", namespace)
out, err := cmd.CombinedOutput()

Why it matters

Argument arrays avoid shell interpretation. Bound output and report exit status.

Chapter 5 · Section 21

Configuration and secrets

Concepts to understand and explain before the lab.

Point 1

Precedence: flags, environment, config file, defaults; validate once at startup.

Point 2

Do not embed credentials or print secret values; use workload identity and SDK credential chains.

Point 3

Redact sensitive fields in logs, errors, and diagnostic output.

Chapter 5 · Section 21 · Applied

Explicit precedence

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

flags > environment > config file > defaults
validate(config) once at startup
log only redacted config

Why it matters

A config value's source matters when debugging behavior across environments.

Chapter 5 · Section 22

OS integration

Concepts to understand and explain before the lab.

Point 1

Handle SIGINT/SIGTERM with signal.NotifyContext; exit cleanly and flush output.

Point 2

Lab 5: implement config loading and atomic report output; test cancellation and invalid paths.

Chapter 5 · Section 22 · Applied

Graceful cancellation

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := run(ctx); err != nil { return err }

Why it matters

Propagate the canceled context into child work, not just the outer loop.

Chapter 5 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

Why write via a temporary file?

To avoid exposing a partially written destination.

How should exec receive arguments?

As a program and argument array, not interpolated shell text.

What does os.Root protect?

Directory-confined access, including paths that would escape through symlinks.

Lab 5

Handle configuration and files

Complete this before starting the next chapter.

Step 1

Implement flag > environment > file > default precedence.

Step 2

Validate values once; redact sensitive diagnostics.

Step 3

Write reports through a temporary file and rename on success; cancel a child process.

Done when: No partial destination file remains after simulated failure.
Chapter 06 · Go for Platform Engineers

Concurrency and context

← Contents
Chapter 6 · Section 23

Goroutines and channels

Concepts to understand and explain before the lab.

Point 1

Launch and join work; buffered versus unbuffered channels; close ownership and select.

Point 2

A goroutine is not free: prevent leaks, blocked sends, and unbounded fan-out.

Chapter 6 · Section 23 · Applied

Channel ownership

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

jobs := make(chan Job)
go func() { defer close(jobs); for _, j := range input { jobs <- j } }()
for j := range jobs { process(j) }

Why it matters

The sender owns closing. Add context-aware sends and receives in real workers.

Chapter 6 · Section 24

Shared state

Concepts to understand and explain before the lab.

Point 1

sync.Mutex, sync.RWMutex, sync.WaitGroup, Go 1.25 WaitGroup.Go, and when channels simplify ownership.

Point 2

Race conditions, data races, and how go test -race helps detect the latter.

Point 3

The Go memory model: happens-before relationships, synchronization, and why an apparently working concurrent program can still be incorrect.

Point 4

Avoid concurrent map writes and copying mutexes.

Chapter 6 · Section 24 · Applied

Happens-before

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

var mu sync.Mutex
mu.Lock(); count++; mu.Unlock()
// A mutex unlock happens before a later lock of that mutex.
go test -race ./...

Why it matters

A program that appears to work may still have a race; synchronization defines correctness.

Chapter 6 · Section 25

Context and lifecycle

Concepts to understand and explain before the lab.

Point 1

Pass context.Context as the first parameter; deadlines, cancellation, and request-scoped values.

Point 2

Never store a context in a struct for convenience; propagate it into AWS, Kubernetes, HTTP, and child-process calls.

Point 3

Distinguish cancellation from timeout for user-facing errors.

Chapter 6 · Section 25 · Applied

One context per operation

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

ctx, cancel := context.WithTimeout(parent, 5*time.Second)
defer cancel()
resp, err := client.Do(req.WithContext(ctx))

Why it matters

Pass context first and never store it inside a long-lived struct for convenience.

Chapter 6 · Section 26

Bounded work

Concepts to understand and explain before the lab.

Point 1

Worker pools, semaphores, errgroup.WithContext with SetLimit, golang.org/x/time/rate, backpressure, retry budgets, and jitter.

Point 2

Decide what can run in parallel without increasing API throttling or cost.

Chapter 6 · Section 26 · Applied

Bounded fan-out

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

g, ctx := errgroup.WithContext(ctx)
g.SetLimit(5)
for _, item := range items { item := item; g.Go(func() error { return fetch(ctx, item) }) }
return g.Wait()

Why it matters

Limit concurrency before API throttling or memory pressure becomes the limiter.

Chapter 6 · Section 27

Concurrency exercise

Concepts to understand and explain before the lab.

Point 1

Lab 6: query multiple fixture services concurrently with a fixed worker limit; prove cancellation stops all workers and -race stays clean.

Chapter 6 · Section 27 · Applied

Cancellation proof

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

start 20 fixture requests with limit 4
cancel after first result
assert active workers return to zero
go test -race ./...

Why it matters

A cancellation test should prove no worker stays blocked, not just that one error is returned.

Chapter 6 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

What does context cancel?

Operations that receive and observe the context; it does not forcibly stop arbitrary goroutines.

What does errgroup add to WaitGroup?

Error propagation and cancellation through a derived context.

What does the memory model describe?

Synchronization and happens-before relations between concurrent operations.

Lab 6

Collect concurrently

Complete this before starting the next chapter.

Step 1

Create 20 fixture requests with errgroup.WithContext and SetLimit(4).

Step 2

Cancel the context mid-run; ensure every worker returns.

Step 3

Run the race detector and a rate-limit test.

Done when: Maximum active workers is four; cancellation drains work; go test -race passes.
Chapter 07 · Go for Platform Engineers

HTTP and service integration

← Contents
Chapter 7 · Section 28

HTTP clients

Concepts to understand and explain before the lab.

Point 1

Reuse http.Client; set timeouts; create requests with context; close and bound response bodies.

Point 2

For HTTP/1 connection reuse, read a response to EOF when consuming it; if discarding it, use a bounded drain on Go 1.26 and earlier when reuse matters. Go 1.27 adds automatic bounded draining of unread bodies. Always close the body.

Point 3

Inspect status codes, headers, and content types before decoding; retry only safe/idempotent operations.

Point 4

TLS verification, proxy behavior, and why disabling certificate checks is not a fix.

Chapter 7 · Section 28 · Applied

HTTP client boundary

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
resp, err := client.Do(req)
if err != nil { return err }
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBytes))

Why it matters

Bound response size. Close every body; understand HTTP/1 reuse behavior for the Go version you ship.

Chapter 7 · Section 29

HTTP servers

Concepts to understand and explain before the lab.

Point 1

net/http handlers, Go 1.22 ServeMux method/wildcard patterns, middleware, request IDs, input limits, ReadHeaderTimeout, and graceful shutdown.

Point 2

Separate transport DTOs from domain logic; validate and return consistent error responses.

Chapter 7 · Section 29 · Applied

ServeMux patterns

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", health)
mux.HandleFunc("GET /services/{name}", showService)
server := &http.Server{Handler: mux, ReadHeaderTimeout: 5*time.Second}

Why it matters

Method and wildcard patterns require Go 1.22+; bound headers and bodies.

Chapter 7 · Section 30

API resilience

Concepts to understand and explain before the lab.

Point 1

Idempotency, pagination, conditional requests, exponential backoff with jitter, and rate-limit handling.

Point 2

Use explicit deadlines and per-call error context to make failures diagnosable.

Chapter 7 · Section 30 · Applied

Retry budget

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

if status == 429 || status >= 500 {
    wait := backoff(attempt) + jitter()
    if err := sleepContext(ctx, wait); err != nil { return err }
}

Why it matters

Retry only safe operations, honor Retry-After when present, and stop at a deadline.

Chapter 7 · Section 31

Authentication boundaries

Concepts to understand and explain before the lab.

Point 1

Explain bearer tokens, service identity, and why credentials should be supplied by the runtime.

Point 2

Avoid logging authorization headers; test redaction and error paths.

Chapter 7 · Section 31 · Applied

Credential boundary

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

token := os.Getenv("API_TOKEN")
req.Header.Set("Authorization", "Bearer "+token)
// Never log req.Header or token.

Why it matters

Prefer workload identity and short-lived tokens over static environment secrets in production.

Chapter 7 · Section 32

Integration exercise

Concepts to understand and explain before the lab.

Point 1

Lab 7: build a small HTTP health aggregator against local test servers; include timeout, malformed JSON, 429, and 5xx cases.

Chapter 7 · Section 32 · Applied

Adversarial local server

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusTooManyRequests)
}))

Why it matters

Test timeout, 429, 5xx, malformed JSON, and cancellation without calling a public API.

Chapter 7 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

Why reuse http.Client?

Its transport can reuse connections and is safe for concurrent use.

Why set ReadHeaderTimeout?

To bound time spent receiving request headers.

Is every retry safe?

No; consider idempotency, deadline, rate limits, and Retry-After.

Lab 7

Aggregate HTTP health

Complete this before starting the next chapter.

Step 1

Serve local healthy, slow, malformed, 429, and 5xx responses with httptest.

Step 2

Use one reusable client with request contexts, timeouts, bounded bodies, and status checks.

Step 3

Emit a report that separates unavailable from unhealthy.

Done when: All five response cases and cancellation have passing tests.
Chapter 08 · Go for Platform Engineers

Platform CLI engineering

← Contents
Chapter 8 · Section 33

Command design

Concepts to understand and explain before the lab.

Point 1

Start with flag; introduce Cobra for a real command tree, help generation, and shared flags.

Point 2

Commands should describe operations (inspect, report, validate), not expose internal package names.

Point 3

Make read-only the default; put any future write action behind an explicit command and dry-run option.

Chapter 8 · Section 33 · Applied

Command tree

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

platformctl services list --output=json
platformctl services inspect api --timeout=5s
platformctl version

Why it matters

Begin with stdlib flag; add Cobra when nested commands and help become real needs.

Chapter 8 · Section 34

CLI contract

Concepts to understand and explain before the lab.

Point 1

Human output versus stable JSON; stdout for data, stderr for diagnostics, useful exit codes.

Point 2

Flags for context, namespace, region, profile, timeout, and output format; validate conflicting flags.

Point 3

Avoid surprise prompts in automation; provide --help, examples, and a version command.

Chapter 8 · Section 34 · Applied

Streams and exit codes

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

stdout: report data only
stderr: diagnostics and warnings
0: success · 2: invalid usage · 3: partial collection · 4: upstream failure

Why it matters

Document exit codes so shell automation can act without parsing prose.

Chapter 8 · Section 35

Usability and safety

Concepts to understand and explain before the lab.

Point 1

Progress only on terminals; no color in redirected output; avoid leaking secrets in debug mode.

Point 2

Show the target account/cluster before any mutating action; require explicit scope in multi-account tools.

Chapter 8 · Section 35 · Applied

Safe target display

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

Target: account 111122223333 / region us-east-1
Mode: read-only
Command: inventory

Why it matters

An operator should see the exact target before any future write mode is introduced.

Chapter 8 · Section 36

CLI exercise

Concepts to understand and explain before the lab.

Point 1

Lab 8: turn platformctl into a command tree with services list, services inspect, and version; snapshot the JSON contract and exit codes.

Chapter 8 · Section 36 · Applied

JSON contract check

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

platformctl services list --output=json | jq -e '.services | type == "array"'
platformctl --help
platformctl version

Why it matters

A CLI is an interface: test its output and behavior, not just internal functions.

Chapter 8 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

What belongs on stdout?

Machine- or human-readable result data only.

Why keep exit codes stable?

Automation can respond without parsing prose.

What is the safe default for a platform CLI?

Read-only behavior with explicit target scope.

Lab 8

Finish the CLI contract

Complete this before starting the next chapter.

Step 1

Add services list, services inspect, and version commands.

Step 2

Support --output=json, --timeout, and clear help examples.

Step 3

Document stdout/stderr and exit-code behavior.

Done when: Help works; JSON schema and exit codes are checked in tests.
Chapter 09 · Go for Platform Engineers

Testing, debugging, and performance

← Contents
Chapter 9 · Section 37

Unit tests

Concepts to understand and explain before the lab.

Point 1

Table-driven tests, subtests, test helpers, golden files where output is intentionally stable.

Point 2

Test observable behavior and failure paths; avoid tests that merely mirror implementation.

Chapter 9 · Section 37 · Applied

Table-driven test

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

tests := []struct{ in string; want bool }{{"api", true}, {"", false}}
for _, tt := range tests { t.Run(tt.in, func(t *testing.T) {
    if got := valid(tt.in); got != tt.want { t.Fatalf("got %v", got) }
}) }

Why it matters

Test one behavior across normal and edge cases; name failures clearly.

Chapter 9 · Section 38

Test boundaries

Concepts to understand and explain before the lab.

Point 1

Inject clocks, HTTP transports, AWS/Kubernetes client interfaces, and filesystem access where it improves isolation.

Point 2

Use Go 1.24 t.Context() for test-scoped cancellation and Go 1.25 testing/synctest for deterministic time and concurrency tests without real sleeps.

Point 3

Use httptest for local HTTP integration; use fakes only for behavior they model accurately.

Chapter 9 · Section 38 · Applied

Time without sleeping

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

synctest.Test(t, func(t *testing.T) {
    ctx, cancel := context.WithTimeout(t.Context(), time.Second)
    defer cancel()
    <-ctx.Done() // virtual time advances
})

Why it matters

Go 1.25 synctest makes timing tests deterministic; avoid real sleeps in unit tests.

Chapter 9 · Section 39

Stronger verification

Concepts to understand and explain before the lab.

Point 1

Race detector, fuzz tests for parsers, coverage as a gap finder rather than a target.

Point 2

Benchmarks for actual bottlenecks with Go 1.24 b.Loop(); compare allocations and wall time before optimizing.

Chapter 9 · Section 39 · Applied

Fuzz a parser

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

func FuzzParseReport(f *testing.F) {
    f.Add([]byte(`{"services":[]}`))
    f.Fuzz(func(t *testing.T, data []byte) { _, _ = ParseReport(data) })
}

Why it matters

A fuzz target should also assert useful invariants, not merely avoid panics.

Chapter 9 · Section 40

Debugging and profiling

Concepts to understand and explain before the lab.

Point 1

Read stack traces; use go test -v, go tool pprof, runtime traces, and net/http/pprof only on protected endpoints.

Point 2

Diagnose memory growth, blocked goroutines, excessive allocations, and API fan-out.

Chapter 9 · Section 40 · Applied

Profile before tuning

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

go test -bench=. -benchmem ./internal/report
go test -cpuprofile=cpu.out ./internal/report
go tool pprof cpu.out

Why it matters

Record a baseline and explain the bottleneck before changing allocations or concurrency.

Chapter 9 · Section 41

Testing exercise

Concepts to understand and explain before the lab.

Point 1

Lab 9: add a failing fixture, a fuzz target for a report parser, a race regression test, and a benchmark; document the observed fix.

Chapter 9 · Section 41 · Applied

Regression evidence

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

1. Save the failing input.
2. Add a test that fails before the fix.
3. Fix the code.
4. Run unit, race, fuzz seed, benchmark.

Why it matters

A reported fix needs evidence that the original failure cannot recur.

Chapter 9 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

What should a regression test prove?

The original failure is reproduced before and prevented after the fix.

Why use synctest?

It virtualizes time for deterministic concurrency and timeout tests.

What is coverage for?

Finding untested behavior, not maximizing a number by itself.

Lab 9

Reproduce and fix a bug

Complete this before starting the next chapter.

Step 1

Save a failing parser input and write a regression test.

Step 2

Add a fuzz target with a useful invariant and run seed cases.

Step 3

Benchmark before and after the fix; profile only if a bottleneck appears.

Done when: Regression test, fuzz target, race run, and benchmark note are present.
Chapter 10 · Go for Platform Engineers

AWS automation with Go

← Contents
Chapter 10 · Section 42

SDK setup and identity

Concepts to understand and explain before the lab.

Point 1

Use config.LoadDefaultConfig, a named profile or workload role, and an explicit region.

Point 2

Understand the credential chain; do not hard-code keys or assume the active AWS account.

Point 3

Check caller identity and target scope before reporting or changing resources.

Chapter 10 · Section 42 · Applied

SDK configuration

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region))
if err != nil { return err }
stsClient := sts.NewFromConfig(cfg)

Why it matters

Resolve account identity before collecting data; never print the credential chain.

Chapter 10 · Section 43

Service clients and API calls

Concepts to understand and explain before the lab.

Point 1

Construct service clients from shared config; pass context to every operation.

Point 2

Understand typed inputs/outputs, pointer helpers, pagination, waiters, and API error types.

Point 3

Use bounded concurrency and account for AWS API throttling.

Chapter 10 · Section 43 · Applied

Paginators are mandatory

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

p := ecs.NewListServicesPaginator(client, &ecs.ListServicesInput{Cluster: &cluster})
for p.HasMorePages() {
    page, err := p.NextPage(ctx)
    if err != nil { return err }
    arns = append(arns, page.ServiceArns...)
}

Why it matters

One API response is often only the first page. Handle access denied and throttling separately.

Chapter 10 · Section 44

Practical inventory workflow

Concepts to understand and explain before the lab.

Point 1

Collect ECS services, ALBs, and CloudWatch alarms as a read-only example.

Point 2

Normalize identifiers, include region/account in every record, and distinguish missing permission from missing resource.

Point 3

Produce JSON and text reports with timestamps and partial-failure summaries.

Chapter 10 · Section 44 · Applied

Normalize inventory

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

type Record struct { Account, Region, ARN, Health string }
// Include account and region in every record.
// Keep collection errors separate from empty results.

Why it matters

A missing resource and a failed read are different findings.

Chapter 10 · Section 45

Reliability and cost

Concepts to understand and explain before the lab.

Point 1

SDK retry defaults versus application retries; avoid duplicate retries and non-idempotent writes.

Point 2

Set deadlines, handle pagination fully, and cap requests; state when an AWS API can incur cost.

Chapter 10 · Section 45 · Applied

Know the cost of a call

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

read-only ≠ free
API throttling ≠ retry immediately
partial data ≠ healthy empty environment

Why it matters

Some AWS APIs bill per request; declare cost and rate limits before a large scan.

Chapter 10 · Section 46

AWS lab

Concepts to understand and explain before the lab.

Point 1

Lab 10: add platformctl aws inventory against a sandbox or recorded SDK fixtures; verify account/region, pagination, access-denied handling, and no write API calls.

Chapter 10 · Section 46 · Applied

Fixture-first AWS lab

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

platformctl aws inventory --account 111122223333 --region us-east-1
# Run against recorded responses first, sandbox second.

Why it matters

Verify account and region from STS; test pagination and AccessDenied without writes.

Chapter 10 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

Why call STS first?

To verify the AWS account actually selected by the credential chain.

What happens if you ignore pagination?

The inventory silently misses resources.

Does read-only mean cost-free?

No; some AWS APIs charge per request.

Lab 10

Read-only AWS inventory

Complete this before starting the next chapter.

Step 1

Start with recorded SDK responses, then use a sandbox profile if available.

Step 2

Check STS account identity and explicit region; paginate ECS service results.

Step 3

Report partial failures and AccessDenied without attempting writes.

Done when: Account/region and pagination are correct; no write API call is made.
Chapter 11 · Go for Platform Engineers

Kubernetes API programming

← Contents
Chapter 11 · Section 47

Kubernetes API mental model

Concepts to understand and explain before the lab.

Point 1

Group/version/kind, namespaced versus cluster-scoped resources, metadata, resourceVersion, and optimistic concurrency.

Point 2

Desired state versus observed state; spec, status, and conditions.

Chapter 11 · Section 47 · Applied

Spec, status, generation

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

metadata.generation: desired-spec revision
status.observedGeneration: revision reconciled
metadata.resourceVersion: optimistic concurrency token

Why it matters

Do not confuse generation with resourceVersion; they answer different questions.

Chapter 11 · Section 48

Authentication and clients

Concepts to understand and explain before the lab.

Point 1

Local kubeconfig versus in-cluster ServiceAccount credentials; never embed a kubeconfig in the binary.

Point 2

Typed client-go clients, REST config, timeouts, user agent, and rate limits.

Point 3

RBAC: discover exactly which verbs and resources a tool needs.

Chapter 11 · Section 48 · Applied

Client configuration

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
// In a Pod, use rest.InClusterConfig().
// Scope permissions with RBAC, not a hidden CLI flag.

Why it matters

Local kubeconfig and in-cluster ServiceAccount credentials are different auth paths.

Chapter 11 · Section 49

Read and write patterns

Concepts to understand and explain before the lab.

Point 1

Get, list, create, patch, update, delete; label/field selectors and pagination.

Point 2

Handle NotFound, Conflict, Forbidden, and transient failures distinctly; use retry-on-conflict only around fresh reads.

Point 3

Server-side apply and field ownership at a conceptual level; avoid blind full-object updates.

Chapter 11 · Section 49 · Applied

Conflict-safe update

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

retry.RetryOnConflict(retry.DefaultRetry, func() error {
    current, err := client.Get(ctx, name, metav1.GetOptions{})
    if err != nil { return err }
    mutate(current)
    _, err = client.Update(ctx, current, metav1.UpdateOptions{})
    return err
})

Why it matters

Read a fresh object inside every retry; never re-send an old resourceVersion.

Chapter 11 · Section 50

Watches and discovery

Concepts to understand and explain before the lab.

Point 1

Watch events and resourceVersion expiration; why informers/cache are preferred for long-running controllers.

Point 2

Dynamic client and discovery for unknown resource types; use typed clients when schemas are known.

Chapter 11 · Section 50 · Applied

Watch recovery

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

watch from resourceVersion → receive events
if watch expires (410 Gone): list again, capture new resourceVersion
for controllers: use informer/cache instead of a raw watch

Why it matters

Watch streams are not a durable queue. Re-list when state may have been missed.

Chapter 11 · Section 51

Kubernetes lab

Concepts to understand and explain before the lab.

Point 1

Lab 11: add platformctl k8s workloads to list Deployments and Pods in a named local namespace; show readiness, owner, and actionable errors. Run the CLI in a kind Pod under a least-privilege ServiceAccount, or run it locally with a temporary kubeconfig built from a short-lived kubectl create token token. Use kubectl --as=system:serviceaccount:<namespace>:<name> only to verify RBAC when the caller has impersonation permission.

Chapter 11 · Section 51 · Applied

Prove ServiceAccount scope

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

kubectl create token platform-reader -n lab
# Build a temporary kubeconfig with token + cluster CA.
# Or run platformctl as a Pod using serviceAccountName: platform-reader.

Why it matters

A local process does not inherit a Pod's ServiceAccount. Impersonation needs explicit permission.

Chapter 11 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

How does a local CLI get a ServiceAccount identity?

It needs a temporary kubeconfig/token, or it must run as a Pod under that ServiceAccount.

When retry a conflict?

After reading a fresh object inside the retry loop.

What follows watch expiration?

List again to establish current state and a new resourceVersion.

Lab 11

Inspect Kubernetes workloads

Complete this before starting the next chapter.

Step 1

Create a platform-reader ServiceAccount and narrow Role in kind.

Step 2

Run platformctl as a Pod under that account or use a short-lived token in a temporary kubeconfig.

Step 3

List Pods and Deployments in one namespace; verify forbidden cross-namespace access.

Done when: Scoped inventory is correct and RBAC denies out-of-scope reads.
Chapter 12 · Go for Platform Engineers

Controllers and operators

← Contents
Chapter 12 · Section 52

Reconciliation model

Concepts to understand and explain before the lab.

Point 1

Level-triggered reconciliation: repeatedly make actual state converge on desired state.

Point 2

Idempotency, eventual consistency, at-least-once events, and why a controller must tolerate missing or stale objects.

Point 3

Compare a one-shot CLI action with a continuous controller.

Chapter 12 · Section 52 · Applied

Reconciliation is level-triggered

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

desired = read(PlatformEnvironment)
actual = read(Namespace, ResourceQuota)
if different: apply minimal change
update status; requeue only when needed

Why it matters

A missed event must not break convergence: the next reconcile can recover from current state.

Chapter 12 · Section 53

CRD and API design

Concepts to understand and explain before the lab.

Point 1

Define a cluster-scoped PlatformEnvironment that owns the Namespace it creates. Keep the spec small (namespace label set, quota, and optional config) and expose a status condition.

Point 2

Schema, validation, defaults, versioning, and compatibility; avoid exposing unstable internal fields.

Point 3

Explain why a cluster-scoped Namespace cannot have a namespaced owner. Document the operator's cluster-wide blast radius and refuse to adopt a pre-existing Namespace by accident.

Chapter 12 · Section 53 · Applied

Cluster-scoped owner

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

PlatformEnvironment (cluster-scoped)
└── Namespace (cluster-scoped dependent)
    └── ResourceQuota (namespaced dependent)

Why it matters

A cluster-scoped Namespace cannot have a namespaced owner; refuse to adopt a pre-existing Namespace.

Chapter 12 · Section 54

Kubebuilder and controller-runtime

Concepts to understand and explain before the lab.

Point 1

Scaffold API and controller; understand manager, cache, client, scheme, watches, predicates, and workqueue.

Point 2

Reconcile request, fetch, compare, create/update, status update, and requeue decision.

Point 3

Keep business logic separate from Kubernetes transport details.

Chapter 12 · Section 54 · Applied

Reconcile skeleton

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    var env platformv1.PlatformEnvironment
    if err := r.Get(ctx, req.NamespacedName, &env); err != nil {
        return ctrl.Result{}, client.IgnoreNotFound(err)
    }
    return r.converge(ctx, &env)
}

Why it matters

A controller-runtime manager supplies the cache, client, watches, and workqueue.

Chapter 12 · Section 55

Ownership and deletion

Concepts to understand and explain before the lab.

Point 1

Owner references from the Namespace and namespaced dependents to the cluster-scoped PlatformEnvironment; garbage collection in a full cluster. Use finalizers when external or non-owned cleanup must finish first.

Point 2

Deletion timestamp, idempotent cleanup, stuck finalizers, and how to recover safely.

Chapter 12 · Section 55 · Applied

Ownership and deletion

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

Create Namespace with ownerReference → PlatformEnvironment UID
Use finalizer only for external or non-owned cleanup
Test actual GC in kind, not envtest

Why it matters

Owner references are a deletion mechanism only when the owner/dependent scope is valid.

Chapter 12 · Section 56

Status and operations

Concepts to understand and explain before the lab.

Point 1

Conditions, observed generation, meaningful messages, and avoiding status update loops.

Point 2

Leader election, retries, rate limits, and avoiding hot reconciliation loops.

Chapter 12 · Section 56 · Applied

Status without loops

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

condition: Ready=False, Reason=Creating
observedGeneration: 3
condition: Ready=True, Reason=Available

Why it matters

Update status only when it changes; otherwise status writes can trigger hot loops.

Chapter 12 · Section 57

Controller tests

Concepts to understand and explain before the lab.

Point 1

Pure unit tests for decision logic; envtest for API-server behavior; kind tests for namespace-controller and garbage-collector behavior absent from envtest.

Point 2

envtest can validate ownership metadata but cannot complete Namespace deletion: the Namespace stays Terminating without built-in controllers. Run delete/GC assertions in kind.

Point 3

Test create, update, conflicts, invalid specs, missing RBAC, and restart convergence; test full deletion in kind.

Chapter 12 · Section 57 · Applied

Test boundary

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

unit: decide desired changes
envtest: API server, admission/defaulting, ownership metadata
kind: namespace controller, garbage collection, restart

Why it matters

envtest has no built-in controllers: Namespace deletion remains Terminating.

Chapter 12 · Section 58

Operator lab

Concepts to understand and explain before the lab.

Point 1

Lab 12: implement the cluster-scoped PlatformEnvironment in kind with a minimal ClusterRole; provision an owned Namespace and quota, update status, and verify deletion/garbage collection in kind. Use envtest for API and reconciliation checks, not Namespace deletion.

Chapter 12 · Section 58 · Applied

Local operator drill

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

create PlatformEnvironment → observe Namespace + quota
update labels/quota → observe convergence
delete CR → observe cleanup in kind

Why it matters

Use a dedicated kind cluster and a minimal ClusterRole; never point the lab at production.

Chapter 12 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

Why is PlatformEnvironment cluster-scoped?

It owns a Namespace, which is cluster-scoped.

What is the reconcile goal?

Make actual state converge to desired state idempotently.

Can envtest prove Namespace deletion?

No; use kind because envtest lacks namespace and garbage-collection controllers.

Lab 12

Build PlatformEnvironment

Complete this before starting the next chapter.

Step 1

Scaffold a cluster-scoped CRD and minimal ClusterRole in a dedicated kind cluster.

Step 2

Reconcile an owned Namespace and ResourceQuota; update status and observed generation.

Step 3

Test API logic with envtest; test create/update/delete and garbage collection in kind.

Done when: Reconciliation converges, restart recovers, and kind confirms deletion.
Chapter 13 · Go for Platform Engineers

Production readiness

← Contents
Chapter 13 · Section 59

Observability

Concepts to understand and explain before the lab.

Point 1

Structured logs with log/slog, request/reconcile IDs, useful metrics, and traces across API calls.

Point 2

Health/readiness endpoints, error classification, cardinality limits, and secret redaction.

Point 3

Use OpenTelemetry where traces clarify cross-service latency; avoid telemetry that cannot drive action.

Chapter 13 · Section 59 · Applied

Actionable telemetry

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

slog.InfoContext(ctx, "reconcile complete", "name", env.Name, "duration", elapsed)
metric: reconcile_errors_total{reason="conflict"}
trace: API read → apply → status

Why it matters

Avoid high-cardinality labels such as resource UID or error text.

Chapter 13 · Section 60

Resource and lifecycle safety

Concepts to understand and explain before the lab.

Point 1

Graceful shutdown, bounded queues, memory/CPU limits, pprof access controls, and SIGTERM behavior.

Point 2

GOMEMLIMIT as a memory-pressure control; Go 1.25 container-aware default GOMAXPROCS uses Linux cgroup CPU limits when not overridden.

Point 3

Timeouts and connection reuse; understand how limits and probes interact during rollouts.

Chapter 13 · Section 60 · Applied

Container limits

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

GOMEMLIMIT=700MiB
# Go 1.25+ default GOMAXPROCS considers cgroup CPU limits.
# Set explicit limits and measure throttling and GC pressure.

Why it matters

GOMEMLIMIT is guidance to the runtime, not a hard container-memory limit.

Chapter 13 · Section 61

Security

Concepts to understand and explain before the lab.

Point 1

Least-privilege RBAC/IAM, non-root container, pinned dependencies, vulnerability scanning, and signed releases.

Point 2

Threat model untrusted config, API responses, and user input; never execute input as shell syntax.

Chapter 13 · Section 61 · Applied

Least privilege

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

ClusterRole: get/list/watch/update PlatformEnvironment; status/finalizers as needed
Namespace: get/list/watch/create/update/delete
ResourceQuota: get/list/watch/create/update/delete

Why it matters

Scope each verb and resource; confirm generated RBAC against actual API calls.

Chapter 13 · Section 62

Build and release

Concepts to understand and explain before the lab.

Point 1

Multi-stage Docker build, small runtime image, architecture targets, version/commit metadata, SBOM, and provenance.

Point 2

CI checks: format, vet, unit/integration tests, race detector where supported, vulnerability scan, image build.

Chapter 13 · Section 62 · Applied

Release evidence

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

gofmt → vet → unit/integration → race → vuln scan
→ build Linux binary → image → SBOM/signature → deploy

Why it matters

A release should be traceable to source, dependencies, tests, and a unique artifact digest.

Chapter 13 · Section 63

Production lab

Concepts to understand and explain before the lab.

Point 1

Lab 13: containerize the operator, add probes and metrics, deploy into kind with narrow RBAC, then rehearse shutdown and a failed reconciliation.

Chapter 13 · Section 63 · Applied

Shutdown drill

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

send SIGTERM during reconciliation
expect no new work, bounded exit time, and accurate status after restart

Why it matters

A controller must recover from interruption because work may stop between any two API writes.

Chapter 13 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

Is GOMEMLIMIT a hard memory cap?

No; it guides runtime GC behavior.

What happens on SIGTERM?

Stop accepting work, let in-flight work finish within a deadline, and recover on restart.

What should a metric label avoid?

Unbounded values such as resource names, UIDs, or raw error messages.

Lab 13

Ship and interrupt the operator

Complete this before starting the next chapter.

Step 1

Build a small image and deploy with narrow RBAC, probes, and metrics.

Step 2

Send SIGTERM during reconciliation; restart the controller.

Step 3

Inspect logs, conditions, and resource ownership after recovery.

Done when: Bounded shutdown and eventual convergence are demonstrated.
Chapter 14 · Go for Platform Engineers

Capstone and review

← Contents
Chapter 14 · Section 64

Capstone architecture

Concepts to understand and explain before the lab.

Point 1

Deliver two connected artifacts: platformctl for read-only inventory and PlatformEnvironment for local self-service provisioning.

Point 2

Draw data flow, identity boundaries, API permissions, retry behavior, and failure modes before implementation.

Chapter 14 · Section 64 · Applied

Two artifacts, one architecture

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

platformctl: human-triggered, read-only, short-lived
PlatformEnvironment: continuous, scoped writes, long-lived

Why it matters

Draw identity and permission boundaries for both before implementation.

Chapter 14 · Section 65

Acceptance criteria

Concepts to understand and explain before the lab.

Point 1

A new learner can clone, build, test, and run both artifacts from documented commands.

Point 2

platformctl has stable JSON output, useful errors, cancellation, bounded concurrency, and no embedded credentials.

Point 3

The operator converges after create/update/restart, reports status, handles deletion, and runs under least-privilege RBAC.

Point 4

CI runs relevant checks; a release is traceable to a commit and dependency set.

Chapter 14 · Section 65 · Applied

Acceptance checklist

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

clone → build → test → run
inspect JSON + exit codes
create/update/delete CR in kind
review CI evidence and image digest

Why it matters

A new engineer should succeed from the repository guide alone.

Chapter 14 · Section 66

Final review

Concepts to understand and explain before the lab.

Point 1

Explain when Go is the right tool and when Bash, Python, Terraform, or an existing controller is simpler.

Point 2

Review the most common failure patterns: nil dereference, slice aliasing, ignored errors, leaking goroutines, unbounded retries, stale cache reads, broad IAM/RBAC, and non-idempotent reconciliation.

Point 3

Lab 14: demo both artifacts, run a failure drill, and answer design-review questions about safety and operability.

Chapter 14 · Section 66 · Applied

Choose a simpler tool when possible

A focused fragment or decision pattern. Try it, then change one condition.

Worked pattern

one-off file rename → shell
stateful infrastructure declaration → Terraform
Kubernetes desired-state loop → controller

Why it matters

The senior skill is choosing the smallest reliable mechanism and explaining its limits.

Chapter 14 · Self-check

Explain it without notes

Open each question only after you have answered it aloud.

What proves the CLI is usable?

A fresh clone can build, test, and run it with documented commands.

What proves the controller is safe?

It converges across create/update/restart/delete with narrow permissions and status.

When should you avoid Go?

When a simpler shell, Python, Terraform, or existing controller solves the task reliably.

Lab 14

Capstone demonstration

Complete this before starting the next chapter.

Step 1

From a clean clone, build and run platformctl against fixtures and kind.

Step 2

Create, update, and delete PlatformEnvironment; show tests and CI evidence.

Step 3

Explain identity boundaries, failure handling, and why Go was appropriate.

Done when: A new engineer can reproduce both artifacts from the runbook.
Back matter

Sources and version checks

Use the official source when a version-sensitive detail changes.

Back matter

Command reference

Commands used repeatedly in the labs.

Go

go version
go mod init example.com/platformctl
go fmt ./...
go vet ./...
go test ./...
go test -race ./...
go test -fuzz=FuzzParseReport ./internal/report

Kubernetes

kind create cluster --name go-platform
kubectl config current-context
kubectl create token platform-reader -n lab
kubectl get platformenvironments
kubectl get namespace,resourcequota -A
Back matter

Failure patterns

Start with evidence; do not guess from the last error line.

Go

Nil dereference · slice aliasing · ignored error · leaked goroutine · data race

AWS and HTTP

Wrong account/region · first page only · throttling loops · unbounded body · missing deadline

Kubernetes

Stale resourceVersion · broad RBAC · invalid owner scope · status loop · assuming envtest runs GC

Back matter

Glossary

Use these terms precisely in code reviews.

Go

Module: versioned collection of packages. Interface: behavior contract. Context: cancellation/deadline signal. Goroutine: concurrent execution unit.

Kubernetes

CRD: custom resource definition. Reconciliation: convergence toward desired state. Finalizer: deletion hold for cleanup. Condition: structured status signal.

Reliability

Idempotency: repeated operation has the same desired effect. Backpressure: limit incoming work. Observed generation: spec revision reflected in status.

1 / 1