Skip to content

[release] fix(httpx): reuse one HttpClient for token refresh and retry it once on network error (2.7.1) - #129

Merged
pditommaso merged 3 commits into
masterfrom
fix/httpx-shared-refresh-client
Sep 28, 2026
Merged

pditommaso merged 3 commits into
masterfrom
fix/httpx-shared-refresh-client

Conversation

@pditommaso

@pditommaso pditommaso commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

HxTokenManager now performs every JWT refresh through a single shared java.net.http.HttpClient instead 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

doRefreshTokenInternal created, for every refresh:

  • a fresh CookieManager (to keep one user's cookies from leaking into another user's refresh), and
  • a fresh HttpClient with that CookieManager as its cookie handler.

The client was never closed (HttpClient.close() only exists from Java 21 and the library targets --release 17). Each client starts a SelectorManager thread (reported as RUNNABLE) 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: TokenRefreshWorker refreshes 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 to jvm_threads_started_threads_total. Every refresh also paid a new TCP + TLS handshake.

After

  • One refresh HttpClient per HxTokenManager, created lazily on the first refresh (a manager that never refreshes never creates it). Same settings as before: HTTP/1.1, Redirect.NORMAL, tokenRefreshTimeout connect timeout, proxy settings inherited from HxConfig.
  • The shared client has no cookie handler, so it holds no cookie state across users.
  • Each refresh still gets its own CookieManager (same refreshCookiePolicy logic), populated from the response with cookieManager.put(response.uri(), response.headers().map()) — the same call the JDK client makes internally when a cookie handler is configured. extractAuthFromResponse and the cookie/JSON token extraction are untouched.
  • The refresh request is retried once on an 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 a POST by itself. HttpTimeoutException (including connect timeouts) is rethrown, so a refresh still gives up after one tokenRefreshTimeout; if the retry also fails, the refresh returns null as 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.getAuthentication re-stores the same token with a new expiry, and Auth0RefreshTokenPersistence delegates 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:

  • No cookie cross-talk. The shared client has no cookie handler, so it keeps no cookie state. Each refresh creates its own local CookieManager and fills it only from its own HttpResponse; a concurrent refresh has no path to another's Set-Cookie. The refresh request sends no Cookie header, as before (each refresh previously started with an empty manager).
  • No response mix-up. HTTP/1.1 pooled connections carry one exchange at a time; overlapping refreshes get separate connections (the JDK pool is unbounded by default) and each send() returns its own response.
  • Single client creation. Lazy init is double-checked locking on a volatile field, so two racing first refreshes produce exactly one client (and one selector thread); later calls read the field without locking. This is the only synchronized (this) in HxTokenManager, so it cannot contend with other locking.
  • Same-key dedup unchanged. ongoingRefreshes.computeIfAbsent still collapses concurrent 401s for one key into a single refresh; different keys refresh in parallel, as before.
  • No head-of-line blocking. The shared selector thread does non-blocking I/O and dispatches to the client's executor, so a slow or hung refresh endpoint delays only its own call, still bounded by tokenRefreshTimeout.
  • Virtual threads. The synchronized block pins a carrier on Java 21–23, but it only builds the client (no I/O) and runs once; Java 24+ no longer pins on synchronized.

The isolation guarantee is structural (nothing per-user is shared), not timing-dependent.

Possible side effects

  • Cookies on redirect hops are no longer captured. With a per-refresh cookie handler, the JDK stored Set-Cookie from every response in a redirect chain; now only the final response's cookies are parsed. If a refresh endpoint issued JWT/JWT_REFRESH_TOKEN on a 3xx and then redirected, the token would no longer be picked up (the JSON-body fallback still applies). No current caller is affected:
    • Platform has set micronaut.security.redirect.refresh.enabled: false since 2020 (tower-config/src/main/resources/application.yml), so /oauth/access_token answers with a direct 200 plus Set-Cookie, on Cloud and Enterprise alike.
    • sched's deprecated OauthRefreshRedirectFilter answers 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 no JWT_REFRESH_TOKEN cookie) still holds, more strictly now that the shared client has no cookie handler at all.
  • Connection reuse. Refreshes may now reuse a pooled keep-alive connection. A connection the server closed while idle would surface as an IOException on the POST; that case is covered by the single retry above. The JDK also evicts idle HTTP/1.1 connections after jdk.httpclient.keepalive.timeout (30s by default on JDK 20+).
  • One long-lived client per HxTokenManager. After its first refresh, each manager keeps one idle HttpClient (one daemon selector thread) for its lifetime instead of short-lived ones. For callers that create many HxClient instances 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.
  • Proxy settings are captured at first refresh, not per refresh. HxConfig is immutable, so this is only visible to code that mutates config via reflection/tests.

Impact on consumers

Project lib-httpx Refresh-enabled clients Impact
wave not used — None: no direct or transitive (lib-cloudinfo) dependency.
nextflow 2.7.0 TowerClient (nf-tower), WaveClient (nf-wave), SchedClient (nf-seqera), one each per run At most one extra idle daemon selector thread per client after its first refresh.
sched 2.6.0 PlatformAuthRefresher, CachingPlatformClient (singletons), SchedClient The per-tick spike of ~100 threads becomes ~2 persistent threads.

No consumer subclasses HxTokenManager or overrides doRefreshTokenInternal / extractAuthFromResponse, and all refreshing consumers use CookiePolicy.ACCEPT_ALL.

Tests

  • HxClientJwtIntegrationTest (WireMock):
    • one manager, two refreshes for different users — the first returns tokens via 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;
    • connection reset on the first attempt, 200 on the second → the refresh succeeds after 2 POSTs;
    • connection reset on every attempt → returns null after exactly 2 POSTs (a single retry);
    • response slower than tokenRefreshTimeout → returns null after 1 POST (timeouts are not retried).
  • The two connection-reset cases fail with the retry reverted.
  • ./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):

  • sched: bump io.seqera:lib-httpx from 2.6.0 to 2.7.1 in platform-client, sched-client, wave-client. This also brings in 2.7.0's removal of HxProxyConfig; sched does not use HxProxyConfig or withProxyConfig. Then confirm in sched-prod that the RUNNABLE spike at each TokenRefreshWorker tick is gone.
  • nextflow: bump libHttpxVersion from 2.7.0 to 2.7.1.

🤖 Generated with Claude Code

pditommaso and others added 2 commits September 26, 2026 12:39
… 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>
@pditommaso pditommaso changed the title fix(httpx): reuse one HttpClient for token refresh instead of one per refresh [release] fix(httpx): reuse one HttpClient for token refresh and retry it once on network error (2.7.1) Sep 28, 2026
@pditommaso
pditommaso requested a review from jordeu September 28, 2026 06:21
*
* @return the shared refresh {@link HttpClient}
*/
private HttpClient refreshHttpClient() {

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.

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.

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.

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
pditommaso merged commit 084c445 into master Sep 28, 2026
9 checks passed
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>
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.

2 participants