Skip to content

[ISSUE #11620] Avoid redundant tree lookups in consistent-hash routing - #11621

Open
biheto wants to merge 1 commit into
apache:developfrom
biheto:perf/consistent-hash-single-lookup
Open

biheto wants to merge 1 commit into
apache:developfrom
biheto:perf/consistent-hash-single-lookup

Conversation

@biheto

@biheto biheto commented Nov 26, 2026 •

Copy link
Copy Markdown

Which Issue(s) This PR Fixes

Fixes #11620.

Brief Description

AllocateMessageQueueConsistentHash.allocate routes each message queue through ConsistentHashRouter.routeNode. The current lookup creates a tail-map view, checks it, finds its first key and then searches the ring again for the corresponding value.

Use NavigableMap.ceilingEntry to obtain the successor and its value together, falling back to firstEntry on wrap-around. The ring remains a TreeMap and lookup complexity remains O(log V); this removes repeated tree searches and temporary views. There is no new API, configuration, dependency or retained cache. Hashing, node placement and membership changes are unchanged. The separate shared-MD5 concurrency issue #11264 is outside this change.

Add two tests for signed hash extremes and collision/removal behavior alongside the existing exact-match, successor, wrap-around and empty-ring tests.

How Did You Test This Change?

  • mvn -B -ntp -pl common -am test -Dtest=ConsistentHashRouterTest -Dsurefire.failIfNoSpecifiedTests=false: BUILD SUCCESS, 5 tests, 0 failures/errors/skips. Lifecycle Checkstyle reported 0 violations and SpotBugs passed.
  • Additionally compiled the existing AllocateMessageQueueConsitentHashTest and its three client strategy/interface sources with javac --release 8, using the built common module and its Maven test dependencies, and ran it via JUnitCore: 7 tests passed. This checks queue assignment after consumer additions/removals; it was not a full client-module Maven run.
  • git diff --check passed. The standalone Maven/JMH reproduction project below packaged successfully and its executable jar completed a two-size smoke run. Full broker/integration suites were not run.

Upstream CI on 45fde8c6e0055e8b2c95410323f308559348914d has also completed successfully: all seven workflows (Maven builds/tests on Linux, Windows and macOS, Bazel, integration tests, coverage, CodeQL, license and spelling checks). Codecov reports that all modified coverable lines are covered. This is additional CI evidence; the local validation scope above is unchanged.

Measurement

The benchmark calls the actual routeNode implementation and includes default MD5 hashing and its per-call allocations. Ring construction and input generation are setup work. It cycles through 1,024 prebuilt queue keys, with 10 virtual nodes per physical node. This isolates the changed lookup; it does not establish an end-to-end rebalance or message-throughput gain.

Windows, Intel i5-12500H, Oracle JDK 17.0.4.1, JMH 1.37, one fixed logical processor for both versions, -Xms256m -Xmx256m, GC profiler, two forks, five one-second warmups and ten one-second measurements. Mean +/- JMH 99.9% confidence error:

Physical nodes Before, ns/op After, ns/op Before, B/op After, B/op
8 359.747 +/- 29.783 325.222 +/- 39.755 216.027 160.023
128 479.735 +/- 53.218 365.068 +/- 34.362 216.039 136.026

The 8-node time intervals overlap, so no speedup is claimed there. The 128-node mean is about 24% lower. Allocation savings depend on JVM optimization, including whether the returned entry escapes; the table reports measurements rather than a fixed object-size guarantee. A shorter initial run was noisy, so these default-MD5 comparisons were repeated with longer measurement after concurrent build work finished.

Baseline: e114b542620c4169d016f25b63c2c377b2e279a7; candidate: this PR. Both were compiled for Java 8 and run on the same JDK 17.

Reproduce with Maven and JMH (compiles the selected checkout's production sources)

Save pom.xml and RingLookupBenchmark.java below together in a separate benchmark directory. Run once with rocketmq.checkout pointing to the baseline checkout, then again with it pointing to the candidate. clean package prevents reuse of the other version's classes. Use separate JSON output files and the same JDK, JVM flags and CPU affinity for both runs. Replace the example paths for your system; the Maven and Java commands work on Windows and POSIX systems.

mvn -B -ntp -f /path/to/benchmark/pom.xml -Drocketmq.checkout=/path/to/rocketmq-checkout clean package
java -jar /path/to/benchmark/target/benchmarks.jar -p hash=MD5 -f 2 -wi 5 -i 10 -w 1s -r 1s -prof gc -jvmArgs "-Xms256m -Xmx256m" -rf json -rff /path/to/before.json

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>benchmark</groupId>
  <artifactId>ring-lookup</artifactId>
  <version>1.0</version>
  <properties>
    <maven.compiler.release>8</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <rocketmq.checkout>${project.basedir}/../../rocketmq</rocketmq.checkout>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.openjdk.jmh</groupId><artifactId>jmh-core</artifactId><version>1.37</version>
    </dependency>
  </dependencies>
  <build>
    <sourceDirectory>${project.basedir}</sourceDirectory>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId><artifactId>build-helper-maven-plugin</artifactId><version>3.6.1</version>
        <executions><execution><id>production-source</id><phase>generate-sources</phase><goals><goal>add-source</goal></goals>
          <configuration><sources><source>${rocketmq.checkout}/common/src/main/java</source></sources></configuration>
        </execution></executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.15.0</version>
        <configuration>
          <includes><include>RingLookupBenchmark.java</include><include>org/apache/rocketmq/common/consistenthash/*.java</include></includes>
          <annotationProcessorPaths><path>
            <groupId>org.openjdk.jmh</groupId><artifactId>jmh-generator-annprocess</artifactId><version>1.37</version>
          </path></annotationProcessorPaths>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>3.6.0</version>
        <executions><execution><phase>package</phase><goals><goal>shade</goal></goals><configuration>
          <finalName>benchmarks</finalName><createDependencyReducedPom>false</createDependencyReducedPom>
          <transformers><transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
            <mainClass>org.openjdk.jmh.Main</mainClass>
          </transformer></transformers>
        </configuration></execution></executions>
      </plugin>
    </plugins>
  </build>
</project>

RingLookupBenchmark.java:

package benchmark;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.rocketmq.common.consistenthash.ConsistentHashRouter;
import org.apache.rocketmq.common.consistenthash.Node;
import org.openjdk.jmh.annotations.*;

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(2)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
public class RingLookupBenchmark {
    @Param({"8", "128"})
    public int nodes;
    @Param({"MD5", "CUSTOM"})
    public String hash;
    private ConsistentHashRouter<Node> router;
    private String[] keys;
    private int cursor;

    @Setup
    public void setup() {
        List<Node> consumers = new ArrayList<>();
        for (int i = 0; i < nodes; i++) {
            final String key = "consumer-" + i;
            consumers.add(() -> key);
        }
        router = "MD5".equals(hash)
                ? new ConsistentHashRouter<>(consumers, 10)
                : new ConsistentHashRouter<>(consumers, 10, String::hashCode);
        keys = new String[1024];
        for (int i = 0; i < keys.length; i++) {
            keys[i] = "MessageQueue [topic=orders, brokerName=broker-" + (i % 8) + ", queueId=" + i + "]";
        }
    }

    @Benchmark
    public Node route() {
        return router.routeNode(keys[cursor++ & (keys.length - 1)]);
    }
}

OpenAI Codex assisted with investigation, implementation, tests, benchmarks and this description. The commit includes an Assisted-By trailer.

Use the existing TreeMap through NavigableMap.ceilingEntry and fall back to firstEntry when the lookup wraps around the ring. This avoids creating a tail-map view and searching again for the selected key.

Preserve hashing and node placement. Cover signed hash boundaries, collisions and removal alongside existing routing tests.

Fixes apache#11620

Assisted-By: OpenAI Codex
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 50.89%. Comparing base (e114b54) to head (45fde8c).

Additional details and impacted files
@@              Coverage Diff              @@
##             develop   #11621      +/-   ##
=============================================
+ Coverage      50.86%   50.89%   +0.02%     
- Complexity     14881    14887       +6     
=============================================
  Files           1391     1391              
  Lines         103773   103774       +1     
  Branches       13614    13614              
=============================================
+ Hits           52789    52811      +22     
+ Misses         44724    44704      -20     
+ Partials        6260     6259       -1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Distzzc Distzzc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ceilingEntry preserves exact-match routing, and firstEntry preserves wrap-around. I compiled the base (e114b542) and this revision (45fde8c6) with javac --release 8 on JDK 17 and ran the same deterministic cases against both. Across 256 rounds covering node additions and removals, signed hash boundaries, virtual-node collisions, and empty rings, all 9,216 routing results and 1,024 replica counts matched. The five tests in ConsistentHashRouterTest also passed on the candidate revision.

@biheto

biheto commented Nov 26, 2026

Copy link
Copy Markdown
Author

ceilingEntry preserves exact-match routing, and firstEntry preserves wrap-around. I compiled the base (e114b542) and this revision (45fde8c6) with javac --release 8 on JDK 17 and ran the same deterministic cases against both. Across 256 rounds covering node additions and removals, signed hash boundaries, virtual-node collisions, and empty rings, all 9,216 routing results and 1,024 replica counts matched. The five tests in ConsistentHashRouterTest also passed on the candidate revision. ceilingEntry 保留了完全匹配路由的方式,而 firstEntry 则保留了循环覆盖的方式。我使用 JDK 17 版本,对基础版本 ( e114b542 ) 和修订版本 ( 45fde8c6 ) 进行了编译,并分别针对这两种版本运行了相同的确定性测试。在包含节点添加和删除、签名哈希边界、虚拟节点冲突以及空环等 256 轮测试过程中,所有 9,216 次路由结果以及 1,024 次副本计数都完全一致。 ConsistentHashRouterTest 中的五项测试也都在候选版本上通过了。

@Distzzc
Thanks for the thorough validation against the base revision, especially the signed hash boundaries and virtual-node collisions. The matching results support that this change preserves the existing routing behavior while removing redundant tree lookups. No changes to node placement or replica management are intended.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Enhancement] Avoid redundant tree lookups in consistent-hash routing

3 participants