Repository navigation
[release] fix(httpx): reuse one HttpClient for token refresh and retry it once on network error (2.7.1) - #129
Merged
Conversation
… refresh Each JWT refresh built a new java.net.http.HttpClient (to scope cookies per user) and never closed it, starting a selector thread and worker pool that lived until GC. Share one lazily created refresh client with no cookie handler and parse Set-Cookie into a per-refresh CookieManager instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Paolo Di Tommaso <paolo.ditommaso@gmail.com>
The shared refresh HttpClient may pick a pooled keep-alive connection the server closed while idle, and the JDK client does not retry a POST, so the refresh failed and the caller got the original 401. Send the refresh once more on an IOException; HttpTimeoutException (including connect timeouts) is not retried, so a refresh still gives up after tokenRefreshTimeout. Re-sending is safe: Platform does not rotate refresh tokens on use (RefreshTokenPersistenceImpl re-stores the same token, and the Auth0 persistence delegates to it for Platform-issued tokens). Bump lib-httpx to 2.7.1 with changelog and README. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jordeu
approved these changes
Sep 28, 2026
| * | ||
| * @return the shared refresh {@link HttpClient} | ||
| */ | ||
| private HttpClient refreshHttpClient() { |
Member
There was a problem hiding this comment.
HxClient has the same leak in another place: when a server answers 401 with a Bearer challenge, the anonymous-token lookup (HxClient.java:938-940) builds a new HttpClient on every call and never closes it. Not in scope here, but worth a follow-up, maybe reusing a shared client like this one.
Contributor
Author
There was a problem hiding this comment.
Fixed in #133: HxClient now reuses one anonymous-token client, created on first use. It keeps its own builder settings instead of sharing the refresh client, because that one follows redirects and forces HTTP/1.1, which would change how the anonymous lookup behaves.
Address review on #129: assert user-b's refresh request carries no Cookie header, and correct the retry javadoc, since each attempt gets its own tokenRefreshTimeout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pditommaso
added a commit
that referenced
this pull request
Nov 24, 2026
…133) getAnonymousBearerToken built a new HttpClient on every Bearer 401 without credentials and never closed it, keeping a selector thread and worker pool alive until GC. Create one lazily per HxClient instead, with the same builder settings (JDK defaults plus the inherited proxy configuration). Follow-up to the review on #129. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
HxTokenManagernow performs every JWT refresh through a single sharedjava.net.http.HttpClientinstead of building a new one per refresh and never closing it, and retries a refresh request once when it fails with a network error. Refresh behaviour (tokens from cookies or JSON, cookie policy, proxy, timeouts, redirects) is otherwise unchanged; the difference is that a refresh no longer starts JDK HTTP client threads that linger until garbage collection.Released as lib-httpx 2.7.1 (VERSION, changelog and README bumped).
Before
doRefreshTokenInternalcreated, for every refresh:CookieManager(to keep one user's cookies from leaking into another user's refresh), andHttpClientwith thatCookieManageras its cookie handler.The client was never closed (
HttpClient.close()only exists from Java 21 and the library targets--release 17). Each client starts aSelectorManagerthread (reported asRUNNABLE) plus a worker from its own cached executor (TIMED_WAITING), and those threads live until the client is GC'd — typically minutes.Observed in sched-prod:
TokenRefreshWorkerrefreshes up to ~100 Platform tokens every 2.5h. Each tick produced a spike of +1 RUNNABLE thread per refreshed token (e.g.due=100→ runnable 40 → 134;due=28→ 31 → 59), matched 1:1 across 5 consecutive ticks on two pods, plus a corresponding TIMED_WAITING spike, and added ~2 platform thread starts per refresh tojvm_threads_started_threads_total. Every refresh also paid a new TCP + TLS handshake.After
HttpClientperHxTokenManager, created lazily on the first refresh (a manager that never refreshes never creates it). Same settings as before: HTTP/1.1,Redirect.NORMAL,tokenRefreshTimeoutconnect timeout, proxy settings inherited fromHxConfig.CookieManager(samerefreshCookiePolicylogic), populated from the response withcookieManager.put(response.uri(), response.headers().map())— the same call the JDK client makes internally when a cookie handler is configured.extractAuthFromResponseand the cookie/JSON token extraction are untouched.IOException. Sharing the client means a refresh can pick a pooled keep-alive connection the server closed while idle, and the JDK client does not retry aPOSTby itself.HttpTimeoutException(including connect timeouts) is rethrown, so a refresh still gives up after onetokenRefreshTimeout; if the retry also fails, the refresh returnsnullas before.Net effect: token refresh creates no new threads after the first one, and consecutive refreshes to the same host can reuse a keep-alive connection.
Why re-sending a refresh is safe
The retry can re-send a refresh token the server already received (e.g. a reset after the request was processed). Platform does not rotate refresh tokens on use:
RefreshTokenPersistenceImpl.getAuthenticationre-stores the same token with a new expiry, andAuth0RefreshTokenPersistencedelegates to it for Platform-issued tokens. A duplicate refresh therefore cannot invalidate the token.Concurrency (overlapping refreshes)
Overlapping refreshes share only the
HttpClient, which the JDK documents as immutable and thread-safe. All per-refresh state stays local to the call:CookieManagerand fills it only from its ownHttpResponse; a concurrent refresh has no path to another'sSet-Cookie. The refresh request sends noCookieheader, as before (each refresh previously started with an empty manager).send()returns its own response.volatilefield, so two racing first refreshes produce exactly one client (and one selector thread); later calls read the field without locking. This is the onlysynchronized (this)inHxTokenManager, so it cannot contend with other locking.ongoingRefreshes.computeIfAbsentstill collapses concurrent 401s for one key into a single refresh; different keys refresh in parallel, as before.tokenRefreshTimeout.synchronizedblock pins a carrier on Java 21–23, but it only builds the client (no I/O) and runs once; Java 24+ no longer pins onsynchronized.The isolation guarantee is structural (nothing per-user is shared), not timing-dependent.
Possible side effects
Set-Cookiefrom every response in a redirect chain; now only the final response's cookies are parsed. If a refresh endpoint issuedJWT/JWT_REFRESH_TOKENon a 3xx and then redirected, the token would no longer be picked up (the JSON-body fallback still applies). No current caller is affected:micronaut.security.redirect.refresh.enabled: falsesince 2020 (tower-config/src/main/resources/application.yml), so/oauth/access_tokenanswers with a direct 200 plusSet-Cookie, on Cloud and Enterprise alike.OauthRefreshRedirectFilteranswers legacy refreshes with a 307 to Platform. The 307 sets no cookies and Platform's final 200 does, so tokens are still captured. The filter's discriminator (a programmatic refresh carries noJWT_REFRESH_TOKENcookie) still holds, more strictly now that the shared client has no cookie handler at all.IOExceptionon thePOST; that case is covered by the single retry above. The JDK also evicts idle HTTP/1.1 connections afterjdk.httpclient.keepalive.timeout(30s by default on JDK 20+).HxTokenManager. After its first refresh, each manager keeps one idleHttpClient(one daemon selector thread) for its lifetime instead of short-lived ones. For callers that create manyHxClientinstances that each refresh once, this trades transient threads for one persistent thread per instance. When the manager becomes unreachable the client is collected and its thread exits, as before.HxConfigis immutable, so this is only visible to code that mutates config via reflection/tests.Impact on consumers
lib-cloudinfo) dependency.TowerClient(nf-tower),WaveClient(nf-wave),SchedClient(nf-seqera), one each per runPlatformAuthRefresher,CachingPlatformClient(singletons),SchedClientNo consumer subclasses
HxTokenManageror overridesdoRefreshTokenInternal/extractAuthFromResponse, and all refreshing consumers useCookiePolicy.ACCEPT_ALL.Tests
HxClientJwtIntegrationTest(WireMock):Set-Cookie, the second via JSON only. Asserts the first user's cookies do not leak into the second refresh and that both refreshes used the same client instance;nullafter exactly 2 POSTs (a single retry);tokenRefreshTimeout→ returnsnullafter 1 POST (timeouts are not retried)../gradlew :lib-httpx:test— 216 tests pass (existing cookie-refresh, JSON-refresh, proxy-auth and multi-tenant tests unchanged).Follow-up
After merge (publishes 2.7.1):
io.seqera:lib-httpxfrom2.6.0to2.7.1inplatform-client,sched-client,wave-client. This also brings in 2.7.0's removal ofHxProxyConfig; sched does not useHxProxyConfigorwithProxyConfig. Then confirm in sched-prod that the RUNNABLE spike at eachTokenRefreshWorkertick is gone.libHttpxVersionfrom2.7.0to2.7.1.🤖 Generated with Claude Code