Skip to main content
Kubernetes internalsLesson 5 of 12

Leader Election with Leases

kube-controller-manager, kube-scheduler and most operators run several replicas for availability, but only one may act at a time. They agree on who that is with a small Lease object in the API server. Follow how the Lease is taken, renewed, lost and taken over.

holderIdentity—
renewTime—
leaseTransitions—
Operator · 3 replicasReplica AcandidateReplica BcandidateReplica CcandidateAPI serverstores the LeaseLeasecoordination.k8s.ioNode Leaseskube-node-leaseManaged objectsDeployments · CRsLeaseCandidatescoordinated electionkubeletnode heartbeat
RequestWatchAppears in a later step

What you will learn

  • Why two active controllers fight over the same objects
  • holderIdentity, leaseDurationSeconds and renewTime in a Lease
  • leaseDuration, renewDeadline and retryPeriod, and how failover happens
  • Why a paused leader can still act, and what fencing means
  • Node heartbeats and coordinated leader election also use Leases

The three timings​

Setting (client-go name)What it controlskube-controller-manager defaultIf set too lowIf set too high
leaseDurationHow long followers wait without a renewal before taking over15 sLeadership flaps on short API hiccupsSlow failover after a crash
renewDeadlineHow long the leader keeps trying to renew before giving up10 sLeader steps down on brief API slownessLess margin before followers may take over
retryPeriodHow often the leader renews and followers retry2 sMore writes to the API serverRenewals may miss the deadline

The flags are --leader-elect-lease-duration, --leader-elect-renew-deadline and --leader-elect-retry-period on kube-controller-manager and kube-scheduler. Keep leaseDuration > renewDeadline > retryPeriod.

Try it yourself​

kubectl get lease -n kube-system # HOLDER for controller-manager, scheduler, and more
kubectl get lease kube-controller-manager -n kube-system -o yaml # holderIdentity, leaseDurationSeconds, renewTime, leaseTransitions
kubectl get lease kube-scheduler -n kube-system \
-o jsonpath='{.spec.holderIdentity}{"\n"}' # Which instance schedules right now
kubectl get lease -n kube-system -w # Each update line is a renewal or takeover
kubectl get lease -n kube-node-lease # One heartbeat Lease per node
kubectl get lease <node-name> -n kube-node-lease \
-o jsonpath='{.spec.renewTime}{"\n"}' # Last kubelet heartbeat
kubectl get leasecandidates -n kube-system # Only if coordinated leader election is enabled

Check yourself

  1. The leader replica crashes. Why does the next leader take over only after a delay?
  2. A leader freezes in a long GC pause, its Lease expires and another replica takes over. What can go wrong when it wakes up?
  3. Why must leaseDuration be longer than renewDeadline?

Further reading: Leases · Coordinated leader election · client-go leaderelection · CRDs and Operators · Distributed Systems Basics · Control Plane HA and etcd Quorum