Skip to content

Conversation

@Abdulkbk
Copy link
Contributor

Change Description

fixes #10522

When LND starts with a Postgres backend, and Postgre isn't ready yet LND fails immediately and exits. There is no retry logic for the initial database connection, forcing users to use shell script workarounds.

This PR does the following:

  • Add startup-max-retries and startup-retry-delay config options to the postgres backend.
  • Add WaitForPostgresReady() that pings postgres in a fixed-delay retry loop before opening the database.
  • Enabled by default (10 attempts, 1s delay), disabled with startup-max-retries=0.

Steps to test

  • Unit tests for retry skip, retry exhaustion, and context cancellation (cd sqldb && go test -v -run TestWaitForPostgres).

@gemini-code-assist
Copy link

Summary of Changes

Hello @Abdulkbk, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances LND's resilience by introducing a retry mechanism for its initial connection to a PostgreSQL database. Previously, LND would fail and exit if the database wasn't immediately available, requiring manual intervention or external workarounds. The new changes allow LND to gracefully wait and retry connecting, making it more robust in dynamic environments like Kubernetes where database services might not start simultaneously with LND.

Highlights

  • Postgres Connection Retry Logic: Implemented robust retry logic for initial Postgres database connections, preventing LND from exiting prematurely if the database is unavailable at startup.
  • Configurable Retry Options: Introduced startup-max-retries and startup-retry-delay configuration options for fine-grained control over the retry behavior.
  • New WaitForPostgresReady Function: Added a new WaitForPostgresReady() function to actively ping the database until it becomes available or retries are exhausted.
  • Comprehensive Unit Tests: Included comprehensive unit tests to validate the retry mechanism's functionality, including scenarios for skipping retries, exhausting attempts, and context cancellation.
  • Documentation Updates: Updated documentation in release notes and sample-lnd.conf to reflect the new features and configuration options.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • docs/release-notes/release-notes-0.21.0.md
    • Added a release note entry detailing the new WaitForPostgresReady function and the startup-max-retries and startup-retry-delay configuration options.
    • Added Abdulkbk to the list of contributors.
  • lncfg/db.go
    • Defined defaultPostgresStartupMaxRetries and defaultPostgresStartupRetryDelay constants.
    • Updated the DefaultDB function to initialize PostgresConfig with these new startup retry parameters.
    • Integrated a call to sqldb.WaitForPostgresReady before attempting to open the Postgres connection.
  • sample-lnd.conf
    • Added commented-out configuration examples and descriptions for db.postgres.startup-max-retries and db.postgres.startup-retry-delay.
  • sqldb/config.go
    • Added StartupMaxRetries and StartupRetryDelay fields to the PostgresConfig struct, including their long flag and description tags.
  • sqldb/postgres.go
    • Implemented the WaitForPostgresReady function, which attempts to ping the Postgres database in a loop, respecting retry limits and delays, and handling context cancellation.
  • sqldb/postgres_wait_test.go
    • Added TestWaitForPostgresReadySkipsWhenDisabled to verify immediate return when retries are disabled.
    • Added TestWaitForPostgresReadyExhaustsRetries to confirm error handling after exhausting retry attempts.
    • Added TestWaitForPostgresReadyContextCancel to ensure proper context cancellation handling during retries.
Activity
  • Unit tests were added for the retry logic, covering scenarios where retries are skipped, exhausted, and when the context is cancelled.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a retry mechanism for the initial PostgreSQL database connection, enhancing LND's resilience in environments like Kubernetes. However, a critical security flaw exists in the WaitForPostgresReady function in sqldb/postgres.go, where sensitive database credentials can be leaked into logs and error messages due to incomplete DSN sanitization. It is recommended to improve the sanitization logic or avoid logging the full DSN. Additionally, consider making the ping timeout configurable for better flexibility.

Comment on lines +201 to +236
sanitizedDSN, err := replacePasswordInDSN(cfg.Dsn)
if err != nil {
return err
}

db, err := sql.Open("pgx", cfg.Dsn)
if err != nil {
return fmt.Errorf("error creating postgres connection: %w",
err)
}
defer db.Close()

for attempt := 0; attempt < cfg.StartupMaxRetries; attempt++ {
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err = db.PingContext(pingCtx)
cancel()

if err == nil {
log.Infof("Postgres is ready at '%s'", sanitizedDSN)
return nil
}

log.Warnf("Failed to connect to postgres at '%s' "+
"(attempt %d/%d): %v", sanitizedDSN, attempt+1,
cfg.StartupMaxRetries, err)

select {
case <-time.After(cfg.StartupRetryDelay):
case <-ctx.Done():
return fmt.Errorf("context canceled while waiting "+
"for postgres: %w", ctx.Err())
}
}

return fmt.Errorf("failed to connect to postgres at '%s' after %d "+
"attempts: %w", sanitizedDSN, cfg.StartupMaxRetries, err)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The WaitForPostgresReady function in this section (lines 201-236) has a critical security flaw: sensitive database credentials (passwords) can be leaked into application logs and error messages. The replacePasswordInDSN function (defined at line 48) only sanitizes DSNs in URL format, failing to handle "keyword=value" formats. This can result in unsanitized passwords being logged (lines 219, 223) or included in errors (line 235). It is crucial to improve replacePasswordInDSN to robustly sanitize both DSN formats or avoid logging the full DSN. Furthermore, the ping timeout is currently hardcoded to 5 seconds (lines 214-215). For better flexibility and environmental tuning, consider making this configurable by utilizing cfg.Timeout from PostgresConfig if available, otherwise defaulting to 5 seconds.

Suggested change
sanitizedDSN, err := replacePasswordInDSN(cfg.Dsn)
if err != nil {
return err
}
db, err := sql.Open("pgx", cfg.Dsn)
if err != nil {
return fmt.Errorf("error creating postgres connection: %w",
err)
}
defer db.Close()
for attempt := 0; attempt < cfg.StartupMaxRetries; attempt++ {
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err = db.PingContext(pingCtx)
cancel()
if err == nil {
log.Infof("Postgres is ready at '%s'", sanitizedDSN)
return nil
}
log.Warnf("Failed to connect to postgres at '%s' "+
"(attempt %d/%d): %v", sanitizedDSN, attempt+1,
cfg.StartupMaxRetries, err)
select {
case <-time.After(cfg.StartupRetryDelay):
case <-ctx.Done():
return fmt.Errorf("context canceled while waiting "+
"for postgres: %w", ctx.Err())
}
}
return fmt.Errorf("failed to connect to postgres at '%s' after %d "+
"attempts: %w", sanitizedDSN, cfg.StartupMaxRetries, err)
pingTimeout := 5 * time.Second
if cfg.Timeout > 0 {
pingTimeout = cfg.Timeout
}
pingCtx, cancel := context.WithTimeout(ctx, pingTimeout)
err = db.PingContext(pingCtx)

Add StartupMaxRetries and StartupRetryDelay fields to PostgresConfig
to control connection retry behavior at startup. This prepares for
retry logic that helps in environments like Kubernetes where the
database container may not be ready when LND starts.
Add a WaitForPostgresReady function that pings postgres in a retry
loop with a fixed delay before any backends are opened. This prevents
LND from failing immediately with "connection refused" when postgres
isn't ready yet.

The function is called at the top of the PostgresBackend case in
GetBackends, gating all downstream connection attempts. Retries are
enabled by default (10 attempts, 1s delay) and can be disabled by
setting startup-max-retries=0.
@lightninglabs-deploy
Copy link
Collaborator

🟠 PR Severity: HIGH

sqldb package | 7 files | 174 lines changed

🟠 High (2 files)
  • sqldb/config.go - Database configuration for Postgres backend
  • sqldb/postgres.go - Database connection initialization and retry logic
🟡 Medium (1 file)
  • lncfg/db.go - Configuration options for startup retry behavior
🟢 Low (4 files)
  • docs/postgres.md - Documentation
  • docs/release-notes/release-notes-0.21.0.md - Release notes
  • sample-lnd.conf - Configuration sample
  • sqldb/postgres_wait_test.go - Test file

Analysis

This PR adds retry logic for Postgres database connections during LND startup. The highest severity comes from changes to the sqldb/ package, which manages the Postgres backend implementation.

Key areas of impact:

  • Modifies database initialization flow in sqldb/postgres.go with new WaitForPostgresReady() function
  • Adds startup configuration options (startup-max-retries, startup-retry-delay)
  • Changes affect critical startup path before database is opened

Why HIGH severity:

  • The sqldb package handles database backend operations (categorized as HIGH)
  • Changes modify core initialization logic that could affect startup reliability
  • While adding defensive retry logic is generally safe, errors in connection handling could prevent LND from starting or cause startup delays

Mitigating factors:

  • Small, focused change (~84 non-test/doc lines)
  • Includes comprehensive unit tests for retry scenarios
  • Feature can be disabled with startup-max-retries=0

To override, add a severity-override-{critical,high,medium,low} label.

@lightninglabs-deploy
Copy link
Collaborator

🟠 PR Severity: HIGH

sqldb database operations | 7 files | 174 lines changed

🟠 High (2 files)
  • sqldb/config.go - Database configuration options
  • sqldb/postgres.go - Postgres connection retry logic with startup wait mechanism
🟡 Medium (1 file)
  • lncfg/db.go - Configuration management for database retry settings
🟢 Low (3 files)
  • docs/postgres.md - Documentation updates
  • docs/release-notes/release-notes-0.21.0.md - Release notes
  • sample-lnd.conf - Configuration sample file
🧪 Test Files (1 file, excluded from severity)
  • sqldb/postgres_wait_test.go - Unit tests for retry logic

Analysis

This PR is classified as HIGH severity because it modifies core database connection logic in the sqldb/ package. While the changes add retry logic for improved reliability (a positive enhancement), they affect how LND establishes its initial database connection, which is a critical startup operation.

Key considerations:

  • The retry mechanism is enabled by default (10 attempts, 1s delay), changing startup behavior for all Postgres users
  • Connection initialization is a sensitive area - bugs here could prevent LND from starting or cause unexpected delays
  • The implementation looks solid with proper context handling and configurable timeouts, but should be reviewed by engineers familiar with the sqldb layer

The configuration changes in lncfg/ are supportive but the driving factor is the database operation modifications.


To override, add a severity-override-{critical,high,medium,low} label.

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.

[bug]: startup: no retry on postgres DB connection refused

2 participants