{"record":{"id":"33cfa5e2a48ac723","repo":"nautechsystems/nautilus_trader","slug":"failed-to-connect-after-max-attempts-attempts","errorCode":null,"errorMessage":"Failed to connect after {max_attempts} attempts","messagePattern":"Failed to connect after (.+?) attempts","errorType":"exception","errorClass":"anyhow::Error","httpStatus":null,"severity":"error","filePath":"crates/adapters/interactive_brokers/src/common/connection.rs","lineNumber":99,"sourceCode":"    ///\n    /// # Returns\n    ///\n    /// Returns the connected client on success.\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if connection fails after max attempts.\n    pub async fn connect_with_retry(&self) -> anyhow::Result<Arc<Client>> {\n        const MAX_BACKOFF: Duration = Duration::from_secs(60);\n        let mut attempt = 0;\n        let mut backoff = Duration::from_secs(1);\n\n        loop {\n            attempt += 1;\n            self.attempt_count.store(attempt, Ordering::Relaxed);\n\n            if !self.retry_indefinitely && attempt > self.max_attempts {\n                anyhow::bail!(\"Failed to connect after {} attempts\", self.max_attempts);\n            }\n\n            tracing::debug!(\n                \"Connection attempt {} to {}:{} (client_id: {})\",\n                attempt,\n                self.host,\n                self.port,\n                self.client_id\n            );\n\n            let address = format!(\"{}:{}\", self.host, self.port);\n            match Client::connect(&address, self.client_id).await {\n                Ok(client) => {\n                    tracing::info!(\n                        \"Successfully connected to IB Gateway/TWS at {} (client_id: {})\",\n                        address,\n                        self.client_id\n                    );","sourceCodeStart":81,"sourceCodeEnd":117,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/adapters/interactive_brokers/src/common/connection.rs#L81-L117","documentation":"connect_with_retry in the Interactive Brokers connection manager gives up after exhausting the configured attempt budget: when retry_indefinitely is false and the attempt counter exceeds max_attempts, it bails with this error. It signals that the TWS/IB Gateway socket could not be established within the allowed retries, aborting the connection attempt.","triggerScenarios":"Calling connect/connect_with_retry on the IB connection when the host:port is unreachable (TWS/Gateway not running, wrong port, firewall) and max_attempts is exceeded with retry_indefinitely=false. Also produced immediately if max_attempts is configured to 0 or 1 and the first connect fails.","commonSituations":"TWS or IB Gateway not started or not listening on the API port (default 7497/4001); wrong host in config (localhost vs remote container); paper vs live account port mix-up; Docker networking blocking the socket; very low max_attempts with a slow-to-start gateway.","solutions":["Verify TWS/IB Gateway is running and API connections are enabled with the correct listening port; restart it if needed.","Check host/port configuration (and paper vs live port: 7497/7496, Gateway 4002/4001) and network reachability (telnet/nc the port).","Increase max_attempts and the retry backoff in the connection config to tolerate slow gateway startup.","Set retry_indefinitely=true if the process should keep retrying until the gateway becomes available.","Catch this error at startup and re-attempt after a delay (e.g. waiting for the gateway container to become healthy)."],"exampleFix":"// before\nlet conn = IbConnection::new(\"127.0.0.1\", 7497, /* max_attempts */ 3);\nconn.connect_with_retry().await?;\n// after\nlet conn = IbConnection::new(\"127.0.0.1\", 7497, /* max_attempts */ 10);\nmatch conn.connect_with_retry().await {\n    Ok(()) => {}\n    Err(e) => {\n        tokio::time::sleep(Duration::from_secs(5)).await;\n        conn.connect_with_retry().await?;\n    }\n}","handlingStrategy":"retry","validationCode":"// pre-check reachability before connect_with_retry\nlet reachable = tokio::net::TcpStream::connect((host, port)).await.is_ok();\nif !reachable {\n    anyhow::bail!(\"IB gateway at {host}:{port} unreachable; start TWS/Gateway first\");\n}","typeGuard":null,"tryCatchPattern":"match conn.connect_with_retry().await {\n    Ok(()) => {}\n    Err(e) if e.to_string().contains(\"Failed to connect after\") => {\n        tracing::error!(\"gateway down: {e}; retrying in 30s\");\n        tokio::time::sleep(Duration::from_secs(30)).await;\n        conn.connect_with_retry().await?;\n    }\n    Err(e) => return Err(e),\n}","preventionTips":["Health-check the TWS/Gateway port before starting the trading process","Configure generous max_attempts and backoff for gateway startup windows","Use the correct paper (7497/4002) vs live (7496/4001) port","Set retry_indefinitely=true for long-running live processes"],"tags":["interactive-brokers","network","connection","retry","rust"],"backgroundTag":"connection-refused","analyzedSha":"18893faf8b356be3320add8de2f861b0b647cf06","analyzedAt":"2026-09-08T20:49:34.690Z","contentChangedAt":"2026-09-08T20:49:34.690Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}