Operators

Difficulty: Advanced

Question

What is the Kubernetes Operator pattern, how does an operator work, and when should you build or use one?

Answer

An operator is a custom controller that manages an application through a custom resource. You declare what you want (for example kind: PostgresCluster with 3 instances and daily backups) and the operator runs a reconciliation loop that continuously drives the real world toward that spec, encoding the operational knowledge a human SRE would otherwise apply by hand: provisioning, failover, backups, upgrades and scaling.

The building blocks

  • CRD: defines the new API, such as PostgresCluster or KafkaTopic.
  • Controller: a process, usually running as a Deployment in the cluster, that watches those objects plus related built-in objects (StatefulSets, Services, Secrets, PVCs).
  • Reconcile function: given an object's name, read the desired state, observe the actual state, take the next step to close the gap, and update status.

This is exactly how built-in controllers work. The Deployment controller reconciles Deployments into ReplicaSets; an operator applies the same pattern to domain-specific objects.

How reconciliation behaves

  • Level-triggered, not edge-triggered: the operator does not ask "what event happened?" but "what does the world look like now?" If it crashes and restarts, it simply reconciles everything again.
  • Idempotent: running reconcile twice must be safe. Create the Service only if it does not exist.
  • Watches and caches: libraries like controller-runtime use informers to cache objects and a work queue to process changes with rate-limited retries.
  • Owner references make child objects get garbage collected when the parent is deleted, and finalizers let the operator clean up external resources (like a cloud bucket) before deletion completes.
  • Status and conditions report progress, such as Ready=True, so users and tools like Argo CD can see health.

Real operators you will meet

  • CloudNativePG and Zalando's operator for PostgreSQL, handling replicas, failover and point-in-time recovery
  • Strimzi for Kafka, managing brokers, topics and users as CRs
  • Prometheus Operator, generating Prometheus configuration from ServiceMonitor objects
  • cert-manager, issuing and renewing TLS certificates from Certificate objects

A team running Kafka for order events at a food delivery company would typically use Strimzi rather than hand-written StatefulSets, because broker rolling restarts and partition-safe upgrades are already encoded in it.

When to build one, and the cost

Build an operator when an application has real operational logic that must run repeatedly and correctly, and when many instances of it exist. Use Kubebuilder or Operator SDK (Go, built on controller-runtime), or Kopf if your team prefers Python.

Do not build one for a stateless web app; a Deployment plus a Helm chart is enough. Operators are software you must test, upgrade and secure. Common mistakes include non-idempotent reconcile logic, hot loops that hammer the API server, writing to spec instead of status, and granting the operator cluster-admin when it needs a handful of resources.

One pass of an operator's reconcile loop. The loop repeats on every change and on a periodic resync until actual state matches desired state.
  1. Event queues the object: A watch sees a change to the custom resource or a child.
  2. Read desired state: Fetch the custom resource spec from the cache.
  3. Observe actual state: List owned StatefulSets, Services, PVCs and external systems.
  4. Take the next action: Create, update or delete objects to close the gap.
  5. Update status: Write conditions like Ready so users see progress.
  6. Requeue if needed: Retry with backoff on error or check again later.

Code examples

Reconcile handler with Kopf (Python)

import kopf
from kubernetes import client

@kopf.on.create("db.example.com", "v1", "postgresclusters")
@kopf.on.update("db.example.com", "v1", "postgresclusters")
def reconcile(spec, name, namespace, logger, **_):
    apps = client.AppsV1Api()
    sts = build_statefulset(name, spec)   # desired child object
    kopf.adopt(sts)                       # owner reference for cleanup

    try:
        apps.read_namespaced_stateful_set(name, namespace)
        apps.patch_namespaced_stateful_set(name, namespace, sts)
    except client.ApiException as e:
        if e.status != 404:
            raise                         # Kopf retries with backoff
        apps.create_namespaced_stateful_set(namespace, sts)

    logger.info(f"{name}: want {spec['instances']} instances")
    # Returned dict is written under .status.reconcile
    return {"desiredInstances": spec["instances"]}

The handler is idempotent (create or patch), adopts its child so it is garbage collected with the parent, and reports progress in status. Go operators built with Kubebuilder follow the same structure in a Reconcile function.

What the user writes

apiVersion: db.example.com/v1
kind: PostgresCluster
metadata:
  name: orders-db
spec:
  instances: 3
  version: "17"
  backup:
    schedule: "0 2 * * *"
    retentionDays: 7

The user declares intent; the operator turns it into StatefulSets, Services, Secrets and backup jobs and keeps them correct.

Key points

  • Operator = CRD + custom controller + domain knowledge
  • Reconciliation is level-triggered and must be idempotent
  • Owner references handle cleanup of children; finalizers handle external resources
  • Controllers write spec-derived objects and update status, never the user's spec
  • Build with Kubebuilder or Operator SDK (Go) or Kopf (Python)

Common follow-up questions

  • What does level-triggered mean and why is it better than edge-triggered for controllers?
  • How do finalizers and owner references differ?
  • How would you test an operator?
  • When is a Helm chart enough and when do you need an operator?

Interview tips

  • Explain the reconcile loop step by step; that is the heart of the question
  • Name a real operator you have used or studied, such as Strimzi or CloudNativePG
  • Show judgement by saying when an operator is overkill

Concepts covered

Operator Pattern, Reconciliation Loop, Custom Controllers, Kubebuilder, Stateful Workload Automation

More Kubernetes & Orchestration questions