{"record":{"id":"fc036e665182cb99","repo":"nautechsystems/nautilus_trader","slug":"timed-out-connecting-to-ib-gateway-tws-after-s","errorCode":null,"errorMessage":"Timed out connecting to IB Gateway/TWS after {}s","messagePattern":"Timed out connecting to IB Gateway/TWS after (.+?)s","errorType":"exception","errorClass":"anyhow::Error","httpStatus":null,"severity":"error","filePath":"crates/adapters/interactive_brokers/src/common/shared_client.rs","lineNumber":171,"sourceCode":"            host,\n            port,\n            client_id,\n            ref_count_val\n        );\n        return Ok(SharedClientHandle::new(client, registry, key));\n    }\n\n    let address = format!(\"{host}:{port}\");\n    let connect_timeout = Duration::from_secs(connection_timeout_secs);\n    log::debug!(\n        \"No shared IB client found, establishing new connection to {} with timeout {:?}\",\n        address,\n        connect_timeout\n    );\n    let client = tokio::time::timeout(connect_timeout, Client::connect(&address, client_id))\n        .await\n        .map_err(|_| {\n            anyhow::anyhow!(\n                \"Timed out connecting to IB Gateway/TWS after {}s\",\n                connection_timeout_secs\n            )\n        })?\n        .context(\"Failed to connect to IB Gateway/TWS\")?;\n    let client = Arc::new(client);\n\n    {\n        let mut guard = registry.lock();\n        log::debug!(\n            \"Registering shared IB client in registry (host={}, port={}, client_id={})\",\n            host,\n            port,\n            client_id\n        );\n        guard.insert(key.clone(), (Arc::clone(&client), 1));\n    }\n","sourceCodeStart":153,"sourceCodeEnd":189,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/adapters/interactive_brokers/src/common/shared_client.rs#L153-L189","documentation":"The IB shared client wraps `ibapi::Client::connect` in a `tokio::time::timeout` using the configured `connect_timeout`. When the TCP/IB handshake does not complete in time, it raises this timeout error. Note the message interpolates `connection_timeout_secs` while the timeout uses `connect_timeout`, so verify both config values agree.","triggerScenarios":"Calling `get_or_connect` (on first use of the cached IB client) when IB Gateway/TWS is not running, is listening on a different host/port, or accepts the TCP connection but never completes the `Client::connect` handshake within `connect_timeout` seconds.","commonSituations":"Gateway not started or API connections disabled in Gateway settings; wrong `address` (host:port) in config (default 127.0.0.1:4001/7496 depending on live/paper); firewall blocking localhost port; Gateway API socket busy or stale client_id conflict; slow startup right after launching Gateway.","solutions":["Confirm IB Gateway/TWS is running and API access is enabled (Configure → API → Settings → Enable ActiveX and Socket Clients).","Verify the configured `address` matches the Gateway API port (4001 live / 4002 paper for Gateway; 7496/7497 for TWS).","Increase the connect timeout in your adapter config if Gateway is slow to start.","Fix any variable mismatch so the message and the actual timeout use the same value (`connect_timeout` vs `connection_timeout_secs`).","Check firewall/antivirus blocking the local port; test with `nc -vz 127.0.0.1 4002`."],"exampleFix":null,"handlingStrategy":"retry","validationCode":"// Check reachability before connecting\nassert!(std::net::TcpStream::connect(&address).is_ok(), \"IB Gateway port unreachable: {address}\");\n","typeGuard":null,"tryCatchPattern":"match get_or_connect().await {\n    Ok(c) => c,\n    Err(e) if e.to_string().contains(\"Timed out connecting\") => {\n        tokio::time::sleep(Duration::from_secs(5)).await;\n        get_or_connect().await? // bounded retry\n    }\n    Err(e) => return Err(e),\n}","preventionTips":["Start IB Gateway before the adapter and wait for its API port to listen.","Confirm host/port config (4001/4002 Gateway, 7496/7497 TWS) and enable API connections in Gateway settings.","Set a connect timeout with headroom for Gateway startup.","Ensure client_id uniqueness to avoid handshake contention."],"tags":["network","timeout","interactive-brokers","connection"],"backgroundTag":"request-timeout","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"}