Platform Engineering · Lesson 101

Extending Kubernetes: CRDs, Controllers, and Operators

Kubernetes is an API with controllers attached. A Deployment is only a stored object until the Deployment controller reads it and makes ReplicaSets, and a ReplicaSet is only a stored object until its controller makes pods. A CustomResourceDefinition lets you add your own kind of object to that API, and a controller you write turns it into real things the same way. An operator is that pair, a custom resource and its controller, built to run one piece of software the way an expert would. This lesson follows one custom resource from kubectl apply to a running database, shows the reconcile loop every controller is built on, and what happens when the schema rejects the object or the controller is not running.

Difficulty: Advanced · Know this first: Lesson 98, Lesson 95, Lesson 96

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar splits the time from kubectl apply to a Ready status, in milliseconds. It is a worked example, not a measurement. The operator's own work, watch, queue, reconcile, children, status, is tens of milliseconds; starting the pods is the rest.

Try it: how long until every object is reconciled?

When an operator restarts, its informer lists every object and queues them all. Set how many custom resources it manages, how long one reconcile takes, and how many workers run in parallel.

time to drain the queue after a restart = objects × reconcile time ÷ workers · the last object in the queue waits about that long

10,000ms to reconcile all
50reconciles a second
10 sworst wait for one object

A restart catches up in seconds

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Extending Kubernetes grows in four levels: first what a CRD and a controller are, then writing a CRD with a real schema, then writing a controller that is correct under retries and restarts, and finally deciding when an operator is worth building at all.

Basic — A new kind of object, and something that acts on it

At the basic level you can say what each piece is. A custom resource is an object of a kind Kubernetes did not ship with. A CustomResourceDefinition (CRD) teaches the API server that kind: its name, its group and versions, and its schema. A controller watches objects and makes the world match them. An operator is a CRD plus a controller that runs one application the way an expert operator would: install, upgrade, back up, fail over.

Examples you may already run: cert-manager's Certificate, Prometheus Operator's ServiceMonitor, Strimzi's Kafka, CloudNativePG's Cluster, Argo CD's Application.

Where it breaks: installing the CRDs without the controller. The objects are accepted and nothing happens.

Try it: Basic

You install only the CRDs of an operator and create one of its objects. What happens?

Now do it: Run kubectl get crd in a cluster you use and pick three. For each, find the controller that acts on it and which namespace it runs in.

Intermediate — Write a CRD with a schema that protects you

At the intermediate level you write a CRD: group, names, scope, one served and stored version, and a structural OpenAPI v3 schema with types, required, minimum and maximum, enums, and defaults. You enable the status subresource so users cannot edit status and controllers cannot edit spec by accident, and you add additionalPrinterColumns so kubectl get shows something useful.

  • CEL rules (x-kubernetes-validations) for checks across fields: "replicas must be odd", "version may not go down".
  • The schema prunes unknown fields, so a typo in a field name is dropped, not stored.

Troubleshooting: a 422 names the field and the rule; kubectl explain database.spec reads the schema back.

Try it: Intermediate

You want the API server to reject a Database whose replicas is even. Where does that rule belong?

Now do it: Add the rule self.replicas % 2 == 1 to the CRD in Go deeper and try to apply replicas: 4 against a test cluster.

Advanced — A controller that is correct under retries and restarts

At the advanced level you write the controller, usually with controller-runtime through Kubebuilder or Operator SDK. Correctness comes from a handful of rules more than from clever code.

  • Level-triggered: read the current state every time; never depend on having seen an event.
  • Idempotent steps: create-or-update, compare before you write, so a second run changes nothing.
  • Owner references and finalizers for cleanup inside and outside the cluster.
  • Status with conditions and observedGeneration, written through the status subresource.
  • Requeue with backoff on errors, and a periodic resync for state that can drift outside Kubernetes.
  • Leader election so only one replica acts, and RBAC limited to the kinds it really touches.

Observability: reconcile duration and errors, work-queue depth and retries, all exported by controller-runtime on its metrics endpoint.

Try it: Advanced

Your controller sometimes creates two StatefulSets for one Database after a restart. What is the likely bug?

Now do it: Run reconcile.py in Go deeper. Then change it to create the StatefulSet under a new random name each time and watch step 4 go wrong.

Master — When an operator is worth building

At the master level you decide whether to build one. An operator is code you will own for years: it runs with cluster permissions, it must handle every version of the software it manages, and a bug in it can delete data on every cluster at once.

  • Build when the software has real operational knowledge to encode: ordered upgrades, failover, backups and restores, resharding.
  • Do not build when a Helm chart, a Kustomize overlay, or a GitOps tool already expresses it; a CRD for a "template with three fields" is a maintenance cost with no operator in it.
  • Buy or adopt mature operators (CloudNativePG, Strimzi, cert-manager) and read their CRDs as an API you depend on.
  • Version the API: served and stored versions, conversion webhooks, and a deprecation policy, like any other API.

Failure-mode analysis: what does the operator do if it is down for an hour (nothing changes, which must be safe), if it loses the API server mid-upgrade, if two clusters' operators share an external resource? Design so that "operator stopped" is always a safe state.

Try it: Master

A team wants an operator whose CRD has three fields that fill in a Deployment and a Service, with no upgrades, backups, or failover logic. What do you recommend?

Now do it: For one operator you run, list what it does after install: upgrades, backups, failover. That list is why it exists. If it is empty, ask why it is an operator.

Go deeper

Every controller, from the Deployment controller to a database operator, has the same loop at its heart. This script is that loop with the cluster replaced by a dictionary: it is level-triggered, idempotent, survives a crash halfway, follows a spec change, and undoes drift. Standard library only; python3 reconcile.py.

The reconcile loop, and why it must be idempotent

# reconcile.py - a level-triggered reconcile loop, the shape every controller has
cluster = {}                     # what exists: name -> {"replicas": n, "version": v}

def reconcile(obj, crash_after=None):
    """Compare what the object asks for with what exists, and fix the difference.
    Safe to run any number of times: it reads the world first, never a list of past events."""
    actions = []
    cur = cluster.get(obj["name"])
    if cur is None:
        cluster[obj["name"]] = cur = {"replicas": 0, "version": obj["version"]}
        actions.append("create StatefulSet")
    if crash_after is not None and len(actions) >= crash_after:
        raise RuntimeError("controller crashed after " + ", ".join(actions))
    if cur["version"] != obj["version"]:
        cur["version"] = obj["version"]
        actions.append(f"upgrade to {obj['version']}")
    if cur["replicas"] != obj["replicas"]:
        cur["replicas"] = obj["replicas"]
        actions.append(f"scale to {obj['replicas']}")
    ready = cur == {"replicas": obj["replicas"], "version": obj["version"]}
    return actions or ["nothing to do"], ready

db = {"name": "shop-db", "replicas": 3, "version": "16.4"}

print("1. new object:", reconcile(db))
print("2. same object again:", reconcile(db))

cluster.clear()
try:
    reconcile(db, crash_after=1)
except RuntimeError as err:
    print("3. crash:", err)
print("4. restarted, same object:", reconcile(db))

db["replicas"], db["version"] = 5, "16.6"
print("5. spec changed:", reconcile(db))

cluster["shop-db"]["replicas"] = 2          # someone scaled it by hand
print("6. drift from a hand edit:", reconcile(db))
$ python3 reconcile.py
1. new object: (['create StatefulSet', 'scale to 3'], True)
2. same object again: (['nothing to do'], True)
3. crash: controller crashed after create StatefulSet
4. restarted, same object: (['scale to 3'], True)
5. spec changed: (['upgrade to 16.6', 'scale to 5'], True)
6. drift from a hand edit: (['scale to 5'], True)

Read it like this: the second run does nothing, because nothing differs; the crash leaves a StatefulSet with zero replicas, and the restarted reconcile finishes the job instead of creating a second one; a spec change and a hand edit are both just "a difference to fix".

A CRD with a schema, a CEL rule, status, and printer columns

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: databases.data.example.com
spec:
  group: data.example.com
  scope: Namespaced
  names:
    kind: Database
    plural: databases
    singular: database
    shortNames: ["db"]
  versions:
    - name: v1
      served: true
      storage: true
      subresources:
        status: {}
      additionalPrinterColumns:
        - name: Version
          type: string
          jsonPath: .spec.version
        - name: Ready
          type: string
          jsonPath: .status.conditions[?(@.type=="Ready")].status
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              required: ["version", "replicas"]
              properties:
                version:
                  type: string
                  enum: ["16.4", "16.6", "17.2"]
                replicas:
                  type: integer
                  minimum: 1
                  maximum: 7
              x-kubernetes-validations:
                - rule: "self.replicas % 2 == 1"
                  message: "replicas must be odd, so a quorum always exists"
            status:
              type: object
              properties:
                observedGeneration:
                  type: integer
                conditions:
                  type: array
                  items:
                    type: object
                    x-kubernetes-preserve-unknown-fields: true

The object a user writes

apiVersion: data.example.com/v1
kind: Database
metadata:
  name: shop-db
  namespace: shop
spec:
  version: "16.4"
  replicas: 3

Both manifests were parsed as YAML and checked against the apiextensions.k8s.io/v1 field names; apply them to a test cluster (kind or minikube) and you get the 422 from the spike scenario by changing replicas to "three", and the CEL message by changing it to 4. Nothing will reconcile the Database until a controller for it runs.

The same loop in controller-runtime (a sketch)

// Sketch of the Go shape Kubebuilder generates; not compiled here.
func (r *DatabaseReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    var db datav1.Database
    if err := r.Get(ctx, req.NamespacedName, &db); err != nil {
        return ctrl.Result{}, client.IgnoreNotFound(err)   // deleted: nothing to do
    }
    sts := &appsv1.StatefulSet{ObjectMeta: metav1.ObjectMeta{Name: db.Name, Namespace: db.Namespace}}
    _, err := controllerutil.CreateOrUpdate(ctx, r.Client, sts, func() error {
        sts.Spec.Replicas = ptr.To(db.Spec.Replicas)       // desired state, every time
        return controllerutil.SetControllerReference(&db, sts, r.Scheme)
    })
    if err != nil {
        return ctrl.Result{}, err                          // requeued with backoff
    }
    db.Status.ObservedGeneration = db.Generation
    return ctrl.Result{}, r.Status().Update(ctx, &db)
}

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A platform team ran an in-house operator that created a cloud DNS record for every custom Endpoint object. Cleanup relied on a finalizer.

Timeline

  • Day 1The operator is uninstalled during a cluster migration, CRD and all, while Endpoint objects still exist. Each one is stuck deleting: its finalizer waits for a controller that is gone.
  • Day 1Someone removes the finalizers by hand to unblock the namespace deletion. The objects disappear; their DNS records stay in the cloud.
  • Day 40A record left behind still points at an address the cloud has since given to another customer. Traffic for an internal name goes to a stranger.

What changed after

The runbook says: delete the custom objects first and let the operator clean up, then remove the operator, then the CRD. Removing a finalizer by hand needs a written record of what it was protecting. And the operator gained a periodic sweep that deletes DNS records tagged with its cluster's ID that no longer have an owner object.

If you remember nothing else

Design exercise

Design an operator for a team that runs 200 PostgreSQL databases across four clusters and wants self-service creation, minor-version upgrades, and nightly backups.

Clarifying questions to ask

Does a mature operator (CloudNativePG, Crunchy) already do this? What must users be allowed to set, and what must they never set? What happens to a database when the operator is down for an hour? How are backups restored, and who tests that? How will the CRD version evolve?

Rough sizing

Say 200 Database objects per cluster at peak, a reconcile of 50 ms with two API calls, 4 workers, and a full resync every 10 hours.

Shape of the answer

Adopt CloudNativePG for the database lifecycle, and if a platform API is still needed, add a thin CRD (Team database: size, version from an enum, backup schedule) whose controller only creates the CloudNativePG Cluster with the platform's defaults. Schema and CEL rules for every limit, the status subresource with conditions, ownerReferences to the Cluster, a finalizer only for the backup bucket, leader election, and RBAC limited to its own kinds.

Trade-offs to name

Adopting an operator gives years of edge cases for free and ties you to its API and release cadence. A thin platform CRD on top gives users a smaller, safer API and adds a controller you own. Building the whole operator gives full control and makes you responsible for every failover and upgrade bug.

Saved on this device, in this browser.
Next in this series · Lesson 102
OpenShift

Kubernetes gives you the pieces to run containers. It does not give you a finished platform. You still have to add a way to build images, a way to get traffic in, a way to decide which pods may do what, and a way to keep all of…

Go to Lesson 102 →

Or browse the full course from the Lessons index.