Appearance

Leases and leader election

Follow Lease renewal and takeover, then see where a former leader could still affect an external system.

What you will understand

  • Explain how controller replicas use a Lease to coordinate leadership.
  • Identify the evidence for acquisition, renewal, and a holder change.
  • Explain why an external system needs its own way to reject a stale writer.

Builds on: Scheduler internals

How controller replicas elect a leader

Suppose you run two copies of a controller for availability. Both are ready, but you only want one reconciling at a time. Kubernetes supports coordination through a Lease, an API object that can record the current holder and renewal information. A participating controller acquires leadership and regularly renews it. Other candidates wait or attempt to take over if the current holder stops renewing. The API’s update conflict handling helps ensure two candidates racing to update the same Lease cannot both write the same version successfully.

In the election scene, stop renewal from controller A and watch when controller B can take over. The delay gives A a chance to recover from transient problems while bounding how long the system waits for a failed candidate. A leader election library handles renewal timing and calls the local start and stop functions when leadership changes.

When can another controller take the Lease?

The current leader renews its Lease. A participant may acquire leadership when the preceding holder can no longer renew within the configured timing.

  1. Acquire leadership

    A participant successfully updates the coordination record according to the election algorithm.

  2. Renew leadership

    The active participant renews through API writes; standby participants observe the record.

  3. Take over an expired Lease

    If renewal stops, another participant can acquire according to election timing and optimistic concurrency.

One generic client-go-style election is illustrated; exact durations and coordinated election options depend on component configuration.

Inspect the leadership handoff

Two teaching controllers contend for the same Lease. Watch the first controller stop renewing, then see the second take over.

1 / 4

From Controller ATo Election Lease

Observe the current leader renew

Controller A is the recorded holder. Successful renewals advance renewTime while holderIdentity stays the same.

Lease record
Before
Holder A / earlier renewTime
After
Holder A / later renewTime
Observe the current leader renew

Controller A is the recorded holder. Successful renewals advance renewTime while holderIdentity stays the same.

The contenders use one workstation clock and win writes through Kubernetes resourceVersion checks. Timings are illustrative. A Lease does not fence unrelated external writers.

If the recorded renew time stops, has the holder already changed?
Reveal prediction answer

The record can still name the old holder while contenders wait. Look for the changed identity and then a fresh renewal.

Record holderIdentity, leaseTransitions, and renewTime before A stops renewing and after the handoff.

Observe the live Lease handoff
Explore another case

Open Inspect the leadership handoff to see when the recorded holder stops renewing and when a standby contender takes over.

Read election Leases and node heartbeats

Leases also support Kubernetes node heartbeats. A node lease in kube-node-lease records that the kubelet has renewed contact with the API. A controller election Lease records coordination over who should perform a particular role. The two uses share an API type. Interpreting a holder and renewal requires knowing which component maintains that Lease.

The sample Lease names a holder and duration but has no process renewing it. Save it as lease.yaml and treat it as a record to inspect. A real election library also maintains acquisition and renewal fields.

apiVersion: coordination.k8s.io/v1
kind: Lease
metadata:
  name: m15-example
  namespace: kv-lab
  labels:
    lab: m15
spec:
  holderIdentity: training-controller-a
  leaseDurationSeconds: 30
# A real election library maintains acquisition and renewal fields.

Compare a sample Lease with a live one

Look at the sample record, then inspect available system Leases without editing them. Depending on the cluster, an election record can show a holder, renew time, and transition count. Repeated reads can show renewals over time. Use the coordination lab to practice reading these objects alongside the scene.

kubectl --context kind-kv-lab -n kv-lab apply -f lease.yaml
kubectl --context kind-kv-lab -n kv-lab get lease m15-example -o yaml
kubectl --context kind-kv-lab -n kube-system get leases
kubectl --context kind-kv-lab -n kube-node-lease get leases
# This is inspection, not an instruction to edit system leadership records.
kubectl --context kind-kv-lab -n kube-system get lease kube-scheduler -o yaml

Observe a live Lease handoff

Source lab-env.sh in the disposable kind lab. Create a dedicated namespace and Lease. The example uses two teaching contenders running on the same workstation clock.

kubectl --context kind-kv-lab create namespace kv-lease-trace
kubectl --context kind-kv-lab -n kv-lease-trace apply -f - <<'YAML'
apiVersion: coordination.k8s.io/v1
kind: Lease
metadata:
  name: demo-election
spec:
  leaseDurationSeconds: 12
YAML

Save the following as contender.py. Each contender can renew its own Lease or try to take over an expired Lease. The API’s version check prevents a writer from replacing a newer record it has not read yet.

import datetime
import json
import subprocess
import sys
import time

identity, seconds = sys.argv[1:]
deadline = time.monotonic() + int(seconds)
base = ["kubectl", "--context", "kind-kv-lab", "-n", "kv-lease-trace", "--request-timeout=8s"]


def kubectl(*args, body=None):
    return subprocess.run([*base, *args], input=body, text=True, capture_output=True)


while time.monotonic() < deadline:
    result = kubectl("get", "lease", "demo-election", "-o", "json")
    result.check_returncode()
    lease = json.loads(result.stdout)
    spec = lease["spec"]
    now = datetime.datetime.now(datetime.timezone.utc)
    holder = spec.get("holderIdentity")
    renewed = spec.get("renewTime")
    expired = not renewed or (
        now - datetime.datetime.fromisoformat(renewed.replace("Z", "+00:00"))
    ).total_seconds() >= spec["leaseDurationSeconds"]

    if holder == identity or expired:
        if holder != identity:
            spec["leaseTransitions"] = spec.get("leaseTransitions", 0) + 1
        spec["holderIdentity"] = identity
        spec["renewTime"] = now.isoformat(timespec="microseconds").replace("+00:00", "Z")
        result = kubectl("replace", "-f", "-", body=json.dumps(lease))
        if result.returncode and "(Conflict)" not in result.stderr:
            raise SystemExit(result.stderr)
        if not result.returncode:
            print(identity, "renewed the Lease", flush=True)

    time.sleep(1)

Start A, wait for it to acquire the Lease, and start B. A stops after 18 seconds. B waits for the last renewal to expire, takes over, and starts renewing. While both commands run, read the Lease with kubectl in a second shell if you want to see the intermediate holder and timestamps.

python3 contender.py A 18 &
kubectl --context kind-kv-lab -n kv-lease-trace wait \
  --for='jsonpath={.spec.holderIdentity}=A' lease/demo-election --timeout=30s
python3 contender.py B 50 &
kubectl --context kind-kv-lab -n kv-lease-trace wait \
  --for='jsonpath={.spec.holderIdentity}=B' lease/demo-election --timeout=60s
kubectl --context kind-kv-lab -n kv-lease-trace get lease demo-election \
  -o 'custom-columns=HOLDER:.spec.holderIdentity,TRANSITIONS:.spec.leaseTransitions,RENEWED:.spec.renewTime'
wait
kubectl --context kind-kv-lab delete namespace kv-lease-trace

Protect external data from a former leader

A former leader can pause and later resume after a replacement has started. Its delayed write might still reach an external database. To protect that system, it needs fencing, a way for the destination to recognize and reject stale writers. For example, the destination could require an increasing leadership epoch and reject writes carrying an older one. The fencing scene illustrates the extra decision at the destination.

Shorter election times can reduce takeover delay and make temporary API slowdown cause more leadership changes. Evaluate renewal timing and monitoring together.

Where can a delayed former leader be stopped?

The destination needs a fencing rule to reject stale writes. The current holder recorded in Kubernetes is only one part of that guarantee.

  1. Leader A starts external work

    A sends a request while leading; the request may remain in flight after A pauses.

  2. Leader B acquires the Lease

    B acquires the Lease after A stops renewing, but the Lease cannot revoke the old request.

  3. External destination enforces the epoch

    A target that validates a monotonic fencing epoch can reject stale writes; idempotency addresses a different duplicate-work boundary.

The external system must implement the protection; client-go leader election alone offers no fencing guarantee.

Explore another case

Check your understanding

The Lease now lists controller B. Does that prove controller A can no longer update the external database?

It shows the holder recorded in Kubernetes. Protection of the external data depends on how the writer stops and what the database enforces, such as checking a fencing epoch before accepting a write.

Go to the source

Reviewed 2026-10-27 · Kubernetes 1.37 · Related local exercise

Search the book

Search loads when you open it.

Keyboard shortcuts

Ctrl + K / ⌘ + K
Search the book
?
Open this guide
Tab / Shift + Tab
Move between controls
Enter / Space
Activate a focused button or disclosure
← / →
Focused visual timeline · previous or next step
Home / End
Focused visual timeline · first or last point
Esc
Close the open dialog or menu