Fixed Partitions
Keep the number of partitions fixed so that the mapping of data to partition stays the same when the size of a cluster changes.
Problem
To split data across a set of cluster nodes, each data item needs to be mapped to them. There are two requirements for mapping data to the cluster nodes.
-
The distribution should be uniform.
-
It should be possible to know which cluster node stores a particular data item without making a request to all the nodes.
Consider a key-value store, which is a good proxy for many storage systems. Both requirements can be fulfilled by taking a hash of the key and using the modulo operation to map it to a cluster node. So if we have a three-node cluster, we can map keys Alice, Bob, Mary, and Philip, as Table 19.1 demonstrates.
Table 19.1 Key Mapping in a Three-Node Cluster
| Keys | Hash | Node Index = Hash % 3 |
|---|---|---|
| Alice | 133299819613694460644197938031451912208 | 0 |
| Bob | 63479738429015246738359000453022047291 | 1 |
| Mary | 37724856304035789372490171084843241126 | 2 |
| Philip | 83980963731216160506671196398339418866 | 2 |
However, this method creates a problem when the cluster size changes. If two more nodes are added to the cluster, we will have five nodes. The mapping will then look as shown in Table 19.2 .
Table 19.2 Key Mapping in a Five-Node Cluster
| Keys | Hash | Node Index = Hash % 5 |
|---|---|---|
| Alice | 133299819613694460644197938031451912208 | 3 |
| Bob | 63479738429015246738359000453022047291 | 1 |
| Mary | 37724856304035789372490171084843241126 | 1 |
| Philip | 83980963731216160506671196398339418866 | 1 |
This way, mapping for almost all the keys changes. Even after adding only a few new cluster nodes, all the data needs to be moved. When the data size is large, this is undesirable.
Solution
A message broker such as Apache Kafka needs an ordering guarantee for the data per partition. With fixed partitions, the data per partition doesn’t change even when partitions are moved around the cluster nodes after new nodes are added. This maintains the ordering of data per partition.
One of the most commonly used solution is to map data to logical partitions. Logical partitions are mapped to the cluster nodes. Even if cluster nodes are added or removed, the mapping of data to partitions doesn’t change. The cluster is launched with a preconfigured number of partitions—for the sake of this example, 1024. This number does not change when new nodes are added to the cluster. So the way data is mapped to partitions using a hash of the key remains the same.
It’s important that partitions are evenly distributed across cluster nodes. When partitions are moved to new nodes, it should be relatively quick with only a smaller portion of the data being moved.
Once configured, the partition number won’t change. This means it should have enough room for future growth of data volumes—it should be significantly higher than the number of cluster nodes. For example, Akka suggests you should have the number of shards ten times the number of nodes. Partitioning in Apache Ignite 58 has its default value at 1024. Hazelcast has a default value of 271 for cluster size smaller than 100.
-
[https://ignite.apache.org/docs/latest/data-modeling/data-partitioning](https://ignite.apache.org/docs/latest/data-modeling/data-partitioning)
Data storage or retrieval is then a two-step process.
-
First, you find the partition for the given data item.
-
Then you find the cluster node where the partition is stored.
To balance data across the cluster nodes when new ones are added, some of the partitions can be moved to the new nodes.
Choosing the Hash Function
It’s critical to choose the hashing method that gives the same hash values independent of the platform and runtime. For example, programming languages like Java provide a hash for every object. However, that hash value is dependent on the JVM runtime, so two different JVMs could give a different hash for the same key. To tackle this, use hashing algorithms such as MD5 hash or Murmur hash.
Click here to view code image
class HashingUtil...
public static BigInteger hash(String key)
{
try {
var messageDigest = MessageDigest.getInstance("MD5");
return new BigInteger(messageDigest.digest(key.getBytes()));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
The keys are mapped to partitions, not to nodes. If there are nine partitions, the result might look like Table 19.3 .
Table 19.3 Key Mapping with Fixed Logical Partitions
| Keys | Hash | Partition = Hash % 9 | Node |
|---|---|---|---|
| Alice | 133299819613694460644197938031451912208 | 0 | 0 |
| Bob | 63479738429015246738359000453022047291 | 1 | 1 |
| Mary | 37724856304035789372490171084843241126 | 5 | 1 |
| Philip | 83980963731216160506671196398339418866 | 2 | 2 |
When new nodes are added to the cluster, the mapping of a key to partition does not change.
Mapping Partitions to Cluster Nodes
Partitions need to be mapped to cluster nodes. This mapping also needs to be stored and made accessible to the clients. It’s common to use a dedicated Consistent Core that handles both. The dedicated Consistent Core acts as a coordinator that keeps track of all nodes in the cluster and maps partitions to nodes. It also stores the mapping in a fault-tolerant way by using a Replicated Log . The master cluster in YugabyteDB and the controller implementation in Kafka [ McCabe2021 ] are both good examples of this.
Peer-to-peer systems such as Akka or Hazelcast also need a particular cluster node to act as a coordinator. They use Emergent Leader as the coordinator.
Systems like Kubernetes use a generic Consistent Core, such as etcd. They need to elect one of the cluster nodes to play the role of coordinator as discussed in the section “ Leader Election Using a Consistent Core ” of the Leader and Followers pattern.
Tracking Cluster Membership
Each cluster node will register itself with the consistent core ( Figure 19.1 ). It also periodically sends a HeartBeat to allow the consistent core detect node failures.
Figure 19.1 Consistent Core tracking cluster membership
Click here to view code image
class KVStore...
public void start() {
socketListener.start();
requestHandler.start();
network.sendAndReceive(coordLeader,
new RegisterClusterNodeRequest(generateMessageId(),
listenAddress));
scheduler.scheduleAtFixedRate(() -> {
network
.send(coordLeader,
new HeartbeatMessage(generateMessageId(),
listenAddress));
}, 200, 200, TimeUnit.MILLISECONDS);
}
The coordinator handles the registration and then stores member information.
Click here to view code image
class ClusterCoordinator...
ReplicatedLog replicatedLog;
Membership membership = new Membership();
TimeoutBasedFailureDetector failureDetector
= new TimeoutBasedFailureDetector(Duration.ofMillis(TIMEOUT_MILLIS));
private void handleRegisterClusterNodeRequest(Message message) {
logger.info("Registering node " + message.from);
var completableFuture = registerClusterNode(message.from);
completableFuture.whenComplete((response, error) -> {
logger.info("Sending register response to node " + message.from);
network.send(message.from,
new RegisterClusterNodeResponse(message.messageId,
listenAddress));
});
}
public CompletableFuture registerClusterNode(InetAddressAndPort address) {
return replicatedLog.propose(new RegisterClusterNodeCommand(address));
}
When a registration is committed in the Replicated Log , the membership will be updated.
Click here to view code image
class ClusterCoordinator...
private void applyRegisterClusterNodeEntry(
RegisterClusterNodeCommand command) {
updateMembership(command.memberAddress);
}
class ClusterCoordinator...
private void updateMembership(InetAddressAndPort address) {
membership = membership.addNewMember(address);
failureDetector.heartBeatReceived(address);
}
The coordinator maintains a list of all nodes that are part of the cluster:
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));
}
class Member...
public class Member implements Comparable<Member> {
InetAddressAndPort address;
MemberStatus status;
The coordinator will detect cluster node failures using a mechanism similar to Lease . If a cluster node stops sending the heartbeat, the node will be marked as failed.
Click here to view code image
class ClusterCoordinator...
@Override
public void onBecomingLeader() {
scheduledTask = executor.scheduleWithFixedDelay(this::checkMembership,
1000,
1000,
TimeUnit.MILLISECONDS);
failureDetector.start();
}
private void checkMembership() {
var failedMembers = getFailedMembers();
if (!failedMembers.isEmpty()) {
replicatedLog.propose(new MemberFailedCommand(failedMembers));
}
}
private List<Member> getFailedMembers() {
var liveMembers = membership.getLiveMembers();
return liveMembers.stream()
.filter(m ->
failureDetector.isMonitoring(m.getAddress())
&& !failureDetector.isAlive(m.getAddress()))
.collect(Collectors.toList());
}
The coordinator updates membership once the MemberFailedCommand is committed.
Click here to view code image
class ClusterCoordinator...
private void applyMemberFailedCommand(MemberFailedCommand command) {
membership = membership.failed(command.getFailedMember());
}
class Membership...
public Membership failed(List<Member> failedMembers) {
List<Member> liveMembers = new ArrayList<>(this.liveMembers);
liveMembers.removeAll(failedMembers);
for (Member m : failedMembers) {
m.markDown();
}
return new Membership(version + 1, liveMembers, failedMembers);
}
Assigning Partitions to Cluster Nodes
For data stores like Apache Kafka or Hazelcast that have logical storage structures such as topics, caches, or tables, the partitions are created at the same time as these logical structures. The expectation is that the storage structures will be created after all nodes in the cluster are launched and have registered with the consistent core.
The coordinator assigns partitions to cluster nodes that are known at that point in time. If it’s triggered every time a new cluster node is added, it might map partitions too early before the cluster reaches a stable state. This is why the coordinator should be configured to wait until the cluster reaches a minimum size.
The first time the partitions are assigned, it can be done simply in a round robin fashion. Apache Ignite uses a more sophisticated mapping using rendezvous hashing. 59
-
[https://www.gridgain.com/resources/blog/data-distribution-in-apache-ignite](https://www.gridgain.com/resources/blog/data-distribution-in-apache-ignite)
Click here to view code image
class ClusterCoordinator...
CompletableFuture assignPartitionsToClusterNodes() {
if (!minimumClusterSizeReached()) {
var e = new NotEnoughClusterNodesException(MINIMUM_CLUSTER_SIZE);
return CompletableFuture.failedFuture(e);
}
return initializePartitionAssignment();
}
private boolean minimumClusterSizeReached() {
return membership.getLiveMembers().size() >= MINIMUM_CLUSTER_SIZE;
}
private CompletableFuture initializePartitionAssignment() {
partitionAssignmentStatus = PartitionAssignmentStatus.IN_PROGRESS;
var partitionTable = arrangePartitions();
return replicatedLog.propose(new PartitiontableCommand(partitionTable));
}
public PartitionTable arrangePartitions() {
var partitionTable = new PartitionTable();
var liveMembers = membership.getLiveMembers();
for (int partitionId = 1; partitionId <= noOfPartitions;
partitionId++) {
var index = partitionId % liveMembers.size();
var member = liveMembers.get(index);
partitionTable.addPartition(partitionId,
new PartitionInfo(partitionId,
member.getAddress(),
PartitionStatus.ASSIGNED));
}
return partitionTable;
}
The Replicated Log makes the partition table persistent.
Click here to view code image
class ClusterCoordinator...
PartitionTable partitionTable;
PartitionAssignmentStatus partitionAssignmentStatus
= PartitionAssignmentStatus.UNASSIGNED;
private void applyPartitionTableCommand(PartitiontableCommand command) {
this.partitionTable = command.partitionTable;
partitionAssignmentStatus = PartitionAssignmentStatus.ASSIGNED;
if (isLeader()) {
sendMessagesToMembers(partitionTable);
}
}
Once the partition assignment is persisted, the coordinator sends messages to all cluster nodes to tell each node which partitions it now owns.
Click here to view code image
class ClusterCoordinator...
List<Integer> pendingPartitionAssignments = new ArrayList<>();
private void sendMessagesToMembers(PartitionTable partitionTable) {
var partitionsTobeHosted = partitionTable.getPartitionsTobeHosted();
partitionsTobeHosted.forEach((partitionId, partitionInfo) -> {
pendingPartitionAssignments.add(partitionId);
var message = new HostPartitionMessage(requestNumber++,
this.listenAddress, partitionId);
scheduler.execute(new RetryableTask(partitionInfo.hostedOn,
network, this, partitionId, message));
});
}
The controller will keep trying to reach nodes continuously until its message is successful.
Click here to view code image
class RetryableTask...
static class RetryableTask implements Runnable {
Logger logger = LogManager.getLogger(RetryableTask.class);
InetAddressAndPort address;
Network network;
ClusterCoordinator coordinator;
Integer partitionId;
int attempt;
private Message message;
public RetryableTask(InetAddressAndPort address,
Network network,
ClusterCoordinator coordinator,
Integer partitionId,
Message message) {
this.address = address;
this.network = network;
this.coordinator = coordinator;
this.partitionId = partitionId;
this.message = message;
}
@Override
public void run() {
attempt++;
try {
//stop trying if the node has failed.
if (coordinator.isSuspected(address)) {
return;
}
network.send(address, message);
} catch (Exception e) {
scheduleWithBackOff();
}
}
private void scheduleWithBackOff() {
scheduler.schedule(this, getBackOffDelay(attempt),
TimeUnit.MILLISECONDS);
}
private long getBackOffDelay(int attempt) {
long baseDelay = (long) Math.pow(2, attempt);
long jitter = randomJitter();
return baseDelay + jitter;
}
private long randomJitter() {
int i = new Random(1).nextInt();
i = i < 0 ? i * -1 : i;
long jitter = i % 50;
return jitter;
}
}
When a cluster node receives the request to create a partition, it creates one with the given partition ID. If we imagine this happening within a simple key-value store, its implementation could look something like this:
Click here to view code image
class KVStore...
Map<Integer, Partition> allPartitions = new ConcurrentHashMap<>();
private void handleHostPartitionMessage(Message message) {
var partitionId = ((HostPartitionMessage) message).getPartitionId();
addPartitions(partitionId);
logger.info("Adding partition " + partitionId + " to " + listenAddress);
network.send(message.from,
new HostPartitionAcks(message.messageId,
this.listenAddress, partitionId));
}
public void addPartitions(Integer partitionId) {
allPartitions.put(partitionId, new Partition(partitionId));
}
class Partition...
SortedMap<String, String> kv = new TreeMap<>();
private Integer partitionId;
Once the coordinator receives the message that the partition has been successfully created, it persists it in the replicated log and updates the partition status to be online:
Click here to view code image
class ClusterCoordinator...
private void handleHostPartitionAck(Message message) {
var partitionId = ((HostPartitionAcks) message).getPartitionId();
pendingPartitionAssignments.remove(Integer.valueOf(partitionId));
var future =
replicatedLog.propose(
new UpdatePartitionStatusCommand(partitionId,
PartitionStatus.ONLINE));
future.join();
}
Once the High-Water Mark is reached and the record is applied, the partition’s status will be updated.
Click here to view code image
class ClusterCoordinator...
private void updateParitionStatus(UpdatePartitionStatusCommand command) {
removePendingRequest(command.partitionId);
partitionTable.updateStatus(command.partitionId, command.status);
}
Client Interface
Again, consider the example of a simple key-value store. If a client needs to store or get a value for a particular key, it can do so by following these steps:
-
The client applies the hash function to the key and finds the relevant partition based on the total number of partitions.
-
The client gets the partition table from the coordinator and finds the cluster node that is hosting the partition. The client also periodically refreshes the partition table.
Apache Kafka encountered an issue 60 when all the producers and consumers simultaneously fetched partition metadata. This placed a heavy load on Kafka brokers as they retrieved all the metadata from ZooKeeper. As a solution, the decision was made to cache metadata across all the brokers.
-
[https://issues.apache.org/jira/browse/KAFKA-901](https://issues.apache.org/jira/browse/KAFKA-901)
A similar issue 61 was also observed in YugabyteDB.
-
[https://gist.github.com/jrudolph/be4e04a776414ce07de6019ccb0d3e42](https://gist.github.com/jrudolph/be4e04a776414ce07de6019ccb0d3e42)
Clients fetching a partition table from the coordinator can quickly lead to bottlenecks, especially if all requests are being served by a single coordinator leader. That is why it is common practice to keep metadata available on all cluster nodes. The coordinator can either push metadata to cluster nodes, or cluster nodes can pull it from the coordinator. Clients can then connect with any cluster node to refresh the metadata.
This can be implemented inside the client library provided by the key-value store or inside client request handling which happens on the cluster nodes.
Click here to view code image
class Client...
public void put(String key, String value) throws IOException {
var partitionId = findPartition(key, noOfPartitions);
var nodeAddress = getNodeAddressFor(partitionId);
sendPutMessage(partitionId, nodeAddress, key, value);
}
private InetAddressAndPort getNodeAddressFor(Integer partitionId) {
var partitionInfo = partitionTable.getPartition(partitionId);
var nodeAddress = partitionInfo.getAddress();
return nodeAddress;
}
private void sendPutMessage(Integer partitionId,
InetAddressAndPort address,
String key, String value) throws IOException {
var partitionPutMessage = new PartitionPutMessage(partitionId, key, value);
var socketClient = new SocketClient(address);
socketClient
.blockingSend(new RequestOrResponse(partitionPutMessage));
}
public String get(String key) throws IOException {
var partitionId = findPartition(key, noOfPartitions);
var nodeAddress = getNodeAddressFor(partitionId);
return sendGetMessage(partitionId, key, nodeAddress);
}
private String sendGetMessage(Integer partitionId,
String key,
InetAddressAndPort address) throws IOException {
var partitionGetMessage = new PartitionGetMessage(partitionId, key);
var socketClient = new SocketClient(address);
var response =
socketClient
.blockingSend(new RequestOrResponse(partitionGetMessage));
var partitionGetResponseMessage =
deserialize(response.getMessageBody(),
PartitionGetResponseMessage.class);
return partitionGetResponseMessage.getValue();
}
Moving Partitions to Newly Added Members
When new nodes are added to a cluster, some partitions can be moved to other nodes. This can be done automatically once a new cluster node is added. But it can involve a lot of data being moved across the cluster, which is why an administrator will typically trigger the repartitioning. One simple method to do this is to calculate the average number of partitions each node should host and then move this many partitions to the new node. For example, if the number of partitions is 30 and there are three existing nodes in the cluster, each node should host 10 partitions. If a new node is added, the average per node is about 7. The coordinator will therefore try to move 3 partitions from each cluster node to the new node.
Click here to view code image
class ClusterCoordinator...
List<Migration> pendingMigrations = new ArrayList<>();
boolean reassignPartitions() {
if (partitionAssignmentInProgress()) {
logger.info("Partition assignment in progress");
return false;
}
var migrations = repartition(this.partitionTable);
var proposalFuture =
replicatedLog.propose(new MigratePartitionsCommand(migrations));
proposalFuture.join();
return true;
}
public List<Migration> repartition(PartitionTable partitionTable) {
int averagePartitionsPerNode = getAveragePartitionsPerNode();
List<Member> liveMembers = membership.getLiveMembers();
var overloadedNodes = partitionTable
.getOverloadedNodes(averagePartitionsPerNode, liveMembers);
var underloadedNodes = partitionTable
.getUnderloadedNodes(averagePartitionsPerNode, liveMembers);
return tryMovingPartitionsToUnderLoadedMembers(averagePartitionsPerNode,
overloadedNodes, underloadedNodes);
}
private List<Migration>
tryMovingPartitionsToUnderLoadedMembers(int averagePartitionsPerNode,
Map<InetAddressAndPort, PartitionList> overloadedNodes,
Map<InetAddressAndPort, PartitionList> underloadedNodes) {
List<Migration> migrations = new ArrayList<>();
for (InetAddressAndPort member : overloadedNodes.keySet()) {
var partitions = overloadedNodes.get(member);
var toMove = partitions
.subList(averagePartitionsPerNode, partitions.getSize());
overloadedNodes.put(member,
partitions.subList(0, averagePartitionsPerNode));
var moveQ = new ArrayDeque<Integer>(toMove.partitionList());
while (!moveQ.isEmpty() && nodeWithLeastPartitions(underloadedNodes,
averagePartitionsPerNode).isPresent()) {
assignToNodesWithLeastPartitions(migrations,
member, moveQ,
underloadedNodes, averagePartitionsPerNode);
}
if (!moveQ.isEmpty()) {
overloadedNodes.get(member).addAll(moveQ);
}
}
return migrations;
}
int getAveragePartitionsPerNode() {
return noOfPartitions / membership.getLiveMembers().size();
}
The coordinator will persist the computed migrations in the replicated log and then send requests to move partitions across the cluster nodes.
Click here to view code image
private void applyMigratePartitionCommand(
MigratePartitionsCommand command) {
logger.info("Handling partition migrations " + command.migrations);
for (Migration migration : command.migrations) {
var message = new RequestPartitionMigrationMessage(requestNumber++,
this.listenAddress, migration);
pendingMigrations.add(migration);
if (isLeader()) {
scheduler.execute(new RetryableTask(migration.fromMember,
network, this, migration.getPartitionId(), message));
}
}
}
When a cluster node receives a request to migrate, it will mark the partition as migrating. This stops any further modifications to the partition. It will then send the entire partition data to the target node.
Click here to view code image
class KVStore...
private void handleRequestPartitionMigrationMessage(
RequestPartitionMigrationMessage message) {
Migration migration = message.getMigration();
Integer partitionId = migration.getPartitionId();
InetAddressAndPort toServer = migration.getToMember();
if (!allPartitions.containsKey(partitionId)) {
return;// The partition is not available with this node.
}
Partition partition = allPartitions.get(partitionId);
partition.setMigrating();
network.send(toServer,
new MovePartitionMessage(requestNumber++, this.listenAddress,
toServer, partition));
}
The cluster node that receives the request will add the new partition to itself and return an acknowledgment.
Click here to view code image
class KVStore...
private void handleMovePartition(Message message) {
var movePartitionMessage = (MovePartitionMessage) message;
var partition = movePartitionMessage.getPartition();
allPartitions.put(partition.getId(), partition);
network.send(message.from,
new PartitionMovementComplete(message.messageId, listenAddress,
new Migration(movePartitionMessage.getMigrateFrom(),
movePartitionMessage.getMigrateTo(),
partition.getId())));
}
The cluster node that previously owned the partition will then send the “migration complete” message to the cluster coordinator.
Click here to view code image
class KVStore...
private void handlePartitionMovementCompleteMessage(
PartitionMovementComplete message) {
allPartitions.remove(message.getMigration().getPartitionId());
network.send(coordLeader,
new MigrationCompleteMessage(requestNumber++, listenAddress,
message.getMigration()));
}
The cluster coordinator will then mark the migration as complete. The change will be stored in the replicated log.
Click here to view code image
class ClusterCoordinator...
private void
handleMigrationCompleteMessage(MigrationCompleteMessage message) {
var command = new MigrationCompletedCommand(message.getMigration());
var propose = replicatedLog.propose(command);
propose.join();
}
class ClusterCoordinator...
private void applyMigrationCompleted(MigrationCompletedCommand command) {
pendingMigrations.remove(command.getMigration());
logger.info("Completed migration " + command.getMigration());
logger.info("pendingMigrations = " + pendingMigrations);
partitionTable.migrationCompleted(command.getMigration());
}
class PartitionTable...
public void migrationCompleted(Migration migration) {
this
.addPartition(migration.partitionId,
new PartitionInfo(migration.partitionId,
migration.toMember,
ClusterCoordinator.PartitionStatus.ONLINE));
}
An Example Scenario
Once again, we have three data servers Athens, Byzantium, and Cyrene. If there are nine partitions, the flow might look as shown in Figure 19.2 . Note that, replication messages from leader to followers of the Consistent Core are not shown in the diagram.
Figure 19.2 Partition assignment by a Consistent Core
The client can then use the partition table to map a given key to a particular cluster node ( Figure 19.3 ).
Figure 19.3 Client writing to a partition
Now a new node, Ephesus, is added to the cluster. The admin triggers a reassignment and the coordinator verifies which nodes are underloaded by checking the partition table. It figures out that Ephesus is a node which is underloaded, and decides to allocate partition 7 to it, moving it from Athens. The coordinator stores the migrations and then sends the request to Athens to move partition 7 to Ephesus. Once the migration is complete, Athens lets the coordinator know. The coordinator then updates the partition table ( Figure 19.4 ).
Figure 19.4 Reassigning partitions to a newly added node
Alternative Solution: Partitions Proportional to Number of Nodes
An alternative to fixed partitions, popularized by Apache Cassandra, is to have the number of partitions proportional to the number of nodes in the cluster. The number of partitions increases when new nodes are added to the cluster. This technique is also sometimes called consistent hashing. It requires storing a randomly generated hash per partition, and needs to search through the sorted list of hashes. This takes more time compared to O(1) computation of hash % number of partitions . This technique is also shown to create some imbalance in data assigned to partitions, so most data systems use fixed-partitions technique.
The basic mechanism works as follows. Each node is assigned a random integer token. This value is typically generated as hash of a random GUID.
The client maps the key to the cluster nodes as follows:
-
It computes the hash of the key.
-
It gets the sorted list of all the available tokens. It then searches for the smallest token value that is higher than the hash of the key. The cluster node owning that token is the node storing the given key.
-
The list is considered circular, so any hash value of a key which is greater than the last token in the list maps to the first token.
Here’s what the code looks like:
Click here to view code image
class TokenMetadata...
Map<BigInteger, Node> tokenToNodeMap;
public Node getNodeFor(BigInteger keyHash) {
List<BigInteger> tokens = sortedTokens();
BigInteger token = searchToken(tokens, keyHash);
return tokenToNodeMap.get(token);
}
private static BigInteger searchToken(List<BigInteger> tokens,
BigInteger keyHash) {
int index = Collections.binarySearch(tokens, keyHash);
if (index < 0) {
index = (index + 1) * (-1);
if (index >= tokens.size())
index = 0;
}
BigInteger token = tokens.get(index);
return token;
}
List<BigInteger> sortedTokens() {
List<BigInteger> tokens = new ArrayList<>(tokenToNodeMap.keySet());
Collections.sort(tokens);
return tokens;
}
To see how this works, we take some example values for tokens. Consider a three-node cluster, with Athens, Byzantium, and Cyrene having the token values of 10, 20, and 30, respectively ( Figure 19.5 ).
Figure 19.5 Cluster nodes forming a token ring
For this example, imagine this metadata stored with the Consistent Core . The client library gets the token metadata and uses it to map a given key to the cluster node ( Figure 19.6 ).
Figure 19.6 Client writing to a partition using token ring
Adding New Node to the Cluster
The main advantage of this scheme is that we have more partitions when new nodes are added to the cluster ( Figure 19.7 ).
Figure 19.7 New node owns a part of existing token range.
Consider a new node, Delphi, is added to the cluster, with a random token of 40 assigned to it. We can see that Athens, which was hosting all the keys with hashes above 30, now needs to move the keys with hashes between 30 and 40 to the new node. This does not involve moving all the keys—only a small portion needs to be moved to the new node.
As before, let’s consider a Consistent Core tracking the cluster membership and mapping partitions to the cluster nodes. When Delphi registers with the consistent core, it first figures out which existing nodes are affected because of this new addition. In our example, Athens needs to move part of the data to the new node. The Consistent Core tells Athens to move all the keys with hashes between 30 and 40 to Delphi. After the move is complete, Delphi’s token is added to token metadata ( Figure 19.8 ).
Figure 19.8 Moving a part of the token range to a newly added node
This basic technique of assigning a single token to each node has shown to create data imbalance. When a new node is added, it also puts all the burden of moving data on one of the existing nodes. For this reason, Apache Cassandra changed its design to have multiple random tokens 62 assigned to each node. This allows a more even distribution of data. When a new node is added to the cluster, a small amount of data is moved from multiple existing nodes, without overloading a single node.
-
[https://www.datastax.com/blog/virtual-nodes-cassandra-12](https://www.datastax.com/blog/virtual-nodes-cassandra-12)
In our example, instead of a single token, each of Athens, Byzantium, and Cyrene can have three tokens each. (Three is taken to simplify the example; the default value for Apache Cassandra was 256.) The tokens are randomly allocated to nodes. It is important to note that tokens assigned to nodes are randomly generated GUID hashes, so they are not contiguous. If contiguous numbers like 10, 20, 30 are assigned to each node, that will have the same problem as a single token per node when a new node is added ( Figure 19.9 ).
Figure 19.9 Nodes owning multiple token ranges
When a new node, Delphi, is added, with tokens of 40, 50, and 200, the key ranges of Athens and Byzantium are responsible for changes. The range (130, 10] on Athens is split with Delphi which now owns the keys with hashes within (130, 200]. The range (30, 60] on Byzantium is split, passing to Delphi the keys with hashes within (40, 50]. All keys in the range (130, 200] from Athens and (40, 50] from Byzantium are moved to Delphi ( Figure 19.10 ).
Figure 19.10 Data ranges moved from multiple nodes
Examples
-
In Apache Kafka, each topic is created with a fixed number of partitions.
-
Shard allocation in Akka 63 has a fixed number of shards configured. The guideline is to have the number of shards 10 times the size of the cluster.
-
[https://doc.akka.io/docs/akka/current/typed/cluster-sharding.html#shard-allocation](https://doc.akka.io/docs/akka/current/typed/cluster-sharding.html#shard-allocation)
-
-
In-memory data grid products like partitioning in Apache Ignite 64 and partitioning in Hazelcast 65 have a fixed number of partitions that are configured for their caches.
-
[https://ignite.apache.org/docs/latest/data-modeling/data-partitioning](https://ignite.apache.org/docs/latest/data-modeling/data-partitioning) -
[https://docs.hazelcast.com/imdg/4.2/overview/data-partitioning](https://docs.hazelcast.com/imdg/4.2/overview/data-partitioning)