Q: How does the Kubernetes garbage collector work?
The Kubernetes garbage collector is a controller in kube-controller-manager that deletes dependent objects once their owners are gone, using metadata.ownerReferences to build a dependency graph.
Want to master this scenario in a live sandbox? KodeKloud's CKA & CKAD Hands-On Certification Track covers this exact problem with hands-on terminal drills.
🛠️ Production Runbook & Step-by-Step Resolution
Direct Answer: The <strong>Kubernetes garbage collector</strong> is a controller in kube-controller-manager that deletes dependent objects once their owners are gone, using <code>metadata.ownerReferences</code> to build a dependency graph. It is why deleting a Deployment also removes its ReplicaSets and pods. Interviewers ask it to check that you separate three things: owner-based cascading deletion, kubelet housekeeping of images and containers, and TTL cleanup of finished Jobs. Knowing the three deletion propagation modes and how finalizers interact is what marks a senior answer.
The owner reference graph behind the garbage collector
Every dependent records who owns it; the collector watches that graph.
kubectl get rs -n prod -l app=my-app \
-o custom-columns=NAME:.metadata.name,OWNER:.metadata.ownerReferences[0].name
kubectl get pod my-app-7d9c-xk2lp -n prod -o jsonpath='{.metadata.ownerReferences}'
- ownerReferences: a list of
apiVersion,kind,nameanduid. Controllers set it automatically (Deployment to ReplicaSet to Pod). - Deletion trigger: when no owner with a matching UID exists any more, the dependent becomes garbage and is deleted.
- Namespace rule: a namespaced owner cannot own objects in another namespace, and a namespaced dependent may have a cluster-scoped owner.
- Not everything is owned: objects created by hand have no owner and are never collected automatically.
Three cascading deletion modes
The caller picks how dependents are removed.
# Default: background
kubectl delete deployment my-app -n prod
# Wait for pods to go first
kubectl delete deployment my-app -n prod --cascade=foreground
# Remove only the Deployment, keep ReplicaSet and pods running
kubectl delete deployment my-app -n prod --cascade=orphan
- Background (default): owner is deleted immediately, then the collector removes dependents asynchronously.
- Foreground: the owner gets a
foregroundDeletionfinalizer and stays visible until dependents withblockOwnerDeletion=trueare gone. - Orphan: the owner is deleted and the
ownerReferencesare removed from dependents, leaving them running. - kubectl flag:
--cascade=background|foreground|orphan(older versions used--cascade=falsefor orphan).
Finalizers and objects stuck in Terminating
Finalizers delay actual removal until a controller finishes cleanup.
kubectl get ns demo -o jsonpath='{.metadata.finalizers}{"\n"}'
kubectl get all -n demo
kubectl get pods -A -o json | jq -r '.items[] | select(.metadata.deletionTimestamp) | .metadata.name'
- Mechanism: deletion sets
deletionTimestamp; the object stays until every entry inmetadata.finalizersis removed. - Foreground dependency: an owner waits on blocking dependents, so a stuck child keeps the parent in Terminating.
- Diagnosis: check finalizers and dependents before touching anything.
- Last resort: patching finalizers away skips cleanup and may leak cloud resources, so fix the responsible controller first.
Related cleanup that is not the same collector
Clarify these separately in an interview.
- Kubelet image GC: removes unused images when disk usage passes
imageGCHighThresholdPercent(default 85) until it falls to the low threshold (80). - Kubelet container GC: cleans dead containers on the node.
- PodGC controller: deletes terminated pods beyond
--terminated-pod-gc-thresholdand orphaned pods bound to missing nodes. - Job TTL:
ttlSecondsAfterFinishedin the Job spec removes finished Jobs and their pods through the TTL-after-finished controller.
Production practice
Design for predictable deletion.
- Set ownerReferences in operators: custom controllers should use
controllerutil.SetControllerReferenceso custom resources clean up their children. - Use foreground for ordered teardown: when dependents must finish before the owner disappears.
- Guard Helm and GitOps: prune settings in Argo CD or Flux delete by ownership/labels, so review what a prune will remove.
- Watch for leaks: alert on very old objects lacking owners, such as stray ConfigMaps or PVCs.
- The garbage collector is a kube-controller-manager controller that deletes dependents whose owner (by ownerReferences UID) no longer exists.
- Deletion can cascade in background, foreground or orphan mode, and finalizers can hold objects in Terminating until cleanup completes.
- I inspect ownerReferences and finalizers when deletes hang, and I keep kubelet image GC and Job TTL separate in my mental model.
Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:
- Removing finalizers to unstick a delete without checking the controller It skips external cleanup and can leak load balancers, disks or other cloud resources.
- Assuming deleting a Deployment always deletes its pods immediately Background mode is asynchronous, and orphan mode keeps pods running.
- Confusing kubelet image garbage collection with ownerReference collection They run on different components with different triggers (disk thresholds vs object ownership).
- Setting cross-namespace owner references They are invalid for namespaced owners, so the dependent may be treated as having a missing owner and be collected.