Scrivio Interview library
DebuggingIntermediate7 min read · updated 13 November 2026

A Kubernetes controller written in Java uses Lease-based leader election with leaseDuration 15 s, renewDeadline 10 s and retryPeriod 2 s. After a network blip on one node, logs show two replicas both reconciling resources for about 20 seconds, which created duplicate cloud load balancers.

How could two replicas act as leader at the same time, and what changes in code and configuration stop this from causing harm again?

Two replicas acted as leader because Lease-based leadership is only a promise about time: the old leader lost contact, a second replica waited out the 15-second lease and took over, but the old leader never stopped its reconcile work when renewal failed. The fix is to make losing the lease stop all work at once (often by exiting the process), give the renew call real timeouts, and make every external action idempotent so that a short overlap cannot create a second load balancer.

Why this question is asked

Incidents like this one show that the library only decides who should be leader; it cannot force the old leader to stop. Interviewers ask this because it tests whether we understand that leases are based on time, and that safety comes from what our code does when leadership ends. In this answer, we will recap how Kubernetes Lease election works, replay the timeline of the incident, see why the old leader kept going, and then fix the code, the configuration, the external actions and the monitoring.

1A Quick Recap of Lease-Based Leader Election

Kubernetes has a small object called a Lease, in the coordination.k8s.io API group. It holds the identity of the current holder, the time it last renewed, and the lease duration. Every replica of our controller runs a leader elector, a loop in the client library that tries to write its own name into that Lease.

The three durations each have a job. leaseDuration (15 s) is how long a non-leader waits, after it last saw the Lease change, before it may take the Lease. renewDeadline (10 s) is how long the current leader keeps trying to renew before it must give up leadership. retryPeriod (2 s) is how often each replica tries to acquire or renew. The design depends on renewDeadline being shorter than leaseDuration: the old leader should give up at 10 s, before anybody else may take over at 15 s, which leaves a 5-second safety gap.

Notice that nothing here is enforced by the API server. The Lease only records who claims to lead. The old leader stops working only because its own code notices that it failed to renew and stops.

2Replaying the Incident Timeline

Let us walk through the incident with the numbers from the logs. At t = 0 the network on node A blips, and replica A, the leader, can no longer reach the API server. Its renew attempts every 2 seconds fail or hang. Replica B keeps reading the Lease and sees that it has not changed since t = 0.

At about t = 15 s, B's leaseDuration has passed since the last change it observed, so B writes its own name into the Lease and starts reconciling. If A had stopped at t = 10 s, as designed, there would be no overlap. The logs show both replicas reconciling for about 20 seconds, so A kept working until around t = 35 s, long after it should have stopped.

Step throughTwo leaders after a network blip
Replica AAPI serverReplica BCloud API
renew Lease (t=0, last success)
renew attempts hang during the blip
read Lease: unchanged since t=0
t=15s: take Lease, holder = B
create load balancer for service X
A still reconciling: create load balancer for X
second load balancer created
t=35s: finally notices lost leadership

8 messages in order. Play them, or step through them one at a time.

Replica A never stopped at its 10-second renew deadline, so both replicas called the cloud API.

3Why the Old Leader Kept Working

There are three usual reasons, and often more than one applies. The first is the most common: the code started the reconcile loop in the onStartLeading callback but did nothing useful in onStopLeading. The elector correctly gave up leadership, but the worker threads, informers and queues were separate objects that never heard about it.

The second reason is that the renew call itself had no timeout. If the HTTP request to the API server hangs for 30 seconds during the blip, the elector cannot check its renew deadline until the call returns, so the 10-second rule is applied late. The third reason is a pause: a long garbage collection pause, CPU throttling or a stopped VM freezes the leader's timer while the other replicas' clocks keep running. Clocks that run at slightly different rates make it worse, because each replica measures the durations on its own clock.

We should also check how our client library behaves. Some versions cancel only the elector's own loop and leave work that was already submitted to an executor running, unless we cancel it ourselves.

4Fix 1: Stop Everything When Leadership Ends

The simplest reliable fix, used by many controllers, is to exit the process when leadership is lost. Kubernetes restarts the pod, the new pod starts as a follower, and no stray thread can survive. Here is the shape of the code with the fabric8 Kubernetes client (class names can differ between client versions, so check yours).

Java
LeaderElectionConfig cfg = new LeaderElectionConfigBuilder()
.withName("lb-controller")
.withLeaseDuration(Duration.ofSeconds(15))
.withRenewDeadline(Duration.ofSeconds(10)) // must be shorter than leaseDuration
.withRetryPeriod(Duration.ofSeconds(2))
.withLock(new LeaseLock("infra", "lb-controller", podName))
.withLeaderCallbacks(new LeaderCallbacks(
reconciler::start, // begin work only as leader
() -> { // BEFORE: log.warn("lost leadership") and nothing else
log.error("lost leadership, exiting");
reconciler.shutdownNow(); // interrupt in-flight work
System.exit(1); // nothing can outlive the lease
},
leader -> log.info("leader is now {}", leader)))
.build();
client.leaderElector().withConfig(cfg).build().run();

Notice the comment on the stop callback: the broken version logged and returned, which is exactly what let replica A continue. We also give the Kubernetes client short request timeouts, for example 5 seconds, so that a hanging renew cannot hide the deadline. If we keep the process alive instead of exiting, every worker must check a shared flag or be cancelled through its Future, and the reconcile loop must not start new work after the flag flips.

5Fix 2: Make Every Action Safe to Repeat

Even with a perfect stop callback, a 6-second GC pause can still create a brief overlap, because a paused process cannot notice anything. So the external actions must be harmless when done twice. For the load balancer, that means looking it up by a deterministic name or tag before creating it, for example a tag owner=service-uid derived from the Kubernetes Service's uid. Two leaders that both reconcile service X then find the same tag and the second one does nothing.

For Kubernetes objects we rely on optimistic concurrency. Every object has a resourceVersion, and an update that carries an old resourceVersion fails with 409 Conflict. If both replicas try to write the Service status, only the first succeeds, and the second re-reads and sees the work is already done.

Configuration and code changes
ChangeWhy
renewDeadline 10 s < leaseDuration 15 s, keep the gapold leader must give up before others may take over
Client request timeout about 5 sa hanging renew cannot delay the deadline check
Exit or cancel all work in onStopLeadingno worker survives lost leadership
Look up load balancers by owner tag firsta second leader finds the existing one
Update objects with resourceVersionconcurrent writes fail with 409, not overwrite

6Detecting and Testing It

Finally we make the problem visible. We export a metric for leader transitions and alert when they happen more than a few times an hour, and we run a periodic check that counts cloud load balancers per owner tag and alerts on any count above one. Then we test the fix: in a staging cluster we block the leader pod's traffic to the API server (an iptables rule on the node, or a chaos tool), and we also freeze it with kill -STOP for 20 seconds. The test passes when the old leader exits before the new one starts and no duplicate resources appear.

7Follow-up questions

Why not just make leaseDuration much longer, say 60 seconds?

A longer lease widens the safety gap, but it also means that after a real crash nobody does any reconciling for up to 60 seconds. It does not fix the underlying bug either: an old leader that never stops will overlap whatever the durations are. We keep reasonable durations, fix the stop behaviour, and make actions idempotent, and only then tune the timing for our failover needs.

Does Kubernetes compare timestamps across nodes to decide the lease has expired?

Not in the usual client implementations. A follower records when it last saw the Lease record change and measures leaseDuration on its own monotonic clock from that moment. That avoids wall-clock skew between nodes, but differences in clock rate and process pauses still matter, which is why the design keeps a gap between renewDeadline and leaseDuration.

8Conclusion

In this answer, we saw that Lease-based election only works if the old leader stops before anyone else may take the lease. Replica A lost contact, B correctly took over after 15 seconds, but A kept reconciling because its stop callback did not stop its workers and its renew call could hang. We fixed this by exiting or cancelling all work on lost leadership, adding request timeouts, making load balancer creation idempotent through deterministic tags and resourceVersion checks, and adding alerts and a partition test so the fix stays proven.

What to say in the interviewAbout 90 seconds aloud

Open with

Lease-based leader election is time-based. The leader has to renew within renewDeadline, ten seconds here, and followers only take over after leaseDuration, fifteen seconds, so there is a five-second gap where nobody should be leading.

Then, if they want more

That only works if the old leader actually stops. In this incident the blip stopped replica A's renewals, replica B took the lease after fifteen seconds, but A kept reconciling for another twenty seconds.

The usual causes are a stopped-leading callback that only logs while the worker threads carry on, a renew call with no timeout so the deadline check runs late, or a GC pause. I would fix it in layers.

First, in the stopped-leading callback I cancel all work and exit the process, which is what many controllers do, and I set short client timeouts. I keep renewDeadline clearly below leaseDuration.

Second, because a pause can still cause overlap, I make actions idempotent: look up the load balancer by a deterministic owner tag before creating it, and update Kubernetes objects with resourceVersion so a stale writer gets a conflict. I would also check whether my client library cancels work that was already submitted.

Third, I alert on leader transitions and on more than one load balancer per owner, and I test by cutting the leader off from the API server and by freezing it with SIGSTOP in staging.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How could two replicas act as leader at the same time, and what changes in code and...": https://scrivio-interview-library.netlify.app/architecture/distributed-systems/d37d819c1d/