Kubernetes Operators: Building Custom Resources and Controllers

Kubernetes Operators have become the standard pattern for encoding operational knowledge directly into the cluster. After building and maintaining half a dozen operators for everything from stateful databases to internal platform abstractions, I've learned that the real complexity isn't in writing a controller — it's in modeling your Custom Resource correctly, handling edge cases in reconciliation, and making the operator survivable in production. The official Kubernetes Documentation covers the primitives, but this article focuses on what actually works when you need to extend the Kubernetes API for your own workloads.

Anatomy of an Operator: CRDs, Controllers, and Reconciliation Loops

At its core, an operator is a control loop that watches a Custom Resource Definition (CRD) and drives the cluster toward your desired state. Unlike a simple deployment script, it follows the same level-triggered principles as the built-in controllers for Deployments or StatefulSets. You declare what you want in a Custom Resource (CR) object, and the controller continuously reconciles observed state with desired state.

In my experience, teams new to operators try to treat reconciliation like a one-shot job. That mindset breaks quickly. Your Reconcile function will be called repeatedly — on create, on update, on resync, and even on unrelated events like a pod being evicted. It must be idempotent and it must be able to handle being killed mid-execution. If your operator creates a StatefulSet and crashes before updating the CR status, the next reconciliation needs to detect that the StatefulSet already exists and continue, not create a duplicate.

The Informer Pattern and Controller-Runtime

Under the hood, most operators today use controller-runtime, which abstracts the informer cache, work queues, and client interactions. The controller sets up informers for your CR type and for secondary resources it owns (Deployments, Services, ConfigMaps). When any watched object changes, the reconcile request is enqueued with the namespaced name of the primary CR. This is why you should always fetch the latest version of your CR at the start of reconciliation — the cached object from the event may already be stale.

Why Level-Triggered Beats Edge-Triggered

Edge-triggered systems react only to events. If you miss an event, you are out of sync forever. Kubernetes is level-triggered: your controller compares the spec you want against the world as it is now. In one early operator I built for managing Redis clusters, we initially used finalizers incorrectly and tried to handle deletion as a single event. When the operator pod was OOMKilled during a cluster scale-down, the finalizer never got removed and the namespace hung in Terminating for days. Moving to a proper level-triggered check — verify the deletionTimestamp is set, clean up external resources, then remove the finalizer — made the behavior predictable even after failures.

Scaffolding Your Operator with Kubebuilder vs Operator SDK

Don't start from scratch. Kubebuilder and the Operator SDK both generate the boilerplate for CRDs, RBAC, webhooks, and manager setup. I've found that Kubebuilder stays closer to upstream controller-runtime and is better documented for advanced cases like multiple API versions, while Operator SDK adds extra tooling for OLM packaging and Ansible/Helm-based operators if you don't want to write Go.

To scaffold a new Go operator with Kubebuilder, the workflow is straightforward:

# Install kubebuilder
curl -L -o kubebuilder https://go.kubebuilder.io/dl/latest/$(go env GOOS)/$(go env GOARCH)
chmod +x kubebuilder && sudo mv kubebuilder /usr/local/bin/

# Initialize project and create an API
kubebuilder init --domain platform.example.com --repo github.com/example/cache-operator
kubebuilder create api --group cache --version v1alpha1 --kind MemcachedCluster --resource --controller

This generates a full project layout: config/crd/bases for your CRD, config/rbac for roles, internal/controller for your reconciliation logic, and a Makefile to generate manifests and deploy. The generation step using controller-gen is critical — it translates Go struct markers like //+kubebuilder:validation:Minimum=1 into OpenAPI schemas.

Tool / Framework Language Support Best For Abstraction Level
Kubebuilder Go Complex, production-grade operators needing full Go control Low — direct controller-runtime
Operator SDK (Go) Go Teams wanting OLM integration and mature scaffolding Low — wraps Kubebuilder
Operator SDK (Helm/Ansible) Helm / Ansible Automating existing charts/playbooks without Go High — no custom code
KOPF Python Rapid prototyping and data-centric operators Medium — Pythonic handler model

When choosing, consider long-term maintenance. For platform teams, Go-based operators integrate more cleanly with CI, testing, and the broader Kubernetes toolchain. If your logic is mostly templating Kubernetes manifests with some conditional logic, the Helm-based SDK can be surprisingly effective and keeps the bundle deployment story simple with Helm Chart Development: Templates, Values, Dependencies and Testing. In my case, we migrated a Helm-based operator to Go after six months because we needed fine-grained status conditions and custom validation that Helm couldn't provide.

Designing Custom Resource Definitions with Structural Schemas and Versioning Strategy

Your CRD is your API contract. Once you publish v1 and users start storing objects in etcd, changing it becomes expensive. I’ve found that investing time upfront in the spec design saves painful conversions later.

Structuring Spec and Status Correctly

Follow the Kubernetes conventions: spec is desired state, status is observed state, and the controller is the only writer to status. Never allow users to edit status fields, and never put observed state in spec. Use status.conditions with standard condition types (Ready, Progressing, Degraded) to make your resource behave well with kubectl wait and GitOps tools.

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: memcachedclusters.cache.example.com
spec:
  group: cache.example.com
  scope: Namespaced
  names:
    plural: memcachedclusters
    singular: memcachedcluster
    kind: MemcachedCluster
  versions:
  - name: v1alpha1
    served: true
    storage: true
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            required: ["size", "version"]
            properties:
              size:
                type: integer
                minimum: 1
                maximum: 10
              version:
                type: string
                pattern: '^1\.[0-9]+\.[0-9]+$'
              resources:
                type: object
                x-kubernetes-preserve-unknown-fields: true
          status:
            type: object
            properties:
              conditions:
                type: array
                items:
                  type: object
                  required: ["type", "status", "lastTransitionTime", "reason", "message"]
              readyReplicas:
                type: integer

Notice the use of validation markers: minimum/maximum, pattern, and required. With the v1 CRD API, schemas must be structural — which means you need to define type for every level and avoid arbitrary JSON unless you explicitly use x-kubernetes-preserve-unknown-fields. This is enforced by the API server and prevents invalid objects from being persisted at all.

Versioning and Conversion

Plan for v1alpha1 to v1beta1 to v1. My rule is: v1alpha1 can break, v1beta1 should be upgrade-compatible with conversion webhooks, and v1 is stable. If you expect to change field names or types, implement a conversion webhook from day one. Otherwise, the only safe upgrade path is to serve multiple versions and manually handle hub-spoke conversion in your Go types. Controller-runtime's conversion interfaces make this manageable, but it is still boilerplate you want to avoid if possible.

Another lesson: keep your spec small and focused. An operator I reviewed tried to replicate every flag of an underlying database as top-level spec fields. The CRD became unwieldy and every upstream version bump required CRD changes. We refactored it to expose only the critical operational knobs (size, version, storageClass, resources) and left advanced tuning to an unstructured configTemplate field. Users who need power get it, but the API surface stays maintainable.

Building Resilient Level-Triggered Reconciliation Logic

The Reconcile function is where most operators succeed or fail. The signature in controller-runtime looks simple, but the implementation details determine whether your operator is reliable.

func (r *MemcachedClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    log := r.Log.WithValues("memcachedcluster", req.NamespacedName)

    var cluster cachev1alpha1.MemcachedCluster
    if err := r.Get(ctx, req.NamespacedName, &cluster); err != nil {
        if apierrors.IsNotFound(err) {
            return ctrl.Result{}, nil
        }
        return ctrl.Result{}, err
    }

    // Handle deletion via finalizer
    if !cluster.DeletionTimestamp.IsZero() {
        if controllerutil.ContainsFinalizer(&cluster, finalizerName) {
            if err := r.cleanupExternalResources(ctx, &cluster); err != nil {
                return ctrl.Result{RequeueAfter: 10 * time.Second}, err
            }
            controllerutil.RemoveFinalizer(&cluster, finalizerName)
            if err := r.Update(ctx, &cluster); err != nil {
                return ctrl.Result{}, err
            }
        }
        return ctrl.Result{}, nil
    }

    // Ensure finalizer exists
    if !controllerutil.ContainsFinalizer(&cluster, finalizerName) {
        controllerutil.AddFinalizer(&cluster, finalizerName)
        if err := r.Update(ctx, &cluster); err != nil {
            return ctrl.Result{}, err
        }
    }

    // Reconcile owned StatefulSet
    desiredSts := r.desiredStatefulSet(&cluster)
    var existingSts appsv1.StatefulSet
    err := r.Get(ctx, types.NamespacedName{Name: desiredSts.Name, Namespace: desiredSts.Namespace}, &existingSts)
    if apierrors.IsNotFound(err) {
        if err := controllerutil.SetControllerReference(&cluster, desiredSts, r.Scheme); err != nil {
            return ctrl.Result{}, err
        }
        if err := r.Create(ctx, desiredSts); err != nil {
            return ctrl.Result{}, err
        }
        return ctrl.Result{Requeue: true}, nil
    } else if err != nil {
        return ctrl.Result{}, err
    }

    // Update status based on observed state
    cluster.Status.ReadyReplicas = existingSts.Status.ReadyReplicas
    meta.SetStatusCondition(&cluster.Status.Conditions, metav1.Condition{
        Type: "Ready", Status: metav1.ConditionTrue, Reason: "Reconciled",
        Message: fmt.Sprintf("Ready replicas: %d/%d", existingSts.Status.ReadyReplicas, *desiredSts.Spec.Replicas),
    })
    if err := r.Status().Update(ctx, &cluster); err != nil {
        return ctrl.Result{}, err
    }

    return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}

Idempotency, Status, and Error Handling

Every Create should be guarded by a prior Get, and every update should compare the desired spec with the existing object's spec to avoid unnecessary writes that trigger infinite requeues. Use controllerutil.SetControllerReference so the garbage collector cleans up owned resources, and rely on OwnerReferences instead of manually deleting child objects wherever possible.

Status updates deserve special attention. Always use r.Status().Update() rather than r.Update() for status, as it uses the /status subresource and avoids conflicts with spec writes. I also recommend setting ObservedGeneration in your conditions — this lets users and tools know that the controller has actually processed the latest spec generation.

Requeue Strategies That Prevent Hot Loops

Returning an error automatically requeues with exponential backoff, but not all errors are retryable. Validation errors or quota exceeded should surface as a Degraded condition and not be requeued aggressively. For normal operation, RequeueAfter with a 30-60 second interval gives you periodic drift detection without hammering the API server. One production issue I hit was a hot loop caused by updating status on every reconcile even when nothing changed — this triggered another reconcile, which updated status again. Guard status writes with a deep equality check first.

Securing and Operating Your Operator: RBAC, Webhooks, and Lifecycle Management

An operator is a privileged workload. It often needs permissions to create and patch resources across namespaces, which makes correct RBAC and safe admission critical.

Minimal RBAC and Leader Election

Use kubebuilder markers to generate least-privilege roles: //+kubebuilder:rbac:groups=apps,resources=statefulsets,verbs=get;list;watch;create;update;patch;delete. Never grant wildcard permissions. The generated ClusterRole should be scoped to exactly what the controller touches, plus get/list/watch on the CRD itself. For namespace-scoped operators, consider using Role/RoleBinding instead of ClusterRole to limit blast radius.

Enable leader election in your manager options (ctrl.Options{LeaderElection: true, LeaderElectionID: "memcached-operator-leader"}). This allows you to run multiple replicas for high availability without active-active conflicts. Only the leader reconciles; the others standby and take over if the leader's lease expires. In production I run two replicas with appropriate pod disruption budgets so upgrades don't leave the operator unavailable.

Admission Webhooks for Validation and Defaults

OpenAPI validation catches syntax errors, but business logic validation requires webhooks. A validating webhook can reject a CR that requests an unsupported version combination or an invalid scale-down. A mutating webhook can default resource requests or inject labels. Webhooks introduce operational complexity — you need TLS certificates (cert-manager helps), failure policies, and you must handle the case where the webhook itself is unavailable. Set failurePolicy to Fail for strict validation, but ensure the webhook Service is highly available. If you expose webhooks externally, revisit your policies through Kubernetes Networking: Services, Ingress Controllers and Network Policies to lock down webhook endpoints with NetworkPolicies.

Deployment, Packaging, and Upgrades

Package your operator as a container image using distroless or minimal base images, and distribute manifests via Kustomize or Helm. If your users consume Helm, providing a chart that installs the CRDs and operator Deployment together simplifies adoption — see our notes on Dockerfile Best Practices: Multi-Stage Builds, Layer Caching and Security for keeping that image small and secure. For upgrades, use the Kubebuilder Makefile targets: make manifests, make install, make deploy. When you need ordered dependencies, consider OLM or simply apply CRDs first — CRDs are cluster-scoped and installing them after the manager starts will cause the informer to fail. I also run end-to-end tests with envtest and kind, creating real CRs and asserting that the controller creates the expected child resources. As noted in the Kubernetes Documentation on extensible admission, webhooks must be tested under failure conditions, so we simulate webhook downtime in our staging cluster before any production rollout.

Frequently Asked Questions

Should I use finalizers for every operator?

Only if you manage external resources that Kubernetes garbage collection cannot clean up — such as cloud provider databases, DNS records, or storage buckets. For resources owned via OwnerReferences like Deployments and Services, Kubernetes will delete them automatically when the CR is deleted, so a finalizer just adds latency. In my experience, unnecessary finalizers are the number one cause of stuck namespaces.

How do I handle CRD version upgrades without downtime?

Serve both versions simultaneously and set storage to the newest stable version. For additive changes (new optional fields), no conversion is needed — old objects simply lack the new fields. For breaking changes, implement a conversion webhook that translates between versions. Test conversion with real etcd data in a staging cluster, and always back up CR instances before applying a CRD upgrade.

Can I write an operator without Go?

Yes. Frameworks like KOPF for Python or the Operator SDK's Helm and Ansible variants let you build operators with minimal Go. They are excellent for prototyping or when your logic is primarily templating. For large-scale or performance-sensitive operators that watch many resources or require complex state machines, Go with controller-runtime remains more efficient and gives you full control over caching and concurrency.

How frequently should reconciliation run?

Let events drive reconciliation and use RequeueAfter only for periodic drift checks — typically 30 seconds to a few minutes. Avoid requeueing every few seconds; it creates unnecessary API load and can mask hot loops. If you need faster reaction to external system changes, watch that external system and trigger reconciliation via an external event source rather than polling aggressively.

Related Articles

References & Standards: Kubernetes Documentation · Docker Documentation · Terraform Documentation