← News & analysis

GUIDE · GO KUBERNETES · 32 MIN READ

Writing a Kubernetes controller in Go: level-triggered reconcile, idempotency, status and tests without a cluster

Go Kubernetes controllers with controller-runtime: level-triggered reconcile, CreateOrUpdate, owner references, finalizers, conditions and fake-client tests.

Edition: · Practical guide. Added to the archive on the publication date above. Sources and worked examples below.

An original turquoise rodent engineer watches a copper arm make a built model match its blueprint beside a looping conveyor of blank cards.
Conceptual illustration for Writing a Kubernetes controller in Go: level-triggered reconcile, idempotency, status and tests without a cluster AI-generated conceptual illustration.

What this edition tested

A Kubernetes controller has an unusual contract. It is never told what happened. It is handed the name of an object, reads what the cluster looks like now, and changes things until the two agree. Most controller bugs come from code that quietly assumes otherwise: it trusts the event that woke it, expects a write it just made to be visible to its next read, or writes on every pass because the API server fills in a default that the controller keeps erasing.

This is the 23 November 2026 edition, researched and first published on 3 December 2026. It builds a controller for a small custom kind, Website, which owns a Deployment and a Service and keeps a DNS record in a system outside the cluster. The lab uses sigs.k8s.io/controller-runtime v0.25.3, the latest version on the Go module proxy as of 3 December 2026 (published 15 November). Its go.mod requires the v0.37 line of k8s.io/api, k8s.io/apimachinery and k8s.io/client-go, and the lab pins all three at v0.37.3. client-go's install notes map a v0.x.y tag to Kubernetes v1.x.y, and 1.37.3, released on 25 November, is the newest patch of the newest minor listed on kubernetes.io's releases page. Everything was tested with Go 1.27.3 on darwin/arm64 under gofmt, go vet and go test -race -count=3. Go 1.27.4, released on 10 November 2026 with security fixes, is the current patch release according to go.dev, so build production binaries with it.

The tests run against controller-runtime's fake client, with no cluster, no Docker and no envtest binaries. They show that the first reconcile creates children with controller owner references, that a second reconcile writes nothing even after the API server's defaults are simulated, that manual drift is repaired from a request that carries no event, that the Ready condition and observedGeneration follow a rollout and a spec edit, that a finalizer removes the external record before the object goes, and that status and child conflicts recover. Six deliberate mutations of the lab, such as removing the finalizer before the external cleanup, each make a test fail.

The request names an object, never an event

controller-runtime calls your Reconcile with a reconcile.Request, and the package documentation is blunt about what it holds: a name and a namespace, and no information about any specific event or about the object's contents. The same documentation states the consequence. Reconciliation is level-based: it is driven by the actual cluster state read from the API server or a local cache, not by individual events. A reconcile that follows a Pod deletion is not told that a Pod was deleted; it notices that the Pod is missing.

This is not a framework quirk. The Kubernetes API conventions describe the whole system as level-based rather than edge-based: if a value changes from 2 to 5 and then to 3, the system is not required to touch base at 5, which keeps it robust when intermediate changes are missed. The community guide to writing controllers lists "level driven, not edge driven" among its rules. A controller may be off for an indeterminate time, and even an API watch does not let you count on having seen a value turn from false to true, only that you now observe true. The workqueue adds a practical reason: an object added several times before a worker picks it up is processed once, so ten events can become one reconcile.

The controller-runtime FAQ therefore answers the question of how to run different logic for create, update and delete events with "You should not." A reconcile reads all the state it needs and writes what is missing or wrong. That is the whole shape of the lab's Reconcile:

go
// Reconcile makes the cluster match one Website's spec. The request holds
// only a namespace and a name, never the event that caused it, so every
// call reads the current state and does the whole job.
func (r *WebsiteReconciler) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) {
	var site Website
	if err := r.Client.Get(ctx, req.NamespacedName, &site); err != nil {
		// NotFound means the Website is gone and its finalizer has run;
		// the garbage collector deletes the children it owned.
		return reconcile.Result{}, client.IgnoreNotFound(err)
	}

	if !site.DeletionTimestamp.IsZero() {
		return reconcile.Result{}, r.finalize(ctx, &site)
	}

	if err := validate(site.Spec); err != nil {
		// Retrying cannot repair a spec; editing it starts a new reconcile.
		if serr := r.setStatus(ctx, &site, 0, notReady("InvalidSpec", err.Error())); serr != nil {
			return reconcile.Result{}, serr
		}
		return reconcile.Result{}, reconcile.TerminalError(err)
	}

	if controllerutil.AddFinalizer(&site, FinalizerName) {
		if err := r.Client.Update(ctx, &site); err != nil {
			return reconcile.Result{}, err
		}
	}

	if err := r.DNS.Upsert(ctx, site.Spec.Host, owner(&site)); err != nil {
		return reconcile.Result{}, r.fail(ctx, &site, "DNSRecordFailed", err)
	}

	deploy, err := r.reconcileDeployment(ctx, &site)
	if err != nil {
		return reconcile.Result{}, r.childError(ctx, &site, err)
	}
	if err := r.reconcileService(ctx, &site); err != nil {
		return reconcile.Result{}, r.childError(ctx, &site, err)
	}

	if err := r.setStatus(ctx, &site, deploy.Status.ReadyReplicas, rolloutCondition(deploy)); err != nil {
		return reconcile.Result{}, err
	}
	return reconcile.Result{RequeueAfter: DNSRecheck}, nil
}

Every step is safe to repeat. The finalizer is added only when absent, the DNS upsert is idempotent, CreateOrUpdate writes only differences, and status is written only when it changed. TestReconcileRepairsDrift checks the level-triggered property directly. After a first reconcile, the test scales the Deployment to five replicas by hand, swaps its image for a debug tag, adds an annotation and deletes the Service. It then sends the same request as before, which says nothing about any of this. One reconcile restores two replicas and the spec image, recreates the Service with its owner reference, and leaves the annotation alone, because the controller does not own that field.

A custom kind without code generation

Kubebuilder normally scaffolds a new kind and generates code for it; its object generator writes the runtime.Object implementation that, in the Kubebuilder book's words, all types representing kinds must implement. Neither the scaffold nor the generators are required. For one small kind, the generated parts are short enough to write and to read: a struct embedding metav1.TypeMeta and metav1.ObjectMeta with Spec and Status, a list type, a function that registers both with a scheme, and deep-copy methods. When controller-runtime complains that no kind is registered for a type, the FAQ's diagnosis is an incomplete scheme; the lab's scheme adds client-go's built-in types and its own.

go
// AddToScheme registers the Website types with s. This is the part of
// generated code that a scheme actually needs: Go type to group, version
// and kind.
func AddToScheme(s *runtime.Scheme) error {
	s.AddKnownTypes(GroupVersion, &Website{}, &WebsiteList{})
	metav1.AddToGroupVersion(s, GroupVersion)
	return nil
}

// DeepCopyInto copies w into out without sharing maps or slices. Caches
// hand out shared objects, so every runtime.Object needs a real deep copy.
func (w *Website) DeepCopyInto(out *Website) {
	*out = *w
	w.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
	out.Spec = w.Spec // value types only
	w.Status.DeepCopyInto(&out.Status)
}

Deep copies are not ceremony. Informer caches are shared, and the controller guide's rule is "Never mutate original objects!": mutating a shallow copy that shares a map such as Annotations changes the cached object for every other reader. TestDeepCopySharesNothing changes the labels, finalizers and conditions of a copy and checks that the original did not move.

The cost of writing these by hand is drift. Add a slice to the spec and the one-line spec copy silently becomes shallow; rename a JSON field and the CRD schema no longer matches the type. Two tests stand in for the generator. TestSpecHoldsOnlyValues fails if WebsiteSpec gains a pointer, slice, map or struct field. TestCRDMatchesGoTypes decodes the manifest with sigs.k8s.io/yaml's UnmarshalStrict into the real apiextensions.k8s.io/v1 types, so a misspelt field fails, then compares group, version, kind and the spec and status property names with the Go structs' JSON tags.

The most important part of the manifest is the status subresource:

yaml
versions:
  - name: v1alpha1
    served: true
    storage: true
    subresources:
      status: {}
    additionalPrinterColumns:
      - name: Ready
        type: string
        jsonPath: .status.conditions[?(@.type=="Ready")].status
      - name: Reason
        type: string
        jsonPath: .status.conditions[?(@.type=="Ready")].reason
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            required: [image, host]
            properties:
              image:
                type: string
                minLength: 1
              replicas:
                type: integer
                format: int32
                minimum: 0
                default: 1
              host:
                type: string
                minLength: 1

The CustomResourceDefinition documentation lists what subresources.status changes. PUT requests to /status ignore changes to anything except the status stanza. PUT, POST and PATCH requests to the resource itself ignore changes to status. And .metadata.generation is incremented for all changes except those to .metadata or .status, which is what makes observedGeneration meaningful later. The API conventions add that spec and status can then have distinct authorization scopes: users edit the spec, the controller writes the status. Once you have several kinds or versions, switch to the generators; these tests are a bridge, not a replacement.

A four-panel infographic headed read state, create or update, report status and finalize summarises the reconcile loop.
AI-generated conceptual illustration.

Create or update only the fields you own

Children get deterministic names: the Deployment and the Service are both named after their Website. The FAQ recommends exactly this, because the API server then refuses a second object with the same name, and the API conventions require every API to answer a POST for an existing name with 409. A reconcile that creates children with generateName can create a new one on every pass that runs before its cache has seen the last.

controllerutil.CreateOrUpdate wraps the read-modify-write around such a name. It gets the object. If it is not found, it runs your mutate function and creates the object. Otherwise it runs the mutate function on the live copy, compares the result with equality.Semantic.DeepEqual, and calls Update only if something changed. It returns created, updated or unchanged. Its documentation carries two warnings that decide whether a controller is idempotent in a real cluster. If the mutate function resets a value that has a default, CreateOrUpdate will always perform an update, because the object fetched from the API server holds the defaulted value; the example given is a Deployment's replicas. And it assumes that nothing except name and namespace was set on the object before the call.

The lab's mutate function therefore sets only the fields the controller owns, and edits everything in place:

go
// reconcileDeployment creates the Deployment or brings it back to the spec.
// The mutate function sets only the fields this controller owns. Values the
// API server defaulted, and labels or annotations other actors added, stay
// as they were, so an unchanged Website causes no write.
func (r *WebsiteReconciler) reconcileDeployment(ctx context.Context, site *Website) (*appsv1.Deployment, error) {
	d := &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: site.Name, Namespace: site.Namespace}}
	op, err := controllerutil.CreateOrUpdate(ctx, r.Client, d, func() error {
		labels := selectorLabels(site)
		d.Labels = withLabels(d.Labels, labels)
		if d.Spec.Selector == nil { // immutable once created
			d.Spec.Selector = &metav1.LabelSelector{MatchLabels: labels}
		}
		d.Spec.Replicas = new(site.Spec.Replicas)
		d.Spec.Template.Labels = withLabels(d.Spec.Template.Labels, labels)
		c := container(&d.Spec.Template.Spec, containerName)
		c.Image = site.Spec.Image
		c.Ports = []corev1.ContainerPort{{Name: "http", ContainerPort: containerPort, Protocol: corev1.ProtocolTCP}}
		return controllerutil.SetControllerReference(site, d, r.Scheme)
	})
	if err != nil {
		return nil, fmt.Errorf("deployment %s: %w", d.Name, err)
	}
	logChange(ctx, "Deployment", op)
	return d, nil
}

Labels are merged, not replaced. The selector is set only while it is nil, because the Deployment documentation says .spec.selector is immutable after creation in apps/v1. The web container is found by name and only its image and ports are set, so values the API server defaulted on that container survive. new(site.Spec.Replicas) is the Go 1.26 form of new that takes an expression. The Service follows the same rule and never touches spec.clusterIP, the address the cluster assigns to the Service.

The fake client applies no defaults, so a test that only runs against it passes even with a careless mutate function. The lab's applyServerDefaults helper stores the children the way an API server returns them: the Deployment defaults its documentation lists (10 old ReplicaSets kept, a 600-second progress deadline, 25% surge and unavailability), container and pod defaults, and an allocated cluster IP. With those in place, TestSecondReconcileWritesNothing compares the resourceVersions of the Website, the Deployment and the Service around a reconcile an hour later, and none changed. TestNaiveMutateUpdatesEveryTime shows the alternative: a mutate function that assigns a fresh one-element container list reported updated on every pass. Patching the controller itself that way made the idempotency test fail, with the Deployment's resourceVersion moving from 5 to 6; a second negative control that rebuilt ServiceSpec from scratch failed the same test by rewriting the Service.

controller-runtime's client in v0.25 also has an Apply method for server-side apply. The lab stays with CreateOrUpdate, whose behaviour is easy to follow and to test with the fake client.

Owner references hand cleanup to the garbage collector

controllerutil.SetControllerReference adds an owner reference carrying the owner's API version, kind, name and UID with controller and blockOwnerDeletion set to true. Because only one owner reference may be the controller, it returns an error if another one already is. TestFirstReconcileCreatesOwnedChildren asserts the exact reference on both children: lab.gopherforge.app/v1alpha1, kind Website, name shop, UID uid-shop, both flags true, and no other owners.

The reference does two jobs. It tells the garbage collector what to delete: by default Kubernetes uses background cascading deletion, in which the API server deletes the owner immediately and the garbage collector removes the dependents afterwards. And it routes events. Owns(&appsv1.Deployment{}) enqueues the Website named in a Deployment's controller reference whenever that Deployment changes, which is how a rollout's progress reaches the Website without polling.

The Kubernetes documentation adds two constraints. Cross-namespace owner references are disallowed by design. A namespaced owner must exist in the dependent's namespace; otherwise the reference is treated as absent, the dependent is subject to deletion once all owners are verified absent, and the garbage collector reports an OwnerRefInvalidNamespace event. Cluster-scoped dependents can only have cluster-scoped owners. controller-runtime checks both rules before it sets the reference. Second, blockOwnerDeletion is guarded. With the OwnerReferencesPermissionEnforcement admission plugin, only a client with update permission on the owner's finalizers subresource may set it. The plugin is not in Kubernetes 1.37's default-enabled list, but an administrator can turn it on with --enable-admission-plugins, so grant the controller update on websites/finalizers.

Refusing to adopt matters as much as adopting. TestForeignOwnerIsNotAdopted starts with a Deployment named shop that a Storefront already controls. The reconcile fails with deployment shop: Object shop/shop is already owned by another Storefront controller shop. The Deployment's resourceVersion is unchanged, because the mutate function's error stops CreateOrUpdate before it writes, and the Website's Ready condition reports NameInUse. Someone has to rename one of the two objects; meanwhile the controller retries with backoff.

Neither the fake client nor envtest runs a garbage collector. In the lab's deletion test the Deployment still exists after its Website is gone, owned by a UID that no longer exists. Kubebuilder's envtest page gives the matching advice: test ownership, not deletion. To see the built-in version of the pattern, open the DevOps terminal, create a Deployment, change its image and run kubectl rollout status, then kubectl get rs -o yaml. Each ReplicaSet carries an owner reference to its Deployment with controller: true and blockOwnerDeletion: true. The simulated cluster is a teaching model, not Kubernetes, but the shapes are the ones your controller writes.

Finalizers guard what lives outside the cluster

Owner references only reach objects inside the cluster. The Website's DNS record lives at a provider, so deleting the Website has to wait until the record is gone. The Kubernetes documentation describes the sequence a finalizer creates. When you delete an object that has finalizers, the API sets metadata.deletionTimestamp, returns 202 Accepted, and the object stays in a terminating state while controllers do their work and remove their finalizers; when the list is empty, the object is deleted. During that time finalizers can be removed but not added, and the deletion timestamp cannot change. Custom finalizer names must be publicly qualified, like example.com/finalizer-name, and the documentation says the API server rejects writes that use unqualified custom names. The lab's is lab.gopherforge.app/dns-record.

go
// finalize runs while the Website is terminating. It deletes the DNS
// record and then removes the finalizer; when the last finalizer is gone,
// the API server deletes the object. A failed cleanup keeps the finalizer
// and returns the error, so the object cannot disappear first.
func (r *WebsiteReconciler) finalize(ctx context.Context, site *Website) error {
	if !controllerutil.ContainsFinalizer(site, FinalizerName) {
		return nil
	}
	if err := r.DNS.Delete(ctx, site.Spec.Host, owner(site)); err != nil {
		return fmt.Errorf("delete DNS record %s: %w", site.Spec.Host, err)
	}
	controllerutil.RemoveFinalizer(site, FinalizerName)
	return r.Client.Update(ctx, site)
}

Order is everything: the external delete comes first, and the finalizer goes only after it succeeded. TestFailedCleanupKeepsTheFinalizer makes the fake provider fail with a 503. The reconcile returns the error, so the workqueue retries with backoff, and the Website stays, terminating, with both its finalizer and its record. Once the provider recovers, the next reconcile deletes the record and the Website disappears. In a negative-control copy that removed the finalizer before calling the provider, the same test failed because the Website was already gone while its record remained, which is the leak the finalizer exists to prevent.

Three smaller rules follow from the reconcile being repeatable. The finalizer is added before the record is created, so no record exists without a guard. The provider's delete must succeed when the record is already gone, because a crash between the external delete and the Update that removes the finalizer means the next reconcile deletes again. And a request queued before the deletion can still arrive after it: TestFinalizerRemovesExternalRecordBeforeDeletion sends one more reconcile once the Website is gone, gets a zero result and no error, and counts exactly one provider delete. If an object hangs in a terminating state, the finalizer documentation advises against removing finalizers by hand; find out which controller is not finishing its work.

A copper clasp keeps a departing cabinet in place until the mascot removes a distant signpost tied to it by a cable.
A finalizer keeps the Website in place until its DNS record outside the cluster is gone; only then is the finalizer removed and the object deleted. AI-generated conceptual illustration.

Status reports what the controller observed

The API conventions separate spec, the desired state, from status, the most recent observations of actual state. They prefer conditions to the older phase field, whose pattern they call deprecated. Conditions are a list treated as a map keyed by type. Types are PascalCase, with short names such as Ready preferred; status is True, False or Unknown; reason is a required one-word CamelCase category meant for concise output; message is the human-readable detail; lastTransitionTime records when the status last changed; and each condition's observedGeneration names the .metadata.generation it was based on. metav1.Condition carries exactly those fields.

meta.SetStatusCondition maintains the list. A new condition type is appended. For an existing one, reason, message and observed generation are updated, and lastTransitionTime changes only when status changes, to the time you passed or, if that is zero, to time.Now. It returns whether anything changed. The lab always passes the time from an injected clock, so tests can assert exact transitions.

observedGeneration lets a client tell "not ready yet" from "not looked at yet". Generation does not move for metadata or status updates, so a Website with metadata.generation 2 and status.observedGeneration 1 shows a status that describes an older spec. The controller guide asks controllers to set it to metadata.generation whenever the two differ. The lab sets it on the status and on the condition.

The Ready condition is derived from the Deployment with the same checks, in the same order, that kubectl rollout status makes:

go
// rolloutCondition turns the Deployment's status into the Website's Ready
// condition, making the same checks in the same order as kubectl rollout
// status.
func rolloutCondition(d *appsv1.Deployment) metav1.Condition {
	want := int32(1)
	if d.Spec.Replicas != nil {
		want = *d.Spec.Replicas
	}
	st := d.Status
	switch {
	case d.Generation > st.ObservedGeneration:
		return notReady("RolloutPending", "the Deployment controller has not observed the latest spec")
	case progressDeadlineExceeded(st):
		return notReady("ProgressDeadlineExceeded", "the rollout exceeded its progress deadline")
	case st.UpdatedReplicas < want:
		return notReady("RolloutInProgress", fmt.Sprintf("%d of %d replicas updated", st.UpdatedReplicas, want))
	case st.Replicas > st.UpdatedReplicas:
		return notReady("RolloutInProgress", fmt.Sprintf("%d old replicas pending termination", st.Replicas-st.UpdatedReplicas))
	case st.AvailableReplicas < st.UpdatedReplicas:
		return notReady("RolloutInProgress", fmt.Sprintf("%d of %d updated replicas available", st.AvailableReplicas, st.UpdatedReplicas))
	}
	return metav1.Condition{
		Type:    ConditionReady,
		Status:  metav1.ConditionTrue,
		Reason:  "Available",
		Message: fmt.Sprintf("%d of %d replicas available", st.AvailableReplicas, want),
	}
}

TestStatusFollowsRolloutAndGeneration walks a Website through a rollout and a spec edit, advancing the clock one minute per step. Its log reads: at t0, Ready=False RolloutPending; at t0+1m, Ready=False RolloutInProgress: 1 of 2 updated replicas available, with the transition time still t0 because the status did not change; at t0+2m, Ready=True Available; after an image edit raises the Website's generation to 2, at t0+3m, Ready=False RolloutPending with observed generation 2; at t0+4m, True again.

That test depends on generations the fake client does not maintain; its package documentation warns that Generation and ResourceVersion do not behave properly. The test's bumpGenerations interceptor sets a Deployment's generation to 1 on create and increments it when an update changes the spec. Without it, the same test logged Ready=True Available for generation 2 immediately after the image change, a false positive. If your status logic compares generations, simulate them explicitly or test that logic against envtest.

Error, RequeueAfter or nothing

What Reconcile returns decides when it runs again, and the reconcile package documents three outcomes. A non-nil error means the result is ignored and the request is requeued with exponential backoff, unless the error is a reconcile.TerminalError, which is logged and counted but never retried. A nil error with RequeueAfter above zero requeues the request after that duration. A nil error and a zero result end the matter until the next event. Result.Requeue still exists but is deprecated in favour of RequeueAfter, and in v0.25.3's source the controller logs a warning when a reconcile returns both an error and a requeue, because the error wins.

The backoff belongs to the workqueue. In controller-runtime v0.25 the priority queue is enabled by default, and with it the default rate limiter is a per-request exponential backoff from 5 ms to a cap of 1,000 seconds. TestPerItemBackoff pins the sequence:

go
rl := workqueue.NewTypedItemExponentialFailureRateLimiter[reconcile.Request](5*time.Millisecond, 1000*time.Second)
shop := request("shop")

var got []time.Duration
for range 5 {
	got = append(got, rl.When(shop))
}
want := []time.Duration{5 * time.Millisecond, 10 * time.Millisecond, 20 * time.Millisecond, 40 * time.Millisecond, 80 * time.Millisecond}
if fmt.Sprint(got) != fmt.Sprint(want) {
	t.Fatalf("delays = %v, want %v", got, want)
}

The same test shows that another request starts again at 5 ms, that the cap is reached on the 19th consecutive failure, and that Forget, which the controller calls after a successful reconcile, resets the request to 5 ms. With the priority queue switched off, the default becomes client-go's DefaultTypedControllerRateLimiter, which adds a token bucket of 10 per second with a burst of 100 shared by all requests. Inside a synctest bubble, where the clock stands still, 100 distinct failing requests each waited 5 ms and the 101st waited 100 ms.

Concurrency is bounded too. MaxConcurrentReconciles defaults to 1, and the client-go workqueue guarantees that no two workers process the same item at the same time, so raising it parallelizes across Websites, never within one.

The lab uses each outcome deliberately:

  • Transient failures are returned as errors: a conflict on a child, or the DNS provider failing an upsert. TestDNSFailureIsReportedAndRetried checks that the provider failure is also recorded as Ready=False with reason DNSRecordFailed before the error is returned.
  • A spec that retrying cannot repair returns reconcile.TerminalError, after the Ready condition says InvalidSpec and why. TestInvalidSpecIsATerminalError detects it with errors.Is(err, reconcile.TerminalError(nil)) and checks that nothing was created. Editing the spec produces a new event anyway. In a cluster the CRD's minLength would reject an empty image at admission, so keep such checks for rules a schema cannot express.
  • A healthy Website returns RequeueAfter: 10 * time.Minute, because the DNS provider cannot be watched and drift there is found only by looking again.

What the lab never does is poll the Deployment: its status changes arrive through the Owns watch. RequeueAfter is for state outside the API server. Every external call a reconcile makes can be repeated after a crash or a timeout, so the guidance in retries and idempotency keys about bounded retries and unknown outcomes applies to your provider client as well.

The cache is behind your own writes

Inside a manager, mgr.GetClient() is not a plain API client. By default, according to the cluster package, it uses the cache for reads and direct calls for writes. The cache is fed by watches, so for a short time after your own Create or Update a read can return the old object, or nothing at all. GetAPIReader returns a reader that goes to the API server directly, and its documentation asks that it be used sparingly.

The FAQ's advice is to write the controller on the assumption that information will eventually be correct but may be slightly out of date, and to make each reconcile enforce the entire state of the world. In practice that means four habits:

  • Use deterministic child names, so a create based on a stale read fails with AlreadyExists instead of producing a duplicate.
  • Do not read back what you just wrote. Create and Update update the object you pass with the content the server returned, so the lab computes status from the Deployment that CreateOrUpdate handed back rather than from a fresh Get.
  • Do not act on an object's absence before the cache is filled. controller-runtime starts the workers only after the event sources have synced, waiting at most CacheSyncTimeout, two minutes by default.
  • When a write conflicts, do not retry against the same cache.

The last habit is the easiest to miss. TestConflictRetryReadsTheAPIServer freezes the Website in a lagging cache, lets another writer label it, and then gives the controller a status change to write. When the retry re-read from the cache, it got the same stale resourceVersion every time: five status writes, four backoff sleeps of 10 to 11 ms of virtual time, and a final 409 Conflict. When it re-read through the API reader, the second write succeeded. A real cache usually catches up within milliseconds, but nothing guarantees that it does so inside a retry budget.

Conflicts: retry the write or the whole reconcile

Every Kubernetes object has a resourceVersion, and the API conventions build optimistic concurrency on it: when a record is about to be updated, its version is checked against the one the client sent, and a mismatch fails with a 409 StatusConflict. Clients must treat the value as opaque and pass it back unmodified. The API concepts page is explicit about who does the work: Kubernetes always detects the conflict, but you as the client author need to implement retries.

A controller has two good answers. The first is to return the conflict. The request goes back on the queue, with a 5 ms backoff after a first failure, and the next reconcile starts from fresh state. TestChildConflictIsReturnedAndTheNextReconcileConverges has another actor annotate the Deployment between the controller's read and its write. The reconcile fails with deployment shop: Operation cannot be fulfilled on deployments.apps "shop": object was modified, the fake client's wording of a 409, and the Website's observedGeneration stays at 1 because nothing finished. The next reconcile applies the new image and keeps the other actor's annotation. This is the right default for anything that recomputes from scratch.

The second answer is retry.RetryOnConflict from client-go, for a single write where repeating the whole reconcile would be wasteful. Its function must fetch the object again, apply the change and return the update's error unwrapped, so that the retry recognizes the conflict. retry.DefaultRetry allows five attempts, 10 ms apart, with a factor of 1.0 and 10% jitter. RetryOnConflict takes no context and waits with time.Sleep, so keep its budget small. The lab uses it for status:

go
// setStatus records what this reconcile observed: the generation it acted
// on, the ready replicas and the Ready condition. It writes nothing when the
// status is already right. On a conflict it re-reads the Website from the
// API server and applies the same observation to the fresh copy. The
// observed generation stays the one this reconcile acted on, even if the
// fresh copy is newer: a newer spec gets its own reconcile.
func (r *WebsiteReconciler) setStatus(ctx context.Context, site *Website, ready int32, cond metav1.Condition) error {
	observed := site.Generation
	cond.ObservedGeneration = observed
	cond.LastTransitionTime = metav1.NewTime(r.now()) // kept only if Status changes
	key := client.ObjectKeyFromObject(site)
	attempt := 0
	return retry.RetryOnConflict(r.statusBackoff(), func() error {
		attempt++
		if attempt > 1 {
			if err := r.APIReader.Get(ctx, key, site); err != nil {
				return err
			}
		}
		before := site.Status.DeepCopy()
		site.Status.ObservedGeneration = observed
		site.Status.ReadyReplicas = ready
		meta.SetStatusCondition(&site.Status.Conditions, cond)
		if equality.Semantic.DeepEqual(before, &site.Status) {
			return nil
		}
		return r.Client.Status().Update(ctx, site)
	})
}

One detail is easy to get wrong. On a retry, the fresh copy may carry a newer generation. In TestStatusConflictKeepsTheObservedGeneration, a user scales the Website between the reconcile's read and its status write. The status still describes generation 1, because that is the spec the reconcile acted on, so it is written to the fresh copy with observedGeneration 1; the update event for generation 2 brings another reconcile, which records 2. A negative-control copy that took the generation from the fresh copy wrote 2 for a status computed from generation 1, which is exactly the misreport observedGeneration exists to prevent.

If last-writer-wins is acceptable for fields only your controller writes, a patch can avoid the check altogether: client.MergeFrom builds a JSON merge patch, and client.MergeFromWithOptimisticLock is the option to use when you want the patch applied only to the latest resource version.

Unit tests with the fake client

controller-runtime is candid about its fake client. The FAQ recommends envtest instead, because in the maintainers' experience tests using fake clients gradually re-implement poorly-written impressions of a real API server. The package documentation lists the limitations: partial subresource support that can surprise a test updating metadata and status in one reconcile, no OpenAPI validation, and Generation and ResourceVersion that do not behave properly. It also says the client cannot inject specific errors, although the builder has WithInterceptorFuncs, which every conflict test in the lab uses.

Used with those limits in mind, it is fast and adequate for reconcile logic. Reading the v0.25.3 source shows what it does: it stores objects through your scheme, increments the resourceVersion on every write and rejects an update with a stale one as a 409 Conflict. With WithStatusSubresource, Update leaves status alone and Status().Update changes only status. Deleting an object with finalizers sets its deletion timestamp and removes it once the finalizers are cleared. What it does not do is set uid, generation or creationTimestamp, apply defaults, validate schemas or run any controller.

The lab makes each missing behaviour explicit instead of pretending it exists. Fixtures carry a UID and generation 1. editSpec increments the Website's generation as the API server would. rollOut plays the Deployment controller by writing a Deployment status. applyServerDefaults stores defaulted fields, and bumpGenerations maintains Deployment generations. Each helper's comment names the part of the API server it imitates, so a reader can see where the fake ends.

go
// newEnv builds the fake client the way the tests need it: the Website has a
// status subresource, so Update ignores status and Status().Update ignores
// everything else, as on a real API server.
func newEnv(t *testing.T, funcs *interceptor.Funcs, objs ...client.Object) *env {
	t.Helper()
	b := fake.NewClientBuilder().
		WithScheme(newScheme(t)).
		WithStatusSubresource(&reconciler.Website{}).
		WithObjects(objs...)
	if funcs != nil {
		b = b.WithInterceptorFuncs(*funcs)
	}
	c := b.Build()
	e := &env{t: t, c: c, dns: &fakeDNS{}, now: t0, key: types.NamespacedName{Namespace: "shop", Name: "shop"}}
	e.r = &reconciler.WebsiteReconciler{
		Client:    c,
		APIReader: c, // in a manager: mgr.GetAPIReader()
		Scheme:    c.Scheme(),
		DNS:       e.dns,
		Now:       func() time.Time { return e.now },
	}
	return e
}

Conflicts come from an interceptor that performs a competing write through the underlying client and then lets the original call proceed, so the 409 is produced by the fake's own resourceVersion check rather than invented by the test:

go
funcs := &interceptor.Funcs{
	SubResourceUpdate: func(ctx context.Context, c client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error {
		attempts++
		if attempts == 1 {
			// Between our read and our status write, a user scales
			// the Website: a new generation the reconcile never saw.
			var w reconciler.Website
			if err := c.Get(ctx, client.ObjectKeyFromObject(obj), &w); err != nil {
				return err
			}
			w.Spec.Replicas = 3
			w.Generation++
			if err := c.Update(ctx, &w); err != nil {
				return err
			}
		}
		return c.SubResource(sub).Update(ctx, obj, opts...)
	},
}

Two habits keep these tests honest. Assert state, not calls: the FAQ recommends checking that the state of the world is as expected rather than that particular API calls were made, and the lab's no-write check compares resourceVersions instead of counting method calls. And keep the wall clock out. Conditions use an injected clock, and conflict backoff runs inside testing/synctest, a standard package since Go 1.25, where time is virtualized and the clock jumps forward when every goroutine in the bubble is blocked. The retry's 10 ms sleeps cost nothing, yet the test can still assert that the backoff lasted between 10 and 11 ms of virtual time. The suite finishes in well under a second without the race detector, and passed three runs under it.

Integration tests with envtest

envtest is the other half. The envtest package starts real etcd and kube-apiserver binaries, loaded by default from /usr/local/kubebuilder/bin or from the directory named by KUBEBUILDER_ASSETS; kubebuilder projects fetch matching binaries with its setup-envtest tool. It can also be pointed at an existing cluster, where it only installs CRDs and provides client configuration. With a real API server, the behaviour the fake client skips becomes real: the CRD's schema would reject an empty image and default replicas to 1, generation and resourceVersion behave as in production, and the server, not a test option, enforces the status subresource.

It is still not a cluster. Kubebuilder's envtest page warns that, unless you use an existing cluster, no built-in controllers run. There is no Deployment controller to create ReplicaSets and no garbage collector, so objects with owner references are not deleted, and deleted namespaces stay in a Terminating state. Integration tests have to play the Deployment controller too, and should assert ownership rather than cascading deletion.

A sensible split for a controller like this one is a fake-client test for every branch of Reconcile, as in the lab, plus a small envtest suite for the CRD manifest, defaulting and one create, update and delete round trip against a real API server. Keep the envtest suite behind a build tag or in its own package, so that go test ./... still runs on a laptop without the binaries. The lab stops at the first half, which is why it runs anywhere Go runs.

Wiring the manager and its permissions

Registration is a few lines. For names the primary kind, each Owns adds a watch whose events are mapped to the controlling Website, and Complete builds the controller:

go
// SetupWithManager registers the controller with a manager. Websites are
// the primary resource; a change to a Deployment or Service that a Website
// controls enqueues that Website. It needs a cluster, so the lab's tests
// compile it but do not run it.
func (r *WebsiteReconciler) SetupWithManager(mgr ctrl.Manager) error {
	r.Client = mgr.GetClient()
	r.APIReader = mgr.GetAPIReader()
	r.Scheme = mgr.GetScheme()
	return ctrl.NewControllerManagedBy(mgr).
		For(&Website{}).
		Owns(&appsv1.Deployment{}).
		Owns(&corev1.Service{}).
		Named("website").
		Complete(r)
}

The lab's cmd/website-controller builds a scheme with client-go's types and the Website types, creates a manager with leader election, and starts it with ctrl.SetupSignalHandler(), whose context is canceled on SIGTERM or SIGINT; a second signal exits the process with code 1. The command compiles as part of the lab but was never run against a cluster:

go
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
	Scheme:           scheme,
	LeaderElection:   true,
	LeaderElectionID: "website-controller.lab.gopherforge.app",
})
if err != nil {
	ctrl.Log.Error(err, "create manager")
	os.Exit(1)
}
r := &reconciler.WebsiteReconciler{DNS: logDNS{}}
if err := r.SetupWithManager(mgr); err != nil {
	ctrl.Log.Error(err, "set up controller")
	os.Exit(1)
}
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
	ctrl.Log.Error(err, "manager stopped")
	os.Exit(1)
}

Leader election matters because the controller guide recommends running several replicas with one active, and adds that even with leader election it is possible, though very unlikely, for more than one copy to be active at once. That is one more reason every write carries a resourceVersion and every external call is idempotent. controller-runtime takes the lock with a Lease object by default. Shutdown timing in a pod is the same as for any Go service on Kubernetes, covered in graceful shutdown in Kubernetes.

The role this controller needs follows from its code: get, list, watch and update on websites; update on websites/status, and on websites/finalizers for clusters that enforce owner-reference permissions; get, list, watch, create and update on Deployments and Services; and the Lease permissions that leader election uses. If the objects your controller manages are still unfamiliar, the Kubernetes course covers Deployments, rollouts, RBAC and client-go, and its labs run in the same simulated cluster as the browser terminal.

A checklist before you ship a controller

  • Reconcile from state. One function reads everything it needs, never branches on the kind of event, and is safe to run at any moment and any number of times.
  • Deterministic names. Name children after their owner; keep generateName out of reconcile loops.
  • Own your fields, nothing more. Mutate functions set owned fields, edit containers and maps in place, leave server-assigned values such as clusterIP alone and immutable ones such as a Deployment selector unchanged. Test a second reconcile against defaulted objects.
  • Controller references on every child, in the owner's namespace. Report an AlreadyOwnedError in status; never overwrite someone else's object.
  • A domain-qualified finalizer for anything outside the cluster, added before the external resource exists and removed only after idempotent cleanup succeeded.
  • Conditions by the conventions: PascalCase types, CamelCase reasons, transition times from an injectable clock, and observedGeneration on the status and on each condition, set to the generation this reconcile acted on.
  • Status written only when it changed, through the status subresource.
  • The right return value: errors for transient failures, TerminalError for what retrying cannot fix, RequeueAfter only for state you cannot watch.
  • Know the queue: in controller-runtime v0.25 the priority queue is on by default, with 5 ms to 1,000 s of backoff per request and one worker unless you raise MaxConcurrentReconciles.
  • No read-after-write through the cache. Retry conflicts by re-reading through GetAPIReader, or return the conflict and let the queue retry.
  • Tests without a cluster: fake-client tests that simulate generations, defaults and the Deployment controller explicitly, testing/synctest instead of sleeps, and envtest for the CRD, defaulting and one round trip.
  • Operations: RBAC for the status and finalizers subresources, leader election on, SIGTERM handled.

The lab is part of this edition's downloadable archive, in the reconciler folder. Run go test -race ./... there; it needs no cluster, no Docker and no envtest binaries.

Primary sources & editorial method

We checked these primary references on 3 December 2026. Release facts are attributed; recommended workflows and examples are GopherForge analysis. Illustrations are conceptual, not vendor screenshots or benchmarks.