Emergent Leader
Order cluster nodes based on their age within the cluster to allow nodes to select a leader without running an explicit election.
Problem
Peer-to-peer systems treat each cluster node as equal: there is no leader. This means there is no explicit leader election process as happens in the Leader and Followers pattern. Sometimes the cluster also doesn’t want to depend on a separate Consistent Core to improve availability. However, there still needs to be one cluster node acting as cluster coordinator for tasks such as assigning data partitions to other cluster nodes and tracking when new cluster nodes join or fail and taking corrective actions.
Solution
One of the common techniques used in peer-to-peer systems is to order cluster nodes according to their age in the cluster. The oldest member of the cluster plays the role of the coordinator. The coordinator is responsible for deciding on membership changes and making cluster-wide decisions, such as ensuring the distribution of Fixed Partitions across cluster nodes.
To form the cluster, one of the cluster nodes acts as a seed node or an introducer node. All the cluster nodes join the cluster by contacting the seed node.
Various discovery mechanisms can be provided to find the node to join the cluster. For example, JGroups provides different discovery protocols. 99 Akka provides several discovery mechanisms 100 as well.
-
[https://docs.jboss.org/jbossas/docs/Clustering_Guide/beta422/html/jbosscache-jgroups-discovery.html](https://docs.jboss.org/jbossas/docs/Clustering_Guide/beta422/html/jbosscache-jgroups-discovery.html) -
[https://doc.akka.io/docs/akka-management/current/discovery/index.html](https://doc.akka.io/docs/akka-management/current/discovery/index.html)
Every cluster node is configured with the seed node address. When a cluster node is started, it tries to contact the seed node to join the cluster.
Click here to view code image
class ClusterNode...
MembershipService membershipService;
public void start(Config config) {
this.membershipService = new MembershipService(config.getListenAddress());
membershipService.join(config.getSeedAddress());
}
The seed node could be any of the cluster nodes. It’s configured with its own address as the seed node address and is the first node that is started. It immediately begins accepting requests. The age of the seed node is 1.
Click here to view code image
class MembershipService...
Membership membership;
public void join(InetAddressAndPort seedAddress) {
var maxJoinAttempts = 5;
for(int i = 0; i < maxJoinAttempts; i++){
try {
joinAttempt(seedAddress);
return;
} catch (Exception e) {
logger.info("Join attempt "
+ i + "from "
+ selfAddress + " to "
+ seedAddress + " failed. Retrying");
}
}
throw new JoinFailedException("Unable to join the cluster after "
+ maxJoinAttempts + " attempts");
}
private void joinAttempt(InetAddressAndPort seedAddress)
throws ExecutionException, TimeoutException {
if (selfAddress.equals(seedAddress)) {
int membershipVersion = 1;
int age = 1;
updateMembership(new Membership(membershipVersion,
Arrays.asList(new Member(selfAddress,
age,
MemberStatus.JOINED))));
start();
return;
}
long id = this.messageId++;
var future = new CompletableFuture<JoinResponse>();
var message = new JoinRequest(id, selfAddress);
pendingRequests.put(id, future);
network.send(seedAddress, message);
var joinResponse = Uninterruptibles.getUninterruptibly(future, 5,
TimeUnit.SECONDS);
updateMembership(joinResponse.getMembership());
start();
}
private void start() {
heartBeatScheduler.start();
failureDetector.start();
startSplitBrainChecker();
logger.info(selfAddress + " joined the cluster. Membership="
+ membership);
}
private void updateMembership(Membership membership) {
this.membership = membership;
}
There can be more than one seed node, but any seed nodes start accepting requests only after they themselves join the cluster. Also, the cluster will remain functional if the seed node is down, but no new nodes will be able to join.
Non-seed nodes then send the join request to the seed node. The seed node handles the join request by creating a new member record and assigning its age. It updates its own membership list and sends messages to all the existing members with the new membership list. It then waits to make sure that the response is returned from every node, but will eventually return the join response even if the response is delayed.
Click here to view code image
class MembershipService...
public void handleJoinRequest(JoinRequest joinRequest) {
handlePossibleRejoin(joinRequest);
handleNewJoin(joinRequest);
}
private void handleNewJoin(JoinRequest joinRequest) {
List<Member> existingMembers = membership.getLiveMembers();
updateMembership(membership.addNewMember(joinRequest.from));
var resultsCollector = broadcastMembershipUpdate(existingMembers);
var joinResponse = new JoinResponse(joinRequest.messageId, selfAddress,
membership);
resultsCollector.whenComplete((response, exception) -> {
logger.info("Sending join response from "
+ selfAddress
+ " to "
+ joinRequest.from);
network.send(joinRequest.from, joinResponse);
});
}
class Membership...
public Membership addNewMember(InetAddressAndPort address) {
var newMembership = new ArrayList<>(liveMembers);
int age = yongestMemberAge() + 1;
newMembership.add(new Member(address, age, MemberStatus.JOINED));
return new Membership(version + 1, newMembership, failedMembers);
}
private int yongestMemberAge() {
return liveMembers.stream().map(m -> m.age).max(Integer::compare)
.orElse(0);
}
If a node that’s already part of the cluster is trying to rejoin after a crash, the failure detector state related to that member is cleared.
Click here to view code image
class MembershipService...
private void handlePossibleRejoin(JoinRequest joinRequest) {
if (membership.isFailed(joinRequest.from)) {
//member rejoining
logger.info(joinRequest.from
+ " rejoining the cluster. Removing it from failed list");
membership.removeFromFailedList(joinRequest.from);
}
}
That node is then added as a new member. Each member needs to be identified uniquely. It can be assigned a unique identifier at startup. This is a point of reference that makes it possible to detect that it is an existing cluster node that is rejoining.
The membership class maintains the list of live members as well as failed members. The members are moved from the live to failed list if they stop sending HeartBeat , as described in the “ Failure Detection ” section.
Click here to view code image
class Membership...
List<Member> liveMembers = new ArrayList<>();
List<Member> failedMembers = new ArrayList<>();
public boolean isFailed(InetAddressAndPort address) {
return failedMembers.stream().anyMatch(m -> m.address.equals(address));
}
Sending Membership Updates to All the Existing Members
Membership updates are sent to all the other nodes concurrently. The coordinator also needs to track whether all the members successfully received the updates.
A common technique is to send a one-way request to all nodes and expect an acknowledgment message. Cluster nodes send acknowledgment messages to the coordinator to confirm receipt of the membership update. A ResultCollector object can track receipt of all the messages asynchronously: It is notified every time an acknowledgment is received for a membership update. It completes its future once the expected acknowledgment messages are received.
Click here to view code image
class MembershipService...
private ResultsCollector
broadcastMembershipUpdate(List<Member> existingMembers) {
var resultsCollector = sendMembershipUpdateTo(existingMembers);
resultsCollector.orTimeout(2, TimeUnit.SECONDS);
return resultsCollector;
}
Map<Long, CompletableFuture> pendingRequests = new HashMap();
private ResultsCollector
sendMembershipUpdateTo(List<Member> existingMembers) {
var otherMembers = otherMembers(existingMembers);
var collector = new ResultsCollector(otherMembers.size());
if (otherMembers.size() == 0) {
collector.complete();
return collector;
}
for (Member m : otherMembers) {
var id = this.messageId++;
var future = new CompletableFuture<Message>();
future.whenComplete((result, exception) -> {
if (exception == null){
collector.ackReceived();
}
});
pendingRequests.put(id, future);
network.send(m.address,
new UpdateMembershipRequest(id, selfAddress, membership));
}
return collector;
}
class MembershipService...
private void handleResponse(Message message) {
completePendingRequests(message);
}
private void completePendingRequests(Message message) {
var requestFuture = pendingRequests.get(message.messageId);
if (requestFuture != null) {
requestFuture.complete(message);
}
}
class ResultsCollector...
class ResultsCollector {
int totalAcks;
int receivedAcks;
CompletableFuture future = new CompletableFuture();
public ResultsCollector(int totalAcks) {
this.totalAcks = totalAcks;
}
public void ackReceived() {
receivedAcks++;
if (receivedAcks == totalAcks) {
future.complete(true);
}
}
public void orTimeout(int time, TimeUnit unit) {
future.orTimeout(time, unit);
}
public void
whenComplete(BiConsumer<? super Object, ? super Throwable> func) {
future.whenComplete(func);
}
public void complete() {
future.complete("true");
}
}
To see how ResultCollector works, consider a cluster with the nodes Athens, Byzantium, and Cyrene. Athens is acting as a coordinator. When a new node, Delphi, sends a join request to Athens, Athens updates the membership and sends the updateMembership request to Byzantium and Cyrene. It also creates a ResultCollector object to track acknowledgments. It records each acknowledgment received with ResultCollector . When it receives acknowledgments from both Byzantium and Cyrene, it responds to Delphi ( Figure 29.1 ).
Figure 29.1 Node join completes after membership is updated on all the nodes.
Frameworks such as Akka use Gossip Dissemination and gossip convergence 101 to track whether updates have reached all cluster nodes.
-
[https://doc.akka.io/docs/akka/current/typed/cluster-concepts.html#gossip-convergence](https://doc.akka.io/docs/akka/current/typed/cluster-concepts.html#gossip-convergence)
An Example Scenario
Consider another three nodes. Again, we’ll call them Athens, Byzantium, and Cyrene. Athens acts as a seed node; the other two nodes are configured with Athens’ address.
When Athens starts, it detects that it is itself the seed node. It immediately initializes the membership list and starts accepting requests ( Figure 29.2 ).
Figure 29.2 Seed node starts
When Byzantium starts, it sends a join request to Athens. Even if Byzantium starts before Athens, it will keep trying to send join requests until it can connect to Athens. Athens finally adds Byzantium to the membership list and sends the updated membership list to Byzantium. Once Byzantium receives the response from Athens, it can start accepting requests ( Figure 29.3 ).
Figure 29.3 Node joins the cluster by contacting the seed node.
With all-to-all heartbeating, Byzantium starts sending heartbeats to Athens, and Athens sends heartbeats to Byzantium.
Cyrene starts next. It sends join requests to Athens. Athens updates the membership list and sends the updated membership list to Byzantium. It then sends the join response with the membership list to Cyrene ( Figure 29.4 ).
Figure 29.4 Existing members get membership updates.
With all to all heartbeating, Cyrene, Athens, and Byzantium all send heartbeats to each other.
Handling Missing Membership Updates
It’s possible that some cluster nodes miss membership updates. There are two ways to handle this problem.
If all members are sending heartbeats to all other members, the membership version number can be sent as part of the heartbeat. The cluster node that handles the heartbeat can then ask for the latest membership.
Click here to view code image
class MembershipService...
private void handleHeartbeatMessage(HeartbeatMessage message) {
failureDetector.heartBeatReceived(message.from);
if (isCoordinator()
&& (message.getMembershipVersion()
< this.membership.getVersion())) {
membership.getMember(message.from)
.ifPresent(member -> {
logger.info("Membership version in "
+ selfAddress + "="
+ this.membership.version
+ " and in " + message.from
+ "=" + message.getMembershipVersion());
logger.info("Sending membership update from "
+ selfAddress + " to " + message.from);
sendMembershipUpdateTo(Arrays.asList(member));
});
}
}
In the above example, if Byzantium misses a membership update from Athens, it will be detected when Byzantium sends a heartbeat to Athens. Athens can then send the latest membership to Byzantium ( Figure 29.5 ).
Figure 29.5 Nodes detect missing membership using a version number.
Alternatively, each cluster node can check the latest membership list periodically—say, every one second—with other cluster nodes. If any of the nodes figures out that its member list is outdated, it can then ask for the latest membership list so it can update it. To be able to compare membership lists, a version number is maintained and incremented every time there is a change.
Failure Detection
In a simple case, all cluster nodes send heartbeats to all the other nodes. Each cluster node also runs a failure detector to check if heartbeats are missing from any of the cluster nodes. But only the coordinator marks the nodes as failed and communicates the updated membership list to all the other nodes. This makes sure that nodes don’t unilaterally decide if some other node has failed. Hazelcast is an example of this implementation.
Click here to view code image
class MembershipService...
private boolean isCoordinator() {
Member coordinator = membership.getCoordinator();
return coordinator.address.equals(selfAddress);
}
TimeoutBasedFailureDetector<InetAddressAndPort> failureDetector
= new TimeoutBasedFailureDetector<InetAddressAndPort>(Duration.ofSeconds(2));
private void checkFailedMembers(List<Member> members) {
if (isCoordinator()) {
removeFailedMembers();
} else {
//if failed member consists of coordinator,
// then check if this node is the next coordinator.
claimLeadershipIfNeeded(members);
}
}
void removeFailedMembers() {
var failedMembers =
checkAndGetFailedMembers(membership.getLiveMembers());
if (failedMembers.isEmpty()) {
return;
}
updateMembership(membership.failed(failedMembers));
sendMembershipUpdateTo(membership.getLiveMembers());
}
Avoiding All-to-All Heartbeating
All-to-all heartbeating is not feasible in large clusters. Typically, each node will receive heartbeats from only a few other nodes. If a failure is detected, it’s broadcasted to all the other nodes including the coordinator.
For example, in Akka, a node ring is formed by sorting network addresses so that each cluster node only sends heartbeats to a few cluster nodes. Apache Ignite arranges all the nodes in the cluster in a ring so that each node only sends heartbeat to the node next to it. Hazelcast 102 uses all-to-all heartbeat.
-
[https://hazelcast.com/](https://hazelcast.com/)
Any membership changes, because of nodes being added or node failures, need to be broadcast to all the other cluster nodes. A node can connect to every other node to send the required information. Gossip Dissemination can be used to broadcast this information.
Split Brain
Even though a single coordinator node decides when to mark another node as down, there’s no explicit leader election to select which node acts as a coordinator. Every cluster node expects a heartbeat from the existing coordinator node; if it doesn’t get a heartbeat in time, it can then claim to be the coordinator and remove the existing coordinator from the memberlist.
Click here to view code image
class MembershipService...
private void claimLeadershipIfNeeded(List<Member> members) {
var failedMembers = checkAndGetFailedMembers(members);
if (!failedMembers.isEmpty() && isOlderThanAll(failedMembers)) {
var newMembership = membership.failed(failedMembers);
updateMembership(newMembership);
sendMembershipUpdateTo(newMembership.getLiveMembers());
}
}
private boolean isOlderThanAll(List<Member> failedMembers) {
return failedMembers.stream().allMatch(m -> m.age < thisMember().age);
}
private List<Member> checkAndGetFailedMembers(List<Member> members) {
List<Member> failedMembers = members
.stream()
.filter(this::isFailed)
.map(member ->
new Member(member.address,
member.age,
member.status))
.collect(Collectors.toList());
failedMembers.forEach(member -> {
failureDetector.remove(member.address);
logger.info(selfAddress + " marking " + member.address + " as DOWN");
});
return failedMembers;
}
private boolean isFailed(Member member) {
return !member.address.equals(selfAddress)
&& failureDetector.isMonitoring(member.address)
&& !failureDetector.isAlive(member.address);
}
This can create a situation where two or more subgroups form in an existing cluster, each subgroup considering the others to have failed. This is called a split brain problem .
Consider a five-node cluster: Athens, Byzantium, Cyrene, Delphi, and Ephesus. If Athens receives heartbeats from Delphi and Ephesus, but stops getting heartbeats from Byzantium and Cyrene, it marks both Byzantium and Cyrene as failed.
Byzantium and Cyrene could send heartbeats to each other but stop receiving heartbeats from Cyrene, Delphi, and Ephesus. Byzantium, being the second oldest member of the cluster, then becomes the coordinator. So two separate clusters are formed, one with Athens as the coordinator and the other with Byzantium as the coordinator ( Figure 29.6 ).
Figure 29.6 Partial connectivity leads to a split brain.
Handling Split Brain
One common way to handle the split brain issue is to check whether there are enough members to handle any client request, and reject the request if there are not enough live members. For example, Hazelcast allows you to configure the minimum cluster size to execute any client request.
Click here to view code image
public void handleClientRequest(Request request) {
if (!hasMinimumRequiredSize()) {
throw new NotEnoughMembersException("Requires minimum 3 members " +
"to serve the request");
}
}
private boolean hasMinimumRequiredSize() {
return membership.getLiveMembers().size() > 3;
}
The part which has the majority of the nodes continues to operate.The nodes in the minority stop serving client requests. As explained in the Hazelcast documentation, there will always be a time window 103 before this mechanism comes into effect.
-
[https://docs.hazelcast.com/imdg/4.2/network-partitioning/split-brain-protection#time-window-for-split-brain-protection](https://docs.hazelcast.com/imdg/4.2/network-partitioning/split-brain-protection#time-window-for-split-brain-protection)
The problem can be avoided if cluster nodes are not marked as down unless it’s guaranteed that this won’t cause a split brain. For example, Akka recommends that you don’t have nodes marked as down 104 through the failure detector; instead, you can use its split brain resolver 105 component.
-
[https://doc.akka.io/docs/akka/2.5/cluster-usage.html#auto-downing-do-not-use-](https://doc.akka.io/docs/akka/2.5/cluster-usage.html#auto-downing-do-not-use-) -
[https://doc.akka.io/docs/akka-enhancements/current/split-brain-resolver.html](https://doc.akka.io/docs/akka-enhancements/current/split-brain-resolver.html)
Recovering from Split Brain
The coordinator runs a periodic job to check if it can connect to the failed nodes. If a connection can be established, it sends a special message indicating that it wants to trigger a split brain merge.
If the receiving node is the coordinator of a subcluster, it will check to see if the cluster that is initiating the request is part of a minority group. If it is, it will send a merge request. The coordinator of the minority group, upon receiving the merge request, will execute the merge request on all the nodes in the minority subgroup.
Click here to view code image
class MembershipService...
splitbrainCheckTask = taskScheduler.scheduleWithFixedDelay(() -> {
searchOtherClusterGroups();
},
1, 1, TimeUnit.SECONDS);
class MembershipService...
private void searchOtherClusterGroups() {
if (membership.getFailedMembers().isEmpty()) {
return;
}
var allMembers = new ArrayList<Member>();
allMembers.addAll(membership.getLiveMembers());
allMembers.addAll(membership.getFailedMembers());
if (isCoordinator()) {
for (Member member : membership.getFailedMembers()) {
logger.info("Sending SplitBrainJoinRequest to "
+ member.address);
network.send(member.address,
new SplitBrainJoinRequest(messageId++,
this.selfAddress,
membership.version,
membership.getLiveMembers().size()));
}
}
}
If the receiving node is the coordinator of the majority subgroup, it asks the sending coordinator node to merge with itself.
Click here to view code image
class MembershipService...
private void handleSplitBrainJoinMessage(
SplitBrainJoinRequest splitBrainJoinRequest) {
logger.info(selfAddress + " Handling SplitBrainJoinRequest from "
+ splitBrainJoinRequest.from);
if (!membership.isFailed(splitBrainJoinRequest.from)) {
return;
}
if (!isCoordinator()) {
return;
}
if(splitBrainJoinRequest.getMemberCount()
< membership.getLiveMembers().size()) {
//requesting node should join this cluster.
logger.info(selfAddress
+ " Requesting "
+ splitBrainJoinRequest.from
+ " to rejoin the cluster");
network.send(splitBrainJoinRequest.from,
new SplitBrainMergeMessage(splitBrainJoinRequest.messageId,
selfAddress));
} else {
//we need to join the other cluster
mergeWithOtherCluster(splitBrainJoinRequest.from);
}
}
private void mergeWithOtherCluster(
InetAddressAndPort otherClusterCoordinator) {
askAllLiveMembersToMergeWith(otherClusterCoordinator);
//initiate merge on this node.
handleMerge(new MergeMessage(messageId++,
selfAddress, otherClusterCoordinator));
}
private void askAllLiveMembersToMergeWith(
InetAddressAndPort mergeToAddress) {
List<Member> liveMembers = membership.getLiveMembers();
for (Member m : liveMembers) {
network.send(m.address,
new MergeMessage(messageId++, selfAddress, mergeToAddress));
}
}
In our last example shown in Figure 29.7 , when Athens can communicate with Byzantium, it will ask Byzantium to merge with itself.
Figure 29.7 Triggering split brain merge
The coordinator of the smaller subgroup then asks all the cluster nodes inside its group to trigger a merge. The merge operation shuts down the cluster nodes and rejoins them to the coordinator of the larger group.
In this example, Byzantium and Cyrene shut down and rejoin Athens to form a full cluster again ( Figure 29.8 ).
Figure 29.8 Nodes rejoin after split brain merge.
Click here to view code image
class MembershipService...
private void handleMerge(MergeMessage mergeMessage) {
logger.info(selfAddress + " Merging with " + mergeMessage.getMergeToAddress());
shutdown();
//join the cluster again through the other cluster's coordinator
taskScheduler.execute(() -> {
join(mergeMessage.getMergeToAddress());
});
}
Comparison with Leader and Followers
Let’s compare this pattern with Leader and Followers . The leader-follower setup, as used by patterns like Consistent Core , does not function unless the leader is chosen by running an election. This guarantees that the Majority Quorum of cluster nodes have an agreement about who the leader is. In the worst case, if an agreement isn’t reached, the system will be unavailable to process any requests. In other words, it prefers consistency over availability.
The emergent leader, on the other hand, will always have some cluster node acting as a leader for processing client requests. In this case, availability is preferred over consistency.
Examples
-
In JGroups, the oldest member is the coordinator that decides on membership changes.
-
In Akka, the oldest member of the cluster runs actor singletons, such as the shard coordinator which decides on the placement of Fixed Partitions across cluster nodes.
-
In-memory data grids, such as Hazelcast and Apache Ignite, have the oldest member act as the cluster coordinator.