nautechsystems/nautilus_trader · critical

Error connecting to Postgres

Error message

Error connecting to Postgres

What it means

BlockchainCacheDatabase::init connects to PostgreSQL via sqlx using the provided `PgConnectOptions` and panics with "Error connecting to Postgres" if the connection fails. The library treats a working database as a hard precondition for the cache, so connection errors are unrecoverable at init time.

Source

Thrown at crates/adapters/blockchain/src/cache/database.rs:325

    token1_chain,
    token1_address,
    fee,
    tick_spacing,
    initial_tick,
    initial_sqrt_price_x96,
    hook_address
";

impl BlockchainCacheDatabase {
    /// Initializes a new database instance by establishing a connection to PostgreSQL.
    ///
    /// # Panics
    ///
    /// Panics if unable to connect to PostgreSQL with the provided options.
    pub async fn init(pg_options: PgConnectOptions) -> Self {
        Self::connect(pg_options)
            .await
            .expect("Error connecting to Postgres")
    }

    /// Establishes a connection to PostgreSQL and returns a new database instance.
    ///
    /// # Errors
    ///
    /// Returns an error if a connection cannot be established with the provided options.
    pub async fn connect(pg_options: PgConnectOptions) -> anyhow::Result<Self> {
        let pool = sqlx::postgres::PgPoolOptions::new()
            .max_connections(32) // Increased from default 10
            .min_connections(5) // Keep some connections warm
            .acquire_timeout(std::time::Duration::from_secs(3))
            .connect_with(pg_options)
            .await?;
        Ok(Self { pool })
    }

    /// Seeds the database with a blockchain chain record.

View on GitHub (pinned to 18893faf8b)

Solutions

  1. Verify the connection options (host, port, user, password, dbname) and test them with `psql`.
  2. Ensure the Postgres server is running and reachable from the process (docker ps, firewall, listen_addresses).
  3. Check TLS/sslmode settings on PgConnectOptions match the server requirement.
  4. Retry with backoff if the failure is transient (startup ordering); or fix the URL in config/env.

Example fix

// before
let db = BlockchainCacheDatabase::init(
    PgConnectOptions::new().host("localhost").port(5433),
).await; // panics if server unreachable
// after
if let Ok(db) = BlockchainCacheDatabase::connect(options).await {
    BlockchainCacheDatabase::init_from(db)
} else {
    // handle: log, backoff, or abort with a clear error
}
Defensive patterns

Strategy: retry

Validate before calling

// Pre-check connectivity before init
let ok = tokio::net::TcpStream::connect((host, port)).await.is_ok();
if !ok { /* fail fast with a clear config error */ }

Try / catch

// Use connect() instead of expect-based init
match BlockchainCacheDatabase::connect(pg_options).await {
    Ok(db) => db,
    Err(e) => { log::error!("Postgres unreachable: {e}"); /* retry with backoff or abort */ }
}

Prevention

When it happens

Trigger: Calling `BlockchainCacheDatabase::init(pg_options)` when the Postgres host/port is wrong, the server is down, credentials are invalid, TLS requirements are unmet, or the network is unreachable.

Common situations: Wrong DATABASE_URL/host in config or environment; Postgres not running or not exposed; bad username/password; SSL mode mismatch (require vs disable); DNS/firewall blocking the port; database does not exist.

Understand the failure class

Background: ECONNREFUSED and "connection refused" / "could not connect to server" errors: what they mean and how to fix them — this error's family across 44 libraries.

Related errors


AI-assisted analysis of nautechsystems/nautilus_trader@18893faf8b (2026-09-08). Data as JSON: /api/errors/78394493fe4da0b2. Report an issue: GitHub.