Skip to content

Fix canceled session pool waiters - #797

Open
lebmax wants to merge 33 commits into
ydb-platform:masterfrom
lebmax:fix/794-issue
Open

lebmax wants to merge 33 commits into
ydb-platform:masterfrom
lebmax:fix/794-issue

Conversation

@lebmax

@lebmax lebmax commented Nov 24, 2026 •

Copy link
Copy Markdown

Changes

  • Propagate completion of the caller-facing acquire future to the corresponding internal acquire in both the Table and Query session pools.
  • Remove completed waiters promptly and keep the waiting count consistent during cancellation, requeueing, and pool shutdown.
  • Preserve the reservation for a session creation that is already in progress. If creation succeeds after the caller cancels, offer the session to another waiter or retain it as idle.
  • Update WaitingQueueTest.canceledWaitingTest to assert the intentional behavior change: a cancelled waiter now frees its waiting slot immediately, rather than remaining counted until the next session release.
  • Add regression tests for timeouts, cancellation, queue admission after cancellation at the waiting limit, requeueing, shutdown, and acquire metrics.

Regression tests

  • Verify that cancellation and timeout free a slot in a full Table or Query pool before any session is returned.
  • Verify that concurrent cancellation and replacement admit new waiters on the first attempt and preserve FIFO handoff.
  • Verify that cancellation during a resize frees the slot even when the waiter has been temporarily removed from the queue.
  • Verify that races between cancellation, session return, and pool shutdown keep the waiting count consistent.

Performance note

Removing a cancelled waiter from ConcurrentLinkedDeque is linear in the queue length.

Fixes #794

@lebmax lebmax changed the title Fix/794 issue Fix canceled session pool waiters and add acquire metrics Nov 24, 2026
@lebmax

lebmax commented Nov 25, 2026

Copy link
Copy Markdown
Author

@snaury @shadchin @jamel
Hi, everyone!
I’d appreciate a review and any feedback on this approach.

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

LGTM, but I'm not part of YDB at the moment.

// close() can run after the count is reserved but before this offer.
// In that case clear() cannot see the new entry, so clean it here.
if (stopped && waitingAcquires.remove(acquire)) {
waitingAcqueireCount.decrementAndGet();

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.

Maybe fix a typo? waitingAcqueireCount -> waitingAcquireAcount.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks for catching this! Fixed.

}

waitingAcquires.offer(acquire); // ConcurrentLinkedQueue always return true
acquire.whenComplete((ignored, th) -> removeWaitingAcquire(acquire));

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.

To be honest I'm a little worried that this call happens in all cases, both when the call is cancelled and when successful. In the case of success, since the future is removed immediately before completion, this operation is always O(n) on the number of awaiters, with potentially very expensive worst-case walk over the concurrent list, since the future is guaranteed to not be in the list. The total complexity grows quadratically, and completing 1000 awaiters will take on the order of 1 million operations. Historically things like that were enough to cause clients problems in production, even with modest spikes in concurrent requests.

Ideally this should be amortized somehow. At the minimum awaiters which are already dequeued shouldn't incur this cost at all when completing. Would be best if this cost is never quadratic, because a spike in concurrent requests with many such requests cancelled at roughly the same time is also very much possible to cause problems. I'm not sure how to solve the latter with standard java ConcurrentLinkedDeque though.

@lebmax lebmax Nov 29, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks for calling this out. You were right: ConcurrentLinkedDeque.remove could walk the entire waiter queue even after a waiter had been dequeued. I replaced it with WaitingAcquires, which removes a waiter through its node reference, so completing a dequeued waiter no longer searches the queue.

I compared the first fix with the current version against a local YDB container. Each run used 1,000 waiters, a pool of 100 real YDB sessions, and 8 callback workers. These are median times in milliseconds:

JDK Workload First fix Current
8 Hand off 1,000 sessions 23.4 6.6
8 Cancel 1,000 waiters 16.5 11.8
21 Hand off 1,000 sessions 27.1 6.5
21 Cancel 1,000 waiters 24.4 15.7

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.

Looks good to me (I have minor nitpicks, but it's not really about the new code, so I'm not going to voice them).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks for the review and the helpful feedback!

@snaury

snaury commented Dec 1, 2026

Copy link
Copy Markdown
Member

@alex268 @KirillKurdyukov a gentle reminder to look at this PR, please don't forget to communicate with your external contributors! Could you please assign a current YDB employee as a reviewer and maybe leave a comment on how long the review is expected to take, and what needs to be done before that?

@KirillKurdyukov

Copy link
Copy Markdown
Collaborator

Thanks for looking into the leak of cancelled waiters — it's a real issue. But I'm against making WaitingQueue synchronized: it's lock-free by design, and with this change every release() goes through tryToCompleteWaiting() → synchronized pollFirst(), even when nobody is waiting. So every session return in both Table and Query pools contends on a single pool-wide monitor (plus carrier pinning for virtual threads on JDK 21–23). That's a performance regression risk for all users, and there are no benchmarks showing otherwise.

The leak can be fixed without a lock, e.g. purge completed futures from the ConcurrentLinkedDeque lazily in tryToCreateNewWaiting before rejecting with LIMIT_EXCEEDED, or remove(acquire) on completion and decrement the counter only if remove returned true. Also the cancel propagation in SessionPool.pollNext is independent and could go as a separate PR.

@snaury

snaury commented Dec 3, 2026

Copy link
Copy Markdown
Member

I don't have a stake here, but I'd argue that in my experience mutex guarded data structures are usually enough for millions of operations per second and only pose a problem when you're close to that throughput. Since this data structure is used for a session pool, and sessions are used for making YDB calls, which always go over the network in one way or the other (with each transaction on the order of milliseconds, rarely less even in single-dc clusters), current code looks complicated and could be simplified to make more decisions under a mutex instead of spinning in complicated compare-and-swap loops.

Also correct me if I'm wrong, but carrier pinning is mostly harmful when performing i/o (or generally parking) within synchronized methods. When entering a synchronized method it might block the carrier thread temporarily (like any other thread), but the actual harm depends on the use case.

Benchmarks are a good idea. Without them discussions and decisions tend to become theoretical, and implementations are ripe for premature optimizations, which could unintentionally bring worse scalability and performance.

lebmax and others added 9 commits December 4, 2026 15:15
Set latency bucket boundaries for duration histograms
Release each waiting slot once, including when resize has detached the
waiter. Skip removal on normal handoff and cover both concurrent cases.
Propagate cancellation and timeouts in the Table and Query pools. Use an ordered concurrent map for key-based waiter removal and test immediate slot reuse during parallel cancellation and resize.
@lebmax

lebmax commented Dec 4, 2026 •

Copy link
Copy Markdown
Author

Thanks for the feedback on the release path and the benchmark suggestions.

The revised queue uses ConcurrentSkipListMap. Session return avoids a shared queue monitor. Cancellation removes the waiter by key, and normal handoff releases the slot before completing the future, so the callback can skip the lookup. The Table and Query pools propagate cancellation and timeout to the queued acquire.

The regression tests cover slot reuse while a session is still held, cancellation while resize has detached the waiter, and parallel cancellation and replacement without retries.

JMH with 16 workers

Workload Measurement Java 8 upstream Java 8 skip list Java 21 upstream Java 21 skip list
Empty queue, platform workers Acquire/return p99 (µs) 14.00 14.50 38.85 33.86
Empty queue, platform workers Throughput (million cycles/s) 3.89 3.10 2.29 2.26
Empty queue, virtual workers Acquire/return p99 (µs) — — 39.68 30.88
Empty queue, virtual workers Throughput (million cycles/s) — — 2.24 2.32
Cancel and replace, 4,000 waiters, platform workers Replacement p99 (µs) — 13.7 — 12.2
Cancel and replace, 4,000 waiters, platform workers Throughput (million replacements/s) — 2.33 — 2.14
Cancel and replace, 4,000 waiters, platform workers Worker allocation (bytes/replacement) — 1,276 — 1,681
Cancel and replace, 4,000 waiters, platform workers Capacity refusals Retry budget exhausted 0 Retry budget exhausted 0

In a short check at the same queue depth, upstream exhausted the 1,024-attempt retry budget on both JDKs while the only resource was held. The virtual-worker runs used Java 21.

Point reads against local YDB

Measurement JDK Upstream Skip list
Request p99 without a wait queue (ms) Java 8 4.04 4.56
Request p99 without a wait queue (ms) Java 21 5.57 5.07

Upstream rejected the replacement attempts with CLIENT_RESOURCE_EXHAUSTED. JMH sources and reproduction instructions

Could you take another look at the queue and the regression tests?

@lebmax lebmax changed the title Fix canceled session pool waiters and add acquire metrics Fix canceled session pool waiters Dec 6, 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.

Cancel queued session acquisition when SessionPool.acquire() times out or is cancelled

5 participants