Skip to content

Restore configurable ioRatio-based task scheduling in SingleThreadIoEventLoop - #17481

Merged
normanmaurer merged 6 commits into
4.2from
io_ratio
Sep 22, 2026
Merged

normanmaurer merged 6 commits into
4.2from
io_ratio

Conversation

@normanmaurer

Copy link
Copy Markdown
Member

Motivation:

The unification done in #13991/#14557 replaced the per-transport ioRatio
scheduling with a fixed maxTaskProcessingQuantumMs cap on task processing
before returning to IO. Under sustained load the task queue is never
empty, so the event loop can spend up to the full quantum on tasks every
iteration regardless of how little time was just spent on IO, delaying
IO servicing (and so response completion) for a minority of requests.
This was observed as an elevated mean (but not median) round-trip
latency after upgrading from 4.1 to 4.2, which went away on rollback.

Modifications:

  • Add back a volatile ioRatio field and functional getIoRatio()/
    setIoRatio(int) on SingleThreadIoEventLoop, configurable via the new
    io.netty.eventLoop.ioRatio system property (default 100, which
    preserves the current fixed-quantum behaviour unchanged).
  • When ioRatio < 100, size each iteration's task budget as
    ioTime * (100 - ioRatio) / ioRatio, capped by
    maxTaskProcessingQuantumNs, matching the pre-4.2 NioEventLoop formula
    while keeping the existing quantum as a safety upper bound.
  • Add setter / getter to MultiThreadIoEventLoopGroup so it is supported globally

Result:

Users hitting the 4.2 scheduling regression can restore proportional
IO/task balancing with a single setIoRatio(50) call (or the new system
property), with no change in behaviour for anyone who doesn't opt in.

…ventLoop

Motivation:

The unification done in #13991/#14557 replaced the per-transport ioRatio
scheduling with a fixed maxTaskProcessingQuantumMs cap on task processing
before returning to IO. Under sustained load the task queue is never
empty, so the event loop can spend up to the full quantum on tasks every
iteration regardless of how little time was just spent on IO, delaying
IO servicing (and so response completion) for a minority of requests.
This was observed as an elevated mean (but not median) round-trip
latency after upgrading from 4.1 to 4.2, which went away on rollback.

Modifications:

- Add back a volatile ioRatio field and functional getIoRatio()/
  setIoRatio(int) on SingleThreadIoEventLoop, configurable via the new
  io.netty.eventLoop.ioRatio system property (default 100, which
  preserves the current fixed-quantum behaviour unchanged).
- When ioRatio < 100, size each iteration's task budget as
  ioTime * (100 - ioRatio) / ioRatio, capped by
  maxTaskProcessingQuantumNs, matching the pre-4.2 NioEventLoop formula
  while keeping the existing quantum as a safety upper bound.
- Add setter / getter to MultiThreadIoEventLoopGroup so it is supported globally

Result:

Users hitting the 4.2 scheduling regression can restore proportional
IO/task balancing with a single setIoRatio(50) call (or the new system
property), with no change in behaviour for anyone who doesn't opt in.
@normanmaurer normanmaurer added this to the 4.2.19.Final milestone Sep 15, 2026
@normanmaurer normanmaurer added the needs-cherry-pick-5.0 This PR should be cherry-picked to 5.0 once merged. label Sep 15, 2026

@franz1981 franz1981 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.

ObjectUtil.checkInRange is inclusive, so setIoRatio(0) is accepted and line 212 then does ioTime * 100 / 0 -> ArithmeticException out of run(), killing the loop and every channel on it. 4.1 rejected <= 0.

-        this.ioRatio = ObjectUtil.checkInRange(ioRatio, 0, 100, "ioRatio");
+        this.ioRatio = ObjectUtil.checkInRange(ioRatio, 1, 100, "ioRatio");

That's the red SingleThreadIoEventLoopTest.testSetIoRatio() on CI - the test is right.

Same issue on DEFAULT_IO_RATIO, which isn't validated at all: -Dio.netty.eventLoop.ioRatio=0 kills every loop in the JVM; >100 or negative yields a negative quantum, so runAllTasks falls into the deadline = 0 branch and silently caps at 64 tasks per iteration.

@normanmaurer

Copy link
Copy Markdown
Member Author

ObjectUtil.checkInRange is inclusive, so setIoRatio(0) is accepted and line 212 then does ioTime * 100 / 0 -> ArithmeticException out of run(), killing the loop and every channel on it. 4.1 rejected <= 0.

-        this.ioRatio = ObjectUtil.checkInRange(ioRatio, 0, 100, "ioRatio");
+        this.ioRatio = ObjectUtil.checkInRange(ioRatio, 1, 100, "ioRatio");

That's the red SingleThreadIoEventLoopTest.testSetIoRatio() on CI - the test is right.

Same issue on DEFAULT_IO_RATIO, which isn't validated at all: -Dio.netty.eventLoop.ioRatio=0 kills every loop in the JVM; >100 or negative yields a negative quantum, so runAllTasks falls into the deadline = 0 branch and silently caps at 64 tasks per iteration.

doh! you are right... fixed both. PTAL again.

@franz1981 franz1981 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.

Default 100 means the fix is off unless you already know the bug exists.
The symptom is mean-only with the median unmoved, so nobody goes looking for an event loop knob - the reported path was upgrade, mean RTT up, roll back to 4.1.

What 100 preserves also isn't a design we picked: before #14557 the budget was runAllTasks(4096), a task count in a nanos parameter, which always expired at the first 64-task check. Fixing the unit to 1s removed that implicit ceiling too. So 100 pins compatibility to an accident rather than to 4.1.

Why not default to 50?

@normanmaurer

Copy link
Copy Markdown
Member Author

I am not strong on it ... I just wanted to restore the ability to set a IO ratio again . What the default should be is another question

@franz1981

Copy link
Copy Markdown
Contributor

@normanmaurer

Remaining issues after 744417d72c:

1. ioTime includes the blocking select/epoll_wait. It brackets all of runIo(), whereas 4.1 started the timer after the select returned and timed only processSelectedKeys() (NioEventLoop.java:559-566 on 4.1). So the budget isn't the quantity the PR says it restores. IoHandlerContext.reportActiveIoTime already measures the right thing - NioIoHandler even comments "We start the timer after the blocking select() call has returned."

2. Thread.sleep(1000) lands inside that measurement. NioIoHandler.handleLoopException sleeps a second and is called at :474 and :493, both inside run() (starts at :419). One selector exception pins the task budget at the cap.

3. testDefaultIoRatio asserts a property, not a default. assertEquals(100, loop.getIoRatio()) reads DEFAULT_IO_RATIO, which is sourced from io.netty.eventLoop.ioRatio. The test fails under -Dio.netty.eventLoop.ioRatio=50 - exactly what someone validating this feature would run.

4. MultiThreadIoEventLoopGroup.setIoRatio applies partially, then throws. The UnsupportedOperationException fires mid-iteration, so children visited earlier keep the new ratio and the caller can't tell how far it got. Validating types and range in a first pass, applying in a second, avoids it.

5. Two validation policies on one field. The property clamps silently (0 -> 1, the most task-favouring setting there is); setIoRatio throws for the same input. -Dio.netty.eventLoop.ioRatio=0 as an attempt to disable the feature gives you the opposite, with nothing in the log.

6. Deprecated no-op setIoRatio becomes live on upgrade. Applications still carrying their 4.1 call site get proportional scheduling without opting in, which is at odds with "no change in behaviour for anyone who doesn't opt in". In-tree: BurstCostExecutorsBenchmark:209,216,223 call setIoRatio(1), now a 99x task budget. Also getIoRatio() was documented "Returns 0" / "Always return 0" and now returns 100.

I haven't run revapi on JDK 11, so no claim either way on whether the removed public methods trip the API check.

@normanmaurer

Copy link
Copy Markdown
Member Author

@franz1981 I think 1,3 and 4 are valid... just pushed a fix for these. PTAL again

@franz1981 franz1981 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.

Measurement looks right now, thanks. Issues in the new version:

1. shouldReportActiveIoTime() should compare against 100, not DEFAULT_IO_RATIO. When the ratio comes from the property, ioRatio == DEFAULT_IO_RATIO, so that clause is false and the feature rests entirely on isSuspensionSupported(). That's true for nio/epoll/kqueue, but io_uring is !copy.singleIssuer() and singleIssuer defaults to true, and LocalIoHandler inherits the interface default false. On those, -Dio.netty.eventLoop.ioRatio=50 leaves activeIoTimeNanos == -1, so run() takes the full-quantum branch and the property silently does nothing - while setIoRatio(50) works.

2. activeIoTimeNanos is sticky. Nothing resets it before runIo(), and handlers can return without reporting: NioIoHandler:470-475 catches IOException, rebuilds the selector, sleeps 1s in handleLoopException and return 0s; and the report sits after processSelectedKeys() with no finally. Either way the next budget is computed from an older iteration. activeIoTimeNanos = -1 before runIo() fixes it.

3. LocalIoHandler reports 0 unconditionally, so with ioRatio < 100 its budget is permanently 0 - 64 tasks per iteration forever. Probably intended (matches 4.1's runAllTasks(0)), but the javadoc only describes a budget "proportional to the time just spent on IO" and never mentions the floor.

4. The override changes reportActiveIoTime semantics from accumulate (accumulatedActiveTimeNanos += nanos, "@PARAM nanos The active time in nanoseconds to add") to assignment. Latent - every in-tree handler reports once per run() - but the two overloads now disagree.

5. testDefaultIoRatio is tautological: it compares DEFAULT_IO_RATIO against a field initialised from DEFAULT_IO_RATIO, so it passes unconditionally and no longer checks that the default is 100.

Still open from before: the property clamps 0 -> 1 silently while setIoRatio(0) throws, and the deprecated no-op setIoRatio on the Nio/Epoll/KQueue loops and groups goes live on upgrade (BurstCostExecutorsBenchmark:209,216,223 is the in-tree case).

Minor: the commit message says "setter / getter" for MultiThreadIoEventLoopGroup, but only the setter is there.

@normanmaurer

Copy link
Copy Markdown
Member Author

@franz1981 thanks.... I fixed everything that is not by design. PTAL again

@franz1981

franz1981 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Both fixes look right. One thing the reset introduced, though: when no measurement arrives, the fallback is now the maximum budget rather than a stale one.

activeIoTimeNanos = -1;
runIo();
if (ioRatio == 100 || activeIoTimeNanos == -1) {
    taskQuantumNs = maxTaskProcessingQuantumNs;   // full quantum
}

Both handlers have paths that return from run(context) without reporting:

Before the reset those iterations reused a stale (usually small) value; now they get the full maxTaskProcessingQuantumNs - the exact behaviour ioRatio is there to prevent. For a latency knob the safe fallback when the measurement is missing is the minimum budget - 0, i.e. the 64-task floor, which is what 4.1 did in its no-IO branch (runAllTasks(0) // This will run the minimum number of tasks).

Same applies to any third-party IoHandler that never calls reportActiveIoTime: every iteration takes the full quantum, so ioRatio is silently inert rather than conservative.

Suggestion: keep -1 meaning "unmeasured", but make it choose the floor:

-            if (ioRatio == 100 || activeIoTimeNanos == -1) {
+            if (ioRatio == 100) {
                 taskQuantumNs = maxTaskProcessingQuantumNs;
+            } else if (activeIoTimeNanos == -1) {
+                taskQuantumNs = 0;
             } else {

@normanmaurer

Copy link
Copy Markdown
Member Author

Both fixes look right. One thing the reset introduced, though: when no measurement arrives, the fallback is now the maximum budget rather than a stale one.

activeIoTimeNanos = -1;
runIo();
if (ioRatio == 100 || activeIoTimeNanos == -1) {
    taskQuantumNs = maxTaskProcessingQuantumNs;   // full quantum
}

Both handlers have paths that return from run(context) without reporting:

Before the reset those iterations reused a stale (usually small) value; now they get the full maxTaskProcessingQuantumNs - the exact behaviour ioRatio is there to prevent. For a latency knob the safe fallback when the measurement is missing is the minimum budget - 0, i.e. the 64-task floor, which is what 4.1 did in its no-IO branch (runAllTasks(0) // This will run the minimum number of tasks).

Same applies to any third-party IoHandler that never calls reportActiveIoTime: every iteration takes the full quantum, so ioRatio is silently inert rather than conservative.

Suggestion: keep -1 meaning "unmeasured", but make it choose the floor:

-            if (ioRatio == 100 || activeIoTimeNanos == -1) {
+            if (ioRatio == 100) {
                 taskQuantumNs = maxTaskProcessingQuantumNs;
+            } else if (activeIoTimeNanos == -1) {
+                taskQuantumNs = 0;
             } else {

I think it is fine as it is... these Exceptions should never happen and the guards are only there to guard against the thread dying if something unexpected happens.

@franz1981 franz1981 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.

LGTM thanks Norman!

@franz1981

Copy link
Copy Markdown
Contributor

@dreamlike-ocean any concerns? you raised the point for the uring case for ioRatio IIRC?

@dreamlike-ocean

Copy link
Copy Markdown
Member

@dreamlike-ocean any concerns? you raised the point for the uring case for ioRatio IIRC?

My earlier concern was that we couldn't distinguish time spent in blocking syscalls from time spent actively processing I/O. Now that we have reportActiveIoTime, we can implement ioRatio based on active I/O time.

@chrisvest chrisvest left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

One comment

@normanmaurer

Copy link
Copy Markdown
Member Author

@dreamlike-ocean PTAL as well

// Give tasks a budget proportional to the time just spent on IO, still bounded by the
// configured maximum so a burst of IO activity cannot starve the task queue indefinitely.
long quantum = Math.min(maxTaskProcessingQuantumNs, activeIoTimeNanos * (100 - ioRatio) / ioRatio);
if (quantum == 0) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

1.Tasks remain queued(the task budget was exhausted), so epoll polls without blocking.
2.No ready events → activeIoTime = 0.
3.The full-quantum fallback can delay newly arriving I/O.
This may be an edge case, but when it happens, netty will fall back to the same behavior this PR is trying to fix.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Imho this is fine as it would be an edge case and only be true for a Limited time

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@dreamlike-ocean or any concerns with just ignoring this case ?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

OK, no further concerns from me.

@testlens-app

testlens-app Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

✅ All tests passed ✅

⚠️ TestLens detected flakiness ⚠️

Test Summary

Build PR / linux-x86_64-java17 build > Netty/Handler/Ssl/Ocsp

Test Runs Flakiness
OcspServerCertificateValidatorTest ❌ ✅ 🚫 🚫 3% 🟡

Build PR / linux-x86_64-java26 build > Netty/Handler/Ssl/Ocsp

Test Runs Flakiness
OcspServerCertificateValidatorTest ❌ ❌ ❌ ✅ 3% 🟡

Build PR / macos-aarch64-java11-boringssl build > Netty/Transport/Native/KQueue

Test Runs Flakiness
KQueueDatagramUnicastIPv6MappedTest > testSimpleSendWithoutBind(TestInfo) ❌ ✅ 🚫 🚫 2% 🟡

🏷️ Commit: 375e9bf
▶️ Tests: 37742 executed
⚪️ Checks: 27/27 completed

Test Failures

OcspServerCertificateValidatorTest (Netty/Handler/Ssl/Ocsp in Build PR / linux-x86_64-java17 build | Attempt 1/4)
java.lang.IllegalStateException: Possible memory leak detected for resource scope 'OcspServerCertificateValidatorTest'. Please use paranoid leak detection to get more information, or set -Dio.netty.util.LeakPresenceDetector.trackCreationStack=true
	at io.netty.util.LeakPresenceDetector$ResourceScope.check(LeakPresenceDetector.java:308)
	at io.netty.util.LeakPresenceDetector$ResourceScope.close(LeakPresenceDetector.java:328)
	at io.netty.util.test.LeakPresenceExtension.afterAll(LeakPresenceExtension.java:140)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
OcspServerCertificateValidatorTest (Netty/Handler/Ssl/Ocsp in Build PR / linux-x86_64-java26 build | Attempt 3/4)
java.lang.IllegalStateException: Possible memory leak detected for resource scope 'OcspServerCertificateValidatorTest'. Please use paranoid leak detection to get more information, or set -Dio.netty.util.LeakPresenceDetector.trackCreationStack=true
	at io.netty.util.LeakPresenceDetector$ResourceScope.check(LeakPresenceDetector.java:308)
	at io.netty.util.LeakPresenceDetector$ResourceScope.close(LeakPresenceDetector.java:328)
	at io.netty.util.test.LeakPresenceExtension.afterAll(LeakPresenceExtension.java:140)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1612)
OcspServerCertificateValidatorTest (Netty/Handler/Ssl/Ocsp in Build PR / linux-x86_64-java26 build | Attempt 2/4)
java.lang.IllegalStateException: Possible memory leak detected for resource scope 'OcspServerCertificateValidatorTest'. Please use paranoid leak detection to get more information, or set -Dio.netty.util.LeakPresenceDetector.trackCreationStack=true
	at io.netty.util.LeakPresenceDetector$ResourceScope.check(LeakPresenceDetector.java:308)
	at io.netty.util.LeakPresenceDetector$ResourceScope.close(LeakPresenceDetector.java:328)
	at io.netty.util.test.LeakPresenceExtension.afterAll(LeakPresenceExtension.java:140)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1612)
OcspServerCertificateValidatorTest (Netty/Handler/Ssl/Ocsp in Build PR / linux-x86_64-java26 build | Attempt 1/4)
java.lang.IllegalStateException: Possible memory leak detected for resource scope 'OcspServerCertificateValidatorTest'. Please use paranoid leak detection to get more information, or set -Dio.netty.util.LeakPresenceDetector.trackCreationStack=true
	at io.netty.util.LeakPresenceDetector$ResourceScope.check(LeakPresenceDetector.java:308)
	at io.netty.util.LeakPresenceDetector$ResourceScope.close(LeakPresenceDetector.java:328)
	at io.netty.util.test.LeakPresenceExtension.afterAll(LeakPresenceExtension.java:140)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1612)
KQueueDatagramUnicastIPv6MappedTest > testSimpleSendWithoutBind(TestInfo) (Netty/Transport/Native/KQueue in Build PR / macos-aarch64-java11-boringssl build | Attempt 1/4)
org.opentest4j.AssertionFailedError
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSend0(DatagramUnicastTest.java:360)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSend(DatagramUnicastTest.java:192)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSendWithoutBind(DatagramUnicastTest.java:185)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest$6.run(DatagramUnicastTest.java:178)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest$6.run(DatagramUnicastTest.java:175)
	at io.netty.testsuite.transport.AbstractComboTestsuiteTest.run(AbstractComboTestsuiteTest.java:52)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSendWithoutBind(DatagramUnicastTest.java:175)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)

Learn more about TestLens at testlens.app/docs.

@franz1981 franz1981 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.

LGTM so far!

*/
public void setIoRatio(int ioRatio) {
ObjectUtil.checkInRange(ioRatio, 1, 100, "ioRatio");
for (EventExecutor e: this) {

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.

Suggested change
for (EventExecutor e: this) {
for (EventExecutor e : this) {

} else {
// Give tasks a budget proportional to the time just spent on IO, still bounded by the
// configured maximum so a burst of IO activity cannot starve the task queue indefinitely.
long quantum = Math.min(maxTaskProcessingQuantumNs, activeIoTimeNanos * (100 - ioRatio) / ioRatio);

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.

what's special about 100 here? From this code it doesn't look like a percentage

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@normanmaurer
normanmaurer requested a review from yawkat September 17, 2026 14:34

@yawkat yawkat 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.

i think it'll work fine but the significance of 100 mystifies me. it just seems arbitrary

@normanmaurer
normanmaurer merged commit 22e4967 into 4.2 Sep 22, 2026
70 of 75 checks passed
@normanmaurer
normanmaurer deleted the io_ratio branch September 22, 2026 22:34
@netty-project-bot

Copy link
Copy Markdown
Contributor

Could not create auto-port PR.
Got conflicts when cherry-picking onto 5.0.

@normanmaurer

Copy link
Copy Markdown
Member Author

Port for 5.0: #17603

normanmaurer added a commit that referenced this pull request Sep 25, 2026
…eadIoEventLoop (#17481) (#17603)

Motivation:

The unification done in #13991/#14557 replaced the per-transport ioRatio
scheduling with a fixed maxTaskProcessingQuantumMs cap on task
processing
before returning to IO. Under sustained load the task queue is never
empty, so the event loop can spend up to the full quantum on tasks every
iteration regardless of how little time was just spent on IO, delaying
IO servicing (and so response completion) for a minority of requests.
This was observed as an elevated mean (but not median) round-trip
latency after upgrading from 4.1 to 4.2, which went away on rollback.

Modifications:

- Add back a volatile ioRatio field and functional getIoRatio()/
  setIoRatio(int) on SingleThreadIoEventLoop, configurable via the new
  io.netty.eventLoop.ioRatio system property (default 100, which
  preserves the current fixed-quantum behaviour unchanged).
- When ioRatio < 100, size each iteration's task budget as
  ioTime * (100 - ioRatio) / ioRatio, capped by
  maxTaskProcessingQuantumNs, matching the pre-4.2 NioEventLoop formula
  while keeping the existing quantum as a safety upper bound.
- Add setter / getter to MultiThreadIoEventLoopGroup so it is supported
globally

Result:

Users hitting the 4.2 scheduling regression can restore proportional
IO/task balancing with a single setIoRatio(50) call (or the new system
property), with no change in behaviour for anyone who doesn't opt in.
@normanmaurer normanmaurer removed the needs-cherry-pick-5.0 This PR should be cherry-picked to 5.0 once merged. label Oct 16, 2026
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.

7 participants