-
Notifications
You must be signed in to change notification settings - Fork 1.5k
feat(bigtable): add preemptive connection recycler #13860
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+288
−3
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| // Copyright 2026 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package internal | ||
sushanb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| import ( | ||
| "context" | ||
| "math/rand" | ||
| "sync" | ||
| "time" | ||
|
|
||
| btopt "cloud.google.com/go/bigtable/internal/option" | ||
| ) | ||
|
|
||
| // maxRecyclePerBatch limits the number of connections we replace in a single pass. | ||
| const maxRecyclePerBatch = 2 | ||
|
|
||
| // ConnectionRecycler monitors connection age and recycles them to prevent long-lived connections. | ||
| type ConnectionRecycler struct { | ||
| pool *BigtableChannelPool | ||
| config btopt.ConnectionRecycleConfig | ||
| ticker *time.Ticker | ||
| done chan struct{} | ||
| stopOnce sync.Once | ||
| rng *rand.Rand | ||
| } | ||
|
|
||
| // NewConnectionRecycler creates a new recycler with the provided configuration. | ||
| func NewConnectionRecycler(config btopt.ConnectionRecycleConfig, pool *BigtableChannelPool) *ConnectionRecycler { | ||
| return &ConnectionRecycler{ | ||
| pool: pool, | ||
| config: config, | ||
| done: make(chan struct{}), | ||
| rng: rand.New(rand.NewSource(time.Now().UnixNano())), | ||
sushanb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
|
|
||
| // Start begins the periodic monitoring. | ||
| func (cr *ConnectionRecycler) Start(ctx context.Context) { | ||
| btopt.Debugf(cr.pool.logger, "bigtable_connpool: ConnectionRecyler starting...") | ||
sushanb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // default to 1 minute | ||
| freq := cr.config.RunFrequency | ||
sushanb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if freq < 1*time.Minute { | ||
| freq = 1 * time.Minute | ||
| } | ||
sushanb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // at least once per MaxAge interval. | ||
| if cr.config.MaxAge > 0 && freq > cr.config.MaxAge { | ||
| freq = cr.config.MaxAge | ||
| } | ||
|
|
||
| cr.ticker = time.NewTicker(freq) | ||
| go func() { | ||
| defer cr.ticker.Stop() | ||
| for { | ||
| select { | ||
| case <-cr.ticker.C: | ||
| cr.checkRecycle() | ||
| case <-cr.done: | ||
| return | ||
| case <-ctx.Done(): | ||
| return | ||
| } | ||
| } | ||
| }() | ||
| } | ||
|
|
||
| // Stop terminates the ConnectionRecycler. | ||
| func (cr *ConnectionRecycler) Stop() { | ||
| cr.stopOnce.Do(func() { | ||
| close(cr.done) | ||
| }) | ||
| } | ||
|
|
||
| // background period task | ||
| func (cr *ConnectionRecycler) checkRecycle() { | ||
| conns := cr.pool.getConns() | ||
| recycledCount := 0 | ||
|
|
||
| hasJitter := cr.config.MaxJitter > 0 | ||
| jitterVal := int64(cr.config.MaxJitter) | ||
|
|
||
| for _, entry := range conns { | ||
| if recycledCount >= maxRecyclePerBatch { | ||
| btopt.Debugf(cr.pool.logger, "bigtable_connpool: Hit max recycle cap (%d) for this round", maxRecyclePerBatch) | ||
| break | ||
| } | ||
|
|
||
| createdAt := time.UnixMilli(entry.createdAt()) | ||
| age := time.Since(createdAt) | ||
|
|
||
| var currentJitter time.Duration | ||
| if hasJitter { | ||
| currentJitter = time.Duration(cr.rng.Int63n(jitterVal)) | ||
| } | ||
|
|
||
| if age > cr.config.MaxAge+currentJitter { | ||
| btopt.Debugf(cr.pool.logger, "bigtable_connpool: Recycling connection age %v > %v + %v", age, cr.config.MaxAge, currentJitter) | ||
| cr.pool.replaceConnection(entry) | ||
| recycledCount++ | ||
| } | ||
| } | ||
| } | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| // Copyright 2026 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package internal | ||
|
|
||
| import ( | ||
| "context" | ||
| "testing" | ||
| "time" | ||
|
|
||
| btopt "cloud.google.com/go/bigtable/internal/option" | ||
| ) | ||
|
|
||
| func TestConnectionRecycler_CheckRecycle(t *testing.T) { | ||
| fake := &fakeService{} | ||
| addr := setupTestServer(t, fake) | ||
| dialFunc := func() (*BigtableConn, error) { return dialBigtableserver(addr) } | ||
| ctx := context.Background() | ||
|
|
||
| setAge := func(entry *connEntry, age time.Duration) { | ||
| entry.conn.createdAt.Store(time.Now().Add(-age).UnixMilli()) | ||
| } | ||
|
|
||
| t.Run("RecycleOldConnection", func(t *testing.T) { | ||
| config := btopt.ConnectionRecycleConfig{ | ||
| MaxAge: 10 * time.Minute, | ||
| MaxJitter: 0, | ||
| } | ||
|
|
||
| pool, err := NewBigtableChannelPool(ctx, 1, btopt.RoundRobin, dialFunc, time.Now()) | ||
| if err != nil { | ||
| t.Fatalf("Failed to create pool: %v", err) | ||
| } | ||
| defer pool.Close() | ||
|
|
||
| recycler := NewConnectionRecycler(config, pool) | ||
|
|
||
| conns := pool.getConns() | ||
| if len(conns) != 1 { | ||
| t.Fatalf("Expected 1 connection, got %d", len(conns)) | ||
| } | ||
| originalEntry := conns[0] | ||
| originalConnPtr := originalEntry.conn | ||
|
|
||
| // maxAge > 20m | ||
| setAge(originalEntry, 20*time.Minute) | ||
| recycler.checkRecycle() | ||
|
|
||
| // recycled fast as it does not have any pending rpcs | ||
| newConns := pool.getConns() | ||
| if newConns[0].conn == originalConnPtr { | ||
| t.Error("Connection was older than MaxAge but was NOT recycled") | ||
| } | ||
| }) | ||
|
|
||
| t.Run("DoesNotReplaceIfConnWithinMaxAge", func(t *testing.T) { | ||
| config := btopt.ConnectionRecycleConfig{ | ||
| MaxAge: 10 * time.Minute, | ||
| MaxJitter: 0, | ||
| } | ||
|
|
||
| pool, err := NewBigtableChannelPool(ctx, 1, btopt.RoundRobin, dialFunc, time.Now()) | ||
| if err != nil { | ||
| t.Fatalf("Failed to create pool: %v", err) | ||
| } | ||
| defer pool.Close() | ||
|
|
||
| recycler := NewConnectionRecycler(config, pool) | ||
|
|
||
| entry := pool.getConns()[0] | ||
| originalConnPtr := entry.conn | ||
|
|
||
| // < 10mins | ||
| setAge(entry, 5*time.Minute) | ||
|
|
||
| // recycled fast as it does not have any pending rpcs | ||
| recycler.checkRecycle() | ||
|
|
||
| if pool.getConns()[0].conn != originalConnPtr { | ||
| t.Error("Connection WAS recycled unexpectedly") | ||
| } | ||
| }) | ||
|
|
||
| t.Run("RespectsMaxRecyclePerBatch", func(t *testing.T) { | ||
| config := btopt.ConnectionRecycleConfig{ | ||
| MaxAge: 10 * time.Minute, | ||
| MaxJitter: 0, | ||
| } | ||
| // 5 conns | ||
| poolSize := 5 | ||
| pool, err := NewBigtableChannelPool(ctx, poolSize, btopt.RoundRobin, dialFunc, time.Now()) | ||
| if err != nil { | ||
| t.Fatalf("Failed to create pool: %v", err) | ||
| } | ||
| defer pool.Close() | ||
|
|
||
| recycler := NewConnectionRecycler(config, pool) | ||
|
|
||
| // force age to be old | ||
| conns := pool.getConns() | ||
| originalConns := make(map[*BigtableConn]bool) | ||
| for _, e := range conns { | ||
| setAge(e, 60*time.Minute) | ||
| originalConns[e.conn] = true | ||
| } | ||
|
|
||
| // Trigger recycle | ||
| recycler.checkRecycle() | ||
|
|
||
| currentConns := pool.getConns() | ||
| changedCount := 0 | ||
| for _, e := range currentConns { | ||
| if !originalConns[e.conn] { | ||
| changedCount++ | ||
| } | ||
| } | ||
| if changedCount != maxRecyclePerBatch { | ||
| t.Errorf("Expected exactly %d recycled connections (batch limit), but got %d", maxRecyclePerBatch, changedCount) | ||
| } | ||
| }) | ||
| } |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This makes the code a little hard to read. Is it possible to have a constructor function that returns true for these variables by default?