You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Fix logservice client fallback from slow replica addresses - #25289
This PR improves logservice client creation when candidate replica addresses include stale or unreachable endpoints.
Previously, connectToLogService tried replica addresses sequentially. If one address accepted a TCP connection but did not respond, client creation could wait until the outer context deadline before trying later
candidates.
Changes:
Keep the existing shuffled address order.
Start connection attempts with staggered fallback instead of strict sequential dialing.
Apply a per-address attempt timeout.
Return the first successfully connected client.
Cancel remaining attempts and close losing clients after a winner is selected.
Add a regression test covering a slow/unresponsive address followed by a reachable address.
This reduces the impact of stale or slow replica addresses returned by discovery/gossip without changing HAKeeper or gossip behavior.
Logservice client: staggered fallback when replica addresses are slow/unresponsive
🐞 Bug fix🧪 Tests🕐 20-40 Minutes
AI Description
• Shuffle replica addresses and use staggered connection attempts instead of strict sequential
dialing.
• Enforce per-address attempt timeouts and return the first successfully connected client.
• Add a regression test to ensure fast fallback from a hanging TCP endpoint.
Diagram
graph TD
A["newClient()"] --> B["connectToLogService()"] --> C["shuffle addresses"] --> D["connectToLogServiceAddresses()"]
D --> E{Winner?
client connected}
D --> F["launch attempt (goroutine)"] --> G["connectToLogServiceAddress()"] --> H["getRPCClient() + RW/RO handshake"]
F -. "per-attempt timeout" .-> D
E -->|yes| I["cancel others + close losers"]
E -->|no| D
Loading
High-Level Assessment
The following are alternative approaches to this PR:
1. Sequential dialing with per-address timeout
➕ Much simpler control flow (no goroutines/results channel)
➕ Still avoids waiting for the outer context deadline on a single bad address
➖ Still serializes attempts; worst-case latency adds up across multiple stale endpoints
➖ Does not opportunistically connect to later addresses while the first is hanging
2. Move timeout/handshake deadline into getRPCClient()
➕ Centralizes connection deadlines in one place
➕ Avoids adding more orchestration logic in client creation
➖ Does not solve the core problem if the hang happens after TCP connect but before higher-level handshake
➖ May affect other callers of getRPCClient() with different expectations
3. Bounded parallelism (N concurrent attempts)
➕ More robust if many endpoints are stale; avoids waiting fallback delay repeatedly
➕ Can cap resource usage explicitly while still parallelizing
➖ More parameters/tuning complexity (choose N, scheduling strategy)
➖ Potentially higher load burst on startup vs staggered approach
Recommendation: The chosen staggered fallback (Happy-Eyeballs-style) is a good balance: it preserves randomized address order, reduces tail latency when an early address hangs, and limits connection bursts via a short fallback delay. Keep this approach, but consider making the attempt timeout/fallback delay configurable (or at least documented) if operators need to tune for different environments.
Files changed (2) +235 / -39
Bug fix (1) +140 / -39
client.goStaggered concurrent dialing with per-address timeouts and cleanup+140/-39
Staggered concurrent dialing with per-address timeouts and cleanup
• Refactors client creation to shuffle candidate replica addresses and connect via staggered concurrent attempts rather than strict sequential dialing. Each attempt runs with its own timeout; the first successful connection cancels remaining attempts and closes losing clients. Adds helper functions to isolate single-address connection logic and to safely stop/drain the fallback timer.
client_test.goRegression test for fast fallback from a hanging replica endpoint+95/-0
Regression test for fast fallback from a hanging replica endpoint
• Adds a test that starts a TCP listener which accepts connections but never responds, then verifies client creation quickly falls back to a reachable logservice address. Introduces a small helper to run the hanging TCP server and temporarily reduces the fallback delay to keep the test fast.
connectToLogServiceAddresses can leak RPC clients when multiple connection attempts succeed: a
losing goroutine may successfully send its client into the buffered results channel before
cancellation, and that client is never closed because the winner path returns immediately without
draining/closing remaining successes. This can accumulate open connections/goroutines/FDs over time
and violates the intended “close losing clients” behavior.
+ if err == nil {+ select {+ case results <- result{client: c}:+ case <-ctx.Done():+ if closeErr := c.close(); closeErr != nil {+ logutil.Error("failed to close the client", zap.Error(closeErr))+ }
}
- e = err+ return
}
- } else {- // TODO: add a test to check whether it works when there is no truncated- // LSN known to the logservice.- if err := c.connectReadWrite(ctx); err == nil {- return c, nil- } else {- if err := c.close(); err != nil {- logutil.Error("failed to close the client", zap.Error(err))- }- e = err+ select {+ case results <- result{err: err}:+ case <-ctx.Done():
}
+ }()+ }++ var lastErr error+ launched, active := 0, 0+ for active > 0 || launched < len(addresses) {+ if active == 0 {+ launch(addresses[launched])+ launched+++ active+++ continue+ }++ var fallback <-chan time.Time+ var timer *time.Timer+ if launched < len(addresses) {+ timer = time.NewTimer(logServiceConnectFallbackDelay)+ fallback = timer.C+ }++ select {+ case r := <-results:+ stopConnectFallbackTimer(timer)+ active--+ if r.client != nil {+ cancel()+ wg.Wait()+ return r.client, nil+ }
Evidence
Attempt goroutines can enqueue a successful client into the buffered results channel without
closing it; the winner path cancels and returns immediately, leaving any already-enqueued successful
clients unreachable but still open (since only the ctx-canceled branch closes them, and
client.close() is otherwise never invoked).
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
### Issue description
`connectToLogServiceAddresses` returns immediately after receiving the first successful `result{client: c}`. If another goroutine already sent a successful client into the buffered `results` channel before the cancellation happens, that “losing” client is never closed.
### Issue Context
- Each attempt goroutine sends a successful client to `results` and returns without closing it.
- The main select loop cancels and returns on the first success, but does not drain `results` to close any other successful clients already queued.
- `client.close()` is the only cleanup path for these clients.
### Fix Focus Areas
- pkg/logservice/client.go[559-641]
- pkg/logservice/client.go[655-657]
### Suggested fix approach
- After selecting a winning client, cancel the shared context as you do today.
- Drain any already-available `results` entries (and/or wait for remaining goroutines to report) and close any `r.client` where `r.client != winner`.
- One simple pattern: after `cancel()`, loop `active-1` times receiving from `results` (or use a `for active > 0` drain loop) and call `close()` on any non-nil `r.client`.
- Alternatively, use an `atomic.Bool`/`sync.Once` winner selection in goroutines: if not the winner, close the client before returning, regardless of send timing.
- Ensure you still `wg.Wait()` before returning.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
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
kind/bugSomething isn't workingsize/MDenotes a PR that changes [100,499] lines
4 participants
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.
What type of PR is this?
Which issue(s) this PR fixes:
issue #25274 #25277
What this PR does / why we need it:
This PR improves logservice client creation when candidate replica addresses include stale or unreachable endpoints.
Previously, connectToLogService tried replica addresses sequentially. If one address accepted a TCP connection but did not respond, client creation could wait until the outer context deadline before trying later
candidates.
Changes:
This reduces the impact of stale or slow replica addresses returned by discovery/gossip without changing HAKeeper or gossip behavior.