How Kubernetes Operators Actually Work: CRDs, Informers, and Reconciliation

A Kubernetes Operator extends the Kubernetes API with Custom Resource Definitions (CRDs) to automate stateful applications. Learn how SharedInformers, rate-limited WorkQueues, level-triggered reconciliation loops, and finalizers drive self-healing clusters in production.

How Kubernetes Operators Actually Work: CRDs, Informers, and Reconciliation

If you deploy a stateless web server on Kubernetes, a built-in Deployment handles almost everything you need. When a Pod crashes, Kubernetes schedules a replacement. When traffic spikes, it adds identical replicas behind a Service. Every replica is interchangeable, and the order in which Pods start or stop rarely matters.
Now try running a stateful distributed database like PostgreSQL, etcd, or Kafka using only a Deployment or StatefulSet. Scaling up is no longer a matter of simply starting another container. A new database node has to join an existing quorum, authenticate with internal TLS certificates, replicate terabytes of write-ahead logs from a primary node, and register itself with a connection pooler. If the primary node goes offline, a human operator normally has to inspect replication lag, promote the healthiest replica, and reconfigure every client endpoint.
Kubernetes Operators exist to encode that human operational knowledge directly into software running inside your cluster. People often ask what an Operator actually is and how it differs from a standard Kubernetes controller. Both components share the exact same goal of driving a cluster toward a declared state, yet they operate at different scopes and extend Kubernetes in fundamentally different ways.

Kubernetes Controllers vs. Operators: What Is the Actual Difference?

To understand how an Operator works under the hood, you first have to look at the foundation it is built on: the Kubernetes controller pattern. Inside kube-controller-manager, dozens of built-in controllers run side by side, including the Deployment controller, ReplicaSet controller, Node controller, and Job controller. Each one watches a specific set of core Kubernetes API types and takes corrective action whenever reality diverges from configuration.
An Operator takes that exact same control-loop machinery and pairs it with custom API schemas. Instead of compiling new logic into the upstream Kubernetes binaries, you register a Custom Resource Definition (CRD) with the API Server and deploy a custom controller Pod that watches those custom objects.
In short, every Operator is a controller, while a controller only becomes an Operator when it combines custom resource APIs with domain-specific operational automation.

Desired State vs. Current State: Why Reconciliation Is Level-Triggered

Every Kubernetes resource separates intent from reality using two top-level fields: .spec and .status. When you apply a manifest declaring replicas: 3, you are writing your desired state into .spec and persisting it in etcd through the API Server. The .status section reflects the current observed state of the cluster, such as how many Pods are actually running and passing readiness probes right now.
Controllers bridge the gap between those two fields through continuous reconciliation. If a Pod terminates because a worker node loses power, the current state drops to two running replicas while the desired state remains at three. The controller detects this drift, schedules a replacement Pod, and updates .status once the new Pod becomes healthy. If someone manually creates a fourth Pod matching the Deployment selector, the controller terminates the extra instance. If a configuration template changes, it rolls out updated Pods to match the new specification.
A critical architectural detail is that Kubernetes controllers are level-triggered, not edge-triggered. An edge-triggered system reacts strictly to discrete event notifications (such as "Pod X was deleted at 14:02:11"). If the controller restarts or experiences a brief network interruption at 14:02:11 and misses that event notification, the system stays permanently out of sync.
A level-triggered controller uses watch events merely as a wake-up signal to inspect the full current state of the world against the desired state. Even if ten events arrive while an Operator Pod is restarting, the moment it boots back up, it lists the existing objects, compares .spec against the live cluster state, and executes every action required to converge. This design is what makes Kubernetes genuinely self-healing under real-world failure conditions.

Inside the Controller Architecture

Whether you examine a built-in controller inside kube-controller-manager or a custom Operator written in Go with controller-runtime (the engine behind Kubebuilder and Operator SDK), the internal data flow follows the exact same pipeline. Controllers never poll the API Server in a tight while loop, because thousands of controllers polling etcd every second would overwhelm the control plane. Instead, they rely on an event-driven caching pipeline built into client-go.
Plaintext

+-------------------+      1. Manifest       +-------------------+
|   User / CI/CD    | ---------------------> |    API Server     |
+-------------------+                        +-------------------+
                                                       |
                                              2. Watch Stream (HTTP/2)
                                                       v
+-------------------+   4. Enqueue Key       +-------------------+
|     WorkQueue     | <--------------------- |  SharedInformer   |
|  (Rate-Limited)   |                        |  & Local Cache    |
+-------------------+                        +-------------------+
          |                                            ^
          | 5. Pop Key                                 | 6. Read State
          v                                            |
+----------------------------------------------------------------+
|                      Reconciliation Loop                       |
|  Compare Desired State (.spec) vs. Current State (.status)     |
+----------------------------------------------------------------+
          |
          | 7. Create / Update / Delete Child Resources & Status
          v
+-------------------+
|    API Server     |
+-------------------+

Here is what happens step by step inside the controller process from the moment a manifest hits the cluster:

1. API Server Persistence and Watch Streams

When a user or CI/CD pipeline runs kubectl apply, the API Server authenticates the request, runs admission webhooks, validates the object against its schema, and writes it to etcd. Rather than pushing notifications to every component, the API Server exposes a LIST and WATCH endpoint over long-lived HTTP/2 connections. Every object in etcd carries a monotonically increasing resourceVersion string, allowing clients to list the current state once and then stream incremental ADDED, MODIFIED, and DELETED events starting from that exact version.

2. Reflector, DeltaFIFO, and the SharedInformer Cache

Inside the Operator process, a component called a Reflector opens that LIST/WATCH stream for each resource type the Operator watches (for example, watching both a custom PostgresCluster resource and the child StatefulSet, Service, and Secret objects it owns). In modern client-go releases (with the WatchList feature enabled by default since Kubernetes 1.33), the Reflector can also stream initial state as a sequence of ADDED watch events ending in a bookmark (sendInitialEvents=true) instead of executing a single monolithic LIST call, avoiding memory spikes on kube-apiserver during cache synchronization. As events arrive, the Reflector pushes them into an internal queue called DeltaFIFO.
The SharedInformer drains DeltaFIFO and updates a local, thread-safe in-memory store called an Indexer. When your reconciliation code reads a Pod or Custom Resource, it reads directly from this local RAM cache at memory speed rather than hitting the API Server over the network. Because multiple controllers inside the same Operator binary can share a single informer instance, the Operator maintains only one watch connection per resource type, keeping memory usage and API Server load low.

3. Resource Event Handlers and the Rate-Limiting WorkQueue

As the SharedInformer updates its local cache, it invokes registered callback functions (AddFunc, UpdateFunc, and DeleteFunc). Well-designed Operators never execute heavy reconciliation logic inside these callbacks. Instead, the event handler simply extracts the object's namespace/name identifier (or maps a child resource event back to its parent Custom Resource key) and pushes that string key into a WorkQueue.
The WorkQueue provides three essential guarantees for production stability:

  • Deduplication: If a Custom Resource is modified five times in 50 milliseconds while a worker is busy, the queue collapses duplicate keys so the reconciler processes the latest state once instead of running five redundant loops.
  • Concurrency safety: Multiple worker goroutines can pull from the queue in parallel, while the queue guarantees that two workers never reconcile the exact same namespace/name key simultaneously.
  • Exponential backoff: If a reconciliation attempt fails because a downstream API is temporarily unreachable, the controller requeues the key with an exponential delay so it does not hammer failing dependencies.

4. The Reconciliation Loop (Reconcile)

Worker goroutines continuously pop keys from the WorkQueue and pass them into the Reconcile(ctx, req) function. Inside Reconcile, the Operator fetches the latest Custom Resource from the SharedInformer cache, inspects all owned child resources in the cluster, and calculates the actions needed to align reality with .spec. Every operation inside Reconcile must be idempotent: running the exact same reconciliation logic ten times in a row on an already healthy cluster must produce zero unnecessary mutations.

How Custom Resource Definitions (CRDs) Extend the Kubernetes API

Out of the box, the Kubernetes API Server only understands native resources like Pods, ConfigMaps, and Deployments. To give an Operator its own domain vocabulary, you install a CustomResourceDefinition manifest into the cluster.
As soon as the CRD is applied, kube-apiserver dynamically registers a new RESTful HTTP endpoint and enforces structural OpenAPI v3 schema validation on every incoming object. For Namespaced CRDs, this endpoint lives at /apis/<group>/<version>/namespaces/<namespace>/<plural>, whereas Cluster-scoped CRDs (such as ClusterIssuer in cert-manager) omit the namespace segment and register at /apis/<group>/<version>/<plural>. From that point forward, kubectl, Helm, ArgoCD, and RBAC policies treat your custom resource identically to native Kubernetes objects.
For example, a platform team might define a PostgresCluster custom resource that abstracts away StatefulSets, headless Services, secrets, and backup cron jobs behind a clean interface:
YAML

apiVersion: databases.devopsinside.com/v1alpha1
kind: PostgresCluster
metadata:
  name: payments-db
  namespace: production
spec:
  instances: 3
  postgresVersion: "17.2"
  storageSize: 100Gi
  backupSchedule: "0 2 * * *"

Inside the Operator's Go code, the reconciliation loop translates that high-level specification into concrete Kubernetes primitives and operational API calls:
Go

func (r *PostgresClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	var cluster dbv1alpha1.PostgresCluster
	if err := r.Get(ctx, req.NamespacedName, &cluster); err != nil {
		// Ignore not-found errors after deletion; Kubernetes garbage collection
		// cleans up owned child resources via ownerReferences.
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}

	// 1. Reconcile the underlying StatefulSet against spec.instances and spec.postgresVersion
	if err := r.reconcileStatefulSet(ctx, &cluster); err != nil {
		return ctrl.Result{}, err
	}

	// 2. Check primary/replica health; requeue without error backoff if replication is still syncing
	readyReplicas, ready, err := r.reconcileReplicationTopology(ctx, &cluster)
	if err != nil {
		return ctrl.Result{}, err
	}
	if !ready {
		return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
	}

	// 3. Update the /status subresource to reflect current observed state
	cluster.Status.ReadyInstances = readyReplicas
	cluster.Status.ObservedGeneration = cluster.Generation
	if err := r.Status().Update(ctx, &cluster); err != nil {
		return ctrl.Result{}, err
	}

	return ctrl.Result{}, nil
}

Notice how clean that separation is: application teams only author a 12-line PostgresCluster YAML manifest, while the Operator handles StatefulSet creation, replication topology checks, and status reporting behind the scenes.

Essential Production Mechanics: OwnerReferences, Finalizers, and Status Subresources

Writing a proof-of-concept reconciliation loop takes a few dozen lines of code, but making an Operator safe for production clusters requires three core Kubernetes mechanisms.

OwnerReferences and Cascading Garbage Collection

When an Operator creates a StatefulSet, Service, or Secret on behalf of a PostgresCluster, it attaches an ownerReferences entry to each child object's metadata pointing back to the parent Custom Resource's UID. If a user later runs kubectl delete postgrescluster payments-db, the built-in Kubernetes garbage collector automatically traces those ownerReferences and deletes every child resource in the proper dependency order without the Operator having to write manual cleanup code for internal cluster objects.

Finalizers for External Resource Cleanup

ownerReferences only work for objects stored inside Kubernetes. If your Operator provisions external cloud infrastructure (such as an AWS S3 backup bucket, a cloud load balancer, or an external DNS record), standard deletion would remove the Custom Resource from etcd before the Operator has a chance to clean up those external resources, leaving orphaned infrastructure behind.
To prevent premature deletion, Operators add a string entry to metadata.finalizers on the Custom Resource. When a user deletes an object that has a finalizer, the API Server does not immediately remove it from etcd. Instead, it sets a metadata.deletionTimestamp field and puts the object into a read-only terminating state. The Operator's reconciliation loop detects deletionTimestamp, deletes the external S3 bucket or DNS record, removes its finalizer string from metadata.finalizers, and updates the object. Only when metadata.finalizers becomes empty does the API Server permanently remove the Custom Resource.

Separating .spec from .status to Prevent Reconcile Storms

Every time a reconciliation loop updates .status at the end of Reconcile(), the API Server emits a MODIFIED watch event for that Custom Resource. If your SharedInformer triggers a new reconciliation on every MODIFIED event blindly, updating .status will immediately trigger another reconcile, which updates .status again, creating an infinite CPU-burning loop.
Production Operators solve this by enabling the /status subresource in the CRD schema and scoping predicate.GenerationChangedPredicate{} specifically to the primary Custom Resource watch (for example, For(&dbv1alpha1.PostgresCluster{}, builder.WithPredicates(predicate.GenerationChangedPredicate{}))). When the /status subresource is enabled, Kubernetes increments metadata.generation only when .spec changes, leaving metadata.generation untouched during .status updates.
Scoping this predicate to the primary resource rather than applying it globally via WithEventFilter(...) is critical: if you filter all watches by generation change, the Operator will ignore .status updates on owned child resources (such as a StatefulSet whose readyReplicas count drops after a Pod crash), because child .status updates do not increment metadata.generation either. By keeping Owns(...) watches unfiltered and tracking status.observedGeneration on the primary resource, the Operator reacts immediately to child health changes while staying idle after its own status updates.

The Kubernetes Operator Capability Maturity Model

Not every Operator provides full autonomous failover and self-tuning. The CNCF and Operator Framework categorize Operators across five maturity phases so platform engineers can evaluate what a given Operator actually automates before adopting it in production:

5 Common Mistakes When Building or Running Kubernetes Operators

  1. Bypassing the Informer cache to query the API Server directly: Creating uncached API clients inside Reconcile() forces direct network reads against kube-apiserver and etcd on every reconciliation cycle, causing severe API throttling in large clusters. Always read through the SharedInformer cache.
  2. Mutating .spec inside the reconciliation loop: An Operator owns .status, while users or GitOps controllers (such as ArgoCD or Flux) own .spec. If an Operator overwrites fields in .spec, it triggers endless reconciliation loops and fights with GitOps drift detection. Use mutating admission webhooks for defaulting .spec values instead.
  3. Leaving namespaces stuck in Terminating due to stale Finalizers: If an Operator Pod is uninstalled before its Custom Resources are deleted, those Custom Resources retain their metadata.finalizers with no controller left to clear them, blocking namespace deletion indefinitely. Always delete Custom Resources before removing the Operator Deployment.
  4. Granting cluster-wide wildcard RBAC permissions: Many third-party Operators request ClusterRole rules with * verbs across all namespaces. Scope RBAC permissions strictly to the specific API groups, resources, and namespaces the Operator actually manages.
  5. Writing a custom Operator for simple stateless applications: An Operator introduces ongoing maintenance, CRD versioning overhead, and cluster-level RBAC surface area. If your application does not require custom runtime state orchestration, Helm charts or Kustomize overlays are simpler and safer.

Frequently Asked Questions

What is the difference between a Kubernetes Controller and an Operator?

A Kubernetes controller is any control loop that watches cluster state through the API Server and makes changes to move current state toward desired state. A Kubernetes Operator is a specialized controller that uses Custom Resource Definitions (CRDs) to manage complex, domain-specific applications (such as databases, message queues, or certificate authorities) using encoded operational knowledge.

Does a Kubernetes Operator run inside the Kubernetes control plane?

No. While built-in controllers run inside kube-controller-manager on control plane nodes, custom Operators run as ordinary Pods on worker nodes, typically managed by a standard Deployment with leader election enabled for high availability. They communicate with the control plane over HTTPS using a mounted ServiceAccount token.

What is a reconciliation loop in Kubernetes?

A reconciliation loop is an idempotent, level-triggered control cycle that compares a resource's desired state (.spec) against the actual observed state of the cluster (.status and live child objects), executes corrective API calls if drift is detected, and repeats whenever relevant cluster resources change.

Which tools and languages are most commonly used to build Kubernetes Operators?

Go is the dominant language for building Kubernetes Operators because Kubernetes itself and its official client-go library are written in Go. Most production Operators are scaffolded using Kubebuilder or the Operator SDK, both of which build on top of the controller-runtime framework. Teams also build Operators in Rust (kube-rs), Python (Kopf), and Java (Java Operator SDK).

Key Takeaways

  • Controllers are the foundation: Every Operator is a custom controller paired with Custom Resource Definitions (CRDs) to automate stateful, domain-specific operational tasks.
  • Level-triggered logic guarantees convergence: Operators use watch events as triggers to compare full desired state (.spec) against current state, ensuring recovery even if events are missed during restarts.
  • Informers and WorkQueues protect the control plane: SharedInformers cache cluster state in local memory, while rate-limiting WorkQueues deduplicate keys and prevent concurrent race conditions.
  • Production safety relies on Kubernetes primitives: ownerReferences handle cascading garbage collection, finalizers ensure external cloud resources are cleaned up before deletion, and GenerationChangedPredicate on primary watches prevents status-update reconcile loops.

Final Thoughts

Kubernetes Operators remove the manual toil of running stateful software on dynamic infrastructure by turning runbooks into continuous, self-healing code. Understanding what happens beneath the CRD manifest, from HTTP/2 watch streams and SharedInformer caches to WorkQueues and finalizers, makes it far easier to debug stalled reconciliations, tune Operator memory limits, and decide when an Operator is genuinely the right tool for your platform.