Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
0ebd75d
Estimate impact of shard movement using node-level write load
nicktindall Jul 17, 2025
e589db4
Naming
nicktindall Jul 17, 2025
beb2611
More randomness
nicktindall Jul 17, 2025
4e0fd1d
Merge remote-tracking branch 'origin/main' into ES-12000_add_write_lo…
nicktindall Jul 17, 2025
3f90889
Pedantry
nicktindall Jul 17, 2025
0b1d4a2
Naming
nicktindall Jul 17, 2025
9527720
Merge remote-tracking branch 'origin/main' into ES-12000_add_write_lo…
nicktindall Jul 17, 2025
9e36975
Merge branch 'main' into ES-12000_add_write_load_modeling_to_balancer
nicktindall Jul 21, 2025
9ca9b4b
Use shard write loads instead of estimating
nicktindall Jul 21, 2025
988ac3c
Add javadoc to WriteLoadPerShardSimulator
nicktindall Jul 24, 2025
f5ed735
Explain simulateShardStarted better for the new shard case
nicktindall Jul 24, 2025
8501b37
Assert on scale of utilisation change
nicktindall Jul 24, 2025
8c21cc0
Improve description of relocation
nicktindall Jul 24, 2025
519d1dd
Typo
nicktindall Jul 24, 2025
58e84a2
Rename test to indicate it also tests missing write loads
nicktindall Jul 24, 2025
faccc3d
Always simulate based on original write loads and thread pool stats
nicktindall Jul 24, 2025
edc259a
Use for-loop instead of stream
nicktindall Jul 24, 2025
f60029f
Consolidate similar tests
nicktindall Jul 24, 2025
94687e3
Naming/description of nodeUsageStatsForThreadPools
nicktindall Jul 24, 2025
466a7e0
Naming of test utility methods
nicktindall Jul 24, 2025
827f637
WriteLoadPerShardSimulator -> ShardMovementWriteLoadSimulator
nicktindall Jul 24, 2025
1c876e7
Merge remote-tracking branch 'origin/main' into ES-12000_add_write_lo…
nicktindall Jul 24, 2025
a072aaf
Increase likelihood of write loads and utilizations being 0, floor ut…
nicktindall Jul 24, 2025
6ae4aa4
Pedantry
nicktindall Jul 24, 2025
1dbee7f
Merge branch 'main' into ES-12000_add_write_load_modeling_to_balancer
nicktindall Jul 24, 2025
a4d89b9
Merge branch 'main' into ES-12000_add_write_load_modeling_to_balancer
nicktindall Jul 24, 2025
89c4d28
Merge branch 'main' into ES-12000_add_write_load_modeling_to_balancer
nicktindall Jul 25, 2025
770e04d
Assert that shardStarted only happens on destination node ina reloca…
nicktindall Jul 28, 2025
2b3ebf6
Merge branch 'main' into ES-12000_add_write_load_modeling_to_balancer
nicktindall Jul 28, 2025
34472f6
Typo
nicktindall Jul 28, 2025
cf81780
Update server/src/main/java/org/elasticsearch/cluster/routing/ShardMo…
nicktindall Jul 29, 2025
27a9ba0
Update server/src/main/java/org/elasticsearch/cluster/routing/ShardMo…
nicktindall Jul 29, 2025
1e0a4a0
Naming
nicktindall Jul 29, 2025
38c79a7
Merge branch 'main' into ES-12000_add_write_load_modeling_to_balancer
nicktindall Jul 29, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import org.elasticsearch.cluster.ClusterInfo.NodeAndShard;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.WriteLoadPerShardSimulator;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.util.CopyOnFirstWriteMap;
import org.elasticsearch.index.shard.ShardId;
Expand All @@ -34,7 +35,7 @@ public class ClusterInfoSimulator {
private final Map<ShardId, Long> shardDataSetSizes;
private final Map<NodeAndShard, String> dataPath;
private final Map<String, EstimatedHeapUsage> estimatedHeapUsages;
private final Map<String, NodeUsageStatsForThreadPools> nodeThreadPoolUsageStats;
private final WriteLoadPerShardSimulator writeLoadPerShardSimulator;

public ClusterInfoSimulator(RoutingAllocation allocation) {
this.allocation = allocation;
Expand All @@ -44,7 +45,7 @@ public ClusterInfoSimulator(RoutingAllocation allocation) {
this.shardDataSetSizes = Map.copyOf(allocation.clusterInfo().shardDataSetSizes);
this.dataPath = Map.copyOf(allocation.clusterInfo().dataPath);
this.estimatedHeapUsages = allocation.clusterInfo().getEstimatedHeapUsages();
this.nodeThreadPoolUsageStats = allocation.clusterInfo().getNodeUsageStatsForThreadPools();
this.writeLoadPerShardSimulator = new WriteLoadPerShardSimulator(allocation);
}

/**
Expand Down Expand Up @@ -115,6 +116,7 @@ public void simulateShardStarted(ShardRouting shard) {
shardSizes.put(shardIdentifierFromRouting(shard), project.getIndexSafe(shard.index()).ignoreDiskWatermarks() ? 0 : size);
}
}
writeLoadPerShardSimulator.simulateShardStarted(shard);
}

private void modifyDiskUsage(String nodeId, long freeDelta) {
Expand Down Expand Up @@ -159,7 +161,7 @@ public ClusterInfo getClusterInfo() {
dataPath,
Map.of(),
estimatedHeapUsages,
nodeThreadPoolUsageStats
writeLoadPerShardSimulator.nodeUsageStatsForThreadPools()
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

package org.elasticsearch.cluster.routing;

import com.carrotsearch.hppc.ObjectFloatHashMap;
import com.carrotsearch.hppc.ObjectFloatMap;

import org.elasticsearch.cluster.NodeUsageStatsForThreadPools;
import org.elasticsearch.cluster.metadata.IndexAbstraction;
import org.elasticsearch.cluster.metadata.ProjectMetadata;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.util.Maps;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.threadpool.ThreadPool;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class WriteLoadPerShardSimulator {

private final ObjectFloatMap<String> writeLoadDeltas;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: simulatedNodesLoad?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 I changed to simulatedWriteLoadDeltas, we only store the delta from the reported/original write load here. The idea there is that if no delta is present, we can just return the original NodeUsageStatsForThreadPools instance.

private final RoutingAllocation routingAllocation;
private final ObjectFloatMap<ShardId> writeLoadsPerShard;

public WriteLoadPerShardSimulator(RoutingAllocation routingAllocation) {
this.routingAllocation = routingAllocation;
this.writeLoadDeltas = new ObjectFloatHashMap<>();
writeLoadsPerShard = estimateWriteLoadsPerShard(routingAllocation);
}

public void simulateShardStarted(ShardRouting shardRouting) {
final float writeLoadForShard = writeLoadsPerShard.get(shardRouting.shardId());
if (writeLoadForShard > 0.0) {
if (shardRouting.relocatingNodeId() != null) {
// relocating
writeLoadDeltas.addTo(shardRouting.relocatingNodeId(), -1 * writeLoadForShard);
writeLoadDeltas.addTo(shardRouting.currentNodeId(), writeLoadForShard);
} else {
// not sure how this would come about, perhaps when allocating a replica after a delay?
writeLoadDeltas.addTo(shardRouting.currentNodeId(), writeLoadForShard);
}
}
}

public Map<String, NodeUsageStatsForThreadPools> nodeUsageStatsForThreadPools() {
return routingAllocation.clusterInfo()
.getNodeUsageStatsForThreadPools()
.entrySet()
.stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, e -> {
if (writeLoadDeltas.containsKey(e.getKey())) {
return new NodeUsageStatsForThreadPools(
e.getKey(),
Maps.copyMapWithAddedOrReplacedEntry(
e.getValue().threadPoolUsageStatsMap(),
"write",
replaceWritePoolStats(e.getValue(), writeLoadDeltas.get(e.getKey()))
)
);
}
return e.getValue();
}));
}

private NodeUsageStatsForThreadPools.ThreadPoolUsageStats replaceWritePoolStats(
NodeUsageStatsForThreadPools value,
float writeLoadDelta
) {
final NodeUsageStatsForThreadPools.ThreadPoolUsageStats writeThreadPoolStats = value.threadPoolUsageStatsMap()
.get(ThreadPool.Names.WRITE);
return new NodeUsageStatsForThreadPools.ThreadPoolUsageStats(
writeThreadPoolStats.totalThreadPoolThreads(),
writeThreadPoolStats.averageThreadPoolUtilization() + (writeLoadDelta / writeThreadPoolStats.totalThreadPoolThreads()),
writeThreadPoolStats.averageThreadPoolQueueLatencyMillis()
);
}

// Everything below this line can probably go once we are publishing shard-write-load estimates to the master

private static ObjectFloatMap<ShardId> estimateWriteLoadsPerShard(RoutingAllocation allocation) {
final Map<ShardId, Average> writeLoadPerShard = new HashMap<>();
final Set<String> writeIndexNames = getWriteIndexNames(allocation);
final Map<String, NodeUsageStatsForThreadPools> nodeUsageStatsForThreadPools = allocation.clusterInfo()
.getNodeUsageStatsForThreadPools();
for (final Map.Entry<String, NodeUsageStatsForThreadPools> usageStatsForThreadPoolsEntry : nodeUsageStatsForThreadPools
.entrySet()) {
final NodeUsageStatsForThreadPools value = usageStatsForThreadPoolsEntry.getValue();
final NodeUsageStatsForThreadPools.ThreadPoolUsageStats writeThreadPoolStats = value.threadPoolUsageStatsMap()
.get(ThreadPool.Names.WRITE);
if (writeThreadPoolStats == null) {
// No stats from this node yet
continue;
}
float writeUtilisation = writeThreadPoolStats.averageThreadPoolUtilization() * writeThreadPoolStats.totalThreadPoolThreads();

final String nodeId = usageStatsForThreadPoolsEntry.getKey();
final RoutingNode node = allocation.routingNodes().node(nodeId);
final Set<ShardId> writeShardsOnNode = new HashSet<>();
for (final ShardRouting shardRouting : node) {
if (shardRouting.role() != ShardRouting.Role.SEARCH_ONLY && writeIndexNames.contains(shardRouting.index().getName())) {
writeShardsOnNode.add(shardRouting.shardId());
}
}
writeShardsOnNode.forEach(
shardId -> writeLoadPerShard.computeIfAbsent(shardId, k -> new Average()).add(writeUtilisation / writeShardsOnNode.size())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you equally divide write-load across all write shards on node?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, this is just a stop-gap until we get actual shard loads, which should work as a drop-in replacement.

Copy link
Contributor

@mhl-b mhl-b Jul 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I was thinking maybe we should have some heuristic from already available data. Otherwise signal/noise ratio is too high. It's not uncommon to have hundreds of shards, and estimation has little to no impact on a single shard.

For example use shardSize heuristic, the larger size more likely it would have write-load. Lets say linearly increase weight of those shards as size approaches 15GB. And then decrease weight as they approach to 30GB since we would roll-over them (most of the time) if size <15GB then size/15GB else max(0, 1-size/30GB)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'll have actual shard write loads shortly. Hopefully we can avoid all this guessing entirely.

#131496

);
}
final ObjectFloatMap<ShardId> writeLoads = new ObjectFloatHashMap<>(writeLoadPerShard.size());
writeLoadPerShard.forEach((shardId, average) -> writeLoads.put(shardId, average.get()));
return writeLoads;
}

private static Set<String> getWriteIndexNames(RoutingAllocation allocation) {
return allocation.metadata()
.projects()
.values()
.stream()
.map(ProjectMetadata::getIndicesLookup)
.flatMap(indicesLookup -> indicesLookup.values().stream())
.map(IndexAbstraction::getWriteIndex)
.filter(Objects::nonNull)
.map(Index::getName)
.collect(Collectors.toUnmodifiableSet());
}

private static final class Average {
int count;
float sum;

public void add(float value) {
count++;
sum += value;
}

public float get() {
return sum / count;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

package org.elasticsearch.cluster.routing;

import org.elasticsearch.action.support.replication.ClusterStateCreationUtils;
import org.elasticsearch.cluster.ClusterInfo;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.NodeUsageStatsForThreadPools;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders;
import org.elasticsearch.snapshots.SnapshotShardSizeInfo;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matchers;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.StreamSupport;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.sameInstance;

public class WriteLoadPerShardSimulatorTests extends ESTestCase {

private static final RoutingChangesObserver NOOP = new RoutingChangesObserver() {
};

/**
* We should not adjust the values if there's no movement
*/
public void testNoShardMovement() {
final var originalNode0WriteLoadStats = randomUsageStats();
final var originalNode1WriteLoadStats = randomUsageStats();
final var allocation = createRoutingAllocation(originalNode0WriteLoadStats, originalNode1WriteLoadStats);

final var writeLoadPerShardSimulator = new WriteLoadPerShardSimulator(allocation);
final var calculatedNodeUsageStates = writeLoadPerShardSimulator.nodeUsageStatsForThreadPools();
assertThat(calculatedNodeUsageStates, Matchers.aMapWithSize(2));
assertThat(
calculatedNodeUsageStates.get("node_0").threadPoolUsageStatsMap().get("write"),
sameInstance(originalNode0WriteLoadStats)
);
assertThat(
calculatedNodeUsageStates.get("node_1").threadPoolUsageStatsMap().get("write"),
sameInstance(originalNode1WriteLoadStats)
);
}

public void testMovementOfAShardWillReduceThreadPoolUtilisation() {
final var originalNode0WriteLoadStats = randomUsageStats();
final var originalNode1WriteLoadStats = randomUsageStats();
final var allocation = createRoutingAllocation(originalNode0WriteLoadStats, originalNode1WriteLoadStats);
final var writeLoadPerShardSimulator = new WriteLoadPerShardSimulator(allocation);

// Relocate a random shard from node_0 to node_1
final var randomShard = randomFrom(StreamSupport.stream(allocation.routingNodes().node("node_0").spliterator(), false).toList());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

log randomShard? For debug purposes, then we can match it with the ClusterInfo info I suggest logging in createRoutingAllocation.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again given that this is a unit test with no concurrency any failure should be reliably reproducible. Going to not log here assuming someone investigating a failure can log the things they're interested in.

final var moveShardTuple = allocation.routingNodes().relocateShard(randomShard, "node_1", randomNonNegativeLong(), "testing", NOOP);
writeLoadPerShardSimulator.simulateShardStarted(moveShardTuple.v2());

final var calculatedNodeUsageStates = writeLoadPerShardSimulator.nodeUsageStatsForThreadPools();
assertThat(calculatedNodeUsageStates, Matchers.aMapWithSize(2));

// Some node_0 utilization should have been moved to node_1
assertThat(
getAverageWritePoolUtilization(writeLoadPerShardSimulator, "node_0"),
lessThan(originalNode0WriteLoadStats.averageThreadPoolUtilization())
);
assertThat(
getAverageWritePoolUtilization(writeLoadPerShardSimulator, "node_1"),
greaterThan(originalNode1WriteLoadStats.averageThreadPoolUtilization())
);
}

public void testMovementFollowedByMovementBackWillNotChangeAnything() {
final var originalNode0WriteLoadStats = randomUsageStats();
final var originalNode1WriteLoadStats = randomUsageStats();
final var allocation = createRoutingAllocation(originalNode0WriteLoadStats, originalNode1WriteLoadStats);
final var writeLoadPerShardSimulator = new WriteLoadPerShardSimulator(allocation);

// Relocate a random shard from node_0 to node_1
final long expectedShardSize = randomNonNegativeLong();
final var randomShard = randomFrom(StreamSupport.stream(allocation.routingNodes().node("node_0").spliterator(), false).toList());
final var moveShardTuple = allocation.routingNodes().relocateShard(randomShard, "node_1", expectedShardSize, "testing", NOOP);
writeLoadPerShardSimulator.simulateShardStarted(moveShardTuple.v2());
final ShardRouting movedAndStartedShard = allocation.routingNodes().startShard(moveShardTuple.v2(), NOOP, expectedShardSize);

// Some node_0 utilization should have been moved to node_1
assertThat(
getAverageWritePoolUtilization(writeLoadPerShardSimulator, "node_0"),
lessThan(originalNode0WriteLoadStats.averageThreadPoolUtilization())
);
assertThat(
getAverageWritePoolUtilization(writeLoadPerShardSimulator, "node_1"),
greaterThan(originalNode1WriteLoadStats.averageThreadPoolUtilization())
);

// Then move it back
final var moveBackTuple = allocation.routingNodes()
.relocateShard(movedAndStartedShard, "node_0", expectedShardSize, "testing", NOOP);
writeLoadPerShardSimulator.simulateShardStarted(moveBackTuple.v2());

// The utilization numbers should be back to their original values
assertThat(
getAverageWritePoolUtilization(writeLoadPerShardSimulator, "node_0"),
equalTo(originalNode0WriteLoadStats.averageThreadPoolUtilization())
);
assertThat(
getAverageWritePoolUtilization(writeLoadPerShardSimulator, "node_1"),
equalTo(originalNode1WriteLoadStats.averageThreadPoolUtilization())
);
}

public void testMovementBetweenNodesWithNoThreadPoolStats() {
final var originalNode0WriteLoadStats = randomBoolean() ? randomUsageStats() : null;
final var originalNode1WriteLoadStats = randomBoolean() ? randomUsageStats() : null;
final var allocation = createRoutingAllocation(originalNode0WriteLoadStats, originalNode1WriteLoadStats);
final var writeLoadPerShardSimulator = new WriteLoadPerShardSimulator(allocation);

// Relocate a random shard from node_0 to node_1
final long expectedShardSize = randomNonNegativeLong();
final var randomShard = randomFrom(StreamSupport.stream(allocation.routingNodes().node("node_0").spliterator(), false).toList());
final var moveShardTuple = allocation.routingNodes().relocateShard(randomShard, "node_1", expectedShardSize, "testing", NOOP);
writeLoadPerShardSimulator.simulateShardStarted(moveShardTuple.v2());
allocation.routingNodes().startShard(moveShardTuple.v2(), NOOP, expectedShardSize);

final var generated = writeLoadPerShardSimulator.nodeUsageStatsForThreadPools();
assertThat(generated.containsKey("node_0"), equalTo(originalNode0WriteLoadStats != null));
assertThat(generated.containsKey("node_1"), equalTo(originalNode1WriteLoadStats != null));
}

private float getAverageWritePoolUtilization(WriteLoadPerShardSimulator writeLoadPerShardSimulator, String nodeId) {
final var generatedNodeUsageStates = writeLoadPerShardSimulator.nodeUsageStatsForThreadPools();
final var node0WritePoolStats = generatedNodeUsageStates.get(nodeId).threadPoolUsageStatsMap().get("write");
return node0WritePoolStats.averageThreadPoolUtilization();
}

private NodeUsageStatsForThreadPools.ThreadPoolUsageStats randomUsageStats() {
return new NodeUsageStatsForThreadPools.ThreadPoolUsageStats(
randomIntBetween(4, 16),
randomFloatBetween(0.1f, 1.0f, true),
randomLongBetween(0, 60_000)
);
}

private RoutingAllocation createRoutingAllocation(
NodeUsageStatsForThreadPools.ThreadPoolUsageStats node0WriteLoadStats,
NodeUsageStatsForThreadPools.ThreadPoolUsageStats node1WriteLoadStats
) {
final Map<String, NodeUsageStatsForThreadPools> nodeUsageStats = new HashMap<>();
if (node0WriteLoadStats != null) {
nodeUsageStats.put("node_0", new NodeUsageStatsForThreadPools("node_0", Map.of("write", node0WriteLoadStats)));
}
if (node1WriteLoadStats != null) {
nodeUsageStats.put("node_1", new NodeUsageStatsForThreadPools("node_1", Map.of("write", node1WriteLoadStats)));
}

return new RoutingAllocation(
new AllocationDeciders(List.of()),
createClusterState(),
ClusterInfo.builder().nodeUsageStatsForThreadPools(nodeUsageStats).build(),
SnapshotShardSizeInfo.EMPTY,
System.nanoTime()
).mutableCloneForSimulation();
}

private ClusterState createClusterState() {
return ClusterStateCreationUtils.stateWithAssignedPrimariesAndReplicas(new String[] { "indexOne", "indexTwo", "indexThree" }, 3, 0);
}
}