Skip to content

Backoff for KeeperRequestDispatcher busy-waiting - #109255

Merged
al13n321 merged 1 commit into
masterfrom
sleepoff
Jul 6, 2026
Merged

al13n321 merged 1 commit into
masterfrom
sleepoff

Conversation

@al13n321

@al13n321 al13n321 commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Reduced Keeper server idle CPU usage.


Closes #107944

Increase sleep duration from 100us to 10ms after 5ms of inactivity.

Version info

  • Merged into: 26.7.1.566 (included in 26.7 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [040f80b]

Summary: ✅


AI Review

Summary

This PR adds exponential backoff to KeeperRequestDispatcher busy-wait loops so Keeper burns less CPU while idle. The current implementation also applies that backoff while the dispatcher is flow-controlled by in-flight batches / response-queue pressure / stream readiness, so it can leave queued work waiting for multi-millisecond sleeps and regress the hot request path it is supposed to protect. The PR also lacks focused performance evidence for the Performance Improvement claim.

Findings

❌ Blockers

  • src/Coordination/KeeperRequestDispatcher.cpp:655 The new BusyWaitBackoff is reused in the branch that handles num_batches_in_flight >= ..., response_bytes_in_all_queues > ..., and !stream->is_ready(). Those states are not idle; they mean requests are already queued and the dispatcher is waiting for the next pipeline slot. After ~5 ms of continuous backpressure the sleep grows past dispatch_busy_wait_sleep_us, and after ~28 ms it reaches the full 10 ms default, so a commit can free capacity while the dispatcher is still asleep. That underfills the Raft pipeline and can cut Keeper throughput / increase latency under sustained load.
    Suggested fix: keep exponential backoff only on the truly idle !tryPopRequest path (and, if desired, the empty responseThread path). For the throttling branch, keep a fixed short poll interval or a separate much smaller cap that preserves prompt refill of freed slots.
Tests
  • ⚠️ This PR is marked Performance Improvement, but there is no focused before/after evidence showing that the new backoff improves idle CPU without regressing Keeper throughput or request latency under sustained load/backpressure. A small keeper-bench or dedicated dispatcher benchmark covering both idle and saturated conditions would close this gate.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
  1. Split the idle backoff from the active throttling path so queued work is refilled promptly under load.
  2. Add focused performance evidence showing the new defaults help the idle case without harming saturated Keeper throughput / latency.

@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.70% 92.60% -0.10%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 43/44 (97.73%) · Uncovered code

Full report · Diff report

/// request every long_sleep/2 the sleeping will add at most short_sleep to request latency.
/// And if we go idle for >~long_sleep we'll slow down and waste less cpu, but the next request
/// will get up to long_sleep of added latency.
struct BusyWaitBackoff

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.

We already have this primitive - it is called DynamicDelay, can we reuse it here?

BTW: Will it be better to implement something like this https://github.com/ytsaurus/ytsaurus/blob/main/util/system/spin_wait.cpp?

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.

This seems like a bit of an overkill for a case where we have 2 threads just waiting for some work where we really don't need to spin constantly.
I guess this is useful for some kind of spinlock.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

DynamicDelay

I think the part where BusyWaitBackoff's delay doesn't increase for the first few ms is important.

spin_wait.cpp

Possibly some spinning would be marginally better, but I don't really know how to think about those things properly, so I'd err on the side of less code. My speculation for what the considerations are:

  • If we expect to go to sleep for less time than the OS task switch overhead, it makes sense to spin as it would waste less cpu than a yield. This is usually the case for a spinlock just protecting some data structure; e.g. if the other thread does lock(); vector.push_back(42); unlock();, the push_back is presumably much faster than yield overhead.
  • Spinning is less latency, obviously.
  • Yield is presumably only useful when there are other tasks for the OS to run (load average > core count?). (In keeper server we're presumably bottlenecked on ~2 cpu cores: commit thread and preprocess thread, with lots of cores sitting idle, so I'm guessing there's not much point to yield instead of spinning.)
  • A sleep of 100us is barely long enough (according to claude) for the cpu core to go into a low-power C-state; while(true) sleep(100us); would use maaaybe 2x less power than while(true);, 1ms maybe 20x (rough unchecked numbers from claude, don't trust).
  • Jitter is useful if many threads are waiting for the same contended spinlock, so it's better for them to wake up at different times (hoping that the second thread will wake up after the first thread already locked+worked+unlocked the spinlock).

Of all that, only maybe a little spinning could be relevant here, but even then the probability of a new request arriving during the spin vs during the 100us sleep seems small enough to not be worth adding code.

@antonio2368 antonio2368 self-assigned this Jul 3, 2026
@al13n321
al13n321 added this pull request to the merge queue Jul 6, 2026
Merged via the queue into master with commit afd09cf Jul 6, 2026
174 checks passed
@al13n321
al13n321 deleted the sleepoff branch July 6, 2026 19:51
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 6, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Backoff for KeeperRequestDispatcher busy-waiting
mosya415 pushed a commit to mosya415/ClickHouse that referenced this pull request Nov 22, 2026
The two queries of the test (2-15 ms) wait on the server's embedded Keeper.
Its request and response threads poll their queues (BusyWaitBackoff):
100 us sleeps while busy, backing off to dispatch_busy_wait_long_sleep_us
(10 ms) after ~5-8 ms of idleness (ClickHouse#109255). perf.py alternates the server
order (L,R / R,L), so each server's runs alternate between a polling Keeper
(it ran right before: #0 ~5 ms) and a backed-off one (it waited through the
other server's query: #0 ~18 ms). The median lands between the two modes
(in-run CV 47-77% on master CI). perf.py's stop-condition checks before
runs 8, 10, 14 and 20 all precede reference-first runs, which is why on
master CI (two consecutive master builds) the candidate measured 8-20%
faster than the reference.

Disable #0 and ClickHouse#1 (they keep their numbers and history) and append the same
scans run 128 (ClickHouse#2) and 512 (ClickHouse#3) times in one query with loop(view(...)).
LoopSource plans the inner query and builds its pipeline on every pass, so
every pass goes to Keeper again (12800 and 512 ZooKeeperMultiRead per
query); passes 2..N find the Keeper polling, so the wake-up is paid at most
once per query (up to ~20 ms of a 0.5-1 s query).

Validated on CI's amd layout (8 CPUs, one hyperthread per physical core,
max_threads 8, an embedded Keeper per server, master a2126db on both
sides) with CI's stat_threshold method, 10 accepted invocations:
- ClickHouse#2: stat_threshold 0.080-0.119, median |diff| 0.037, in-run CV 6.3%.
  In one invocation |diff| was 0.105, above the 0.10 bar I set for it but
  below its stat_threshold 0.114, so the report would not show it.
- ClickHouse#3: stat_threshold 0.009-0.084, max |diff| 0.066, in-run CV 2.8%.
- Old #0 in the same session: stat_threshold 0.568-0.724, CV 56%; old ClickHouse#1
  0.712-1.127, CV 82%.
- Ratio of the second to the first server position: ClickHouse#2 1.025, ClickHouse#3 1.021,
  old #0 4.07. With dispatch_busy_wait_long_sleep_us=100 the old #0 ratio
  drops from 3.0-4.6 to 0.85-0.96.
- Before ClickHouse#122223 (f0e4854 vs 63c4b93) ClickHouse#2 is 8.2x and ClickHouse#3 19.2x slower
  (ClickHouse#3: 51200 vs 512 multi-reads), so both still measure that change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

KeeperDispatcher (use_new_dispatcher=true) causes constant ~20-25% CPU on idle single-node

4 participants