-
Notifications
You must be signed in to change notification settings - Fork 24
database: add failover-safe pool defaults and pgxpool health checks for Postgres/AlloyDB #490
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
Open
stevemsmith
wants to merge
4
commits into
moov-io:master
Choose a base branch
from
stevemsmith:fix/alloydb-failover-recovery
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
840e9d8
database: add failover-safe defaults and retry logic for Postgres/All…
stevemsmith e7bac19
database: use pgxpool with HealthCheckPeriod under the hood
stevemsmith 9322e7b
database: lower HealthCheckPeriod from 5s to 1s
stevemsmith 22a1b6f
database: address review feedback from Gemini
stevemsmith 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
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 |
|---|---|---|
|
|
@@ -5,12 +5,14 @@ import ( | |
| "database/sql" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "net" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "cloud.google.com/go/alloydbconn" | ||
| "github.com/jackc/pgx/v5" | ||
| "github.com/jackc/pgx/v5/pgconn" | ||
| "github.com/jackc/pgx/v5/pgxpool" | ||
| "github.com/jackc/pgx/v5/stdlib" | ||
| "github.com/moov-io/base/log" | ||
| ) | ||
|
|
@@ -23,67 +25,50 @@ const ( | |
| ) | ||
|
|
||
| func postgresConnection(ctx context.Context, logger log.Logger, config PostgresConfig, databaseName string) (*sql.DB, error) { | ||
| var connStr string | ||
| if config.Alloy != nil { | ||
| c, err := getAlloyDBConnectorConnStr(ctx, config, databaseName) | ||
| if err != nil { | ||
| return nil, logger.LogErrorf("creating alloydb connection: %w", err).Err() | ||
| } | ||
| connStr = c | ||
| } else { | ||
| c, err := getPostgresConnStr(config, databaseName) | ||
| if err != nil { | ||
| return nil, logger.LogErrorf("creating postgres connection: %w", err).Err() | ||
| } | ||
| connStr = c | ||
| poolConfig, err := buildPgxPoolConfig(ctx, config, databaseName) | ||
| if err != nil { | ||
| return nil, logger.LogErrorf("building pgx pool config: %w", err).Err() | ||
| } | ||
|
|
||
| db, err := sql.Open("pgx", connStr) | ||
| // HealthCheckPeriod makes pgxpool ping idle connections in the background. | ||
| // Dead connections (e.g. from an AlloyDB switchover) are evicted before | ||
| // the application ever sees them. | ||
| poolConfig.HealthCheckPeriod = 1 * time.Second | ||
|
|
||
| pool, err := pgxpool.NewWithConfig(ctx, poolConfig) | ||
| if err != nil { | ||
| return nil, logger.LogErrorf("opening database: %w", err).Err() | ||
| return nil, logger.LogErrorf("creating pgx pool: %w", err).Err() | ||
| } | ||
|
|
||
| err = db.Ping() | ||
| err = pool.Ping(ctx) | ||
| if err != nil { | ||
| _ = db.Close() | ||
| pool.Close() | ||
| return nil, logger.LogErrorf("connecting to database: %w", err).Err() | ||
| } | ||
|
|
||
| // Wrap the pgxpool in a *sql.DB so the rest of the codebase doesn't change. | ||
| // pgxpool manages the real pool (with health checks); database/sql pool | ||
| // settings are applied on top via ApplyPostgresConnectionsConfig. | ||
| db := stdlib.OpenDBFromPool(pool) | ||
|
|
||
| return db, nil | ||
| } | ||
|
|
||
| func getPostgresConnStr(config PostgresConfig, databaseName string) (string, error) { | ||
| url := fmt.Sprintf("postgres://%s:%s@%s/%s", config.User, config.Password, config.Address, databaseName) | ||
|
|
||
| params := "" | ||
|
|
||
| if config.TLS != nil { | ||
| if len(config.TLS.Mode) < 1 { | ||
| config.TLS.Mode = "verify-full" | ||
| } | ||
|
|
||
| params += "sslmode=" + config.TLS.Mode | ||
|
|
||
| if len(config.TLS.CACertFile) > 0 { | ||
| params += "&sslrootcert=" + config.TLS.CACertFile | ||
| } | ||
|
|
||
| if len(config.TLS.ClientCertFile) > 0 { | ||
| params += "&sslcert=" + config.TLS.ClientCertFile | ||
| } | ||
|
|
||
| if len(config.TLS.ClientKeyFile) > 0 { | ||
| params += "&sslkey=" + config.TLS.ClientKeyFile | ||
| } | ||
| func buildPgxPoolConfig(ctx context.Context, config PostgresConfig, databaseName string) (*pgxpool.Config, error) { | ||
| if config.Alloy != nil { | ||
| return buildAlloyDBPoolConfig(ctx, config, databaseName) | ||
| } | ||
|
|
||
| connStr := fmt.Sprintf("%s?%s", url, params) | ||
| return connStr, nil | ||
| connStr, err := getPostgresConnStr(config, databaseName) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return pgxpool.ParseConfig(connStr) | ||
| } | ||
|
|
||
| func getAlloyDBConnectorConnStr(ctx context.Context, config PostgresConfig, databaseName string) (string, error) { | ||
| func buildAlloyDBPoolConfig(ctx context.Context, config PostgresConfig, databaseName string) (*pgxpool.Config, error) { | ||
| if config.Alloy == nil { | ||
| return "", fmt.Errorf("missing alloy config") | ||
| return nil, fmt.Errorf("missing alloy config") | ||
| } | ||
|
|
||
| var dialer *alloydbconn.Dialer | ||
|
|
@@ -92,7 +77,7 @@ func getAlloyDBConnectorConnStr(ctx context.Context, config PostgresConfig, data | |
| if config.Alloy.UseIAM { | ||
| d, err := alloydbconn.NewDialer(ctx, alloydbconn.WithIAMAuthN()) | ||
| if err != nil { | ||
| return "", fmt.Errorf("creating alloydb dialer: %v", err) | ||
| return nil, fmt.Errorf("creating alloydb dialer: %v", err) | ||
| } | ||
| dialer = d | ||
| dsn = fmt.Sprintf( | ||
|
|
@@ -104,7 +89,7 @@ func getAlloyDBConnectorConnStr(ctx context.Context, config PostgresConfig, data | |
| } else { | ||
| d, err := alloydbconn.NewDialer(ctx) | ||
| if err != nil { | ||
| return "", fmt.Errorf("creating alloydb dialer: %v", err) | ||
| return nil, fmt.Errorf("creating alloydb dialer: %v", err) | ||
| } | ||
| dialer = d | ||
| dsn = fmt.Sprintf( | ||
|
|
@@ -114,24 +99,49 @@ func getAlloyDBConnectorConnStr(ctx context.Context, config PostgresConfig, data | |
| ) | ||
| } | ||
|
|
||
| // TODO | ||
| //cleanup := func() error { return d.Close() } | ||
|
|
||
| connConfig, err := pgx.ParseConfig(dsn) | ||
| poolConfig, err := pgxpool.ParseConfig(dsn) | ||
| if err != nil { | ||
| return "", fmt.Errorf("failed to parse pgx config: %v", err) | ||
| return nil, fmt.Errorf("failed to parse pgx pool config: %v", err) | ||
| } | ||
|
|
||
| var connOptions []alloydbconn.DialOption | ||
| if config.Alloy.UsePSC { | ||
| connOptions = append(connOptions, alloydbconn.WithPSC()) | ||
| } | ||
|
|
||
| connConfig.DialFunc = func(ctx context.Context, _ string, _ string) (net.Conn, error) { | ||
| poolConfig.ConnConfig.DialFunc = func(ctx context.Context, _ string, _ string) (net.Conn, error) { | ||
| return dialer.Dial(ctx, config.Alloy.InstanceURI, connOptions...) | ||
| } | ||
|
|
||
| connStr := stdlib.RegisterConnConfig(connConfig) | ||
| return poolConfig, nil | ||
| } | ||
|
|
||
| func getPostgresConnStr(config PostgresConfig, databaseName string) (string, error) { | ||
| url := fmt.Sprintf("postgres://%s:%s@%s/%s", config.User, config.Password, config.Address, databaseName) | ||
|
|
||
| params := "" | ||
|
|
||
| if config.TLS != nil { | ||
| if len(config.TLS.Mode) < 1 { | ||
| config.TLS.Mode = "verify-full" | ||
| } | ||
|
|
||
| params += "sslmode=" + config.TLS.Mode | ||
|
|
||
| if len(config.TLS.CACertFile) > 0 { | ||
| params += "&sslrootcert=" + config.TLS.CACertFile | ||
| } | ||
|
|
||
| if len(config.TLS.ClientCertFile) > 0 { | ||
| params += "&sslcert=" + config.TLS.ClientCertFile | ||
| } | ||
|
|
||
| if len(config.TLS.ClientKeyFile) > 0 { | ||
| params += "&sslkey=" + config.TLS.ClientKeyFile | ||
| } | ||
| } | ||
|
|
||
| connStr := fmt.Sprintf("%s?%s", url, params) | ||
| return connStr, nil | ||
| } | ||
|
|
||
|
|
@@ -164,3 +174,77 @@ func PostgresDeadlockFound(err error) bool { | |
|
|
||
| return strings.Contains(err.Error(), postgresErrDeadlockFound) | ||
| } | ||
|
|
||
| // IsRetryablePostgresError returns true if the error is a transient connection-level | ||
| // error that is safe to retry. This covers the errors seen during AlloyDB maintenance | ||
| // switchovers and other transient network failures. | ||
| func IsRetryablePostgresError(err error) bool { | ||
| if err == nil { | ||
| return false | ||
| } | ||
|
|
||
| // PostgreSQL error codes indicating the server is shutting down or unavailable | ||
| var pgErr *pgconn.PgError | ||
| if errors.As(err, &pgErr) { | ||
| switch pgErr.Code { | ||
| case "57P01", "57P02", "57P03": // admin_shutdown, crash_shutdown, cannot_connect_now | ||
| return true | ||
| case "08000", "08001", "08003", "08004", "08006": // connection_exception class | ||
| return true | ||
| } | ||
|
adamdecaf marked this conversation as resolved.
|
||
| return false | ||
| } | ||
|
|
||
| // Network-level errors: connection reset, broken pipe, EOF, etc. | ||
| // These occur when the TCP connection is severed during a switchover. | ||
| var netErr *net.OpError | ||
| if errors.As(err, &netErr) { | ||
| return true | ||
| } | ||
| if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) { | ||
| return true | ||
| } | ||
| if errors.Is(err, context.DeadlineExceeded) { | ||
| return false // don't retry if the caller's context timed out | ||
| } | ||
|
|
||
| // pgx wraps connection errors with these messages | ||
| msg := err.Error() | ||
| if strings.Contains(msg, "connection reset by peer") || | ||
| strings.Contains(msg, "broken pipe") || | ||
| strings.Contains(msg, "connection refused") || | ||
| strings.Contains(msg, "unexpected EOF") || | ||
| strings.Contains(msg, "conn closed") { | ||
| return true | ||
| } | ||
|
|
||
| return false | ||
| } | ||
|
|
||
| // RetryPostgres executes fn up to maxAttempts times, retrying on transient | ||
| // connection errors. This is intended for use around individual database | ||
| // operations to survive brief outages like AlloyDB maintenance switchovers. | ||
| func RetryPostgres(ctx context.Context, maxAttempts int, fn func() error) error { | ||
| if maxAttempts <= 0 { | ||
| maxAttempts = 3 | ||
| } | ||
| var err error | ||
| for attempt := 0; attempt < maxAttempts; attempt++ { | ||
| err = fn() | ||
| if err == nil { | ||
| return nil | ||
| } | ||
| if !IsRetryablePostgresError(err) { | ||
| return err | ||
| } | ||
| if attempt < maxAttempts-1 { | ||
| backoff := time.Duration(attempt+1) * 200 * time.Millisecond | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Backoff is a bad idea in this case as you'll drastically increase the wait, along with it not being configurable. 200ms is an ETERNITY to a program, and is noticeable by a user. Theirs also no variance in this interface, so they will all slam at the same time. |
||
| select { | ||
| case <-ctx.Done(): | ||
| return ctx.Err() | ||
| case <-time.After(backoff): | ||
| } | ||
| } | ||
| } | ||
| return err | ||
| } | ||
Oops, something went wrong.
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.
I want to see documentation on these error cases as being valid to retry. Unsure I trust an AI here with possible data corruption if its incorrect. Or just remove the retry stuff and put it into a different PR.