Master data flows in Go: io.Reader/Writer compositors with Tee, Pipe, and MultiWriter, backpressure management in channel pipelines without goroutine leaks, Kafka integration with franz-go and sarama including batching and rebalancing, efficient batch inserts with pgx COPY and transaction chunking, plus a complete streaming embedding pipeline from files to chunks to vectors.
The »Kant & Kurve« bookstore has been running its API from Module 12 in production — so far on a single VM server. Traffic swings wildly (Christmas season!), and the team decides on Kubernetes. The first step is smaller than feared and more underestimated than expected: the container image.
Go has an unfair advantage here: the compiler produces static binaries. A Go service needs no runtime, no package manager, no shell inside the container — only the binary itself. While Node images quickly weigh 900 MB and more, a slim Go image on a scratch or distroless base is often under 10 MB. Small images mean faster pulls, faster rollouts, a smaller attack surface, and less registry traffic. That is not cosmetics — it is directly noticeable operations quality.
The mechanism for this is the multi-stage Dockerfile: one stage builds with the full Go toolchain, the second stage copies only the finished binary into a minimal runtime image. Whatever happened in the builder (source code, module cache, compiler) stays in the builder.
Multi-stage means: build tooling stays outside
A Docker image is a series of filesystem layers. Multi-stage builds exploit that: FROM golang:1.24-alpine AS build provides compiler and module cache, while FROM gcr.io/distroless/static-debian12:nonroot provides only a minimal runtime — including CA certificates, timezone data, and a non-root user, but no shell, no package manager, no apk. The finished binary travels between stages via COPY --from=build. Everything that was only needed for building never lands in the shipped image.
Here is the complete multi-stage Dockerfile as it might live in the project:
# ---------- Stage 1: Builder ----------
FROM golang:1.24-alpine AS build
WORKDIR /src
# go.mod and go.sum first: this layer stays identical across code-only commits,
# and the module cache from the BuildKit cache mount gets reused
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=v2.4.1" -o /out/bookstore-api ./cmd/bookstore-api
# ---------- Stage 2: Runtime ----------
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/bookstore-api /bookstore-api
USER nonroot
EXPOSE 8080
ENTRYPOINT ["/bookstore-api"]
Three details carry most of the effect: CGO_ENABLED=0 forces a static binary (more on that in a moment), -ldflags "-s -w" strips debug symbols and saves roughly 30 percent of binary size, and -X main.version=v2.4.1 injects the build number into a package variable — exactly the one our program prints at startup:
// cmd/bookstore-api/main.go — version stamp the builder injects
package main
import (
"fmt"
"runtime"
)
// These values are set by the Docker build via -ldflags "-X main.version=…"
var (
version = "dev"
buildTime = "unknown"
)
func main() {
fmt.Println("bookstore-api", version, "build", buildTime, runtime.GOOS+"/"+runtime.GOARCH, "runtime", runtime.Version())
}
// → bookstore-api v2.4.1 build 2026-11-07T09:15:02Z linux/amd64 runtime go1.24.2
When an incident has several pods running different versions mid-rollout, exactly this startup log answers in one second which pod runs which binary.
Distroless images keep promises you should verify. A self-check inside the container — as a go run helper or as a CI test that starts the finished image:
// cmd/selfcheck/main.go — verifies that the runtime image keeps its promises
package main
import (
"fmt"
"os"
"os/user"
)
func main() {
u, err := user.Current()
if err != nil {
fmt.Println("Error:", err)
return
}
_, sslErr := os.Stat("/etc/ssl/certs/ca-certificates.crt")
fmt.Printf("uid=%s group=%s ssl-certs=%v", u.Uid, u.Gid, sslErr == nil)
}
// Terminal: docker run --rm bookstore-api:v2.4.1 /bookstore-api (or inside the pod)
// → uid=65532 group=65532 ssl-certs=true
uid=65532 is the nonroot user of the distroless images — so the process demonstrably runs without root privileges, and ssl-certs=true confirms that HTTPS calls to external APIs (payments, fulfillment) work. The size comparison at the end of the build:
docker image ls bookstore-api
REPOSITORY TAG SIZE
bookstore-api v2.4.1 4.9 MB
bookstore-api fat 913 MB (old single-stage build on the golang:1.24 base)
4.9 MB instead of 913 MB — a factor of more than 180, with direct impact on rollout speed and attack surface. You can additionally audit the image with docker sbom (a software bill of materials) and a scanner like trivy for known CVEs; in CI it is also worth a look at the ko project (github.com/ko-build/ko), which builds Go images straight from the module hash and thereby makes them reproducible.
⚠ Common mistake: The binary is copied, the path is correct, yet startup still fails with a cryptic message like
no such file or directory— even though the file demonstrably exists. The cause is almost always a dynamically linked binary: withoutCGO_ENABLED=0, the Go compiler links against the C library of the builder image, and thescratchor distroless runtime simply lacks the dynamic loader. The kernel's error message refers to the loader, not to the binary — hence the confusion. If you are certain you do not needcgo(pure Go, nosqliteor C-based packages), always build withCGO_ENABLED=0; alternatives are static-linking flags or analpineruntime withmusl.
Check: The pod will not start: 'exec format error' or 'no such file or directory' for a binary that demonstrably exists in the image. What is the most common cause?
Answer: The binary was dynamically linked against glibc and the dynamic loader is missing in the minimal image
The confusion arises because the kernel reports the missing dynamic loader, not the visible binary file. A build without CGO_ENABLED=0 on a glibc-based image produces a dynamically linked binary; in a scratch or distroless image there is no loader and no C library. The fix: set CGO_ENABLED=0 during go build — then the Go linker produces a fully static binary.
Takeaways:
CGO_ENABLED=0 forces static binaries — the prerequisite for scratch and distroless runtimes under 10 MB.-ldflags "-s -w -X main.version=…" shrinks the binary and injects version information that pays off immediately during incidents.»Kant & Kurve« now runs on Kubernetes — and suddenly the environment changes with every deployment: different database hosts, different log levels in staging, different shard counts during the Christmas rush. Configuration baked in at build time (a config file inside the image) forces a separate image per environment. That is exactly what the 12-factor principle Config forbids: configuration lives in the environment, not in the artifact — one image, many environments.
For Kubernetes this is not a recommendation but the platform's native language: ConfigMaps and Secrets arrive in the pod as environment variables or files. The architecture course puts the model in context — Module 3: Architectural Styles treats 12-factor explicitly as an architectural style with consequences reaching all the way into the deployment pipeline. Here is the Go side of it.
Defaults in code, values in the env, secrets never in the image
Three rules suffice: 1) Neutral defaults (port, log level, timeouts) belong in the code so the service starts locally without ceremony. 2) Environment-specific values (DSNs, hostnames, shard counts) come from the env — os.LookupEnv instead of os.Getenv, because LookupEnv distinguishes "not set" from "empty". 3) Secrets get no default and no fallback: if the database password is missing, the service exits cleanly with a clear error message instead of silently running with an empty one.
No framework needed — the standard library is entirely sufficient to start. If you want more (prefixes, parsing, declarative defaults), reach for github.com/caarlos0/env/v11 or Viper from Module 12 (github.com/spf13/viper); both solve the same problem, but os.LookupEnv shows the mechanism without magic:
// internal/config/config.go — 12-factor: configuration from the environment
package config
import (
"fmt"
"os"
"strconv"
)
type Config struct {
HTTPAddr string
LogLevel string
Shards int
DatabaseDSN string
}
func FromEnv() (Config, error) {
cfg := Config{
HTTPAddr: getEnv("BOOKSTORE_HTTP_ADDR", ":8080"),
LogLevel: getEnv("BOOKSTORE_LOG_LEVEL", "info"),
// Secrets: no default, no guessing
DatabaseDSN: os.Getenv("BOOKSTORE_DB_DSN"),
}
shards, err := getEnvInt("BOOKSTORE_SHARDS", 8)
if err != nil {
return Config{}, err
}
cfg.Shards = shards
if cfg.DatabaseDSN == "" {
return Config{}, fmt.Errorf("BOOKSTORE_DB_DSN is missing — config comes from the env, not from the image")
}
return cfg, nil
}
func getEnv(key, fallback string) string {
if v, ok := os.LookupEnv(key); ok && v != "" {
return v
}
return fallback
}
func getEnvInt(key string, fallback int) (int, error) {
v, ok := os.LookupEnv(key)
if !ok || v == "" {
return fallback, nil
}
n, err := strconv.Atoi(v)
if err != nil {
return 0, fmt.Errorf("%s=%q is not an integer: %w", key, v, err)
}
return n, nil
}
// Example: BOOKSTORE_SHARDS=16 BOOKSTORE_DB_DSN=postgres://prod... ./bookstore-api
// → cfg: addr=:8080 log_level=info shards=16 db=postgres://prod… (source: env)
Kubernetes asks two fundamental questions of every pod, and they deserve different answers: Is the process alive? (liveness) and Can it accept traffic? (readiness). A Go service that drains gracefully on SIGTERM (Module 15) needs exactly two routes for this — plus the discipline to check different things on each:
// internal/health/health.go — keep liveness and readiness cleanly separated
package health
import (
"context"
"encoding/json"
"net/http"
"sync"
"time"
"golang.org/x/sync/errgroup"
)
type Checker func(ctx context.Context) error
// Liveness: is the process itself alive? Deliberately NO dependency checks.
func Liveness(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}
// Readiness: can we accept traffic? Check dependencies, with a timeout.
func Readiness(checks map[string]Checker) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
var mu sync.Mutex
results := make(map[string]string, len(checks))
g, gctx := errgroup.WithContext(ctx)
for name, check := range checks {
g.Go(func() error {
err := check(gctx)
mu.Lock()
defer mu.Unlock()
if err != nil {
results[name] = err.Error()
return nil // collect, don't abort: we want the full picture
}
results[name] = "ok"
return nil
})
}
_ = g.Wait()
status := http.StatusOK
for _, v := range results {
if v != "ok" {
status = http.StatusServiceUnavailable
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(results)
}
}
// Terminal: curl -s localhost:8080/readyz (search backend currently down)
// → {"database":"ok","payments":"ok","search":"dial tcp 10.2.7.44:9200: connect: connection refused"}
Add the matching probes in the Deployment: a livenessProbe on /healthz (be generous: failureThreshold: 5) and a readinessProbe on /readyz (be strict: on 503 the service endpoint removes the pod from load balancing without restarting it). All of this becomes observable through the cluster's Events — exactly what we learn to read ourselves with client-go in the next lesson.
⚠ Common mistake: Packing database pings and other dependency checks into the liveness probe — after all, you want to know whether "everything is fine". When the database hiccups briefly, all pods report
unhealthysimultaneously, and the kubelet restarts all pods — a restart storm that additionally hammers the database with every boot and amplifies the outage instead of absorbing it. Liveness only means "the process is not permanently stuck" (deadlocks, GC collapse); readiness means "keep me out of load balancing until I can serve again". Dependency checks belong exclusively in/readyz.
Check: The shared database of the bookstore API is overloaded for two minutes. What should happen to the pods during that time if the probes are built correctly?
Answer: The pods keep running and are removed from the service endpoints until /readyz returns 200 again
This distinction is the most common and most expensive health-endpoint mistake: liveness restarts are an emergency measure for stuck processes, not a load-balancing tool. During database trouble, restarting all pods would make the outage worse (thundering herd as they come back up). Readiness merely pulls pods out of traffic and gently returns them afterward. That is exactly why dependency checks never belong in a liveness probe.
Takeaways:
os.LookupEnv distinguishes "not set" from "empty" — the more honest foundation than os.Getenv; declarative alternatives are github.com/caarlos0/env/v11 or Viper./healthz) checks only the process itself; readiness (/readyz) checks dependencies with a timeout — confusing the two causes restart storms.The ops team at »Kant & Kurve« types the same three kubectl commands every morning: list pods, review last night's events, scale the workers. That is the moment client-go pays off: the same API that kubectl uses is available as a Go library — k8s.io/client-go, the official Kubernetes Go client package, maintained inside the Kubernetes project itself. Everything kubectl can do, your Go program can do too: read, write, watch, scale.
The key to the code is the architecture of the Kubernetes API: it is a typed REST service. client-go maps it to Go types from k8s.io/api/core/v1 (pods, events, services) and k8s.io/apimachinery (options, labels). A clientset (k8s.io/client-go/kubernetes) bundles the typed clients for all core objects; for custom resources like CRDs, a generic client enters the picture later in Lesson 84.
Two paths to cluster config — and one decides on its own
A program running inside the pod authenticates via the pod's ServiceAccount: rest.InClusterConfig() reads the token and CA from /var/run/secrets/kubernetes.io/serviceaccount/. The same program on your laptop instead uses the KUBECONFIG file. The established trick is the order: try InClusterConfig first, then fall back to the local kubeconfig — one binary that runs everywhere. As for permissions: the ServiceAccount needs an RBAC role binding with exactly the verbs (get, list, watch) the program uses — nothing more.
The first automation program lists all bookstore pods in a namespace and decides on its own where the cluster config comes from:
// cmd/kube-report/main.go — list pods: in-cluster first, kubeconfig as fallback
package main
import (
"context"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
func newClientset() (*kubernetes.Clientset, error) {
if cfg, err := rest.InClusterConfig(); err == nil {
return kubernetes.NewForConfig(cfg) // in-pod: ServiceAccount
}
loading := clientcmd.NewDefaultClientConfigLoadingRules()
cfg, err := clientcmd.
NewNonInteractiveDeferredLoadingClientConfig(loading, &clientcmd.ConfigOverrides{}).
ClientConfig()
if err != nil {
return nil, err
}
return kubernetes.NewForConfig(cfg) // locally: ~/.kube/config
}
func main() {
cs, err := newClientset()
if err != nil {
fmt.Println("no cluster reachable:", err)
return
}
ctx := context.Background()
pods, err := cs.CoreV1().Pods("production").
List(ctx, metav1.ListOptions{LabelSelector: "app.kubernetes.io/name=bookstore"})
if err != nil {
fmt.Println("List error:", err)
return
}
for _, p := range pods.Items {
fmt.Printf("%-45s %s", p.Name, p.Status.Phase)
}
}
// → bookstore-api-7d9c5b6f4-kvj2m Running
// → bookstore-api-7d9c5b6f4-q8x7p Running
// → bookstore-worker-59df7d8bc-2nll4 Running
The morning event review is the second classic. Instead of calling List every thirty seconds (which burdens the API server and still misses events between two queries), open a Watch: an HTTP connection on which the API server streams changes as they happen:
// cmd/kube-events/main.go — read events as a stream
package main
import (
"context"
"fmt"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func watchEvents(ctx context.Context, cs *kubernetes.Clientset) error {
watcher, err := cs.CoreV1().Events("production").Watch(ctx, metav1.ListOptions{})
if err != nil {
return err
}
defer watcher.Stop()
for event := range watcher.ResultChan() {
e, ok := event.Object.(*corev1.Event)
if !ok {
continue // ignore watch status messages
}
fmt.Printf("%-7s %-14s %s", string(event.Type), e.Reason, e.InvolvedObject.Name)
}
return nil
}
// → ADDED Scheduled bookstore-api-7d9c5b6f4-kvj2m
// → ADDED Pulling bookstore-api-7d9c5b6f4-kvj2m
// → ADDED Unhealthy bookstore-api-7d9c5b6f4-kvj2m
// → MODIFIED BackOff bookstore-worker-59df7d8bc-2nll4
The raw watch has two weaknesses you must know about: the connection breaks regularly (timeouts, network maintenance), and after a break your application has to reconnect and catch up on the missed events using the resourceVersion. For production code, informers are therefore the right abstraction (k8s.io/client-go/informers): a SharedInformerFactory maintains a local cache of the object type you want, reconnects and re-syncs the watch automatically, and calls your callbacks (AddFunc, UpdateFunc, DeleteFunc). Multiple controllers in the same process share one factory and therefore one connection — hence shared. If you only query occasionally, stick with the plain clientset; if you react continuously, use informers. Scaling is also a one-liner: cs.AppsV1().Deployments("production").Update(...) with an adjusted Spec.Replicas — the same operation kubectl scale performs. The conceptual placement of automation and scaling as a platform concern is covered by the architecture course in Module 7: Scalability.
⚠ Common mistake: A
forloop withtime.Sleep(2 * time.Second)and aListcall in every iteration — "watch is just a convenience, right?" This polling loop scales catastrophically: every iteration serializes and transfers the complete object list from the API server, and with ten such programs the cluster starts choking on its own control-plane traffic. It gets worse when the loop also builds a new clientset — or even a new HTTP connection — per iteration. For continuous observation, use watch or shared informers with a local cache — and build the clientset exactly once at program start.
Check: Why are shared informers the recommended way to react continuously to pod changes — instead of a raw watch call in a loop?
Answer: Informers maintain a local cache, reconnect automatically after a break, and share one connection across multiple controllers
A raw watch delivers a stream but breaks regularly — and then the application must catch up via the resourceVersion and reconnect itself, otherwise events go missing unnoticed. Shared informers encapsulate exactly that responsibility: a local cache for reads without API-server round trips, automatic reconnect with sync, and the shared factory ensures controllers in the same process do not each open their own connection. Security has nothing to do with it — RBAC applies to both paths equally.
Takeaways:
k8s.io/client-go is the official, typed Go binding to the Kubernetes API — the same one kubectl uses.rest.InClusterConfig() with a kubeconfig fallback yields one binary that runs in the pod and on the laptop.k8s.io/client-go/informers) are the standard: cache, reconnect, shared connections, callbacks.The team wants one Kubernetes resource per bookstore branch that bundles everything needed: Deployment, Service, Ingress with the branch hostname, HPA bounds. Copying YAML templates is fragile; Helm charts help with the first deployment but not with operations (the resource drifts, nobody reconciles). Kubernetes' answer to recurring operational logic is the operator: a Custom Resource Definition (CRD) plus a controller process that continuously reconciles the desired state (spec) with the observed state (status).
This has been built for years on sigs.k8s.io/controller-runtime, scaffolded with kubebuilder (currently the kubebuilder v4 plugin, or the go/v4 skeleton). The tool generates the CRD YAML, RBAC manifests, the manager scaffolding, and a reconcile function — the actual domain logic remains your job.
Level-triggered, not edge-triggered
The reconcile loop is not called "once per event" but as often as it takes for the state to converge — and afterwards additionally periodically or after a RequeueAfter. This is called level-triggered: the function looks at the current state ("how many replicas are deployed?"), not at an event ("replicas was changed to…"). From this follows the most important rule for operator code: Reconcile must be idempotent and decide from actual and desired state. Anyone counting events or relying on "only the first time" flags loses as soon as the loop runs again after a timeout — and it will run again, guaranteed.
Our Website operator: the CR describes branch, image, and replica count; the reconciler ensures the associated deployment exists and writes status and conditions back into the CR:
// internal/controller/website_controller.go — the heart of the operator
package controller
import (
"context"
"fmt"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
bookstorev1 "github.com/kant-kurve/bookstore-operator/api/v1"
)
// +kubebuilder:rbac:groups=bookstore.kant-kurve.de,resources=websites,verbs=get;list;watch;update
// +kubebuilder:rbac:groups=bookstore.kant-kurve.de,resources=websites/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
func (r *WebsiteReconciler) Reconcile(ctx context.Context, req reconcile.Request) (ctrl.Result, error) {
// 1) Read the desired state — NotFound is normal (deleted CR), not an error
var site bookstorev1.Website
if err := r.Get(ctx, req.NamespacedName, &site); err != nil {
if errors.IsNotFound(err) {
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
// 2) Compute desired state and reconcile actual state (CreateOrUpdate = idempotent)
want := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{Namespace: site.Namespace, Name: site.Name + "-dep"},
}
if _, err := controllerutil.CreateOrUpdate(ctx, r.Client, want, func() error {
want.Spec.Replicas = ptr.To(site.Spec.Replicas)
want.Spec.Selector = selectorFor(&site)
want.Spec.Template = podTemplateFor(&site)
return controllerutil.SetControllerReference(&site, want, r.Scheme)
}); err != nil {
return ctrl.Result{}, fmt.Errorf("synchronizing deployment: %w", err)
}
// 3) Write the observed state back into the CR
site.Status.ReadyReplicas = want.Status.ReadyReplicas
if err := r.Status().Update(ctx, &site); err != nil {
return ctrl.Result{}, err // conflict? The next loop resolves it — level-triggered
}
// 4) Follow up periodically, even without events
return ctrl.Result{RequeueAfter: resyncInterval(site)}, nil
}
// Terminal: kubectl get websites -n production
// → NAME REPLICAS READY IMAGE HOSTNAME
// → kant-kurve-de 3 3/3 ghcr.io/kant-kurve/bookstore-api:v2.4.1 kant-kurve.de
The +kubebuilder:rbac comments are not decoration: kubebuilder generates the operator's RBAC manifests from them — permissions as code, right next to the logic that needs them.
The second building block is the frame: ctrl.NewManager wires together the cache (the same informer machinery from Lesson 83!), leader election for multiple instances, and the controller server. After scaffolding, surprisingly little of it remains your own code:
// cmd/main.go — start the manager and register the controller
package main
import (
"os"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"github.com/kant-kurve/bookstore-operator/internal/controller"
)
var setupLog = ctrl.Log.WithName("setup")
func main() {
ctrl.SetLogger(zap.New(zap.UseDevMode(false)))
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
if err := (&controller.WebsiteReconciler{
Client: mgr.GetClient(), // reads go through the cache
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "controller registration")
os.Exit(1)
}
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "manager exited with error")
os.Exit(1)
}
}
// → starting manager: website-controller registered, cache synced, leader election active
You can test all of this without special cluster knowledge using envtest (sigs.k8s.io/controller-runtime/pkg/envtest): it starts kube-apiserver and etcd as binaries and runs real reconcile passes against your own CRD — controller tests that actually verify Kubernetes semantics. The strategic context — when an operator is worth it and what automation across layers means — belongs to the scalability decisions the architecture course covers in Module 7: Scalability.
⚠ Common mistake: Reconcile code that assumes it is called "exactly once per change" — for example an
if site.Status.Phase == ""init block that sets configuration only on the first pass, or errors swallowed without returning, so no requeue happens and state silently drifts. controller-runtime may call Reconcile again at any time: after a timeout, after a cache resync, after losing the leader-election race, after a status-update conflict. Only idempotent logic that derives everything from spec and observed state each time (and follows up periodically withRequeueAfter) survives this contract; everything else works in the demo and fails in production.
Check: Your reconciler must ensure periodic follow-up — say, verifying external DNS entries for which Kubernetes delivers no events. What is the correct mechanism?
Answer: Return ctrl.Result with RequeueAfter — the manager calls Reconcile again after that duration
time.Sleep blocks one of the controller's worker slots and breaks on cancellation — an anti-pattern. The intended way is the declarative RequeueAfter in the ctrl.Result: the manager schedules the next call itself while the current pass ends cleanly. For state outside the cluster, for which there are no Kubernetes events, exactly this periodic follow-up is an operator's standard mechanism — level-triggered instead of edge-triggered.
Takeaways:
sigs.k8s.io/controller-runtime, scaffolded with kubebuilder.controllerutil.CreateOrUpdate and SetControllerReference make the reconciliation idempotent and wire up garbage collection for child objects.+kubebuilder:rbac markers generate the RBAC manifests right next to the logic that needs the permissions.RequeueAfter instead of time.Sleep: periodic follow-up for state outside the cluster; test with envtest against real apiserver/etcd binaries.The operator from Lesson 84 is only one of three big extension patterns Kubernetes offers — and choosing between them is an architecture decision, not a Go detail. The rules of thumb:
Choose extension patterns by reach
The three patterns differ in their reach: a sidecar acts per pod and is instantly reversible (remove the container from the pod manifest); a webhook acts cluster-wide on every request in its match scope — powerful and risky at once, because a failure blocks API access itself; a CRD creates a new, versionable domain object with its own lifecycle. Rule of thumb: pod-local concerns (logs, TLS, protocol translation) → sidecar; organization-wide rules (limits, prohibitions, defaults) → webhook; new domain objects with operational logic ("a branch", "a database cluster") → CRD with operator.
The platform team wants every new deployment to automatically get resource requests and a revisionHistoryLimit — retroactive fixes are tedious. A mutating webhook with controller-runtime (sigs.k8s.io/controller-runtime/pkg/webhook/admission) intercepts CREATE requests and writes the patches into the response:
// internal/webhook/deployment_mutator.go — inject defaults on CREATE
package webhook
import (
"context"
"encoding/json"
"net/http"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)
// +kubebuilder:webhook:path=/mutate-apps-v1-deployment,mutating=true,failurePolicy=Fail,groups=apps,resources=deployments,verbs=create,versions=v1,name=mdeployment.kb.io
type DeploymentMutator struct {
decoder *admission.Decoder
}
func (m *DeploymentMutator) Handle(_ context.Context, req admission.Request) admission.Response {
dep := appsv1.Deployment{}
if err := m.decoder.Decode(req, &dep); err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
if dep.Spec.RevisionHistoryLimit == nil {
dep.Spec.RevisionHistoryLimit = ptr.To(int32(3)) // cap the rollout history
}
marshaled, err := json.Marshal(dep)
if err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
return admission.PatchResponseFromRaw(req.Object.Raw, marshaled)
}
// Terminal: kubectl apply -f api-deployment.yaml (submitted without limits)
// → deployment.apps/bookstore-api created (webhook mdeployment.kb.io added revisionHistoryLimit=3)
Validating webhooks look identical, except they answer with admission.Denied(...) instead of a patch response — for instance when spec.hostname is missing on a Website. And the operational note that goes with it: webhooks are served over the manager's webhook server on TLS port 9443 and registered via configuration objects; the certificates are usually provisioned by cert-manager.
A sidecar is of course a Go program too. The classic setup: the application writes structured logs to a file on a shared emptyDir volume, the sidecar reads and forwards them — the application stays completely untouched:
// cmd/log-shipper/main.go — sidecar: read from the shared volume and forward
package main
import (
"bufio"
"fmt"
"os"
"time"
)
func main() {
file, err := os.Open("/var/log/bookstore/access.log")
if err != nil {
fmt.Println("open:", err)
os.Exit(1)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
// shortcut: no tailing past EOF — production uses fluent-bit or github.com/hpcloud/tail
fmt.Printf("shipper %s %s", time.Now().UTC().Format(time.RFC3339), scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Println("scan:", err)
os.Exit(1)
}
}
// → shipper 2026-11-07T10:02:11Z GET /api/v1/books/978-3-423-2089-8 200 3ms
In the pod manifest the shipper lives as a second containers: entry with volumeMounts on the same emptyDir; and since Kubernetes 1.29 there are native sidecars (initContainers with restartPolicy: Always) that start before the main container and terminate with it — exactly what log and mesh sidecars previously had to achieve through lifecycle hacks. If you do not want to operate your own Go binary, use fluent-bit for logs or Envoy for meshes — the pattern stays the same, and it is worth having built it once in Go yourself.
That closes Module 17. The five lessons formed a chain: slim image (81) → configured and observable (82) → automated reading (83) → automated steering (84) → extended (85). With that, »Kant & Kurve« is a genuinely cloud-native application — from the binary to its own platform resource.
⚠ Common mistake: An admission webhook with
failurePolicy: Failand an overly broad rule match — for example, all resources in all namespaces — whose endpoint then goes down. Consequences: the API server rejects every request in the match scope; depending on the match, that includes the very objects you would use to repair the webhook (the webhook's own deployments, its configuration, evenkubectl deleteon the webhook object itself). Operational advice therefore: keep webhook scopes narrow, exempt the webhook itself and system namespaces, set timeouts low, and considerfailurePolicy: Ignorefor transition phases until the webhook has proven stable.
Check: The platform team wants to enforce that from now on EVERY newly submitted resource automatically receives security contexts and defaults — regardless of which team submits it. Which extension pattern fits?
Answer: A mutating admission webhook that intercepts CREATE/UPDATE requests centrally and patches them before they are persisted
The requirement is a cluster-wide policy enforced at submission time — exactly the purpose of admission control. Sidecars act only inside their own pod and after startup; nightly scan loops and operator patches act after the fact (and allow drift between submission and correction). The mutating webhook sits as a final step before persistence in the API request path and thereby guarantees: whatever is stored complies with the policy.
Takeaways:
admission.PatchResponseFromRaw), validating ones reject (admission.Denied) — both via sigs.k8s.io/controller-runtime/pkg/webhook/admission.Course navigation: ← Module 16 · All 20 modules · Module 18 →