Operators and writing a controller
Making a custom resource do something: a controller-runtime reconciler that owns a StatefulSet, writes status, heals drift and cleans up with a finalizer.
Custom resource definitionsControllers and the reconcile loopStatefulSets
Operators and writing a controller
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- An operator is a CRD plus a controller that encodes operational knowledge, such as provisioning, upgrades and backups, as a reconcile loop that keeps real state matching the custom resource.
- controller-runtime gives you informers and a cache, a rate-limited work queue, and a Reconcile(request) function called with just a namespace and name. You re-read everything and converge, whatever the trigger.
- Reconcile must be idempotent and level-triggered. It runs many times for one change, and conflicts and errors are simply retried with back-off.
- Owner references on created objects make Owns() wake the controller when they change, and let the garbage collector delete them with their owner.
- Finalizers block deletion until the controller has cleaned up anything outside the cluster, then are removed. A controller that dies with finalizers set leaves objects stuck in Terminating.
- Status reports what the controller saw, with observedGeneration tying it to a spec. The CRD schema must include every status field, or the API server prunes it.
Turning runbooks into code
The previous lesson’s Database object was validated, defaulted and stored, and then nothing happened. Somebody still has to create the StatefulSet, take backups, run version upgrades in the right order, and fail over when a primary dies. In most companies that knowledge lives in a runbook and in a few people’s heads.
An operator puts it in code: a controller that watches a custom resource and does what a skilled operator would do, continuously. It’s the same reconcile loop the Deployment controller runs, applied to your own domain. Mature examples include CloudNativePG, Strimzi for Kafka, cert-manager, and the Prometheus Operator.
What controller-runtime gives you
Most Go operators are built on controller-runtime (v0.25.3 here, matching Kubernetes 1.37 client libraries), usually through the Kubebuilder or Operator SDK scaffolding. It provides:
- Informers and a cache: one watch per type, shared, so reads in Reconcile hit memory, not the API server.
- A work queue: events are reduced to namespace/name keys, de-duplicated and rate-limited, and failed keys are retried with back-off.
- A manager: client, scheme, leader election, health and metrics endpoints.
- Reconcile: your function, called with a key, returning a result or an error.
A small Database operator
I wrote a 100-line controller and ran it on my machine against the lab API server, the same way make run runs a Kubebuilder project. The heart of it:
func (r *DatabaseReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
db := &unstructured.Unstructured{}
db.SetGroupVersionKind(dbGVK)
if err := r.Get(ctx, req.NamespacedName, db); err != nil {
if apierrors.IsNotFound(err) {
return ctrl.Result{}, nil // deleted; owned objects are garbage-collected
}
return ctrl.Result{}, err
}
if !db.GetDeletionTimestamp().IsZero() {
if controllerutil.ContainsFinalizer(db, finalizer) {
// clean up anything outside the cluster here (final backup, cloud resources)
controllerutil.RemoveFinalizer(db, finalizer)
return ctrl.Result{}, r.Update(ctx, db)
}
return ctrl.Result{}, nil
}
if controllerutil.AddFinalizer(db, finalizer) {
return ctrl.Result{}, r.Update(ctx, db)
}
sts := &appsv1.StatefulSet{ObjectMeta: metav1.ObjectMeta{Name: db.GetName(), Namespace: db.GetNamespace()}}
_, err := controllerutil.CreateOrUpdate(ctx, r.Client, sts, func() error {
sts.Spec.Replicas = ptr.To(int32(replicas))
sts.Spec.Template.Spec.Containers = []corev1.Container{{Name: engine, Image: engine + ":" + version}}
// ...selector, labels, serviceName
return controllerutil.SetControllerReference(db, sts, r.Scheme())
})
if err != nil {
return ctrl.Result{}, err
}
// report status: Ready when all replicas are ready, plus observedGeneration
return ctrl.Result{}, r.Status().Patch(ctx, db, patch)
}
Wired up with:
ctrl.NewControllerManagedBy(mgr).Named("database").
For(db). // reconcile on Database changes
Owns(&appsv1.StatefulSet{}). // and on changes to StatefulSets it owns
Complete(&DatabaseReconciler{Client: mgr.GetClient()})
The real operator would use typed Go structs generated by Kubebuilder. Unstructured objects kept this one to a single file.
Watching it reconcile
Started against the existing orders Database, the log showed the loop doing its job, and two real lessons:
INFO adding finalizer {"Database": {"name":"orders","namespace":"shop"}}
INFO statefulset reconciled {"operation": "created", "replicas": 1, "image": "postgres:17"}
INFO unknown field "status.observedGeneration"
INFO statefulset reconciled {"operation": "updated", ...}
ERROR Reconciler error {"error": "Operation cannot be fulfilled on statefulsets.apps \"orders\": the object has been modified; please apply your changes to the latest version and try again"}
INFO statefulset reconciled {"operation": "updated", ...}
Pruned status. unknown field "status.observedGeneration" is the API server warning that it dropped a field the CRD schema didn’t declare. The status patch “worked” and the field vanished. After I added observedGeneration to the schema, status read {"observedGeneration":2,"phase":"Provisioning"}.
Conflicts are normal. The error is optimistic concurrency. The StatefulSet controller had updated the object between my read and write. Returning the error re-queued the key, and the next pass succeeded. The burst of “updated” lines settled within a second. The StatefulSet’s generation stayed at 1, so those writes changed no spec. CreateOrUpdate saw a difference because my mutate function replaces the whole containers list, which drops fields the API server had defaulted. Setting only the fields you own, or using server-side apply, avoids the churn.
Self-healing, drift and deletion
Then I poked at it:
--- delete the StatefulSet: recreated within a second (orders 0/1 0s)
--- kubectl scale sts --replicas=5: back to 1
--- patch Database spec.replicas=3: StatefulSet replicas 3, status observedGeneration 2
Each is one Reconcile. The deletion and the manual scale arrived as StatefulSet events, mapped through the owner reference (controller: true, blockOwnerDeletion: true) to their Database. The controller didn’t need to know what had changed, only what should be true.
Deleting the Database set its deletion timestamp. The finalizer held it while Reconcile ran the cleanup branch (cleaning up external resources) and removed the finalizer. Then the object disappeared, and the garbage collector in kube-controller-manager deleted the owned StatefulSet. The Pods stayed Pending throughout, so the phase stayed Provisioning, since there’s no kubelet here to run Postgres.
Rules for operators that behave
- Idempotent, level-triggered Reconcile. It will run many times per change, and after restarts.
- Own what you create, with controller references, so watches and garbage collection work.
- Finalizers only for external cleanup, and never block forever. Surface failures in status and events.
- Status with conditions (
Ready,Progressing,Degraded) andobservedGeneration. - Least-privilege RBAC: Kubebuilder’s
+kubebuilder:rbacmarkers generate exactly the verbs used. - Leader election when running more than one replica, so only one reconciles at a time.
- Don’t build one if a good one exists. Operators for popular databases encode years of failure handling.
About the video
The embed is a clip of freeCodeCamp.org and Kubesimplify’s “Build Your Own Kubernetes Operators with Go and Kubebuilder – Full Course”, January 2026, from “What is a Controller?” (1:55) to the start of the CRD section (27:35), about 26 minutes. Going by its chapters, that section covers the observe-compare-act loop, idempotency, a deep dive on the reconcile loop’s happy path, sad path and error handling, the foundations of writing operators, and what an operator is. The rest of the six-hour course builds an EC2 operator with Kubebuilder, including finalizers and informer internals (4:46:35), for anyone who wants to go all the way. I judged it from chapters and description only, since transcripts couldn’t be fetched. English was judged from the title, channel and English caption track. The page shows no audio-language flag. The Cloud Native Skunkworks video in deeper is a half-hour Kubebuilder walkthrough.
What was run: the controller above, built with controller-runtime v0.25.3 and client-go v0.37.0, reconciled against a local Kubernetes v1.37.3 API server whose nodes run no containers. Every log line, the pruning warning, the conflict, the self-healing, drift correction, spec change and finalizer-driven deletion are real. Leader election, webhooks and metrics were off. Practices are from the Kubebuilder book, checked 2026-11-29.
Where this fits
That closes extending Kubernetes. The last group is running clusters, starting with what to do when something’s broken: debugging Pods with describe, logs, events and ephemeral containers.
Check yourself
Why does Reconcile receive only a namespace and name, not the change that happened?
Because controllers are level-triggered. Events can be merged, missed or replayed, so the reconciler must look at current desired and actual state and converge, rather than react to a specific diff. That's also what makes restarts and resyncs safe.
Someone deletes the StatefulSet your operator created. What brings it back, and how fast?
The controller watches StatefulSets it owns (Owns()). The deletion event maps through the owner reference to the Database, which is queued, and Reconcile recreates the StatefulSet within moments.
Your controller logs 'the object has been modified; please apply your changes to the latest version'. Is that a bug?
Usually not. It is optimistic concurrency: the object changed between your read and your write. Return the error (or requeue), and the next reconcile reads the fresh version. Persistent conflicts suggest two writers fighting over the same fields.
A Database has been Terminating for an hour after kubectl delete. What's the likely cause?
A finalizer the operator hasn't removed, because the operator is down, crashing, or failing its cleanup. Fix or restart the operator. Removing the finalizer by hand skips its cleanup, such as a final backup or deprovisioning.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.