{"record":{"id":"78394493fe4da0b2","repo":"nautechsystems/nautilus_trader","slug":"error-connecting-to-postgres","errorCode":null,"errorMessage":"Error connecting to Postgres","messagePattern":"Error connecting to Postgres","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"crates/adapters/blockchain/src/cache/database.rs","lineNumber":325,"sourceCode":"    token1_chain,\n    token1_address,\n    fee,\n    tick_spacing,\n    initial_tick,\n    initial_sqrt_price_x96,\n    hook_address\n\";\n\nimpl BlockchainCacheDatabase {\n    /// Initializes a new database instance by establishing a connection to PostgreSQL.\n    ///\n    /// # Panics\n    ///\n    /// Panics if unable to connect to PostgreSQL with the provided options.\n    pub async fn init(pg_options: PgConnectOptions) -> Self {\n        Self::connect(pg_options)\n            .await\n            .expect(\"Error connecting to Postgres\")\n    }\n\n    /// Establishes a connection to PostgreSQL and returns a new database instance.\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if a connection cannot be established with the provided options.\n    pub async fn connect(pg_options: PgConnectOptions) -> anyhow::Result<Self> {\n        let pool = sqlx::postgres::PgPoolOptions::new()\n            .max_connections(32) // Increased from default 10\n            .min_connections(5) // Keep some connections warm\n            .acquire_timeout(std::time::Duration::from_secs(3))\n            .connect_with(pg_options)\n            .await?;\n        Ok(Self { pool })\n    }\n\n    /// Seeds the database with a blockchain chain record.","sourceCodeStart":307,"sourceCodeEnd":343,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/adapters/blockchain/src/cache/database.rs#L307-L343","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Verify the connection options (host, port, user, password, dbname) and test them with `psql`.","Ensure the Postgres server is running and reachable from the process (docker ps, firewall, listen_addresses).","Check TLS/sslmode settings on PgConnectOptions match the server requirement.","Retry with backoff if the failure is transient (startup ordering); or fix the URL in config/env."],"exampleFix":"// before\nlet db = BlockchainCacheDatabase::init(\n    PgConnectOptions::new().host(\"localhost\").port(5433),\n).await; // panics if server unreachable\n// after\nif let Ok(db) = BlockchainCacheDatabase::connect(options).await {\n    BlockchainCacheDatabase::init_from(db)\n} else {\n    // handle: log, backoff, or abort with a clear error\n}","handlingStrategy":"retry","validationCode":"// Pre-check connectivity before init\nlet ok = tokio::net::TcpStream::connect((host, port)).await.is_ok();\nif !ok { /* fail fast with a clear config error */ }","typeGuard":null,"tryCatchPattern":"// Use connect() instead of expect-based init\nmatch BlockchainCacheDatabase::connect(pg_options).await {\n    Ok(db) => db,\n    Err(e) => { log::error!(\"Postgres unreachable: {e}\"); /* retry with backoff or abort */ }\n}","preventionTips":["Validate DATABASE_URL/host/port/credentials with psql before launching.","Ensure Postgres is running and reachable (docker, firewall, listen_addresses).","Match sslmode on PgConnectOptions to the server's TLS requirement.","Add startup retry/backoff for database-dependent services."],"tags":["postgres","database","connection","panic"],"backgroundTag":"connection-refused","analyzedSha":"18893faf8b356be3320add8de2f861b0b647cf06","analyzedAt":"2026-09-08T20:49:34.690Z","contentChangedAt":"2026-09-08T20:49:34.690Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}