{"record":{"id":"9f21c267f25ddfa8","repo":"nautechsystems/nautilus_trader","slug":"ws-session-authentication-timed-out","errorCode":null,"errorMessage":"WS session authentication timed out","messagePattern":"WS session authentication timed out","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/adapters/binance/src/spot/execution.rs","lineNumber":2006,"sourceCode":"    setup_errors: &mut tokio::sync::mpsc::UnboundedReceiver<String>,\n    timeout_message: &'static str,\n) -> anyhow::Result<()> {\n    tokio::pin!(success);\n\n    let result = tokio::time::timeout(timeout, async {\n        tokio::select! {\n            () = &mut success => Ok(()),\n            err = setup_errors.recv() => {\n                anyhow::bail!(\n                    \"{}\",\n                    err.unwrap_or_else(|| \"WS setup error channel closed\".to_string()),\n                )\n            }\n        }\n    })\n    .await;\n\n    result.map_err(|_| anyhow::anyhow!(timeout_message))?\n}\n\n#[expect(clippy::too_many_arguments)]\nfn dispatch_ws_trading_message(\n    msg: BinanceSpotWsTradingMessage,\n    emitter: &ExecutionEventEmitter,\n    http_client: &BinanceSpotHttpClient,\n    account_id: AccountId,\n    treat_expired_as_canceled: bool,\n    clock: &'static AtomicTime,\n    dispatch_state: &WsDispatchState,\n    ws_authenticated: &tokio::sync::Notify,\n    ws_user_data_subscribed: &tokio::sync::Notify,\n    ws_setup_error_tx: &tokio::sync::mpsc::UnboundedSender<String>,\n    seen_trade_ids: &std::sync::Arc<Mutex<FifoCache<(Ustr, i64), 10_000>>>,\n) {\n    match msg {\n        BinanceSpotWsTradingMessage::OrderAccepted {","sourceCodeStart":1988,"sourceCodeEnd":2024,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/a4b06ed870971b5671d12754ea138a3ab99b1dec/crates/adapters/binance/src/spot/execution.rs#L1988-L2024","documentation":"During Binance Spot WS trading setup, after `session_logon()` succeeds the adapter waits up to `ws_trading_setup_timeout_ms` (default 10,000 ms) for the sessionLogon success confirmation (the `ws_authenticated` Notify). `wait_for_ws_setup_response` wraps this in `tokio::time::timeout`; if neither the success signal nor a setup error arrives in time, the elapsed timeout is replaced with 'WS session authentication timed out' and adapter connection fails.","triggerScenarios":"Building the Binance Spot execution client with WS trading enabled where the `session.logon` request is sent but no response frame arrives within `ws_trading_setup_timeout_ms` — slow or stalled WS connection, high network latency, Binance lagging under load, or a timeout value configured below round-trip time.","commonSituations":"Hosts far from Binance (cross-region VMs) with handshakes exceeding 10s; congested networks or lossy proxies; Binance maintenance/incident windows; users lowering `ws_trading_setup_timeout_ms` from the default; slow machines where the runtime is starved and the response frame is processed late.","solutions":["Increase `ws_trading_setup_timeout_ms` in the exec client config (e.g. 30_000) and retry connecting","Measure latency/connectivity to the Binance WS endpoint and move the runtime closer (or fix proxy/firewall issues)","Retry the connect — transient Binance-side slowness usually clears","Check logs for preceding auth-rejection or error frames: a hard rejection surfaces a different error, so pure silence points to network/latency rather than credentials"],"exampleFix":"# before\nconfig = BinanceExecClientConfig(\n    api_key=os.environ[\"BINANCE_API_KEY\"],\n    api_secret=os.environ[\"BINANCE_API_SECRET\"],\n    use_ws_trading=True,  # default setup timeout 10s\n)\n\n# after\nconfig = BinanceExecClientConfig(\n    api_key=os.environ[\"BINANCE_API_KEY\"],\n    api_secret=os.environ[\"BINANCE_API_SECRET\"],\n    use_ws_trading=True,\n    ws_trading_setup_timeout_ms=30_000,\n)","handlingStrategy":"retry","validationCode":"# Python: pre-flight latency check before building the live node\nimport time, websocket\nstart = time.perf_counter()\nws = websocket.create_connection(\"wss://ws-fapi.binance.com/ws\", timeout=5)  # spot: use the spot WS endpoint\nrtt_ms = (time.perf_counter() - start) * 1000\nws.close()\nsetup_timeout_ms = 10_000 if rtt_ms < 1000 else 30_000\nconfig = BinanceExecClientConfig(\n    api_key=..., api_secret=..., use_ws_trading=True,\n    ws_trading_setup_timeout_ms=setup_timeout_ms,\n)","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Size ws_trading_setup_timeout_ms to at least ~30x your measured WS round-trip time; keep the 10s default unless latency is proven low","Host the runtime close to Binance (e.g. AWS ap-northeast-1 for binance.com) to keep handshakes far under the timeout","Let the trading node retry connect on transient timeouts rather than crash-looping your process","Monitor for Binance connectivity incidents before blaming credentials — hard auth failures produce rejection errors, not timeouts"],"tags":["binance-spot","websocket","timeout","authentication","connection-setup","nautilustrader"],"backgroundTag":"websocket-connection-timeout","analyzedSha":"a4b06ed870971b5671d12754ea138a3ab99b1dec","analyzedAt":"2026-08-16T22:54:50.089Z","schemaVersion":2},"datasetVersion":"2026-08-16T23:17:17.608Z"}