fix: expire inactive HTTP resource pool entries #20403
cc: @maytasm @jtuglu1
CodeQL / Deprecated method or constructor invocation
Invoking [CacheBuilder.expireAfterAccess](1) should be avoided because it has been deprecated.
FYI, #20273 currently modifies the same two files as this PR (ResourcePool.java and ResourcePoolTest.java), and a Git merge simulation confirms textual conflicts in both.
I do not think #20273 makes this fix redundant. Its adaptive pool purges expired idle connections only during a subsequent take(key). If a destination disappears and is never contacted again, its entry remains in the non-expiring LoadingCache, along with its eagerly initialized connections. This PR addresses the separate per-destination lifecycle by evicting the whole key and closing its holder.
Suggestion: coordinate or stack the changes. If #20273 lands first, rebase this PR and port the expiration/removal-listener behavior onto LoadingCache<K, PooledResources<V>>, ensuring that an evicted PooledResources is closed. It would also be useful to add a direct endpoint-churn test: eagerly initialize endpoint A, let it expire, access endpoint B to trigger cache maintenance, and assert that A's resources are closed and its entry is removed. That test would distinguish whole-destination eviction from #20273's same-key connection shrinking.
The expireAfterAccess overload flagged by CodeQL should also be updated while resolving this.
[P1] Do not expire holders while resources are borrowed
Finding: The cache entry's access time is updated when take() starts, not when a resource is returned. If an HTTP request keeps all resources for longer than unusedConnectionTimeout (the documented defaults are 15 minutes for readTimeout and 4 minutes for unusedConnectionTimeout), the next access expires the holder even though it still has lent resources. close() leaves those in-use resources open until their containers return, while the load immediately creates a fresh holder with maxPerKey new resources, so the configured per-key connection limit is violated and repeated long-lived requests can accumulate extra channels and SSL buffers.
Suggestion: Tie key eviction to holder idleness, such as deferring eviction while resources are lent and closing the holder only after the last borrowed container returns; add a test that holds a resource past the timeout before taking another resource for the same key.
[P2] Ensure expired holders are closed during pool shutdown
Finding: Adding expiration makes an entry eligible to be hidden from Cache.asMap().entrySet() before Guava removes it. ResourcePool.close() iterates that view but never calls cleanUp(), so an expired holder can be skipped and its removal notification never delivered; its idle resources then remain open when the HTTP client is stopped. This is a lifecycle leak on the new expiration path.
Suggestion: Run cache maintenance and deliver pending removal notifications before or as part of close(), or explicitly invalidate and close every holder; add a test that lets a key expire and then closes the pool without another cache access.
🟡 Changes recommended
Fix the cache lifecycle before merging: the new TTL can evict holders that still own borrowed channels and can leave already-expired holders unclosed during HTTP client shutdown. Both issues affect the resource-lifecycle contract of this pool and can undermine the memory-leak fix.
Reviewed 2 of 2 changed files; findings in 1 file.
| Severity | Findings |
| --- | ---: |
| P0 | 0 |
| P1 | 1 |
| P2 | 1 |
| P3 | 0 |
| Total | 2 |
<!-- mergelens:review -->
---
This is an automated review by Codex GPT-5.6-Luna(max)
After addressing the findings or replying to the comments, you can request another review from me to trigger a new automated review.
I think you've run into kinda the same problem as what https://github.com/apache/druid/pull/20273 is addressing - I think that will help
@kgyrtkirk The adaptive pool only closes expired or broken idle connections when a later take(key) for the same destination walks past them (ResourcePool.java, takeIdleResource). That lets a destination you still query shrink back to the number of connections its traffic needs.
What it doesn't fix (destinations that go away): On master the outer cache still never expires anything. It's built with CacheBuilder.newBuilder().build(...) and has no expireAfterAccess, no removal listener and no invalidate API (ResourcePool.java:68). Once a destination stops being called, such as a finished task or a replaced Historical, nothing calls take() for it again. Its idle connections, with their SSL engines and buffers, stay on the heap until the process restarts.
@maswin
Can you:
1. Rebase. Both files conflict. The expiration and removal listener need to move onto LoadingCache<K, PooledResources<V>> and close each evicted PooledResources.
2. Don't evict a destination while its connections are lent out (P1 in the review). Access time is only updated in take(). With the defaults (unusedConnectionTimeout PT4M, readTimeout PT15M), a long query can get its destination evicted mid-flight. The next take() then builds a fresh pool for that destination, which breaks the per-destination numConnections limit. Checking getUsedCount() == 0 before closing, or refreshing access time on giveBack, would fix it.
3. Close expired entries on shutdown (P2). close() should run cleanUp() or invalidateAll() first, so expired entries aren't skipped.
4. Fix the CodeQL warning by using the Duration overload of expireAfterAccess.
Thanks!
oh - I see; "destinations that go away" was also not handled correctly.... at first glance it seemed similar - but I think these 2 were amplifying eachother...
1. Rebase. Both files conflict. The expiration and removal listener need to move onto LoadingCache<K, PooledResources> and close each evicted PooledResources.
Done.
2. Don't evict a destination while its connections are lent out (P1 in the review). Access time is only updated in take(). With the defaults (unusedConnectionTimeout PT4M, readTimeout PT15M), a long query can get its destination evicted mid-flight. The next take() then builds a fresh pool for that destination, which breaks the per-destination numConnections limit. Checking getUsedCount() == 0 before closing, or refreshing access time on giveBack, would fix it.
Guava can't veto an expiry. When a take() hits an expired entry, it loads a new holder before the removal listener runs. So a check on getUsedCount() == 0 in the listener comes too late.
Each pool entry now tracks when it was last taken or returned, and a sweep from take() closes one only if nothing is on loan and it has sat idle for 10× unusedConnectionTimeout. That way a long-running query never loses its pool, and take() just retries if it races with an eviction.
3. Close expired entries on shutdown (P2). close() should run cleanUp() or invalidateAll() first, so expired entries aren't skipped.
Since not using expireAfterAccess anymore, asMap would return all entries and closes every entry, including keys that are abandoned but not yet swept.
4. Fix the CodeQL warning by using the Duration overload of expireAfterAccess.
Not using expireAfterAccess anymore
Done. Removed expireAfterAccess usage, current method doesn't have this issue
Agreed, and this is fixed. I dropped the cache-level expireAfterAccess. Guava loads the replacement holder before the removal listener runs, so a getUsedCount() check there comes too late.
Eviction is now tied to idleness instead. Each holder records its last take or return, and the sweep closes a key only when getUsedCount() == 0 and it has been idle for 10× unusedConnectionTimeout. A holder with anything on loan is never evicted, however long the request runs. A later take() for that key gets the same holder, so the limit holds.
testKeyWithResourceOnLoanIsNeverEvicted holds a resource well past the timeout and checks that it isn't closed and is reused after it's returned.
[P1] Serialize eviction with concurrent borrows
Finding: The sweep reads getUsedCount() and then removes the holder in a separate operation. A take() can fetch the same holder after the zero-count read and enter get() before holder.close() runs; the sweep then detaches and closes a holder that has just lent a resource. The next take for the key creates another holder, so a long-lived request can keep the old resource while the new holder lends up to maxPerKey, violating the pool's per-key limit and the retry assumption in the comment.
Suggestion: Coordinate the idle check, removal, and close with holder acquisition, or mark/close the holder so a racing get() reliably returns null and take() retries; add a concurrent sweep-versus-take test for both implementations.
[P2] Do not abort reaping on a close failure
Finding: For RETAINING, ResourceHolderPerKey.close() calls factory.close directly and can throw. Because this call is inside one try around the entire sweep, a single close exception exits the loop after the holder has already been removed; remaining idle resources in that holder are never cleared and future sweeps cannot find it, while later abandoned keys wait for another sweep. This turns a close failure into a permanent cleanup leak.
Suggestion: Isolate failures per holder/resource and continue draining, while preserving a way to retry any resource whose cleanup failed; add a retaining-implementation test with a failing close during abandonment.
🟡 Changes recommended
Rechecked both changed files at the current head, starting from the two original lifecycle findings and the author's replies. Removing the cache-level TTL fixes expiration of borrowed holders, and the existing pool shutdown iteration now covers all live entries, so those original findings are resolved. The current sweep still has a race with concurrent borrowing that can detach a holder after the idle check and violate the per-key limit, and a close exception in the retaining implementation can strand an already-removed holder's remaining resources. Both issues should be addressed before merging.
Reviewed 2 of 2 changed files; this was a sufficient current-head follow-up review of the complete prepared PR scope.
Validation: Static inspection only; git diff --check passed for the two changed files. No builds or tests were run, per the requested review scope.
| Severity | Findings |
| --- | ---: |
| P0 | 0 |
| P1 | 1 |
| P2 | 1 |
| P3 | 0 |
| Total | 2 |
<!-- mergelens:review -->
---
This is an automated review by Codex GPT-5.6-Luna(max)
After addressing the findings or replying to the comments, you can request another review from me to trigger a new automated review.
Any key evicted and closed here will not be counted in stats. When drainStats is called, the pool no longer has the Entry for the evicted Key and hence we would miss the Evicted key's stats from the metrics.
Maybe add a ConcurrentMap (i.e. evictedStats) to hold stats of keys evicted since the last drainStats(), so their last closes are still reported.
I think this is more of a P2 since
I think this should be a simple fix and a nice to have.
You can add try/catch inside the loop on holder.close() and also Also make RETAINING's close() keep going past a failure
i.e.
public void close()
{
synchronized (this) {
closed = true;
for (ResourceHolder<V> holder : resourceHolderList) {
try {
factory.close(holder.getResource());
}
catch (Exception e) {
log.warn(e, "Failed to close resource at key[%s]", key);
}
}
resourceHolderList.clear();
this.notifyAll();
}
}
Please see comments
did you wrote this apdoc?
it just explains the function in unfollowable plain text
not sure if its worth to put so much effort into drainStats - it needs an extra config; also for a removed pool it might not really be relevant...
also it opens problem we might not want to handle...like there was pool to X which is abandoned and re-created in the same minute....
also if the stats are not drained by anything....there is a chance that those will never be drained and thus accumlate forever...
I think if we really want to correct this - another way to implement stats is to utilize a listener pattern; which by design will be resilient for an issue like this
when the removeal of these abandoned stuff happens - these should already be idle for quite some time....so
I feel like we could just let this slip....
why do we have to go to nano precision?
other config is millis either follow that or add Duration or something which could be handled better.
what are you doing here in a drainStats call?
put a method on the holder and ask that....
if(holder.isAbandoned() && ... )
is pretty much talks about what it checks - it can be as complicated as it wants inside that method
do we really need coimments like this?
let's put a comment inside the method body which is documenting the call sites of the function....this is a terrible idea....
unleashed AI?
the defaulting should happen in the config class ....instead of exposing it at all call sites
put this into the config....even if it remains a static final...
I think this could be described in a single line.....long docs are not read because people thing they are AI generated....(is it?)
The pool is purged from stale keys periodically.
if someone is interested; could dive into the code...if not...that's already plenty
note: probably Closeable and/or IOUtils.closeQuietly
is it really necessary to go down to comparision and adding time ? isn't there a higher level construct to limit the rate of something?
there is RateLimiter which could do exactly this
do you really want to catch throwable?
that needs justification....as it includes InterruptedException ; all subclasses of Error including VirtualMachineError which includes things like OOM and other stuff
looks like a pointless optimization - undo this
I think the holder should update this - not an external entity
I think it would be better to have different logics....you are adding a loop and whatnot...
for adaptive it would be safe to dispose it if you could allocate all tokens from the Semaphore without wait....its already a parallel programming construct so that'll be safe
I think it would be better to use a ReadWriteLock or some other construct - I think this part is not that hot that we should be juggling with primitives...
Follow-up assessment
I rechecked 2 changed files for this follow-up. I agree this is better classified as P2 given the narrow race window and bounded, temporary overage. The correctness issue remains: after getUsedCount() == 0, take() can pass the holder's acquisition check before reapAbandonedKeys() removes and closes it, so the old holder can still lend while a new holder is created for the same key. Please make holder invalidation atomic with acquisition, or otherwise make the racing acquisition reliably retry, and add a concurrency regression test; the current tests cover idle eviction and on-loan protection but not this interleaving.
<!-- mergelens:review -->
Follow-up assessment
I rechecked 2 changed files for this follow-up. Agreed that RETAINING cleanup should continue after a per-resource close failure, but catching and then clearing the deque would still lose the failed resource after the holder has already been removed from the cache. Please keep failed resources retryable (or otherwise record retryable cleanup) while continuing to process later resources and holders, and add a test that exercises abandonment with a failing close. This remains a P2 cleanup-leak risk.
<!-- mergelens:review -->
FrankChen021
maswin
We saw a spike in memory in one of the Druid cluster broker node resulting in high GC of the node.
Upon checking the heap dump there was high SSL connection related storage in memory -
Broker setting -
Expire per-key holders after the unused connection timeout and close evicted resources so endpoint churn cannot retain eager connection pools indefinitely.
Description
Expire inactive per-key
ResourcePoolentries using the configured unused connection timeout. A removal listener closes evicted holders so endpoint churn does not retain eager connection pools indefinitely.Guava performs expiration maintenance during subsequent cache activity.
<!-- Describe your patch: what did you change in code? How did you fix the problem? -->
<!-- If there are several relatively logically separate changes in this PR, create a mini-section for each of them. For example: -->
<!--
In each section, please describe design decisions made, including:
- Choice of algorithms
- Behavioral aspects. What configuration values are acceptable? How are corner cases and error conditions handled, such as when there are insufficient resources?
- Class organization and design (how the logic is split between classes, inheritance, composition, design patterns)
- Method organization and design (how the logic is split between methods, parameters and return types)
- Naming (class, method, API, configuration, HTTP endpoint, names of emitted metrics)
-->
<!-- It's good to describe an alternative design (or mention an alternative name) for every design (or naming) decision point and compare the alternatives with the designs that you've implemented (or the names you've chosen) to highlight the advantages of the chosen designs and names. -->
<!-- If there was a discussion of the design of the feature implemented in this PR elsewhere (e. g. a "Proposal" issue, any other issue, or a thread in the development mailing list), link to that discussion from this PR description and explain what have changed in your final design compared to your original proposal or the consensus version in the end of the discussion. If something hasn't changed since the original discussion, you can omit a detailed discussion of those aspects of the design here, perhaps apart from brief mentioning for the sake of readability of this PR description. -->
<!-- Some of the aspects mentioned above may be omitted for simple and small changes. -->
Release note
<!-- Give your best effort to summarize your changes in a couple of sentences aimed toward Druid users.
If your change doesn't have end user impact, you can skip this section.
For tips about how to write a good release note, see Release notes.
-->
Broker HTTP connection pools now release resources associated with inactive destinations.
<hr>
##### Key changed/added classes in this PR
-
ResourcePool-
ResourcePoolTest<hr>
<!-- Check the items by putting "x" in the brackets for the done things. Not all of these items apply to every PR. Remove the items which are not done or not relevant to the PR. None of the items from the checklist below are strictly necessary, but it would be very helpful if you at least self-review the PR. -->
This PR has: