---
title: "Kubernetes Controllers Explained: The Reconciliation Loop"
description: "How Kubernetes controllers work: the reconciliation loop, informers and the workqueue, kube-controller-manager, owner references, finalizers and operators."
url: "https://opsfolk.com/blog/kubernetes-controllers-explained-reconciliation-loop"
author: "admin"
published: "2026-12-02T13:41:02.360Z"
updated: "2026-12-03T22:28:23.415Z"
category: "Kubernetes"
series: "Kubernetes Internals: How a Cluster Really Works"
series_part: 8
series_parts: 9
series_url: "https://opsfolk.com/blog/series/kubernetes-internals-how-a-cluster-really-works"
reading_minutes: 25
image: "https://media.opsfolk.com/2026/12/416f20f973ae236986113b1c-2400x1350.webp"
---

# Kubernetes Controllers Explained: The Reconciliation Loop

You run `kubectl scale deployment web --replicas=5`, and a second later two new Pods exist. Yet `kubectl` never created a Pod. It changed one number in one object, and the API server stored it. Everything that followed was done by programs that were watching: a **controller** noticed the Deployment had changed, another noticed its ReplicaSet had, the scheduler placed the new Pods, and a kubelet started them. None of them was told to act. Each one saw that the cluster was not yet what an object said it should be, and closed the gap.

That pattern, the **reconciliation loop**, is how almost everything in Kubernetes works. In the first part of *Kubernetes Internals: How a Cluster Really Works*, the API server ended its job by storing an object; in the second, the scheduler placed Pods that a ReplicaSet had created. This part opens the controllers themselves: what a control loop is, how a controller watches, queues and reconciles, which controllers run in `kube-controller-manager`, how owners and finalizers decide what gets deleted, and how to write and debug a controller of your own.

*New to the series? Start with [Kubernetes API Server Explained: The Life of a Request](https://opsfolk.com/blog/kubernetes-api-server-explained-the-life-of-a-request), then [How the Kubernetes Scheduler Works](https://opsfolk.com/blog/kubernetes-scheduler-explained-why-pods-stay-pending).*

## What Is a Kubernetes Controller?

> **Definition:** A Kubernetes controller is a control loop that watches the cluster's state through the API server, compares the state it observes with the desired state written in an object's `spec`, and makes changes, through the API server, to bring the two closer. It then records what it saw in the object's `status`, and repeats.

The Kubernetes documentation compares a controller to a thermostat. You set a temperature: that is the desired state. The thermostat reads the room: that is the observed state. When the two differ, it turns the heating on or off. It never "runs" a plan to reach 21 °C; it keeps comparing, forever, and acts on the difference.

In Kubernetes, the desired state is the `spec` you write, and the observed state is what exists: Pods, nodes, endpoints, volumes, or something outside the cluster such as a cloud load balancer. Three facts frame the rest of this article:

- **A controller talks to the API server, and to nothing else in the cluster.** It does not call the scheduler, the kubelet or another controller. The Job controller does not run a Pod; it creates a Pod object, and other components react. Controllers cooperate only through the objects they read and write.
- **A controller acts on state, not on events.** It is told *that* something changed, not *what to do*. Whatever the change, it reads the current state and computes the whole difference again. This is what "level-triggered" means, and it is why a controller survives missed events, restarts and crashes.
- **Each controller owns one job.** The Deployment controller manages ReplicaSets, and the ReplicaSet controller manages Pods. Neither does the other's work. Complex behaviour, such as a rolling update, comes from small controllers chained through objects.

### Spec, Status and Generation

Most Kubernetes objects split into the two halves a controller works between:

| Field | Written by | Says |
| --- | --- | --- |
| `spec` | You, or a higher-level controller | What should be true |
| `status` | The controller that owns the object | What it last observed |
| `metadata.generation` | The API server, on every change to `spec` | Which version of the spec this is |
| `status.observedGeneration` | The controller, after it reconciles | Which version of the spec the status describes |

`spec` and `status` are written through different endpoints. A change to `spec` never touches `status`, and the `status` subresource only changes `status`. So a controller can report what it sees without overwriting the spec you just changed, and RBAC can let a controller write status without letting it change what you asked for. When `observedGeneration` equals `generation`, the controller has seen your latest change; when it is behind, the status is still about an older spec.

## The Reconciliation Loop at a Glance

**How a controller reconciles an object, step by step:**

1. **Observe.** The controller keeps a cache of the objects it cares about, filled and kept current by a watch on the API server.
2. **Get notified.** When an object changes, the controller puts the object's key, `namespace/name`, on a work queue.
3. **Read.** A worker takes the key and reads the object *as it is now* from the cache. The change that triggered it does not matter any more.
4. **Diff.** It compares the desired state with what exists: "the ReplicaSet wants 5 Pods, and 3 match its selector".
5. **Act.** It sends the writes that close the gap to the API server: create 2 Pods, or delete one, or update an object.
6. **Report.** It writes what it observed to `status`.
7. **Repeat.** Its own writes, and anyone else's, come back through the watch as new changes, and the loop runs again. When the diff is empty, it does nothing.

If anything fails, such as a write refused or an object that changed under it, the controller returns an error and the key goes back on the queue, to be tried again later.

![A controller observes objects through a watch, compares the spec with what exists, writes the difference through the API server, reports status, and its writes return as watch events.](https://media.opsfolk.com/2026/12/09c3fa5550ed7e753d803b5a-1344x656.webp)

### Level-Triggered, Not Edge-Triggered

An **edge-triggered** system acts on each change: "a Pod was deleted, so create one". If the message is lost, or the program crashes before it acts, the change is gone for good. A **level-triggered** system acts on the state: "there are 4 Pods and there should be 5, so create one". It does not matter how the cluster got there, or how many changes were missed on the way.

Kubernetes controllers are level-triggered in this sense, even though they are woken by events. The event is only a hint that it is worth looking again. That gives them properties that are easy to take for granted:

- **A missed event is harmless.** The next one, or the next periodic resync, leads to the same comparison of the whole state.
- **A restart is harmless.** A controller that starts keeps no memory of what it was doing. It lists every object, and reconciles each one from scratch.
- **Many events cost one reconcile.** Ten changes to the same Deployment while its key waits in the queue make a single pass, because that pass reads the latest state anyway.

The price is that **every reconcile must be idempotent**: running it twice in a row, on the same state, must do no more than running it once. A reconciler that "creates a Service" must first check whether the Service exists.

## Inside a Controller: Informers, Cache and Workqueue

Watching the API server well is harder than it sounds. A controller that sent a `GET` for every object it needed, on every reconcile, would load the API server more than the rest of the cluster combined. So every controller in Kubernetes, the built-in ones and almost every operator, is built from the same parts of `client-go`, the Go client library:

| Part | What it does |
| --- | --- |
| **Reflector** | Lists every object of one type once, then watches from that list's `resourceVersion`, and puts each change it receives into a queue of deltas |
| **DeltaFIFO** | Holds those changes in order, per object, until the informer has handled them |
| **Indexer** (the cache) | An in-memory, indexed copy of every object, kept current from the deltas. Reconcilers read from it, not from the API server |
| **Event handlers** | `OnAdd`, `OnUpdate`, `OnDelete`: called for each change. In a controller they do one thing, put a key on the workqueue |
| **Workqueue** | A queue of keys, with de-duplication, one worker per key at a time, delays and rate-limited retries |
| **Workers** | A few goroutines that take keys from the queue and call the reconcile function |

![Inside a controller, a reflector watches the API server into a cache; handlers turn each change into a key on a workqueue; workers reconcile keys from the cache and write to the API server.](https://media.opsfolk.com/2026/12/c33556f2ef7358bee6507187-1344x872.webp)

### Informers and the Shared Cache

An **informer** is the reflector, the DeltaFIFO and the indexer together, for one resource type. A **shared informer** is one informer that several controllers use. `kube-controller-manager` runs dozens of controllers, and many of them watch Pods; with a shared informer factory there is one watch on Pods and one copy of every Pod in memory, and each controller registers its own handlers on it.

Three details explain much of a controller's behaviour:

- **Reads come from the cache, and the cache can be behind.** A controller that has just created a Pod may not see it in its cache for a few milliseconds. Code that does not allow for this creates the Pod twice.
- **A watch can expire.** The API server keeps a window of recent changes, and a watch that asks for a `resourceVersion` older than that window is answered with `410 Gone`. The reflector then lists everything again and carries on from the new list. Nothing is missed, because the controller compares states, not events.
- **A resync replays the cache.** Each informer can be given a resync period, after which every object in its cache is passed to the update handler again, as if it had changed. It does not ask the API server for anything. In `kube-controller-manager`, `--min-resync-period` defaults to 12 hours, and each informer's period is picked at random between that and twice that. A resync is a safety net for controllers whose state lives outside the cluster, not the way a controller normally learns about changes.

### The Workqueue: Keys, Not Events

The event handlers do not reconcile anything. They compute the object's key, often `namespace/name` of the object itself or of its owner, and add it to the workqueue. The workqueue then makes three promises:

- **A key that is already waiting is not added twice.** However many changes arrive while a key waits, it is processed once, with the state as it is when a worker takes it.
- **A key is never processed by two workers at once.** If the key is added again while a worker has it, it is marked, and put back in the queue as soon as the worker is done.
- **A failed key is retried later, not at once.** The reconciler returns an error, and the controller adds the key back with a rate limit.

`client-go`'s default rate limiter for controllers combines two limits and uses whichever is longer. The first is per key: the delay starts at 5 ms and doubles with each failure in a row, up to 1000 seconds. The second is for the whole queue: a token bucket of 10 retries a second, with a burst of 100. When a key succeeds, the controller calls `Forget`, and its count of failures goes back to zero.

The canvas below runs three keys through a workqueue, slowed down so that the delays can be seen. Each key receives changes in bursts, as a rollout or a node failure would cause. Watch how many changes become one reconcile, and what happens to `api` when its reconcile keeps failing.

**A controller's workqueue merging changes and backing off.** Three keys, web, api and db, over 20 s, with two workers. Each key is changed in three bursts: a dot per change, hollow when it merged into the key already waiting. Bars are reconciles. With 5 changes a burst, web and db each turn 15 changes into 9 reconciles. While api fails, until 12 s, its failed reconciles are red and each retry waits longer, dashed, unless a new change queues it at once; it succeeds at 13.9 s, after 9 failures. Times are slowed down fifty times. The controls set the changes a burst and whether api fails.

With five changes a burst, `web` and `db` each turn 15 changes into 9 reconciles. The first change of a burst queues the key; the ones that arrive while it waits merge into it; one that arrives while a worker has it brings it back once more, after. `api` fails until 12 s: each retry waits longer than the last, until a new burst of changes queues it at once, since a change is never held back by the backoff. Once its dependency is back, the next retry succeeds, and its count of failures starts again from zero.

### Expectations: When the Cache Is Behind

The ReplicaSet controller shows how a built-in controller handles the lag of its own cache. When it decides to create 3 Pods, it first records an **expectation**: "I expect to see 3 creations for this ReplicaSet". It then creates them. Until its informer has seen all 3 arrive, or five minutes have passed, it does not reconcile that ReplicaSet again; a second pass would count only the Pods in the cache and create them again.

It also creates Pods in growing batches, a "slow start": 1, then 2, then 4, then 8, and stops at the first batch where a creation fails. A ReplicaSet whose Pods are all refused, by a quota or an admission webhook, then sends one failing request instead of hundreds. And one pass never creates or deletes more than 500 Pods.

## kube-controller-manager: The Built-In Controllers

Most of Kubernetes' own controllers run in a single binary, `kube-controller-manager`, as goroutines in one process sharing informers. On a kubeadm cluster, it runs as a static Pod on each control plane node:

```bash
kubectl get pods -n kube-system -l component=kube-controller-manager
```

Some of the controllers it runs, and what each one reconciles:

| Controller | Watches | Keeps true |
| --- | --- | --- |
| Deployment | Deployments, ReplicaSets | One ReplicaSet per Pod template, scaled for the rollout strategy |
| ReplicaSet | ReplicaSets, Pods | `spec.replicas` Pods match the selector |
| StatefulSet | StatefulSets, Pods, PVCs | Pods with stable names and volumes, created and updated in order |
| DaemonSet | DaemonSets, Nodes, Pods | One Pod on each matching node |
| Job, CronJob | Jobs, CronJobs, Pods | Pods run to completion; Jobs are created on schedule |
| Node lifecycle | Nodes, Leases | Unresponsive nodes are tainted, and their Pods evicted |
| EndpointSlice | Services, Pods | Each Service's EndpointSlices list the Pods that match it, and which are ready |
| Namespace | Namespaces | A deleted namespace's contents are deleted before the namespace |
| Garbage collector | Every resource with owners | Objects whose owners are gone are deleted |
| ServiceAccount, token | ServiceAccounts, Secrets | Each namespace has a `default` ServiceAccount |
| PersistentVolume binder | PVs, PVCs | Claims are bound to volumes, or provisioning is requested |
| Horizontal Pod Autoscaler | HPAs, metrics | The target's replicas follow its metrics |
| Disruption | PDBs, Pods | Each PodDisruptionBudget's status says how many Pods may be evicted |
| ResourceQuota | Quotas, and what they count | Each quota's usage is current |

A few flags shape how they run:

- **`--controllers`** picks which controllers start. The default, `*`, starts every controller that is on by default; a few, such as the bootstrap signer and the token cleaner, are off unless named.
- **`--concurrent-*-syncs`** sets the number of workers per controller: 5 for Deployments and ReplicaSets by default, 20 for the garbage collector. More workers means more objects reconciled at once, and more load on the API server.
- **`--kube-api-qps` and `--kube-api-burst`** limit how fast the whole process may write to the API server, so that a storm of reconciles cannot take it down.

### Leader Election: One Active Instance

On a control plane with three nodes, three copies of `kube-controller-manager` run, but only one of them works. Two copies of the ReplicaSet controller acting at once would each see 3 Pods missing and create 6. So they elect a leader with a **Lease** object, `kube-controller-manager` in `kube-system`:

```bash
kubectl get lease kube-controller-manager -n kube-system -o jsonpath='{.spec.holderIdentity}{"\n"}'
```

The leader renews the Lease every few seconds. By default the Lease lasts 15 seconds, the leader must renew it within 10, and the others try to take it every 2. If the leader stops renewing, perhaps because its node failed, another instance takes the Lease once it expires and starts its controllers, which begin by listing everything. Because controllers are level-triggered, the new leader needs nothing from the old one.

The **cloud-controller-manager** works the same way, for the controllers that talk to a cloud provider's API: it fills in a node's provider ID and addresses, deletes Node objects whose instance is gone, sets up routes, and creates a cloud load balancer for each Service of type `LoadBalancer`. It is the clearest example of a controller whose observed state is outside the cluster.

## Worked Example: Scaling a Deployment

Back to `kubectl scale deployment web --replicas=5`, with the Deployment's ReplicaSet at 3 running Pods. Five components act on it, and none of them calls another:

1. **The API server** stores the Deployment's new `spec.replicas` and increments `metadata.generation`. Every watch on Deployments receives the change.
2. **The Deployment controller** reconciles `default/web`. Its Pod template has not changed, so no rollout starts; the current ReplicaSet should simply have 5 replicas. It updates the ReplicaSet's `spec.replicas` from 3 to 5.
3. **The ReplicaSet controller** reconciles the ReplicaSet: 5 wanted, 3 match its selector. It records an expectation of 2 creations and creates 2 Pods, each with an `ownerReference` pointing to the ReplicaSet.
4. **The scheduler** sees two Pods with no node, and binds each one to a node.
5. **The kubelet** on each chosen node sees a Pod bound to it, and starts its containers.

Then the status flows back up. The kubelet reports the Pods as Ready; the ReplicaSet controller counts 5 ready replicas in the ReplicaSet's status; the Deployment controller copies the totals into the Deployment's status, along with `observedGeneration`. The EndpointSlice controller, which watches Pods too, lists the two new Pods in the Service's EndpointSlices, and marks them ready once they are.

The canvas below is the ReplicaSet controller's part of that story, with the scheduler and the kubelet folded into "Pending" and "Running". Set the number of replicas, and press **Kill a Pod** to delete one while it runs.

**A ReplicaSet controller reconciling.** A ReplicaSet's Pods as squares: filled when running, dashed while pending, crossed out while terminating. It starts with 3 Pods; at 1 s spec.replicas becomes the Replicas setting, and the controller creates or deletes the difference: at 5, all five run about 4 s in. At 8 s a Pod is deleted and the controller creates a replacement. Observe, Diff and Act light up as it works. Kill a Pod deletes one more; two kills close together are handled in one pass.

At the default of 5, the controller counts 3 Pods 0.4 s after the change and creates 2, and all five run about 4 s in. The Pod deleted at 8 s is replaced the same way: the controller never learns *why* there are 4 Pods, only that there should be 5. Press **Kill a Pod** twice in quick succession, and a single pass creates both replacements: the key was still waiting when the second deletion arrived.

### How kubectl Knows a Rollout Is Done

`kubectl rollout status` reads nothing but status fields, and it reads them in order. It first waits for `status.observedGeneration` to reach `metadata.generation`: until then, the status describes an older spec, and saying "done" would be a lie. Then it waits for the updated, ready and available replica counts to reach the desired number.

```bash
kubectl get deployment web -o jsonpath='{.metadata.generation} {.status.observedGeneration}{"\n"}'
kubectl rollout status deployment/web --timeout=2m
```

If the rollout makes no progress for `progressDeadlineSeconds`, 600 by default, the Deployment controller sets the `Progressing` condition to `False` with the reason `ProgressDeadlineExceeded`, and `kubectl rollout status` exits with an error. The controller does not roll back on its own; the condition is a signal for you, or for your deployment tooling.

## Owners, Garbage Collection and Finalizers

Controllers create objects, and something has to delete them. Kubernetes answers with two mechanisms that are themselves controllers: owner references, which the garbage collector follows, and finalizers, which let a controller finish its work before an object goes.

### Owner References

Every Pod a ReplicaSet creates carries an owner reference to it:

```yaml
metadata:
  ownerReferences:
  - apiVersion: apps/v1
    kind: ReplicaSet
    name: web-7d4b9c6f5d
    uid: 3f1c2a9e-8b7d-4e21-9c55-0d6a1f2b7e40
    controller: true
    blockOwnerDeletion: true
```

- **`controller: true`** marks the one owner that manages the object. An object can have several owners, but only one controller. A ReplicaSet does not adopt a Pod that another controller already manages, even if its labels match.
- **`uid`** ties the reference to one object, not to a name: a ReplicaSet deleted and created again with the same name does not own the old Pods.
- **`blockOwnerDeletion`** matters for foreground deletion, below: the owner is not removed while this dependent exists.

An owner must be in the same namespace as its dependents, or cluster-scoped. A Pod cannot be owned by an object in another namespace.

### Cascading Deletion

When you delete an object that has dependents, the **garbage collector** in `kube-controller-manager` decides what happens to them, by the deletion's propagation policy:

| Policy | What happens | kubectl |
| --- | --- | --- |
| **Background** (the default) | The owner is deleted at once; the garbage collector then deletes its dependents | `kubectl delete deploy web` |
| **Foreground** | The owner stays, with a `deletionTimestamp` and the `foregroundDeletion` finalizer, until every dependent with `blockOwnerDeletion` is gone; then the owner is deleted | `--cascade=foreground` |
| **Orphan** | The owner is deleted, and its dependents are left, with the owner reference removed | `--cascade=orphan` |

Orphaning lets you replace an owner without restarting what it made. Delete a ReplicaSet with `--cascade=orphan` and its Pods keep running, with no controller; create a new ReplicaSet with the same selector, and it adopts them instead of creating new ones.

![Pods point to the ReplicaSet that owns them, and it to its Deployment. Deleting an owner deletes its dependents after it (background), before it (foreground), or not at all (orphan).](https://media.opsfolk.com/2026/12/095d8206291aaf3da34882c2-1344x864.webp)

### Finalizers: Work Before Deletion

A **finalizer** is a key in `metadata.finalizers`. While the list is not empty, a `DELETE` does not remove the object; the API server only sets `metadata.deletionTimestamp`, and the object stays, read-only except for its finalizers, until they are all removed. Each finalizer belongs to a controller, which sees the `deletionTimestamp`, does its clean-up, and removes its key:

- `kubernetes.io/pvc-protection` keeps a PersistentVolumeClaim while a Pod uses it.
- `foregroundDeletion` holds an owner during foreground deletion, as above.
- The `kubernetes` finalizer in a Namespace's `spec.finalizers` is the namespace controller's: it deletes everything in the namespace, then removes it.
- An operator adds its own, such as `example.com/cleanup`, to delete a cloud database before the custom resource that described it goes.

This is why objects get **stuck in Terminating**: a finalizer remains, and the controller that should remove it is not running, cannot finish, or no longer exists. Removing the finalizer by hand ends the wait, and skips whatever clean-up it guarded. Find out what that was first.

## Writing Your Own Controller: Operators

A **custom resource** adds a new type to the API server: a `CustomResourceDefinition` describes it, and from then on you can create, watch and list objects of that kind like Pods. A custom resource on its own is only data. An **operator** is a custom resource and a controller that reconciles it, usually to run a piece of software the way a person who knows it would: a database cluster, a certificate, a message queue.

Most operators in Go are built on **controller-runtime**, the library behind Kubebuilder and the Operator SDK. It wires the informers, the cache, the workqueue and the leader election for you, and leaves one function to write:

```go
func (r *BackupReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	var backup examplev1.Backup
	if err := r.Get(ctx, req.NamespacedName, &backup); err != nil {
		// Deleted since the key was queued: nothing to do.
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}

	// Desired state: one CronJob per Backup, owned by it.
	cron := &batchv1.CronJob{ObjectMeta: metav1.ObjectMeta{
		Name: backup.Name + "-backup", Namespace: backup.Namespace,
	}}
	_, err := controllerutil.CreateOrUpdate(ctx, r.Client, cron, func() error {
		cron.Spec.Schedule = backup.Spec.Schedule
		cron.Spec.JobTemplate = jobTemplateFor(&backup)
		return controllerutil.SetControllerReference(&backup, cron, r.Scheme)
	})
	if err != nil {
		return ctrl.Result{}, err // requeued with exponential backoff
	}

	// Observed state, through the status subresource.
	backup.Status.ObservedGeneration = backup.Generation
	backup.Status.CronJob = cron.Name
	if err := r.Status().Update(ctx, &backup); err != nil {
		return ctrl.Result{}, err
	}
	return ctrl.Result{}, nil
}
```

The function receives a key, not an event, and returns one of three outcomes:

| Return | What controller-runtime does |
| --- | --- |
| `ctrl.Result{}, nil` | Done. The failure count is reset; the key comes back only on the next change |
| `ctrl.Result{RequeueAfter: d}, nil` | Done for now, check again after `d`: for state outside the cluster that no watch reports |
| `ctrl.Result{}, err` | Failed. The result is ignored, and the key is retried with the exponential backoff above |

The controller also has to say what it watches, so that a change to the CronJob it owns brings its Backup back to the queue:

```go
func (r *BackupReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&examplev1.Backup{}).
		Owns(&batchv1.CronJob{}).
		Complete(r)
}
```

`Owns` maps each CronJob event to the key of its controller owner. If someone deletes the CronJob, the Backup is reconciled, and the CronJob is created again.

### Rules of a Good Reconciler

- **Idempotent.** Read what exists, and create, change or delete only the difference. `CreateOrUpdate` and server-side apply both help.
- **Stateless between calls.** Everything the reconciler needs is in the object, the cluster or the system it manages. A variable that remembers "I already created it" is wrong after the next restart.
- **One owner per field.** Two controllers writing the same field fight forever, each undoing the other on every pass.
- **Status from observation.** Write what you saw, set `observedGeneration`, and use conditions with a `reason` that a person can search for.
- **Expect conflicts.** An update with a stale `resourceVersion` is refused with `409 Conflict`: "the object has been modified". Return the error and let the next pass read the new version; do not retry in a loop inside the reconciler.
- **Requeue on purpose.** A reconciler that always returns `RequeueAfter: time.Second`, or that writes status on every pass and so triggers itself, keeps the API server and its own queue busy for nothing.
- **Finalizers only for clean-up outside the cluster.** Objects inside it should be owned, and the garbage collector will delete them.

## Debugging Controllers

When an object does not reach the state its spec describes, the question is always the same: which controller should be acting on it, did it see the change, and what did it decide?

**1. Has the controller seen the latest spec?**

```bash
kubectl get deployment web -o jsonpath='{.metadata.generation} {.status.observedGeneration}{"\n"}'
```

If `observedGeneration` is behind, the controller has not reconciled your change: it is not running, not the leader, or failing before it writes status.

**2. What did it say?** Controllers report through events and conditions:

```bash
kubectl describe replicaset web-7d4b9c6f5d | sed -n '/^Events:/,$p'
kubectl get deployment web -o jsonpath='{range .status.conditions[*]}{.type}={.status} {.reason}: {.message}{"\n"}{end}'
```

A ReplicaSet that cannot create Pods says why in a `FailedCreate` event: a quota exceeded, a webhook that refused, a missing ServiceAccount.

**3. Is the controller running, and leading?**

```bash
kubectl get lease kube-controller-manager -n kube-system -o yaml
kubectl logs -n kube-system -l component=kube-controller-manager --tail=100
```

A `renewTime` far in the past means no instance holds the Lease, and no built-in controller is working. For an operator, check its Deployment, its own Lease and its logs.

**4. Is its queue keeping up?** `kube-controller-manager` and controller-runtime both expose the workqueue's metrics, labelled by the queue's `name`:

- `workqueue_depth`: keys waiting now. A queue that grows and never drains is behind.
- `workqueue_adds_total` and `workqueue_retries_total`: changes coming in, and keys retried after an error. A high share of retries means reconciles are failing.
- `workqueue_queue_duration_seconds`: how long a key waits before a worker takes it.
- `workqueue_work_duration_seconds`: how long a reconcile takes.
- `workqueue_longest_running_processor_seconds`: a reconcile that is stuck shows here first.

```text
sum by (name) (rate(workqueue_retries_total[5m]))
```

### Common Symptoms and Their Causes

| Symptom | Likely cause | What to do |
| --- | --- | --- |
| Object stuck in `Terminating` | A finalizer remains and its controller is gone or failing | Find the finalizer's owner and fix it; remove the finalizer by hand only if you know what it guarded |
| Namespace stuck in `Terminating` | Content it cannot delete: an API service that is down, or objects with finalizers | Read the namespace's conditions, such as `NamespaceContentRemaining` and `NamespaceDeletionDiscoveryFailure` |
| `observedGeneration` behind `generation` | The controller is not running, not leading, or failing early | Lease, logs, and the controller's own Pod |
| Rollout never finishes | New Pods are not becoming ready, or cannot be created | `Progressing` condition, ReplicaSet `FailedCreate` events, Pod status |
| `409 Conflict` in a controller's logs | Normal under concurrent writes | Nothing, if they resolve on the next pass; many in a row mean two writers fight over one object |
| Two controllers undo each other | Two owners of one field, such as an HPA and a GitOps tool both setting `replicas` | Give the field one owner: leave `replicas` out of the manifest when an HPA scales it |
| An operator's queue never drains | A reconcile that triggers itself, or a retry on every pass | Watch `workqueue_adds_total`; do not write status when nothing changed |

## Key Takeaways

- A controller is a loop that compares the desired state in `spec` with the state it observes, acts through the API server to close the gap, and records what it saw in `status`.
- Controllers are level-triggered: an event only says "look again", and each reconcile computes the whole difference from the current state. Missed events and restarts are harmless, and reconciles must be idempotent.
- Every controller is built from the same parts: a shared informer that lists and watches into a cache, handlers that queue keys, and workers that reconcile them.
- The workqueue merges repeated changes to a key, never gives one key to two workers, and retries failures with an exponential backoff from 5 ms to 1000 s.
- `kube-controller-manager` runs the built-in controllers in one process, and a Lease makes sure only one instance acts at a time.
- `observedGeneration` tells you whether a controller has seen your latest change; `kubectl rollout status` waits for it before anything else.
- Owner references let the garbage collector delete dependents; finalizers let a controller clean up before an object is removed, and explain objects stuck in `Terminating`.
- An operator is a custom resource plus a controller that reconciles it, usually written with controller-runtime.

## FAQ

### What is a controller in Kubernetes?

A controller is a program that runs a control loop: it watches objects through the API server, compares what their `spec` asks for with what exists, and creates, updates or deletes objects to close the difference. The Deployment, ReplicaSet, Job and Node controllers are examples, and most of them run in `kube-controller-manager`.

### What is the reconciliation loop in Kubernetes?

It is the cycle each controller repeats: observe the current state, compare it with the desired state, act to bring them closer, report the result in `status`, and start again when anything changes. Because each pass looks at the whole state, it does not matter how many changes happened in between.

### What is the difference between a controller and an operator?

Every operator is a controller. "Operator" usually means a controller for a custom resource, written to manage one application, such as a database or a certificate, with the knowledge a human operator would otherwise apply by hand. The built-in controllers manage Kubernetes' own resources.

### What does level-triggered mean in Kubernetes?

It means a controller acts on the current state, not on the sequence of events. An event only tells it that something may have changed; the controller then reads the object as it is now and computes what to do. A lost event, a restart or many events in a row all lead to the same result.

### What does kube-controller-manager do?

It is the control plane component that runs Kubernetes' built-in controllers in one process: Deployments, ReplicaSets, StatefulSets, DaemonSets, Jobs, nodes, endpoints, namespaces, garbage collection and more. Several instances can run for high availability, but only the one holding the `kube-controller-manager` Lease in `kube-system` acts.

### Why is my Kubernetes resource stuck in Terminating?

The object has a `deletionTimestamp` and at least one finalizer that has not been removed. The controller that owns the finalizer has not finished its clean-up, or is not running. Find which controller adds that finalizer and why it is stuck before removing the finalizer yourself, since removing it skips the clean-up.

### How often does a Kubernetes controller reconcile?

Whenever something it watches changes, as soon as a worker is free, and again after a failure, with a growing delay. Informers can also resync on a timer, replaying every cached object; in `kube-controller-manager` that happens every 12 to 24 hours by default. A controller that manages state outside the cluster can ask to be called again after a set time with `RequeueAfter`.

## What's Next

You have followed the loop that sits behind every other part of this series. The API server stores what you asked for; controllers keep comparing it with what exists; the [scheduler](https://opsfolk.com/blog/kubernetes-scheduler-explained-why-pods-stay-pending) and the [kubelet](https://opsfolk.com/blog/kubelet-and-container-runtimes-how-kubernetes-runs-pods) are, in the end, controllers of their own, for a Pod's node and its containers; and [etcd](https://opsfolk.com/blog/etcd-kubernetes-raft-quorum-backup-restore) holds the state they all reconcile. One layer is left: the network the Pods talk over, which [Kubernetes Networking Deep Dive: CNI, Overlays and eBPF](https://opsfolk.com/blog/kubernetes-networking-cni-overlays-ebpf) opens up, from CNI plugins to eBPF. When something does not converge, keep the [Kubernetes Troubleshooting](https://opsfolk.com/blog/kubernetes-troubleshooting-crashloopbackoff-oomkilled) playbook close, and see the [whole series](https://opsfolk.com/blog/series/kubernetes-internals-how-a-cluster-really-works) for every part.
