We are going to design a topology-aware sharding scheme with rebalancing.
The key idea is to consider the physical topology (like data centers, racks, etc.) to minimize cross-topology communication and to have a rebalancing mechanism that can move data/shard ownership when nodes are added or removed.
Steps:
Define the topology: We assume the system has a hierarchical topology (e.g., zones -> racks -> nodes).
We want to place shards in a way that replicas of a shard are in different topo units (for fault tolerance) but as close as possible (to minimize latency).
Sharding: We have a set of shards (or partitions) that need to be placed on nodes. Each shard has multiple replicas (say N replicas).
Topology-aware placement:
For each shard, we want to place its replicas in distinct failure domains (e.g., different zones, then different racks within the same zone, etc.).
We also want to balance the load (number of shards) across nodes.
Rebalancing:
When a node is added or removed, we need to adjust the shard placements to maintain balance and topology constraints.
We want to minimize data movement.
Approach:
We can model the problem as:
We have a set of nodes, each with a topology path (e.g., zone1/rack1/node1).
We have a set of shards, each with a set of replica nodes (of size N).
Constraints:
a) For each shard, the replica nodes must be in distinct failure domains at the highest level (e.g., zones) and then distinct at lower levels if possible.
b) The number of shards on a node should be as equal as possible.
We can think of two phases:
Phase 1: Initial placement.
We can use a greedy algorithm that assigns shards to nodes while respecting topology constraints and trying to balance the load.
Phase 2: Rebalancing when the cluster changes.
When a node is added or removed, we need to adjust the placements of some shards.
Let's break down:
Initial Placement:
We have M shards and K nodes.
We want to assign N replica nodes for each shard (N is the replication factor).
We can think of the nodes being grouped by their topology. For example, if we have two levels: zones and racks.
We want to spread the replicas of a shard across as many zones as possible (at least min(N, number of zones)), and then within the same zone, across racks.
Algorithm for initial placement:
Step 1: Precompute the topology groups. For each node, we have a tuple (zone, rack, ...). We can create a tree of groups.
Step 2: Sort the nodes by their topology path (so that we can group by the first element, then second, etc.).
Step 3: For each shard, we want to pick N nodes such that:
- They are in as many distinct top-level groups (e.g., zones) as possible.
- Within a top-level group, they are in distinct next-level groups (e.g., racks) if possible.
We can do:
code
For each shard, we will try to pick one node from each of the top-level groups until we have N replicas or we run out of top-level groups.
Then, if we still need more, we pick from the remaining nodes in the already used top-level groups, but making sure we don't pick two from the same next-level group if possible.
However, we also want to balance the load.
Alternatively, we can use a two-step process:
code
a) First, assign shards to top-level groups (zones) in a round-robin fashion, so that each zone gets roughly the same number of shard replicas.
b) Then, within each zone, assign the shards to racks in a round-robin fashion.
c) Then, within each rack, assign to nodes in a round-robin fashion.
But note: we are assigning N replicas per shard, so we need to assign each shard to N different nodes, and these nodes must be in distinct zones (if N <= number of zones) or as distinct as possible.
We can think of it as:
code
For shard i, we assign it to zone (i mod Z) for the first replica, then (i+1 mod Z) for the second, etc. (if N <= Z). But if N > Z, then we assign the remaining to the same zones but in different racks.
However, we also have to consider that a zone might have multiple racks and nodes.
Let's define:
code
Let Z = number of zones.
Let R_z = number of racks in zone z.
Let N_zr = number of nodes in rack r of zone z.
We want to assign each shard to N nodes such that:
code
Condition 1: The N nodes are in at most N distinct zones, and if possible, in distinct zones (if N <= Z).
Condition 2: Within a zone, the nodes are in distinct racks (if the number of replicas in that zone is less than or equal to the number of racks in that zone).
We can do:
code
For each shard i:
Let assigned_zones = set()
Let assigned_racks_in_zone = defaultdict(set)
For replica j in range(N):
If we still have zones that are not in assigned_zones and we haven't reached the desired number of distinct zones (which is min(N, Z)), then:
pick a zone that is not in assigned_zones, and then within that zone pick a rack that is not in assigned_racks_in_zone[zone] (if possible) and then a node in that rack that hasn't been used for this shard.
Else:
We have to reuse a zone, so we pick a zone that already has a replica for this shard, but then we must pick a rack in that zone that is not already used for this shard (if possible) and then a node.
But we also want to balance the load, so we should pick the node that currently has the least number of shards (or replicas) assigned.
However, note: we are assigning multiple replicas for the same shard, so we are making N assignments for one shard. We want to spread the load across nodes.
Alternatively, we can assign the replicas of a shard to different nodes, but we also want to balance the total number of shards (or replicas) per node.
Since each shard has N replicas, the total number of replicas is MN. We want each node to have about (MN)/K replicas.
But note: we are assigning shards, so the number of shards per node (not replicas) might be what we care about? Actually, in sharding, each node holds a set of shards (and each shard is stored on N nodes). So the load on a node is the number of shards it holds.
We want to balance the number of shards per node.
However, the initial placement algorithm above doesn't consider the current load of nodes. We can try to pick the node with the least current shard count in the desired topology group.
But we are assigning multiple replicas for the same shard, so we have to pick N distinct nodes.
We can do:
code
For each shard, we have a list of candidate nodes (all nodes in the system). We sort the candidate nodes by:
1. Topology preference: We prefer nodes that are in a zone that we haven't used for this shard, then in a rack we haven't used, etc.
2. Then by current shard count (ascending).
Then we pick the top N nodes from this sorted list, but making sure we don't pick two from the same node.
However, this might be expensive if we do for every shard.
Alternatively, we can use a two-level assignment:
code
Step 1: Assign each shard to a set of zones (and racks within zones) in a way that the number of shards per zone (and per rack) is balanced.
Step 2: Then, within each zone-rack, assign the shards to nodes in a round-robin fashion.
But note: we have N replicas per shard, so a shard might appear in multiple zones.
Let's try:
code
We have M shards and we want to assign N replicas per shard.
We can think of the assignment as a bipartite graph between shards and nodes, with constraints on the topology.
Given the complexity, let's simplify:
code
This gives us an initial placement.
Rebalancing:
When a node is added or removed:
code
This is a high-level design. The actual implementation would require careful bookkeeping.
Let's summarize the steps for rebalancing when a node is added:
code
Let avg = (total_shard_replicas) / (number_of_nodes)
Let overloaded = [nodes with shard count > avg]
Let underloaded = [nodes with shard count < avg]
We want to move replicas from overloaded to underloaded.
But we have to consider the new node is underloaded.
We can:
while there exists an overloaded node and an underloaded node (and we can find a move that is allowed and has positive score):
pick the move (from overloaded node X, shard s, to underloaded node Y) with the highest score.
execute the move:
remove s from X's replica set.
add s to Y's replica set.
update the shard count of X and Y.
update the load of X and Y.
remove X from overloaded if now <= avg, similarly for Y.
The score function for a move (s from X to Y):
current_zones = set(zone for node in s.replicas) # before the move, note that X is still in s.replicas.
current_racks_in_zone_y = set(rack for node in s.replicas if node.zone == Y.zone)
score = 0
if Y.zone not in current_zones:
score += 1000
else:
if Y.rack not in current_racks_in_zone_y:
score += 100
# We also want to move to less loaded nodes, so we can add (underloaded_threshold - load[Y]) or something.
# But note: Y is underloaded, so we want to move to it. We can add the difference between avg and load[Y] to encourage moving to the most underloaded.
score += (avg - load[Y]) # so that we prefer more underloaded nodes.
But note: if Y is underloaded, then avg - load[Y] is positive.
However, we must also check that Y is not already a replica of s (but we are considering Y as a candidate, so we would skip if Y is already in s.replicas). So in the candidate generation, we only consider Y that are not in s.replicas.
For node removal:
code
This is a basic rebalancing. We might need to run multiple passes if after moving one shard, another shard becomes a candidate for moving from the same overloaded node? But in the removal case, we are only moving from R (which is removed) to other nodes. So we are only moving the shards that were on R. We don't move shards from other nodes to other nodes in the removal case? Actually, we might need to if after moving the shards from R, some nodes become overloaded and others underloaded. But the goal is to rebalance after removal. We can do:
code
Step 1: Remove R and temporarily assign its shards to a holding area.
Step 2: Assign each shard from the holding area to a new node using the above greedy.
Then we might end up with an unbalanced cluster? Because we are assigning each shard independently, and we are trying to pick underloaded nodes, but we might assign multiple shards to the same underloaded node.
So we might need to iterate until the cluster is balanced.
Alternatively, we can do:
After removing R, we have a set of shards that need a new replica.
We sort these shards by some priority (maybe by the number of distinct zones they have? shards that have fewer distinct zones are less tolerant, so we want to assign them to new zones first?).
Then for each shard in that order, we assign to the best node (using the score above).
Then we update the load.
Then we might have to rebalance among the non-removed nodes? Because after assigning all shards from R, we might have some nodes overloaded and some underloaded.
Then we can run the same rebalancing as in the addition case (but without a new node) to move replicas from overloaded to underloaded nodes.
So in summary, for removal:
Phase 1: Reassign the replicas from the removed node to the remaining nodes, trying to maintain topology and balance.
Phase 2: If after phase 1 the cluster is not balanced (some nodes are overloaded and some underloaded), then we do a rebalancing among the remaining nodes (without adding new nodes) by moving replicas from overloaded to underloaded nodes, respecting topology.
Similarly, for addition:
Phase 1: Assign some replicas from overloaded nodes to the new node (if beneficial for topology and balance).
Phase 2: Then if still unbalanced, we do rebalancing among all nodes (including the new one) by moving replicas from overloaded to underloaded.
This is a very high-level and complex design. In practice, systems like Cassandra, CockroachDB, etc., have their own ways.
Given the constraints of this response, we'll provide a simplified version.
Let's define:
code
Topology: We have a list of nodes, each with a topology path (list of strings, e.g., ["zone1", "rack1", "node1"]).
We assume the topology has L levels (e.g., L=2 for zone and rack).
We have shards, each with a set of replica nodes (size N).
We'll write:
code
class Shard:
id: int
replicas: set of node ids
class Node:
id: int
topology: list of strings # from highest level to lowest
shards: set of shard ids # the shards that this node holds
We'll assume we have a list of shards and a list of nodes.
We'll implement:
code
initial_placement(shards, nodes, N, topology_levels)
rebalance_after_node_addition(shards, nodes, new_node)
rebalance_after_node_removal(shards, nodes, removed_node)
But note: the initial placement is a one-time thing. The rebalancing functions will modify the shards and nodes in place.
However, the rebalancing after node addition and removal are similar, so we can have a common rebalance function that takes a target load (average) and then moves from overloaded to underloaded.
But note: in node addition, we have a new node that is empty (so underloaded). In node removal, we have a node that is removed and its shards need to be reassigned, so we have to first reassign those shards and then possibly rebalance.
Given the complexity, we'll provide a skeleton.
Due to the length, we cannot write the full code, but we can outline the algorithms.
Let's assume:
code
We have a function get_zone(node) that returns the first element of node.topology (the highest level).
Similarly, get_rack(node) returns the second element (if exists).
We'll assume the topology is at least two levels (zone and rack). We can generalize.
Steps for initial placement (for each shard):
code
current_shard = shard i
Let used_zones = set()
Let used_racks_in_zone = defaultdict(set) # zone -> set of racks
For replica in range(N):
# We want to pick a node that is not already in current_shard.replicas, and that is in a zone that is not in used_zones if possible, and within that zone a rack that is not in used_racks_in_zone[zone] if possible.
candidate_nodes = [node for node in nodes if node.id not in current_shard.replicas]
# Sort candidate_nodes by:
# 1. If node.zone in used_zones: penalty (so we prefer not used zones)
# 2. If node.zone in used_zones and node.rack in used_racks_in_zone[node.zone]: penalty (so we prefer not used racks in the same zone)
# 3. Then by node's current shard count (ascending)
candidate_nodes.sort(key=lambda node: (
0 if node.zone not in used_zones else 1,
0 if (node.zone in used_zones and node.rack not in used_racks_in_zone[node.zone]) else 1,
len(node.shards)
))
pick the first candidate node.
current_shard.replicas.add(picked_node.id)
picked_node.shards.add(current_shard.id)
used_zones.add(picked_node.zone)
used_racks_in_zone[picked_node.zone].add(picked_node.rack)
This is a greedy per-shard, per-replica assignment.
But note: this doesn't balance the load globally because we are processing shards one by one and the node's shard set is being updated as we go.
We might want to process the shards in a random order to avoid bias.
Alternatively, we can do multiple passes.
Given the complexity, we'll leave the initial placement as above.
For rebalancing:
code
This is a very basic algorithm and might not be optimal, but it's a starting point.
Note: the find_move function above does not consider that we are moving a replica from a specific node (the overloaded node) to the candidate. It just finds the best candidate for the shard given the current state.
In the move generation for addition/removal, we are only considering moves that involve moving a replica from an overloaded node to an underloaded node (or to a new node in the case of addition). But in the removal case, we are reassigning from the removed node to any node (which might be overloaded or underloaded). We should only assign to underloaded nodes? Not necessarily, because we have to assign the shard to some node, and if all nodes are overloaded, we have to assign to an overloaded node.
So in the removal case, when we reassign the shards from the removed node, we should try to assign to underloaded nodes, but if there are no underloaded nodes, we assign to the least loaded node.
Similarly, in the addition case, we might not be able to move all the replicas to the new node because the new node might become overloaded, or because of topology constraints.
Given the complexity, we'll leave the algorithm as above.
This is a very high-level design and would require a lot of refinement for a production system.
We'll now write a simplified version in Python-like pseudocode.
Note: We assume that the topology levels are fixed and we use the first two levels (zone and rack). We can extend to more levels by using the first L levels.
We'll assume that the topology has at least two levels.
Let's code the initial placement:
code
for shard in shards:
used_zones = set()
used_racks_in_zone = defaultdict(set)
for replica in range(N):
candidate_nodes = [node for node in nodes if node.id not in shard.replicas]
candidate_nodes.sort(key=lambda node: (
0 if get_zone(node) not in used_zones else 1,
0 if (get_zone(node) in used_zones and get_rack(node) not in used_racks_in_zone[get_zone(node)]) else 1,
len(node.shards)
))
if not candidate_nodes:
# This should not happen if we have enough nodes.
raise Exception("Not enough nodes to assign replica")
chosen = candidate_nodes[0]
shard.replicas.add(chosen.id)
chosen.shards.add(shard.id)
used_zones.add(get_zone(chosen))
used_racks_in_zone[get_zone(chosen)].add(get_rack(chosen))
For rebalancing, we define:
code
def compute_avg(nodes):
total = sum(len(node.shards) for node in nodes)
return total / len(nodes)
def find_move(shard, nodes, current_replicas, avg):
# current_replicas: set of node ids that are currently replicas of the shard
candidate_nodes = [node for node in nodes if node.id not in current_replicas]
current_zones = set(get_zone(nodes[node_id]) for node_id in current_replicas)
current_racks_in_zone = defaultdict(set)
for node_id in current_replicas:
node = nodes[node_id]
current_racks_in_zone[get_zone(node)].add(get_rack(node))
candidate_nodes.sort(key=lambda node: (
0 if get_zone(node) not in current_zones else 1,
0 if (get_zone(node) in current_zones and get_rack(node) not in current_racks_in_zone[get_zone(node)]) else 1,
avg - len(node.shards) # we want to move to nodes that are below average, so higher (avg - load) is better.
), reverse=True) # because we want the candidate with the highest (avg - load) to be first.
return candidate_nodes[0] if candidate_nodes else None
Then for node addition:
code
Similarly for node removal, we first reassign the shards from the removed node, and then run the same rebalancing loop.
However, note: in the removal case, after we remove the node, the number of nodes decreases, so the average load increases. We should recompute the average after removing the node and before reassigning its shards.
Steps for removal:
code
This is a very basic rebalancing algorithm. It does not consider that moving a shard might change the topology for the shard and might affect other shards. It also does not consider that we might want to move multiple replicas of the same shard to improve the topology (but note: we are only moving one replica at a time, and we are moving from an overloaded node to an underloaded node, so we are not moving multiple replicas of the same shard to the same node because we check that the candidate node is not already a replica).
However, we might move two replicas of the same shard from two different overloaded nodes to the same underloaded node? That would put two replicas of the same shard on the same node, which is not allowed. But in the move generation, we check that the candidate node is not in shard.replicas. So if we move one replica to the underloaded node, then the shard.replicas will include that node, and the second move for the same shard will not consider that node.
So it's safe.
This algorithm is greedy and might not find the optimal set of moves, but it should work for a basic system.
Note: The above code is pseudocode and may have errors.
We have not considered:
code
- What if there are multiple topology levels? We only used zone and rack. We can extend by using the first L levels.
- We assumed that the topology levels are ordered from highest to lowest (zone is highest, then rack, then node). We used the first two.
- We assumed that the number of zones and racks per zone are fixed and we want to spread across zones first, then racks.
- We did not consider that a node might be in a zone that has no racks? Or that the rack level might not exist.
- We did not consider that the topology might have more than two levels (like zone, rack, row, etc.). We can extend by using a list of levels.
To generalize to L levels:
code
We can define:
def get_topology_level(node, level):
if level < len(node.topology):
return node.topology[level]
return None
Then in the sorting key, we can have:
for level in range(L):
current_levels_used = ... we need to keep track of which topology levels we have used for this shard.
We can maintain:
used_topology = [set() for _ in range(L)] # for each level, the set of topology values used.
Then for a node, we check for each level:
if get_topology_level(node, level) not in used_topology[level]: then benefit.
But note: we want to spread across the highest level first, then the next, etc.
So we can assign a tuple of benefits:
benefits = []
for level in range(L):
if get_topology_level(node, level) not in used_topology[level]:
benefits.append(0)
else:
benefits.append(1)
Then we sort by the tuple of benefits (so that we prefer nodes that have 0 at the first level, then 0 at the second, etc.)
Then we also add the load benefit.
So the sort key becomes:
key = tuple(benefits) + (avg - len(node.shards),)
But note: we want to sort by benefits in ascending order (0 is better than 1) and then by (avg - load) descending? Actually, we are reversing the entire sort? We want the candidate with the smallest tuple of benefits (so 0,0,...) and then the largest (avg - load).
So we can do:
candidate_nodes.sort(key=lambda node: (
tuple(0 if get_topology_level(node, level) not in used_topology[level] else 1 for level in range(L)),
-(avg - len(node.shards)) # because we want to sort by (avg - load) descending, but the default is ascending, so we negate to get descending.
))
But note: the tuple of benefits will be compared lexicographically. So (0,0) is better than (0,1) which is better than (1,0).
Alternatively, we can do:
candidate_nodes.sort(key=lambda node: (
sum(0 if get_topology_level(node, level) not in used_topology[level] else 1 for level in range(L)), # total number of levels that are already used? Not exactly.
...
))
But the lexicographic order on the tuple of 0/1 for each level is what we want: we want to minimize the first level's benefit (0 if not used, 1 if used), then the second, etc.
So we keep the tuple.
However, note: we are only using the first L levels. We must make sure that the node has at least L levels? If not, we can treat missing levels as None and then we consider that as the same for all nodes? Actually, if a node doesn't have a rack (level 1), then we cannot spread at the rack level for that node. So we should treat missing levels as a special value that is the same for all nodes? Or we can ignore that level.
Given the complexity, we'll stick to two levels.
This is a very complex problem and the above is a simplified approach.
We hope this gives a starting point.
I'll design a comprehensive topology-aware sharding scheme with automatic rebalancing that considers physical infrastructure constraints. This design is inspired by systems like CockroachDB, Cassandra, and modern distributed databases.
class Shard:
id: UUID
range: (min_key, max_key) # Hash or range-based
replicas: List[ReplicaInfo] # Ordered by topology preference
leader: NodeID # Current primary
status: ACTIVE|MOVING|REBALANCING
class ReplicaInfo:
node_id: str
topology_path: List[str] # ["us-east", "use1-az1", "rack1", "node1"]
role: LEADER|FOLLOWER|OBSERVER
last_heartbeat: timestamp
lag: int # replication lag
2.2 Topology Constraints
python
constraints = {
"min_distance": {
"same_rack": 0, # Max replicas in same rack (typically 1-2)
"same_zone": 0, # Max replicas in same zone (typically 1-3)
"same_region": 0, # Max replicas in same region (typically 2-4)
},
"preferred_spread": {
"zones_per_shard": 3, # Target distinct zones per shard
"racks_per_shard": 2, # Target distinct racks per shard
"regions_per_shard": 2, # For multi-region
}
}
3. Initial Placement Algorithm
python
def place_shards(shards, nodes, replication_factor=3):
"""
Greedy topology-aware placement with load balancing
"""
placements = []
node_load = {node.id: 0 for node in nodes} # shards per node
# Group nodes by topology
topology_groups = group_by_topology(nodes)
for shard in shards:
candidate_nodes = []
# Phase 1: Select distinct top-level groups (zones/regions)
for level in range(max_levels):
used_groups = set()
for replica_idx in range(replication_factor):
# Find node with minimal load in unused topology group
best_node = find_best_node(
nodes,
shard,
used_groups,
level,
node_load
)
if best_node:
candidate_nodes.append(best_node)
used_groups.add(best_node.topology[level])
node_load[best_node.id] += 1
# Phase 2: Balance remaining constraints
placements.append(optimize_placements(shard, candidate_nodes))
return placements
def plan_cascading_migrations():
"""
Handle dependencies: if moving shard A requires moving shard B first
because they share a node that's being decommissioned.
"""
dependency_graph = build_dependency_graph()
# Topological sort for safe order
migration_order = topological_sort(dependency_graph)
# Group non-dependent migrations for parallel execution
parallel_groups = group_independent(migrations=migration_order)
return parallel_groups
6. Load Balancing Metrics
python
class LoadBalancer:
METRICS = {
"shards_per_node": "primary metric",
"replica_lag": "replication delay",
"request_latency_p99": "performance",
"network_cross_zone": "topology cost",
"disk_usage": "storage balance"
}
def calculate_imbalance_score(self):
"""
Composite score: weighted sum of multiple dimensions
"""
scores = {
"shard_count": self.std_dev_shard_count(),
"load_skew": self.calculate_load_skew(),
"topology_violations": self.count_violations(),
}
weights = {
"shard_count": 0.4,
"load_skew": 0.3,
"topology_violations": 0.3
}
return sum(scores[k] * weights[k] for k in scores)
Initial state: 6 nodes, 100 shards (RF=3)
- Each node: ~50 shards
- All zones have equal shard count
Add: node7 in rack3, use1-az2
Rebalance steps:
1. Detect new node (trigger: NODE_ADDED)
2. Calculate target: each node should have 42.8 shards
3. Identify over-loaded nodes: node1-4 (50 shards each)
4. Select 8 shards from node1-4 to move to node7
5. Filter: only pick shards where zone use1-az2 is acceptable
6. Execute 8 migrations in parallel (max_concurrent=5)
7. Verify: all nodes 43±1 shards, topology intact
10. Failure Handling
python
def handle_migration_failure(migration, error):
if error == "NETWORK_TIMEOUT":
# Retry with smaller chunk size
retry_with_throttle(migration, backoff=exponential)
elif error == "CONSTRAINT_VIOLATION":
# Rollback and mark target as unavailable
rollback(migration)
mark_node_unsuitable(target_node)
elif error == "RESOURCE_EXHAUSTED":
# Pause rebalancer, alert ops
pause_rebalancer()
send_alert(f"Target node {target_node} OOM during migration")
11. Optimization Techniques
Incremental Migration: Stream data in chunks (WAL tailing)
Read/Write Forwarding: Forward requests during migration
Compression: Compress data in transit
Batch Metadata Updates: Group metadata changes
Prediction: Use ML to predict hotspots and pre-rebalance
12. Trade-offs
Aspect
Conservative
Aggressive
Data Movement
Minimal
High
Balance Speed
Slow
Fast
Risk
Low
High
Topology Adherence
Strict
Flexible
Wasted Capacity
High
Low
Key Design Principles
Safety First: Never violate topology constraints unless in emergency mode
Progressive: Small incremental changes vs big bang migrations
Observable: Full visibility into migration progress and impact
This design provides a robust foundation that can be tuned for specific workload patterns (read-heavy vs write-heavy, latency-sensitive vs throughput-oriented) while maintaining high availability and respecting physical infrastructure constraints.
We assume that we have a fixed replication factor N and that we want to assign each shard to exactly one node per failure domain (zone) until we have N replicas.
We can assign the shards to zones in a round-robin fashion, but then we have to assign each shard to multiple zones.
Actually, we want to spread the shards across zones so that each zone gets roughly the same number of shard replicas.
Total replicas = M*N. If we have Z zones, then each zone should get about (M*N)/Z replicas.
But note: a shard can have multiple replicas in the same zone? We want to avoid that if possible, so we want each shard to be in as many zones as possible (up to N).
So, if N <= Z, then we can assign each shard to N distinct zones. Then each zone will get exactly M shards (if we assign each shard to every zone exactly once? No, because each shard is assigned to N zones, so total zone-shard assignments = M*N. And if we have Z zones, then on average each zone gets (M*N)/Z shards.
But we want to balance the number of shards per zone, so we can assign the shards to zones in a round-robin fashion for the first replica, then second, etc.
Example: M=10, N=3, Z=5.
We want to assign each shard to 3 zones. We have 5 zones. We can number the shards 0 to 9.
For shard i, assign to zones: (i mod Z), ((i+1) mod Z), ((i+2) mod Z) -> but then if Z is 5, then for shard 0: zones 0,1,2; shard1:1,2,3; ... shard4:4,0,1; shard5:0,1,2; etc.
Then zone 0 gets shards: 0,4,5,9 -> 4 shards.
zone 1: 0,1,5,6 -> 4 shards.
zone 2: 0,1,2,6,7 -> 5 shards? Wait, let's compute:
Shard0: 0,1,2
Shard1: 1,2,3
Shard2: 2,3,4
Shard3: 3,4,0
Shard4: 4,0,1
Shard5: 0,1,2
Shard6: 1,2,3
Shard7: 2,3,4
Shard8: 3,4,0
Shard9: 4,0,1
Then:
zone0: shards 0,3,4,5,8,9 -> 6 shards? Wait, I see a pattern: each zone gets 6 shards? Let's count:
zone0: 0,3,4,5,8,9 -> 6
zone1: 0,1,4,5,6,9 -> 6
zone2: 0,1,2,6,7,9 -> 6? Actually 0,1,2,6,7,9 -> 6.
zone3: 1,2,3,7,8 -> 5? Wait, 1,2,3,7,8 -> 5.
zone4: 2,3,4,7,8 -> 5.
So it's not perfectly balanced. We can adjust by using a different step.
Alternatively, we can assign the shards to zones by:
For replica j (0 to N-1), assign shard i to zone (i * step + j) mod Z, where step is chosen so that we get a good spread.
But note: we also have racks within zones.
Given the complexity, maybe we should use a more systematic approach:
We want to assign M*N zone-shard pairs (each replica of a shard is assigned to a zone) such that:
- Each shard is assigned to exactly N zones (if N<=Z, then N distinct zones; if N>Z, then we have to reuse zones).
- Each zone gets approximately the same number of shard replicas.
This is equivalent to: we have M shards and we want to choose N zones for each shard (with possible repetition if N>Z) so that the total number of times each zone is chosen is as equal as possible.
We can model this as: we have a matrix of size M x N, and we want to assign to each cell a zone in [0, Z-1] such that:
- For each row (shard), the zones are as distinct as possible (if N<=Z, then all distinct; if N>Z, then we try to minimize the maximum repetition in a row?).
- For each column (replica index), the zones are as balanced as possible? Not necessarily.
Actually, we don't care about the replica index, we care about the total per zone.
So we want to minimize the variance of the counts per zone.
This is similar to a balanced assignment problem.
We can use the following:
For shard i, we assign the j-th replica to zone (i + j * offset) mod Z, where offset is a number coprime with Z to get a good spread.
But then if N>Z, we will have repetitions in the same row (shard). We can then, for the extra replicas (beyond Z), assign to the zones that are already used for that shard, but we want to spread the load.
However, note that we also have racks and nodes.
Given the time, let's assume N <= Z and we assign each shard to N distinct zones in a round-robin fashion with an offset.
We can set offset = (Z // N) or something to balance.
But let's not overcomplicate.
Alternatively, we can use a greedy algorithm for the zone assignment:
Sort the zones by current load (number of shard replicas assigned) and for each shard, pick the N zones with the least load, but then we have to assign the same shard to multiple zones and we want distinct zones.
We can do:
Initialize an array of size Z for the load of each zone (initially 0).
For each shard i from 0 to M-1:
Let candidate_zones = sorted(zones, key=lambda z: (load[z], z)) # sort by load, then by zone id to break ties.
Pick the first N zones from candidate_zones that are not already picked for this shard? But we haven't picked any for this shard yet.
Then assign shard i to these N zones.
Then update the load of these N zones by 1.
This will try to balance the load across zones.
But note: we are assigning each shard to N zones, and we want to avoid assigning the same zone multiple times for the same shard? In this greedy, we pick the first N zones from the sorted list, which are distinct by definition (since we are picking from the set of zones).
So this works if N <= Z.
If N > Z, then we have to assign some zones multiple times for the same shard. We can then:
For the first Z replicas, assign to the Z zones with the least load (so all zones get one).
For the remaining (N-Z) replicas, we assign to the zones with the least load (which now might be the same as some we already assigned to this shard).
But then for the same shard, we might have multiple replicas in the same zone. We don't want that if we can avoid it, but if N>Z we have to.
So algorithm for zone assignment for a shard:
Let assigned_zones = set()
For j in range(N):
candidate_zones = sorted(all_zones, key=lambda z: (load[z] + (1 if z in assigned_zones else 0), z))
# We add a penalty if the zone is already assigned to this shard? Because we prefer distinct zones.
pick the first zone from candidate_zones.
assigned_zones.add(picked_zone)
load[picked_zone] += 1
This way, we try to avoid picking the same zone twice for the same shard if possible, but if we have to (because N>Z) then we will.
Then, after assigning zones, we assign racks:
Within each zone, we have multiple racks. We want to assign the shard replicas (that are in that zone) to distinct racks if possible.
We can do a similar greedy per zone:
For each zone, we have a set of shards that have a replica in that zone.
For each such shard, we want to assign it to a rack in that zone.
We have racks in the zone, and we want to balance the number of shards per rack.
But note: a shard might have multiple replicas in the same zone (if N>Z) and then we want to assign them to different racks in that zone if possible.
So for each zone:
We have a list of shard replicas (each shard may appear multiple times in the same zone, up to the number of replicas we assigned to that zone).
We want to assign each of these replicas to a rack in the zone, with the constraints:
- For the same shard, we want to assign to distinct racks if possible (if the shard has multiple replicas in the same zone).
We can do:
Initialize the load of each rack in the zone (number of shard replicas assigned) to 0.
For each shard replica in the zone (we can process the shards in some order, maybe by shard id or by the number of replicas in this zone for the shard):
Let candidate_racks = sorted(racks_in_zone, key=lambda r: (load[r] + (1 if r is already used by this shard in this zone? then we would avoid, but note: we are processing one replica at a time for the same shard? Actually, we have multiple replicas for the same shard in the same zone, and we want to assign them to different racks if possible.
We can do:
For the first replica of shard i in this zone, pick the rack with the least load.
For the second replica of the same shard in this zone, pick the rack with the least load that is not the same as the first one.
But we are processing all replicas for all shards. We can do:
For each shard, we keep track of which racks we have already used in this zone for that shard.
Then for the current replica (of shard i) in this zone:
candidate_racks = sorted(racks, key=lambda r: (load[r] + (1 if r in used_racks[i] else 0), r))
Then pick the first.
Then update load[r] and used_racks[i].add(r)
Then, after assigning racks, we assign nodes:
Within each rack, we have multiple nodes. We do a similar greedy:
For each rack, we have a list of shard replicas (each shard may appear multiple times in the same rack? Actually, we have already assigned a rack for each replica in the zone, so now for each rack we have a set of shard replicas.
We want to assign each of these to a node in the rack, with the constraint that for the same shard, we don't assign two replicas to the same node (because a node can only hold one replica of a shard? Actually, in some systems, a node can hold multiple replicas of the same shard? Usually not, because then if the node fails, you lose multiple replicas. So we assume each node holds at most one replica of a shard.
So we must assign distinct nodes for the same shard, even within the same rack? But note: we have already assigned a rack for each replica. So if a shard has two replicas in the same zone, they are in two different racks (because we tried to assign to distinct racks). So now within a rack, we are assigning one replica per shard? Not necessarily, because a shard might have multiple replicas in the same rack? No, because we just assigned racks for the shard's replicas in the zone, and we tried to assign distinct racks for the same shard in the same zone. So in a given rack, a shard appears at most once.
Therefore, within a rack, we don't have the same shard multiple times. So we just need to assign each shard replica to a node in the rack, balancing the load across nodes.
So we can do:
For each rack:
Initialize the load of each node in the rack (number of shards assigned) to 0.
For each shard replica in the rack (order doesn't matter because a shard appears at most once in the rack):
Pick the node with the least load.
Assign the shard replica to that node.
Update the node's load.
If a node is removed:
We have to reassign the shards that were on that node to other nodes.
Steps:
1. Identify the shards that had a replica on the removed node.
2. For each such shard, we need to assign a new node for that replica, respecting the topology constraints.
3. We want to balance the load.
We can do:
For each shard that lost a replica:
We have the current set of replica nodes for the shard (minus the removed node).
We need to pick a new node that:
- Is not already a replica for this shard.
- respects the topology constraints: we want to keep the replicas in distinct failure domains as much as possible.
We can try to pick a node that is in a zone that the shard already has a replica in? Or in a new zone?
The goal is to maintain the same topology spread as before, but if we cannot (because the removed node was the only one in a zone), then we might have to put two replicas in the same zone.
However, we also want to balance the load.
Algorithm for picking a new node for a shard:
Let current_zones = set(zone for node in current_replicas)
We want to pick a node that is in a zone that is not in current_zones? But if we already have replicas in all zones (or if we have N replicas and we are at N-1 after removal) then we have to pick a zone that is already in current_zones.
So:
if len(current_zones) < N and there exists a zone not in current_zones that has available nodes (that are not already replicas of this shard and are not the removed node), then pick a node from such a zone.
else, pick a node from any zone that has available nodes, but we prefer zones that have fewer replicas of this shard? Actually, we want to spread the shard's replicas across zones, so if we have to pick a zone that already has a replica, we might pick the zone that has the least number of replicas of this shard (but note: we are replacing one replica, so we are at N-1, and we want to get back to N. So if we have two replicas in one zone and one in another, we might want to add a third in a third zone if possible, else we add to the zone with one to balance? But the constraint is to have distinct zones, so if we have two in one zone and one in another, and we add to the zone with one, then we have two zones with two and one? Actually, we want to maximize the number of distinct zones.
So we want to pick a node that is in a zone that the shard doesn't have a replica in, if possible.
Then, within the chosen zone, we want to pick a rack that the shard doesn't have a replica in (if possible) and then a node that the shard doesn't have a replica in.
And we want to pick the node with the least load (across the whole system? or within the zone?).
We can do:
candidate_nodes = all nodes except:
- the current replica nodes of this shard.
- the removed node (which is already not a replica anymore).
Then, we sort candidate_nodes by:
1. If the node's zone is in current_zones: then penalty (so we prefer new zones).
2. Then, within the same zone, if the node's rack is already used by this shard in that zone? We want to avoid that if possible. But note: we might have multiple replicas in the same zone, so we might have used multiple racks in that zone. So we want to pick a rack that is not used by this shard in that zone.
3. Then by the node's current shard count (ascending).
Then pick the first candidate.
Then assign the shard to that node.
Then update the node's shard count.
If a node is added:
We want to move some shards to the new node to balance the load.
We can compute the average number of shards per node (total_shards * N / (number of nodes)).
Then, for nodes that have above average, we can move some of their shards to the new node (or to other underloaded nodes).
But note: we cannot move a shard replica arbitrarily because of topology constraints.
We can:
1. Identify shards that are on overloaded nodes (above average) and that can be moved to the new node without violating topology constraints.
2. For each such shard, check if moving one of its replicas from the overloaded node to the new node is allowed:
- The new node must not already be a replica of the shard.
- The new node must be in a zone that the shard doesn't have a replica in? Or if it already has, then we are adding a second replica in that zone? That's allowed if we don't have enough distinct zones? But we want to maintain the distinct zone property if possible.
Actually, when we remove a replica from an overloaded node and add to the new node, we are keeping the total number of replicas the same. So if the shard had replicas in zones Z1, Z2, ... and we remove one from Z1 and add one in Z3 (a new zone) then we improve the spread. If we add in Z1 (the same zone) then we are not improving.
We want to move replicas from overloaded nodes to the new node in a way that improves the topology spread if possible, or at least doesn't worsen it.
3. We can try to move replicas from overloaded nodes to the new node if:
- The new node is in a zone that the shard doesn't have a replica in, then we move (because we increase the number of distinct zones).
- If not, then we only move if the new node is in a zone that the shard already has a replica, but then we must check if we are not exceeding the desired number of replicas per zone? Actually, we don't have a per-zone limit, we just want distinct zones as much as possible.
But note: if we move a replica from zone A to the new node in zone A, then the shard still has the same set of zones, so we don't lose a zone. But we are moving within the same zone, so we might be able to move to a different rack in that zone? The new node might be in a different rack, so we might improve the rack spread.
4. We also want to balance the load.
So we can:
For each shard that is on an overloaded node (say node X), we consider moving one of its replicas from X to the new node Y.
We check:
a) Y is not already a replica of the shard.
b) Let current_zones = set(zone for each replica of the shard).
If Y's zone is not in current_zones, then it's a good move (adds a new zone).
Else, if Y's zone is in current_zones, then we are not adding a new zone, but we might be moving to a different rack? We can check the rack spread in that zone.
Let current_racks_in_zone = set(rack for replica in shard if replica.zone == Y.zone)
If Y's rack is not in current_racks_in_zone, then we are adding a new rack in that zone, which is good.
Otherwise, we are just moving within the same rack? That might not be beneficial.
We also consider the load of node Y (we want to move to underloaded nodes).
So we can score the move:
score = 0
if Y.zone not in current_zones: score += 1000 # high priority for new zone
else if Y.rack not in current_racks_in_zone: score += 100 # medium priority for new rack in same zone
Then subtract the current load of Y (or add the negative load) so that we prefer less loaded nodes.
Then we pick the move with the highest score (and positive score?).
But note: we are moving from an overloaded node, so we want to reduce the load of the overloaded node.
We can do:
For each overloaded node X (with shard count > average):
For each shard s on X:
Consider moving s from X to Y (the new node).
Compute the score as above.
Then pick the move with the highest score and perform it.
Then update the loads and the shard's replica set.
We can do multiple moves until the new node is no longer underloaded or until no more beneficial moves.
However, note: moving a shard replica from X to Y might change the topology of the shard. We must update the shard's replica set.
Also, after moving, the node X might still be overloaded, and the new node Y might become overloaded. So we have to recompute the average and the overloaded/underloaded nodes.
We can iterate until the cluster is balanced (or until no more moves with positive score are possible).
We have a removed node R.
For each shard s that had a replica on R:
We need to pick a new node Y.
We can use a similar scoring:
candidate_nodes = all nodes except:
- current replicas of s (including R? but R is removed, so we don't consider R)
- note: R is already removed from the cluster, so we don't consider it.
Then for each candidate node Y:
current_zones = set(zone for node in s.replicas if node != R) # because R is removed, so we don't count it.
current_racks_in_zone_y = set(rack for node in s.replicas if node != R and node.zone == Y.zone)
score = 0
if Y.zone not in current_zones:
score += 1000
else:
if Y.rack not in current_racks_in_zone_y:
score += 100
score += (avg - load[Y]) # but note: after removal, the average changes? Actually, we are replacing R, so the total number of nodes is the same? No, we removed R and then we are adding a new node? Wait, in removal, we are not adding a node, we are just removing. So the number of nodes decreases by 1. Then the average load increases? Actually, we are moving the shards from R to other nodes, so the total number of shards remains the same, but the number of nodes decreases, so the average increases.
But note: we are in the process of rebalancing after removal. We first remove R and then assign its shards to other nodes. So the number of nodes temporarily is (original_nodes - 1). Then we assign the shards from R to the remaining nodes. So the average after we assign all shards from R will be (original_total_shard_replicas) / (original_nodes - 1). But during the assignment, we are assigning to the remaining nodes, so we want to balance among the remaining nodes.
So we can compute the new average: new_avg = (total_shard_replicas) / (current_number_of_nodes) [current_number_of_nodes = original_nodes - 1]
Then we want to move the shards from R to nodes that are underloaded (below new_avg).
So we can use new_avg.
Then we pick the candidate node with the highest score and assign the shard to it.
Then update the node's load.
We might have to do this for multiple shards (all that were on R). We can process them in any order, but note that the assignment of one shard might affect the candidate for another (because we update the load of nodes).
We can:
while there are shards to reassign:
pick the shard s (from those that were on R) that has the highest priority? Maybe we don't need to prioritize.
For s, compute the candidate nodes as above (using the current loads and current replicas of s).
Pick the best Y.
Assign s to Y.
Update load[Y] and remove s from the list of shards to reassign.
But note: we are assigning one replica for s from R to Y. But s already has N-1 replicas (because one was on R). We are adding the N-th? Actually, we are replacing the replica that was on R. So after assignment, s will have N replicas again.
We define:
def compute_average_load(nodes):
total_shards = sum(len(node.shards) for node in nodes)
return total_shards / len(nodes)
Then we define:
def find_move(shard, nodes, current_replicas, avg):
# current_replicas: the set of node ids that are currently replicas of the shard (without the node we are considering removing? or with?)
# We want to find a new node to move one replica of the shard to (from an overloaded node) or to replace a removed node.
candidate_nodes = [node for node in nodes if node.id not in current_replicas]
# We also want to avoid nodes that are already in the shard's replicas? current_replicas is the set of current replicas, so we are excluding them.
current_zones = set(nodes[node_id].zone for node_id in current_replicas)
current_racks_in_zone = defaultdict(set)
for node_id in current_replicas:
node = nodes[node_id]
current_racks_in_zone[node.zone].add(node.rack)
candidate_nodes.sort(key=lambda node: (
0 if node.zone not in current_zones else 1,
0 if (node.zone in current_zones and node.rack not in current_racks_in_zone[node.zone]) else 1,
avg - len(node.shards) # we want to move to underloaded nodes, so higher score for lower load (so we sort by this descending? Actually, we want to pick the node with the least load, so we sort by (avg - load) descending? But note: if load is less than avg, then (avg-load) is positive. We want to maximize that.
), reverse=True) # because we want the first element to have the highest score.
return candidate_nodes[0] if candidate_nodes else None
Then for node addition:
new_node = ... (with empty shards)
nodes.append(new_node)
avg = compute_average_load(nodes)
# We want to move replicas from overloaded nodes to the new node.
# We can create a list of candidate moves: for each overloaded node (len(node.shards) > avg), for each shard on that node, consider moving that shard's replica from the overloaded node to the new_node.
moves = []
for node in nodes:
if node.id == new_node.id:
continue
if len(node.shards) > avg:
for shard_id in node.shards:
shard = shards[shard_id]
# We are considering moving this replica from node to new_node.
# But note: the shard has multiple replicas. We are only moving one replica (the one on this node) to the new_node.
# Check if new_node is already a replica of this shard? We are going to check in find_move.
# We call find_move with current_replicas = shard.replicas (which includes node.id) and we are looking for a node that is not in shard.replicas. But new_node is not in shard.replicas because it's new and empty.
candidate = find_move(shard, nodes, shard.replicas, avg)
if candidate and candidate.id == new_node.id:
# Then moving from this node to new_node is the best move for this shard? Not necessarily, because we are only considering moves to the new_node. We might want to consider moves to any underloaded node.
# Actually, we want to move from overloaded to underloaded, and the new_node is underloaded (since it's empty). So we can consider this move.
score = ... we can compute the score as in find_move? But we don't have the score in find_move, we just sorted.
# Alternatively, we can compute the score for moving from node to new_node.
# But note: we are only considering moves to the new_node? We might want to consider moves to any underloaded node.
# Let's change: we want to consider any underloaded node as a candidate for moving a replica from an overloaded node.
# So we don't fix the candidate as new_node. We let find_move pick the best candidate (which might be the new_node or another underloaded node).
# But then we are not necessarily moving to the new_node. However, the goal of node addition is to use the new node to balance the cluster. So we want to move replicas to the new_node if possible.
# We can adjust the score in find_move to give a bonus for the new_node? But the new_node is underloaded, so it will be preferred anyway.
# So we can do:
candidate = find_move(shard, nodes, shard.replicas, avg)
if candidate and len(candidate.shards) < avg: # candidate is underloaded
moves.append((node, shard, candidate))
Then we sort moves by some criterion (maybe by the benefit of the move, i.e., how much it reduces the overload of node and how much it helps the topology).
Then we perform the moves until the new node is no longer underloaded or no more moves.
Similarly for node removal:
removed_node = ...
# First, we need to reassign the shards on removed_node.
shards_to_reassign = set(removed_node.shards)
# We remove the removed_node from the nodes list.
nodes.remove(removed_node)
avg = compute_average_load(nodes)
for shard_id in shards_to_reassign:
shard = shards[shard_id]
# We remove the removed_node from the shard's replicas.
shard.replicas.remove(removed_node.id)
# Now we need to assign a new node for this shard.
candidate = find_move(shard, nodes, shard.replicas, avg)
if candidate:
shard.replicas.add(candidate.id)
candidate.shards.add(shard.id)
# Now we have reassigned all shards from the removed_node, but the cluster might be unbalanced.
# Then we run a rebalancing among the current nodes (without the removed_node) to move replicas from overloaded to underloaded.
We can use the same move generation as above (but without a new node, we are just rebalancing among existing nodes).
def add_node(nodes, shards, new_node, N):
nodes.append(new_node)
avg = compute_avg(nodes)
# We want to move replicas from overloaded nodes to the new_node.
# We'll create a list of potential moves: (from_node, shard, to_node) where to_node is the new_node and from_node is overloaded.
moves = []
for node in nodes:
if node.id == new_node.id:
continue
if len(node.shards) > avg:
for shard_id in list(node.shards): # list because we might modify during iteration
shard = shards[shard_id]
# We consider moving this replica from node to the new_node.
# But note: the new_node might not be the best candidate. We want to move to any underloaded node, but we are particularly interested in the new_node.
# We can check if the new_node is a valid candidate for this shard.
# We compute the candidate for this shard (without considering the new_node specifically) and see if the new_node is the best.
candidate = find_move(shard, nodes, shard.replicas, avg)
if candidate and candidate.id == new_node.id:
moves.append((node, shard, new_node))
# Now we have a list of moves that would move a replica from an overloaded node to the new_node, and that are the best move for the shard.
# But we might have multiple moves for the same shard? No, because a shard has multiple replicas, and we are considering each replica on an overloaded node. But a shard might have multiple replicas on multiple overloaded nodes? Then we might have multiple moves for the same shard.
# We want to move at most one replica per shard? Not necessarily, we might move multiple replicas of the same shard to the new_node? But then the new_node would have multiple replicas of the same shard? That's not allowed (a node can only hold one replica of a shard). So we cannot move two replicas of the same shard to the new_node.
# Actually, the new_node is empty, so it doesn't have any shards. But if we move two replicas of the same shard to the new_node, then the new_node would have two replicas of the same shard, which is not allowed because then if the new_node fails, we lose two replicas.
# So we must ensure that we don't assign two replicas of the same shard to the same node.
# In our move generation, we are only considering moves where the new_node is not already a replica of the shard (because in find_move, we exclude current_replicas). So if the new_node is not in the shard's replicas, then it's safe to move one replica to it. But if we move two replicas of the same shard to the new_node, then the second move would see that the new_node is already a replica (because we updated the shard's replicas after the first move) and would not consider it.
# So we can perform the moves in order, and after each move update the state.
# But note: we generated the moves all at once, so if a shard appears in two moves (from two different overloaded nodes) and both moves are to the new_node, then the second move would be invalid after the first because the new_node becomes a replica.
# So we should not generate moves that would conflict.
# Alternatively, we can sort the moves by some priority and then perform them one by one, updating the state and regenerating the candidate for each shard? That would be expensive.
# Given the complexity, we can do:
# Sort moves by the benefit (maybe by the score in find_move? but we don't have the score). We can sort by the load of the from_node (higher is better to move from) and then by the load of the new_node (lower is better to move to).
# Then perform the moves in that order, and after each move, update the shard's replicas and the node's shard sets, and recalc the avg? Actually, the avg changes as we move.
# Alternatively, we can do a while loop: while there exists an overloaded node and an underloaded node (including the new_node) and we can find a move that is valid and improves balance, do it.
# Let's do:
while True:
overloaded = [node for node in nodes if len(node.shards) > avg]
underloaded = [node for node in nodes if len(node.shards) < avg]
if not overloaded or not underloaded:
break
# We want to move a replica from an overloaded node to an underloaded node.
# We can try for each overloaded node and each shard on it, find the best underloaded node for that shard.
best_move = None
best_score = -float('inf')
for from_node in overloaded:
for shard_id in list(from_node.shards):
shard = shards[shard_id]
# We are considering moving this replica from from_node to an underloaded node.
# We want to find the best underloaded node for this shard.
candidate_nodes = [node for node in underloaded if node.id not in shard.replicas]
if not candidate_nodes:
continue
# Sort candidate_nodes by the same criteria as find_move, but we only consider underloaded nodes.
current_zones = set(get_zone(nodes[node_id]) for node_id in shard.replicas)
current_racks_in_zone = defaultdict(set)
for node_id in shard.replicas:
node = nodes[node_id]
current_racks_in_zone[get_zone(node)].add(get_rack(node))
candidate_nodes.sort(key=lambda node: (
0 if get_zone(node) not in current_zones else 1,
0 if (get_zone(node) in current_zones and get_rack(node) not in current_racks_in_zone[get_zone(node)]) else 1,
avg - len(node.shards) # positive for underloaded, and we want to maximize
), reverse=True)
chosen = candidate_nodes[0]
# Compute a score for this move: we can use the same sort key as a tuple? But we want to compare moves from different shards and from_nodes.
# We can define score = (zone_benefit, rack_benefit, load_benefit) but we have two binary benefits and one continuous.
# Let's define:
zone_benefit = 1 if get_zone(chosen) not in current_zones else 0
rack_benefit = 1 if (get_zone(chosen) in current_zones and get_rack(chosen) not in current_racks_in_zone[get_zone(chosen)]) else 0
load_benefit = avg - len(chosen.shards) # how much below average the chosen node is.
score = (zone_benefit, rack_benefit, load_benefit)
# We want to maximize zone_benefit, then rack_benefit, then load_benefit.
if score > best_score:
best_score = score
best_move = (from_node, shard, chosen)
if best_move:
from_node, shard, to_node = best_move
# Perform the move
from_node.shards.remove(shard.id)
to_node.shards.add(shard.id)
shard.replicas.remove(from_node.id)
shard.replicas.add(to_node.id)
# Recompute avg? The avg might change because we moved one shard from an overloaded to an underloaded, so the total number of shards is the same, but the distribution changed. The avg is the same? Wait, the avg is total_shards / number_of_nodes. The total_shards is the same (we are moving a shard, not adding or removing). So the avg remains the same.
# But note: we are moving a shard from one node to another, so the number of shards on from_node decreases by 1, and on to_node increases by 1. The total number of shards in the system is the same, so the avg is the same.
# However, the set of overloaded and underloaded nodes might change.
# We don't need to recompute avg, but we can recalc the list of overloaded and underloaded.
else:
break
removed_node = ...
# Remove the node from the nodes list.
nodes.remove(removed_node)
# The shards on the removed_node need to be reassigned.
shards_to_reassign = list(removed_node.shards) # copy because we will modify
# We also remove the removed_node from the shard's replica sets.
for shard_id in shards_to_reassign:
shard = shards[shard_id]
shard.replicas.remove(removed_node.id)
# Now we have a cluster without the removed_node, and some shards have N-1 replicas.
# We want to assign a new node for each of these shards.
avg = compute_avg(nodes) # note: the total number of shard replicas is the same, but the number of nodes is decreased, so avg increases.
for shard_id in shards_to_reassign:
shard = shards[shard_id]
candidate = find_move(shard, nodes, shard.replicas, avg)
if candidate:
shard.replicas.add(candidate.id)
candidate.shards.add(shard.id)
else:
# This is an error: we cannot find a node for the shard.
raise Exception(f"Cannot find a node for shard {shard_id}")
# Now the cluster has the same number of replicas, but we might have an imbalance because we assigned the shards from the removed_node to the remaining nodes, and some of those nodes might become overloaded.
# Then we run the same rebalancing loop as in addition (without a new node, but with the current set of nodes).
while True:
overloaded = [node for node in nodes if len(node.shards) > avg]
underloaded = [node for node in nodes if len(node.shards) < avg]
if not overloaded or not underloaded:
break
best_move = None
best_score = -float('inf')
for from_node in overloaded:
for shard_id in list(from_node.shards):
shard = shards[shard_id]
candidate_nodes = [node for node in underloaded if node.id not in shard.replicas]
if not candidate_nodes:
continue
current_zones = set(get_zone(nodes[node_id]) for node_id in shard.replicas)
current_racks_in_zone = defaultdict(set)
for node_id in shard.replicas:
node = nodes[node_id]
current_racks_in_zone[get_zone(node)].add(get_rack(node))
candidate_nodes.sort(key=lambda node: (
0 if get_zone(node) not in current_zones else 1,
0 if (get_zone(node) in current_zones and get_rack(node) not in current_racks_in_zone[get_zone(node)]) else 1,
avg - len(node.shards)
), reverse=True)
chosen = candidate_nodes[0]
zone_benefit = 1 if get_zone(chosen) not in current_zones else 0
rack_benefit = 1 if (get_zone(chosen) in current_zones and get_rack(chosen) not in current_racks_in_zone[get_zone(chosen)]) else 0
load_benefit = avg - len(chosen.shards)
score = (zone_benefit, rack_benefit, load_benefit)
if score > best_score:
best_score = score
best_move = (from_node, shard, chosen)
if best_move:
from_node, shard, to_node = best_move
from_node.shards.remove(shard.id)
to_node.shards.add(shard.id)
shard.replicas.remove(from_node.id)
shard.replicas.add(to_node.id)
else:
break