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: morpc client lock contention causing long blocking during CN node terminated - #23435
Problem: Synchronous backend creation in getBackend() caused 27 goroutines to serialize for 135 seconds when CN nodes crashed, reducing CPU utilization to 30%.
Solution: Implemented asynchronous backend creation using the existing global client GC mechanism, eliminating lock-held network I/O.
Impact: Recovery time improved from 135 seconds to 200ms (675x improvement).
Pool Saturation Immediate Failure
Problem: When the backend pool was full but all connections were busy/inactive, getBackend() returned ErrBackendUnavailable, causing immediate failure instead of waiting for connections to become available.
Solution: Changed error type to ErrBackendCreating to trigger proper retry logic, allowing requests to wait for free connections under high load.
Impact: Improved system availability by preventing request drops during temporary saturation.
Circuit Breaker Not Triggering on Permanent Failures
Problem: When backend creation repeatedly failed (e.g., permanently crashed nodes), the circuit breaker never opened because failures during async creation waits weren't recorded.
Solution: Added circuit breaker failure recording when auto-create timeouts or retry limits are exceeded.
Impact: Permanent failures now trigger circuit breaker protection, enabling fast failure and preventing wasteful retries.
PR Type
Bug fix, Enhancement
Description
Implement asynchronous backend creation to eliminate lock contention during CN node failures
Add bounded wait timeout for auto-create with circuit breaker integration for fast failure detection
Distinguish transient creation states from permanent unavailability via new error types
Enhance error classification and observability with metrics for backend health and circuit breaker state
Diagram Walkthrough
flowchart LR
A["getBackend Request"] --> B{"Circuit Breaker<br/>Check"}
B -->|Open| C["Return ErrCircuitOpen<br/>Fast Fail"]
B -->|Closed/HalfOpen| D["Check Pool<br/>& Limits"]
D -->|Backend Available| E["Return Backend<br/>Success"]
D -->|Pool Empty| F{"Auto-Create<br/>Enabled?"}
D -->|Pool Busy| G["Return ErrBackendCreating<br/>Trigger Wait"]
F -->|Yes| H["Queue Async Creation<br/>Return ErrBackendCreating"]
F -->|No| I["Return ErrNoAvailableBackend<br/>Fail Fast"]
H --> J["Caller Retries<br/>with Bounded Wait"]
J -->|Timeout| K["Record Failure<br/>Return ErrBackendCreateTimeout"]
J -->|Success| E
K --> L["Circuit Breaker<br/>May Open"]
Loading
File Walkthrough
Relevant files
Enhancement, bug fix
1 files
client.go
Implement async backend creation and bounded wait logic
Below is a summary of compliance checks for this PR:
Security Compliance
⚪
Resource exhaustion
Description: Asynchronous backend auto-creation can be triggered based on the backend string (via globalClientGC.triggerCreate(c, backend)), which may enable resource-exhaustion (task queue pressure, repeated connection attempts, and backend pool growth up to configured limits) if an attacker can influence backend values to cause many distinct endpoints to be enqueued/created. client.go [721-740]
Referred Code
// No backend available in poolcanCreate:=c.canCreateLocked(backend)
enableAutoCreate:=c.options.enableAutoCreatec.mu.Unlock() // Release lock before any potentially blocking operation// Strictly gate creation on enableAutoCreate flagif!enableAutoCreate {
returnnil, moerr.NewNoAvailableBackendNoCtx()
}
ifcanCreate {
// Try to enqueue creation task with backpressure handlingif!globalClientGC.triggerCreate(c, backend) {
// Queue is full - fallback to existing creation path with proper bookkeepingreturnc.createBackendWithBookkeeping(backend, lock)
}
}
// Return error to trigger retry in callerreturnnil, moerr.NewNoAvailableBackendNoCtx()
Ticket Compliance
⚪
🎫 No ticket provided
Create ticket/issue
Codebase Duplication Compliance
⚪
Codebase context is not defined
Follow the guide to enable codebase context checks.
Custom Compliance
🟢
Generic: Comprehensive Audit Trails
Objective: To create a detailed and reliable record of critical system actions for security analysis and compliance.
✅ Refactor to centralize duplicated retry logicSuggestion Impact:The commit introduces shared helper functions (isAutoCreateWaitError and handleAutoCreateWait) and updates Send(), NewStream(), and Ping() to call this centralized logic when handling backend auto-creation wait/retry conditions. While the full retry loops are still present in each method (not fully unified into a single "withRetryableBackend" wrapper), a meaningful portion of the previously duplicated retry/wait behavior was extracted and reused.
code diff:
@@ -322,6 +428,7 @@
policy := c.options.retryPolicy
var backoff time.Duration
retryCount := 0
+ var creationStart time.Time
for {
// Check circuit breaker before each retry attempt
@@ -337,13 +444,13 @@
return nil, err
}
- // Handle NoAvailableBackend error - backend is being created asynchronously- if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {- // Check context first before retrying- select {- case <-ctx.Done():- return nil, ctx.Err()- default:+ waitingForCreate := c.options.enableAutoCreate && isAutoCreateWaitError(err)++ // Handle backend creation-in-progress with bounded wait+ if waitingForCreate {+ shouldContinue, waitErr := c.handleAutoCreateWait(ctx, backend, &creationStart, retryCount)+ if !shouldContinue {+ return nil, waitErr
}
retryCount++
@@ -364,13 +471,6 @@
return nil, ctx.Err()
case <-time.After(backoff):
}
- }-- if retryCount <= 3 || retryCount%10 == 0 {- c.logger.Debug("retrying Send after no available backend",- zap.String("backend", backend),- zap.Int("retry", retryCount),- zap.Duration("backoff", backoff))
}
continue
}
@@ -441,6 +541,7 @@
policy := c.options.retryPolicy
var backoff time.Duration
retryCount := 0
+ var creationStart time.Time
for {
// Check circuit breaker before each retry attempt
@@ -463,8 +564,15 @@
return nil, err
}
- // Handle NoAvailableBackend error - backend is being created asynchronously- if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {+ waitingForCreate := c.options.enableAutoCreate && isAutoCreateWaitError(err)++ // Handle backend creation-in-progress with bounded wait+ if waitingForCreate {+ shouldContinue, waitErr := c.handleAutoCreateWait(ctx, backend, &creationStart, retryCount)+ if !shouldContinue {+ return nil, waitErr+ }+
retryCount++
// Check if max retries exceeded
if policy.MaxRetries > 0 && retryCount >= policy.MaxRetries {
@@ -483,13 +591,6 @@
return nil, ctx.Err()
case <-time.After(backoff):
}
- }-- if retryCount <= 3 || retryCount%10 == 0 {- c.logger.Debug("retrying NewStream after no available backend",- zap.String("backend", backend),- zap.Int("retry", retryCount),- zap.Duration("backoff", backoff))
}
continue
}
@@ -559,17 +660,18 @@
policy := c.options.retryPolicy
var backoff time.Duration
retryCount := 0
+ var creationStart time.Time
for {
b, err := c.getBackend(backend, false)
if err != nil {
- // Handle NoAvailableBackend error - backend is being created asynchronously- if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {- // Check context first before retrying- select {- case <-ctx.Done():- return ctx.Err()- default:+ waitingForCreate := c.options.enableAutoCreate && isAutoCreateWaitError(err)++ // Handle backend creation-in-progress with bounded wait+ if waitingForCreate {+ shouldContinue, waitErr := c.handleAutoCreateWait(ctx, backend, &creationStart, retryCount)+ if !shouldContinue {+ return waitErr
}
retryCount++
@@ -590,13 +692,6 @@
return ctx.Err()
case <-time.After(backoff):
}
- }-- if retryCount <= 3 || retryCount%10 == 0 {- c.logger.Debug("retrying Ping after no available backend",- zap.String("backend", backend),- zap.Int("retry", retryCount),- zap.Duration("backoff", backoff))
}
continue
}
@@ -709,6 +804,7 @@
c.mu.Lock()
b, err := c.getBackendLocked(backend, lock)
+ poolSize := len(c.mu.backends[backend])
if err != nil {
c.mu.Unlock()
return nil, err
@@ -721,6 +817,7 @@
// No backend available in pool
canCreate := c.canCreateLocked(backend)
enableAutoCreate := c.options.enableAutoCreate
+ hasBackends := poolSize > 0
c.mu.Unlock() // Release lock before any potentially blocking operation
// Strictly gate creation on enableAutoCreate flag
@@ -728,15 +825,27 @@
return nil, moerr.NewNoAvailableBackendNoCtx()
}
+ creationQueued := false
if canCreate {
// Try to enqueue creation task with backpressure handling
if !globalClientGC.triggerCreate(c, backend) {
// Queue is full - fallback to existing creation path with proper bookkeeping
return c.createBackendWithBookkeeping(backend, lock)
}
- }-- // Return error to trigger retry in caller+ creationQueued = true+ }++ if creationQueued {+ return nil, ErrBackendCreating+ }++ if hasBackends {+ // Pool had entries but none usable; surface as unavailable to differentiate from "creating"+ c.metrics.backendUnavailableCounter.Inc()+ return nil, ErrBackendUnavailable+ }++ // Pool is empty and cannot create - return ErrNoAvailableBackend to trigger wait logic
return nil, moerr.NewNoAvailableBackendNoCtx()
}
@@ -778,7 +887,7 @@
zap.Int("inactive", inactiveCnt),
zap.Int("max", c.options.maxBackendsPerHost))
if !c.canCreateLocked(backend) {
- return nil, moerr.NewNoAvailableBackendNoCtx()+ return nil, moerr.NewBackendClosedNoCtx()
}
}
@@ -827,7 +936,7 @@
}
if !c.canCreateLocked(backend) {
c.mu.Unlock()
- return nil, moerr.NewNoAvailableBackendNoCtx()+ return nil, moerr.NewBackendClosedNoCtx()
}
c.mu.Unlock()
@@ -848,7 +957,7 @@
if !c.canCreateLocked(backend) {
// Another goroutine may have filled the pool while we were creating.
b.Close()
- return nil, moerr.NewNoAvailableBackendNoCtx()+ return nil, moerr.NewBackendClosedNoCtx()
}
// Apply lock if requested (only after we know the backend will be kept)
@@ -935,7 +1044,7 @@
func (c *client) createBackendLocked(backend string) (Backend, error) {
if !c.canCreateLocked(backend) {
- return nil, moerr.NewNoAvailableBackendNoCtx()+ return nil, moerr.NewBackendClosedNoCtx()
}
b, err := c.doCreate(backend)
@@ -972,6 +1081,66 @@
c.metrics.poolSizeGauge.Set(float64(n))
}
+func isErrBackendCreating(err error) bool {+ if err == nil {+ return false+ }+ // Compare directly since ErrBackendCreating is now a moerr error+ return err == ErrBackendCreating || errors.Is(err, ErrBackendCreating)+}++// isAutoCreateWaitError checks if the error indicates we should wait for backend creation.+// State mapping:+// - ErrBackendCreating: Backend is being created asynchronously, should wait+// - ErrNoAvailableBackend: Pool is empty and cannot create (at capacity), should wait+// - ErrBackendClosed: Backend unavailable or wait timeout exceeded, should NOT wait+func isAutoCreateWaitError(err error) bool {+ return isErrBackendCreating(err) ||+ moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend)+}++// handleAutoCreateWait implements bounded wait logic for backend creation.+// Returns:+// - true: should continue waiting/retrying+// - false: should stop (timeout exceeded or context cancelled)+// - error: ErrBackendCreateTimeout if timeout exceeded, ctx.Err() if context cancelled+func (c *client) handleAutoCreateWait(ctx context.Context, backend string, creationStart *time.Time, retryCount int) (bool, error) {+ // Check context first+ select {+ case <-ctx.Done():+ return false, ctx.Err()+ default:+ }++ // Initialize creation start time+ if creationStart.IsZero() {+ *creationStart = time.Now()+ }++ // Check bounded wait timeout+ if timeout := c.options.autoCreateWaitTimeout; timeout > 0 {+ elapsed := time.Since(*creationStart)+ if elapsed >= timeout {+ c.logger.Warn("auto-create backend timed out",+ zap.String("backend", backend),+ zap.Duration("waited", elapsed),+ zap.Duration("timeout", timeout))+ c.metrics.autoCreateTimeoutCounter.Inc()+ return false, ErrBackendCreateTimeout+ }+ }++ // Log creation wait progress (sparse logging)+ if retryCount == 1 || retryCount%10 == 0 {+ c.logger.Debug("waiting for backend creation",+ zap.String("backend", backend),+ zap.Int("retry", retryCount),+ zap.Duration("waited", time.Since(*creationStart)))+ }++ return true, nil+}
The retry logic for handling asynchronous backend creation is duplicated in Send(), NewStream(), and Ping(). This should be refactored into a single helper function to reduce redundancy and improve maintainability.
ifmoerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {
// Check context first before retryingselect {
case<-ctx.Done():
returnnil, ctx.Err()
default:
}
retryCount++// Check if max retries exceeded (0 means unlimited)... (clipped26lines)
Why: The suggestion correctly identifies significant code duplication across Send(), NewStream(), and Ping(), and centralizing this logic would improve maintainability and consistency.
Medium
Possible issue
✅ Add missing circuit breaker checkSuggestion Impact:The commit updated Ping’s retry/error-handling path to treat circuit breaker errors (ErrCircuitOpen and ErrCircuitHalfOpen) as immediate failures and to return the circuit breaker’s specific error via GetError, improving fast-fail behavior during retries. However, it did not add the explicit `Allow()` check at the top of each Ping retry iteration as suggested (unlike Send/NewStream), so the implementation differs from the proposed change.
code diff:
// Check circuit breaker before attempting
if !c.circuitBreakers.Allow(backend) {
- return ErrCircuitOpen+ return c.circuitBreakers.GetError(backend)
}
policy := c.options.retryPolicy
var backoff time.Duration
retryCount := 0
+ var creationStart time.Time
for {
b, err := c.getBackend(backend, false)
if err != nil {
- // Handle NoAvailableBackend error - backend is being created asynchronously- if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {- // Check context first before retrying- select {- case <-ctx.Done():- return ctx.Err()- default:+ // Handle circuit breaker errors - both open and half-open (exhausted probes) reject immediately+ if errors.Is(err, ErrCircuitOpen) || errors.Is(err, ErrCircuitHalfOpen) {+ return err+ }++ // Wait for backend if:+ // 1. Auto-create enabled and waiting for creation, OR+ // 2. ErrBackendCreating (pool has backends but all busy - wait regardless of auto-create)+ waitingForCreate := (c.options.enableAutoCreate && isAutoCreateWaitError(err)) ||+ isErrBackendCreating(err)++ // Handle backend creation-in-progress with bounded wait+ if waitingForCreate {+ shouldContinue, waitErr := c.handleAutoCreateWait(ctx, backend, &creationStart, retryCount)+ if !shouldContinue {+ // Record circuit breaker failure on timeout+ c.circuitBreakers.RecordFailure(backend)+ return waitErr
}
retryCount++
@@ -579,6 +716,8 @@
zap.String("backend", backend),
zap.Int("retries", retryCount),
zap.Error(err))
+ // Record circuit breaker failure on max retries+ c.circuitBreakers.RecordFailure(backend)
return err
}
@@ -590,13 +729,6 @@
return ctx.Err()
case <-time.After(backoff):
}
- }-- if retryCount <= 3 || retryCount%10 == 0 {- c.logger.Debug("retrying Ping after no available backend",- zap.String("backend", backend),- zap.Int("retry", retryCount),- zap.Duration("backoff", backoff))
}
continue
}
@@ -624,7 +756,7 @@
// Check circuit breaker after failure
if !c.circuitBreakers.Allow(backend) {
- return ErrCircuitOpen+ return c.circuitBreakers.GetError(backend)
}
Add a missing circuit breaker check inside the Ping method's retry loop to ensure it fails fast, consistent with Send and NewStream.
func (c *client) Ping(ctx context.Context, backend string) error {
if ctx == nil {
panic("client Ping nil context")
}
// Check circuit breaker before attempting
if !c.circuitBreakers.Allow(backend) {
return ErrCircuitOpen
}
policy := c.options.retryPolicy
var backoff time.Duration
retryCount := 0
for {
+ // Check circuit breaker before each retry attempt+ if !c.circuitBreakers.Allow(backend) {+ // Don't record failure - circuit is already open+ return ErrCircuitOpen+ }+
b, err := c.getBackend(backend, false)
if err != nil {
+ // Handle circuit open error without recording additional failure+ if errors.Is(err, ErrCircuitOpen) {+ return err+ }+
// Handle NoAvailableBackend error - backend is being created asynchronously
if moerr.IsMoErrCode(err, moerr.ErrNoAvailableBackend) {
...
[To ensure code accuracy, apply this suggestion manually]
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies that the Ping method's retry loop lacks a circuit breaker check, unlike Send and NewStream. Adding this check ensures consistent fast-fail behavior across all retryable methods, improving the robustness of the new error-handling logic.
Medium
General
Improve test to cover retry logic
In TestCrashedNodeRecovery, replace the direct call to c.getBackend with c.Ping to more accurately test the complete retry and recovery mechanism.
func TestCrashedNodeRecovery(t *testing.T) {
...
var totalBlockTime atomic.Int64
var successCount atomic.Int32
var noBackendCount atomic.Int32
start := time.Now()
for i := 0; i < numGoroutines; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
goroutineStart := time.Now()
+ ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)+ defer cancel()- // Try to get backend (should fail quickly)- b, err := c.getBackend("crashed-node", false)+ // Use Ping to test the full retry logic+ err := c.Ping(ctx, "crashed-node")
elapsed := time.Since(goroutineStart)
totalBlockTime.Add(int64(elapsed))
if err == nil {
...
[To ensure code accuracy, apply this suggestion manually]
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly points out that testing getBackend directly doesn't cover the full retry logic introduced in the PR. Changing the test to use c.Ping would provide a more realistic and comprehensive validation of the user-facing behavior, making the test more robust.
XuPeng-SH
changed the title
fix: MORPC client lock contention causing long blocking during CN node crashes
fix: morpc client lock contention causing long blocking during CN node crashes
Jan 4, 2026
XuPeng-SH
changed the title
fix: morpc client lock contention causing long blocking during CN node crashes
fix: morpc client lock contention causing long blocking during CN node terminated
Jan 4, 2026
Below is a summary of compliance checks for this PR:
Security Compliance
⚪
Metrics cardinality DoS
Description: The new circuit breaker metrics use backend as a metric label via v2.NewRPCCircuitBreakerStateGauge(m.name, backend) / v2.NewRPCCircuitBreakerTripsCounter(m.name, backend), which can enable a metrics-cardinality DoS (memory/CPU exhaustion in the process and/or metrics backend) if backend can be influenced to generate many unique values (e.g., dynamic addresses or attacker-controlled strings). circuit_breaker.go [399-413]
Generic: Meaningful Naming and Self-Documenting Code
Objective: Ensure all identifiers clearly express their purpose and intent, making code self-documenting
Status: Comment contradicts behavior: The bounded-wait documentation states a timeout returns ErrBackendClosed, but the implementation returns ErrBackendCreateTimeout, making the code comments misleading.
Referred Code
// - autoCreateWaitTimeout = 0 (default): Wait until context deadline (legacy behavior)// - autoCreateWaitTimeout > 0: Wait up to specified duration, then return ErrBackendClosed//
Generic: Robust Error Handling and Edge Case Management
Objective: Ensure comprehensive error handling that provides meaningful context and graceful degradation
Status: Low-context timeout error: ErrBackendCreateTimeout is created via moerr.NewBackendClosedNoCtx() (same code/message as generic backend-closed), so callers may not receive actionable context distinguishing create-timeout vs other backend-closed scenarios unless they rely on logs/metrics.
Referred Code
// ErrBackendCreateTimeout indicates that auto-create wait timeout exceeded.// This typically means backend creation is too slow or queue congestion.// This is a boundary condition error (NoCtx + Counter for monitoring).// Uses ErrBackendClosed code for compatibility with existing error handling.ErrBackendCreateTimeout=moerr.NewBackendClosedNoCtx()
In canRetryLock, move the txn.HasLockTable(table) check to the beginning of the function to prevent potential deadlocks where a transaction might retry acquiring a lock on a table it already holds a lock on.
func canRetryLock(table uint64, txn client.TxnOperator, err error) bool {
+ // If current transaction already hold the lock table, means it is a remote+ // transaction. And wait and retry will cause deadlock.+ if txn.HasLockTable(table) {+ return false+ }+
if moerr.IsMoErrCode(err, moerr.ErrRetryForCNRollingRestart) {
time.Sleep(defaultWaitTimeOnRetryLock)
return true
- }- if txn.HasLockTable(table) {- return false
}
if moerr.IsMoErrCode(err, moerr.ErrLockTableBindChanged) ||
moerr.IsMoErrCode(err, moerr.ErrLockTableNotFound) {
time.Sleep(defaultWaitTimeOnRetryLock)
return true
}
// Use morpc.GetStatusCategory for unified RPC error classification
// StatusUnknown (non-RPC errors) will fall through to return false
status := morpc.GetStatusCategory(err)
if status == morpc.StatusTransient || status == morpc.StatusUnavailable {
time.Sleep(defaultWaitTimeOnRetryLock)
return true
}
if status == morpc.StatusCancelled {
return false // Client closing/closed should not retry
}
// Unknown errors (non-RPC, non-lock errors) should not retry
return false
}
[To ensure code accuracy, apply this suggestion manually]
Suggestion importance[1-10]: 8
__
Why: This suggestion correctly identifies a potential deadlock scenario where a transaction holding a lock might retry and wait for another lock on the same table. Moving the txn.HasLockTable(table) check to the beginning of the function is a critical fix to prevent this.
Medium
Avoid creating backends when closing
In getBackend, add a check for c.mu.closing before enqueuing a new backend creation task to prevent new tasks from starting during client shutdown.
-if canCreate {+if canCreate && !c.mu.closing {
// Try to enqueue creation task with backpressure handling
if !globalClientGC.triggerCreate(c, backend) {
// Queue is full - fallback to existing creation path with proper bookkeeping
return c.createBackendWithBookkeeping(backend, lock)
}
creationQueued = true
}
Apply / Chat
Suggestion importance[1-10]: 7
__
Why: This is a good suggestion for improving robustness during client shutdown. Checking c.mu.closing before triggering a new backend creation task prevents unnecessary work and potential race conditions or panics if the client closes while a creation task is in flight.
Medium
General
Add minimal sleep on zero backoff
In the retry logic of Send, NewStream, and Ping, add a small sleep (e.g., 10ms) when the calculated backoff is zero to prevent a tight loop that consumes high CPU.
backoff = policy.nextBackoff(backoff)
if backoff > 0 {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(backoff):
}
+} else {+ // prevent busy spin when backoff is zero+ time.Sleep(10 * time.Millisecond)
}
Apply / Chat
Suggestion importance[1-10]: 6
__
Why: The suggestion correctly identifies that a zero backoff can lead to a busy-wait loop, consuming excessive CPU. Adding a small sleep is a standard and effective way to mitigate this, improving system performance under contention.
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
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.
User description
What type of PR is this?
Which issue(s) this PR fixes:
issue #23434
What this PR does / why we need it:
Lock Contention During Backend Creation
Pool Saturation Immediate Failure
Circuit Breaker Not Triggering on Permanent Failures
PR Type
Bug fix, Enhancement
Description
Implement asynchronous backend creation to eliminate lock contention during CN node failures
Add bounded wait timeout for auto-create with circuit breaker integration for fast failure detection
Distinguish transient creation states from permanent unavailability via new error types
Enhance error classification and observability with metrics for backend health and circuit breaker state
Diagram Walkthrough
flowchart LR A["getBackend Request"] --> B{"Circuit Breaker<br/>Check"} B -->|Open| C["Return ErrCircuitOpen<br/>Fast Fail"] B -->|Closed/HalfOpen| D["Check Pool<br/>& Limits"] D -->|Backend Available| E["Return Backend<br/>Success"] D -->|Pool Empty| F{"Auto-Create<br/>Enabled?"} D -->|Pool Busy| G["Return ErrBackendCreating<br/>Trigger Wait"] F -->|Yes| H["Queue Async Creation<br/>Return ErrBackendCreating"] F -->|No| I["Return ErrNoAvailableBackend<br/>Fail Fast"] H --> J["Caller Retries<br/>with Bounded Wait"] J -->|Timeout| K["Record Failure<br/>Return ErrBackendCreateTimeout"] J -->|Success| E K --> L["Circuit Breaker<br/>May Open"]File Walkthrough
1 files
Implement async backend creation and bounded wait logic13 files
Add comprehensive tests for error states and transitionsAdd tests for concurrent access and crash recovery scenariosUpdate existing tests for async creation behaviorAdd helper for async creation and update test expectationsAdd tests for auto-create enable/disable behaviorUpdate tests to pass client name parameterAdd test for ErrBackendCreating status classificationUpdate test expectations for auto-create timeout behaviorUpdate test to expect ErrBackendClosed after timeoutAdd circuit breaker configuration to test clientAdd backend warmup and adjust timeouts for async creationEnable auto-create by default in test clientEnable auto-create in test configuration13 files
Add GetError method and metrics reporting for state changesAdd metrics for auto-create timeout and backend unavailableAdd status classification for new error typesAdd prometheus metrics for backend health and circuit breakerAdd dashboard rows for backend health and circuit breaker metricsRegister new RPC metrics in prometheus registryUse unified error classification for retry logicUse unified error classification for lock retry logicSet bounded wait timeout for fast failure detectionAdd read timeout configuration for backendSet explicit read timeout instead of zeroSet explicit read timeout instead of zeroReduce default RPC read timeout from 2 minutes to 30 seconds1 files
Enforce minimum timeout to prevent misconfiguration1 files
Fix regex patterns for context timeout/deadline checks