The API and the loopLesson 7 of 8
- Desired state and the reconcile loop, not reconciled
- Control plane and nodes, not reconciled
- API machinery: groups, versions and resource versions, not reconciled
- kubectl and kubeconfig, not reconciled
- Namespaces, labels and annotations, not reconciled
- Declarative management and server-side apply, not reconciled
- Owners, finalizers and garbage collection, not reconciled
- Custom resources and operators, not reconciled
Owners, finalizers and garbage collection
A delete starts a process. Dependents name their owners, the garbage collector cascades the delete, and finalizers hold an object until its cleanup is done, which is why things sit in Terminating.
Shows the lesson one block at a time. Arrow keys step, number keys jump to a scene, and Escape returns to the page where you were.
kubectl delete feels final, but the API server rarely removes an object the moment you ask. A Deployment owns ReplicaSets that own pods, and something has to delete those too. A PersistentVolume may still be mounted, a Service may still hold a cloud load balancer, and a custom resource may stand for a database that needs a final backup. Kubernetes handles all of this with two pieces of metadata, owner references and finalizers, and with controllers that act on them. When you understand both, a deletion that hangs stops being a mystery and becomes a question with a short list of answers.
Reconcile, in 7 scenes
ownerReferences
An object that exists because of another object is a dependentAn object whose metadata.ownerReferences names another object as its owner. When every owner is gone, the garbage collector deletes the dependent.. The deployment controller creates a ReplicaSet and writes the Deployment into the ReplicaSet’s metadata.ownerReferences; the ReplicaSet controller does the same for each pod. You can walk the chain from either end:
kubectl -n orders get pods -o custom-columns=POD:.metadata.name,OWNER-KIND:.metadata.ownerReferences[0].kind,OWNER:.metadata.ownerReferences[0].name
POD OWNER-KIND OWNER api-6fbf78644-2cv2c ReplicaSet api-6fbf78644 api-6fbf78644-cfxzk ReplicaSet api-6fbf78644 api-6fbf78644-tfgs5 ReplicaSet api-6fbf78644
kubectl -n orders get replicasets -o jsonpath='{.items[0].metadata.ownerReferences}'
[{"apiVersion":"apps/v1","blockOwnerDeletion":true,"controller":true,"kind":"Deployment","name":"api","uid":"67e5a683-592b-4265-8cb5-e3bbd98e5941"}]An owner reference carries the owner’s apiVersion, kind, name and uid. The uid is the real identity. If you delete a Deployment and create another with the same name, the replacement has a different uid, and dependents that point at the old uid have no owner. Two flags complete the reference:
controller: truemarks the controller referenceThe one owner reference on an object withcontroller: true. It names the controller responsible for the object; an object can have many owners but at most one controller..kubectl describeprints it asControlled By:. Controllers only act on objects they control, so this flag is how a ReplicaSet knows a pod is its own.blockOwnerDeletion: truelets the dependent hold up its owner during foreground deletion. Built-in controllers set it on everything they create. Where theOwnerReferencesPermissionEnforcementadmission plugin is enabled, setting it requires permission to update the owner’sfinalizerssubresource, so a user cannot use the flag to hold up the deletion of an object they do not control.
Ownership has a scope rule. A namespaced dependent can have owners in its own namespace or cluster-scoped owners; a cluster-scoped dependent can only have cluster-scoped owners. Cross-namespace references are disallowed by design. The garbage collector treats a namespaced owner in another namespace as absent, so the dependent is deleted once no valid owner remains, and it records a warning event with reason OwnerRefInvalidNamespace on the dependent. A cluster-scoped object that names a namespaced owner is never collected at all.
Adoption and release
Controllers find their objects by label selector, then confirm ownership by controller reference. When an object matches a controller’s selector and has no controller reference, the controller adopts it by adding one. When an object it owns stops matching, the controller releases it by removing the reference, and then creates a replacement to keep the count right:
kubectl -n orders label pod api-6fbf78644-2cv2c app.kubernetes.io/name=api-debug --overwrite
pod/api-6fbf78644-2cv2c labeled
kubectl -n orders rollout status deployment/api
Waiting for deployment "api" rollout to finish: 2 of 3 updated replicas are available... deployment "api" successfully rolled out
kubectl -n orders get pods -L app.kubernetes.io/name
NAME READY STATUS RESTARTS AGE NAME api-6fbf78644-2cv2c 1/1 Running 0 31s api-debug api-6fbf78644-cfxzk 1/1 Running 0 31s api api-6fbf78644-cgk5t 1/1 Running 0 1s api api-6fbf78644-tfgs5 1/1 Running 0 31s api
kubectl -n orders get pods -o custom-columns=POD:.metadata.name,OWNER:.metadata.ownerReferences[0].name
POD OWNER api-6fbf78644-2cv2c <none> api-6fbf78644-cfxzk api-6fbf78644 api-6fbf78644-cgk5t api-6fbf78644 api-6fbf78644-tfgs5 api-6fbf78644
The released pod keeps running with no owner, out of the Service if the Service selected on the same label. That makes relabelling a standard way to pull a misbehaving pod aside for debugging without losing it. Adoption also explains why overlapping selectors are dangerous: two controllers whose selectors match the same pods race to adopt them.
The garbage collector
The garbage collectorA controller in kube-controller-manager that maintains a graph of owner references and deletes dependents whose owners no longer exist. is one of the controllers in kube-controller-manager. It watches every resource type that supports deletion, builds a graph of who owns whom, and reacts to changes in that graph. It is a reconcile loop like any other: the desired state is that every dependent has at least one live owner, and the action is to delete those that do not.
ExplainerThe reconcile loop
The Deployment goes at once; the garbage collector deletes its dependents after.
Each action runs as a kubectl command; it shows here.
Watch stream0 queued
- Nothing queued, nothing in flight.
and 0 more
Cache, by ownerReferences What the controllers have been told, not yet what is queued.
Empty: no Deployment, ReplicaSet or Pod named web.
No change delivered yet.
Delivered to the informers of
Every controller that watches the object's kind; the one that owns it acts.
- Observe
- What the controller that owns the object reads from its cache.
- Diff
- What the object asks for against what exists.
- Act
- The writes that close the gap, each queued as a change of its own.
Apply the Deployment. Its changes queue in the watch stream, and Step delivers them one at a time.
A dependent goes only when every owner it lists is verified absent, matched by uid. A ConfigMap owned by two custom resources survives the deletion of one of them.
The documentation uses “garbage collection” for a wider family of cleanup, and each member is a separate mechanism with its own trigger. The pod garbage collector removes terminated pods once their number passes a threshold. The TTL-after-finished controller deletes Jobs whose ttlSecondsAfterFinished has elapsed. The kubelet removes unused containers and images when disk usage passes its thresholds. Dynamically provisioned PersistentVolumes with a reclaim policy of Delete go with their claims. The rest of this lesson is about the owner-reference collector, the one that acts when you delete something that owns something else.
Cascading deletion modes
kubectl delete --cascade picks one of three cascading deletionDeleting an owner together with its dependents. The propagation policy says whether the dependents go after the owner, before it, or not at all. policies. In the API they are the propagationPolicy of the delete request.
--cascade | Order | What you see |
|---|---|---|
background (default) | owner first, dependents afterwards | the owner disappears at once; dependents go shortly after |
foreground | dependents first, owner last | the owner stays, with a deletionTimestamp, until blocking dependents are gone |
orphan | owner only | dependents lose the owner reference and keep running |
Background deletion is what you get without the flag. The Deployment and its ReplicaSet are gone by the next get, and the pods follow:
kubectl -n orders delete deployment api
deployment.apps "api" deleted from orders namespace
kubectl -n orders get deployments,replicasets,pods
NAME READY STATUS RESTARTS AGE pod/api-6fbf78644-2cv2c 1/1 Terminating 0 30s pod/api-6fbf78644-cfxzk 1/1 Terminating 0 30s pod/api-6fbf78644-tfgs5 1/1 Terminating 0 30s
kubectl -n orders wait --for=delete pod -l app.kubernetes.io/name=api --timeout=60s
pod/api-6fbf78644-2cv2c condition met pod/api-6fbf78644-cfxzk condition met pod/api-6fbf78644-tfgs5 condition met
kubectl -n orders get deployments,replicasets,pods
No resources found in orders namespace.
Foreground deletion keeps the owner visible while the collector works. The API server sets the owner’s deletionTimestamp and adds the foregroundDeletion finalizer; the collector deletes the dependents, waits for those with blockOwnerDeletion: true, and removes the finalizer last. Use it when something downstream must not see the owner disappear before the dependents, such as a script that waits for the Deployment to be gone before reusing its name:
kubectl -n orders delete deployment api --cascade=foreground --wait=false
deployment.apps "api" deleted from orders namespace
kubectl -n orders get deployment api -o jsonpath='{.metadata.deletionTimestamp} {.metadata.finalizers}'
2026-11-19T09:01:00Z ["foregroundDeletion"]
kubectl -n orders get deployments,replicasets,pods
NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/api 0/3 0 0 30s NAME DESIRED CURRENT READY AGE replicaset.apps/api-6fbf78644 3 0 0 30s NAME READY STATUS RESTARTS AGE pod/api-6fbf78644-2cv2c 1/1 Terminating 0 30s pod/api-6fbf78644-cfxzk 1/1 Terminating 0 30s pod/api-6fbf78644-tfgs5 1/1 Terminating 0 30s
kubectl -n orders wait --for=delete deployment/api --timeout=60s
deployment.apps/api condition met
kubectl -n orders get deployments,replicasets,pods
No resources found in orders namespace.
Orphan deletion adds the orphan finalizer; the collector strips the owner reference from each dependent, and then lets the owner go. Combined with adoption, it replaces an owner without restarting anything. The ReplicaSet below survives the delete, and a Deployment recreated from the same manifest adopts it and its pods; no pod is replaced:
kubectl -n orders delete deployment api --cascade=orphan
deployment.apps "api" deleted from orders namespace
kubectl -n orders get deployments,replicasets,pods
NAME DESIRED CURRENT READY AGE replicaset.apps/api-6fbf78644 3 3 3 30s NAME READY STATUS RESTARTS AGE pod/api-6fbf78644-2cv2c 1/1 Running 0 30s pod/api-6fbf78644-cfxzk 1/1 Running 0 30s pod/api-6fbf78644-tfgs5 1/1 Running 0 30s
kubectl apply -f api.yaml
deployment.apps/api created
kubectl -n orders get deployments,replicasets,pods
NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/api 3/3 3 3 0s NAME DESIRED CURRENT READY AGE replicaset.apps/api-6fbf78644 3 3 3 30s NAME READY STATUS RESTARTS AGE pod/api-6fbf78644-2cv2c 1/1 Running 0 30s pod/api-6fbf78644-cfxzk 1/1 Running 0 30s pod/api-6fbf78644-tfgs5 1/1 Running 0 30s
kubectl delete also waits, by default, until the objects are actually gone. That wait is the hang you see when something blocks the delete. --wait=false returns as soon as the API server accepts the request. In a script, kubectl wait --for=delete deployment/api --timeout=120s blocks until the object is gone and fails when the timeout expires, which turns a stuck delete into an error you can see instead of a job that never ends.
Finalizers
A finalizerA key in metadata.finalizers. While the list is not empty, a deleted object stays in the API with a deletionTimestamp, so that the controller owning the key can clean up first. turns a delete into a request. When you delete an object whose finalizer list is not empty, the API server:
- sets
metadata.deletionTimestampto the time of the request, - returns
202 Acceptedinstead of removing the object, and - keeps the object, in a terminating state, until every key is gone from
metadata.finalizers.
A finalizer can be set from the start, as in this ConfigMap, whose archive must be saved before it goes:
apiVersion: v1
kind: ConfigMap
metadata:
name: settings
finalizers:
- example.com/archive
data:
mode: production
kubectl apply -f settings.yaml
configmap/settings created
kubectl delete configmap settings --wait=false
configmap "settings" deleted from default namespace
kubectl get configmap settings
NAME DATA AGE settings 1 0s
kubectl get configmap settings -o jsonpath='{.metadata.deletionTimestamp} {.metadata.finalizers}'
2026-11-19T09:01:00Z ["example.com/archive"]
From that moment the object is on its way out. You can remove finalizers but not add more, you cannot change the deletionTimestamp, and you cannot undelete the object; the only way back is to create another object. The API server performs none of the cleanup itself; it only refuses to remove the object while the list has entries, and whatever a key stands for happens in a controller. Custom finalizer names must be qualified, like example.com/archive, so that each one points at the team or controller responsible for it. Common built-in ones:
kubernetes.io/pvc-protectionkeeps a PersistentVolumeClaim while a pod uses it, andkubernetes.io/pv-protectionkeeps a PersistentVolume while a claim is bound to it.service.kubernetes.io/load-balancer-cleanupkeeps aLoadBalancerService until its cloud load balancer is deleted.foregroundDeletionandorphanare the garbage collector’s own, from the cascade modes above.
Who removes finalizers
The controller that added a finalizer removes it, and only after its cleanup has succeeded. The pattern is the same in every well-behaved controller. On creation or adoption it adds its key. On each reconcile it checks the deletionTimestamp: if the object is being deleted, it runs the cleanup, such as deleting the cloud load balancer, detaching the volume or taking a final backup, and then patches its key out of the list. If the cleanup fails, it leaves the key in place and retries, so the object cannot vanish while the outside resource still exists.
A finalizer is therefore a promise that a particular controller will come back. The promise breaks when that controller is not running: it was uninstalled before its objects were deleted, its Deployment has no ready pods, or its permissions were revoked. Uninstall operators in the reverse order of installing them: delete the custom resources first, wait for them to go, then remove the controller.
Stuck Terminating
Pods have a reason of their own: a pod’s deletion waits for its kubelet to confirm that the containers stopped, which cannot happen while the node is unreachable. Beyond that, an object that stays in Terminating has one of two causes.
- A finalizer that nobody removes. Read
metadata.finalizers, identify the controller from the key’s prefix, and check that controller’s pods and logs. The fix is almost always to get the controller running again so it can finish its work. - An API the cleanup depends on is unavailable. Deleting a namespace means listing every resource type in it, including those served by aggregated APIs such as
metrics.k8s.io. If an APIService is unavailable, the listing fails and the namespace reportsNamespaceDeletionDiscoveryFailure.kubectl get apiservicesshows which one; repair it, or delete it if its backing service was removed for good.
Removing a finalizer by hand is the last resort. It skips exactly the cleanup the finalizer guarded: the load balancer keeps billing, the volume stays attached, the backup never runs. Do it only once you have confirmed the external resource is gone or not needed:
kubectl -n scratch patch configmap export-state --type=json \
-p '[{"op":"remove","path":"/metadata/finalizers/0"}]'
A JSON patch that removes one entry by index leaves any other finalizers in place, which a merge patch setting finalizers to null does not.
Namespace deletion
Deleting a namespace deletes everything in it. The namespace moves to phase Terminating, rejects the creation of further objects in it, and the namespace controller deletes its contents type by type. The namespace itself carries a kubernetes entry in spec.finalizers, which the controller removes when the namespace is empty. If an object inside is held by a finalizer, the namespace waits for it, and its status conditions say why:
kubectl delete namespace scratch --wait=false
namespace "scratch" deleted
kubectl get namespace scratch
NAME STATUS AGE scratch Terminating 30s
kubectl get namespace scratch -o jsonpath='{range .status.conditions[?(@.status=="True")]}{.type}: {.message}{"\n"}{end}'
NamespaceContentRemaining: Some resources are remaining: configmaps. has 1 resource instances NamespaceFinalizersRemaining: Some content in the namespace has finalizers remaining: example.com/upload-report in 1 resource instances
kubectl -n scratch get configmaps,pods
NAME DATA AGE configmap/export-state 1 30s
kubectl -n scratch get configmap export-state -o jsonpath='{.metadata.finalizers}'
["example.com/upload-report"]
Ordered namespace deletion, GA in Kubernetes 1.34, fixes the order of that cleanup: the controller deletes all pods first, waits for them to stop, and only then deletes everything else. Without an order, a NetworkPolicy could disappear while the pods it protected were still running and reachable. Pods going first means policies and other guard rails stay in force until the workloads they protect are gone.
kubectl --context kind-kx create deployment gc-demo --image=nginx:1.30 --replicas=2kubectl --context kind-kx get pods -l app=gc-demo -o custom-columns=POD:.metadata.name,OWNER-KIND:.metadata.ownerReferences[0].kind,OWNER:.metadata.ownerReferences[0].namekubectl --context kind-kx delete deployment gc-demo --cascade=orphankubectl --context kind-kx get replicasets,pods -l app=gc-demokubectl --context kind-kx delete replicasets -l app=gc-demo --cascade=foreground --wait=falsekubectl --context kind-kx get replicasets -l app=gc-demo -o jsonpath='{.items[*].metadata.finalizers}'kubectl --context kind-kx get events -A --field-selector=reason=OwnerRefInvalidNamespacekubectl --context kind-kx get apiservices
For your own kind cluster kx: copy a command and paste it into your terminal. Run in the simulator runs the same command in this page's simulated cluster instead; nothing on this page touches your machine. The foreground delete shows foregroundDeletion in the ReplicaSet's finalizers only while its pods are terminating; run the jsonpath command quickly. Every APIService should report True in the AVAILABLE column; one that does not will stall namespace deletion.
Actual state
Check your understanding
Your first answer to each check is the one that counts. After a miss you can answer again; passing every check reconciles the lesson.
Lesson not yet reconciled
Desired: 4 objectives, 0 metReconciled: 4 of 4 objectives met
- Trace ownerReferences from a Pod to its ReplicaSet and Deployment. (not yet met)
- Choose background, foreground or orphan cascading deletion. (not yet met)
- Explain what a finalizer blocks and why an object sits in Terminating. (not yet met)
- Find what holds a namespace in Terminating and release it safely. (not yet met)
Pass every check above to reconcile this lesson.
Every check has passed, so the desired state is met. First-try accuracy: 0 of 5. This lesson's review cards are in your queue.
Practice
Put this lesson to work on the simulated cluster. Everything runs in your browser, with nothing to install.
Changed since the notes
This lesson draws on an earlier set of study notes. Where the documentation contradicts a claim in them, qualifies it or has moved past it, the claim is listed here with the corrected statement and the source it was checked against.
Show 7 corrections
The notes saidNo protobuf support. CRDs use JSON only.
CorrectedCRDs still do not support Protocol Buffers (aggregated APIs do). CBOR is being added as a second encoding: KEP-4222 alpha in 1.32 (CBORServingAndStorage gate, off by default, which also makes CBOR the storage encoding for custom resources) with beta listed for 1.37; the exact default state in 1.37 was not confirmed here.
The notes saidOnly one version can be storage; deprecate old versions before removing them.
CorrectedCorrect, plus: before removing a version, rewrite stored objects to the new storage version and remove the old version from the CRD's status.storedVersions. Built-in Storage Version Migration (storagemigration.k8s.io) went beta in 1.35 and GA (v1, enabled by default) in 1.37, replacing the out-of-tree migrator.
The notes saidSample Database uses version: "14" which fails the schema pattern '^\d+\.\d+$'.
CorrectedThe sample is rejected with 'spec.version in body should match '^\d+\.\d+$''. Use version: "14.0" or relax the pattern to '^\d+(\.\d+)?$'.
Sourcekubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions
The notes saidScale subresource maps statusReplicasPath to .status.readyReplicas.
CorrectedstatusReplicasPath maps to scale.status.replicas and conventionally points to .status.replicas; labelSelectorPath (required for HPA/VPA) must point to a string field holding a serialized label selector (for example .status.labelSelector of type string), not a selector struct.
Sourcekubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions
The notes saidlog := r.Log.WithValues(…)
CorrectedCurrent Kubebuilder scaffolds have no Log field on the reconciler; they get a contextual logger with log := logf.FromContext(ctx) (sigs.k8s.io/controller-runtime/pkg/log), which already carries controller, namespace and name values.
The notes saidStatus example appends a new Ready condition every reconcile with LastTransitionTime: metav1.Now().
CorrectedUse meta.SetStatusCondition(&obj.Status.Conditions, metav1.Condition{Type, Status, Reason, Message, ObservedGeneration: obj.Generation}): it updates the existing condition of that type and changes LastTransitionTime only when Status changes, so conditions stay one per type.
Sourcepkg.go.dev/k8s.io/apimachinery/pkg/api/meta#SetStatusCondition
The notes saidAdoption snippet ignores the r.Update error and checks OwnerReferences == nil.
CorrectedCheck metav1.GetControllerOf(obj) (or metav1.IsControlledBy) instead of a nil slice, set ownership with controllerutil.SetControllerReference (it errors if another controller already owns the object), and return the Update error so the request is retried.
Sourcepkg.go.dev/sigs.k8s.io/controller-runtime/pkg/controller/controllerutil#SetControllerReference
Every correction across the guide, by note and topic.
Sources
Checked against kubernetes.io documentation for Kubernetes 1.37 on .
- kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents
- kubernetes.io/docs/concepts/architecture/garbage-collection
- kubernetes.io/docs/tasks/administer-cluster/use-cascading-deletion
- kubernetes.io/docs/concepts/overview/working-with-objects/finalizers
- kubernetes.io/docs/tasks/administer-cluster/namespaces
- kubernetes.io/docs/concepts/storage/persistent-volumes
- kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer
- kubernetes.dev/resources/keps/5080
- pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/controller/controllerutil
Owners, finalizers and garbage collection
↓ ↑ step, 1 to 7 scene, Esc leave