Sub topic 18
Leader election and debugging controllers
This chapter assumes you know the reconcile loop, work queues, and status conditions from earlier chapters. You should also be comfortable with kubectl describe and kubectl logs.
Running more than one replica
A controller is a Deployment like any other, so you can run several replicas for availability. If all of them reconciled at once, they would create duplicate children and fight over updates. Leader election prevents this: replicas compete for a lock, and only the winner runs reconcile loops.
The lock is a Lease object in the coordination.k8s.io API group. The leader writes its identity into spec.holderIdentity and refreshes spec.renewTime at a regular interval. Standby replicas watch the Lease. If the renew time is older than leaseDurationSeconds, a standby takes over by updating the Lease. That update relies on the same optimistic concurrency covered earlier, so only one replica's write succeeds.
In controller-runtime you turn this on in the manager options:
package main
import (
"os"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
)
func main() {
ctrl.SetLogger(zap.New())
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
LeaderElection: true,
LeaderElectionID: "namespace-defaults.example.com",
})
if err != nil {
os.Exit(1)
}
// Register reconcilers with SetupWithManager here.
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
os.Exit(1)
}
}Standby replicas still start their informer caches, so a new leader begins with warm caches. Only the controllers wait for the lock.
Failover takes about one lease duration, so the controller pauses briefly while the old leader's lease runs out. Existing workloads keep running during this time.
Debugging a controller that will not converge
"Not converging" means the status never catches up with the spec. Work from the object outward.
- Compare
metadata.generationwithstatus.observedGeneration. If they differ, the controller has not processed the latest spec. - Read
status.conditionsfor a reason and message. - Run
kubectl describeand read the Events section. - Read the controller logs, filtered by object name.
- Check the Lease to confirm a leader exists.
kubectl get deployment web -o jsonpath='{.metadata.generation} {.status.observedGeneration}{"\n"}'
kubectl describe deployment web
kubectl logs deploy/my-controller -n my-system | grep web
kubectl get lease namespace-defaults.example.com -n my-system -o jsonpath='{.spec.holderIdentity}{"\n"}'| Symptom | Likely cause |
|---|---|
| `observedGeneration` is behind and logs are silent | No leader, or the controller is not watching this kind |
| The same error repeats with growing gaps | Reconcile returns an error, and backoff is working |
| Repeated conflict errors | Two writers, or a stale cache read |
| Object stuck in `Terminating` | A finalizer that cleanup never removes |
| Children keep reappearing | Another controller owns and recreates them |
Controllers also expose Prometheus metrics. Watch workqueue_depth and workqueue_retries_total, plus controller_runtime_reconcile_errors_total if you use controller-runtime. A deep queue means reconciles are too slow. Climbing retries mean they are failing.
Exercise
A controller has three replicas. Users report that new custom resources are ignored. The logs of two replicas show "attempting to acquire leader lease", and the third shows no reconcile output. What do you check first, and why?
Show answer
Check the Lease with kubectl get lease and read holderIdentity and renewTime. The two logs are normal standby behavior. If a leader holds the Lease and renewTime is fresh, the leader is the third replica, so read its logs and the object's conditions and events for the real error. If no one holds the Lease or renewTime is stale, look at why the leader cannot renew it, for example missing RBAC permission on leases.