{"record":{"id":"5790b551d2a92efa","repo":"nautechsystems/nautilus_trader","slug":"failed-to-send-query-add-trade-to-database-message","errorCode":null,"errorMessage":"Failed to send query add_trade to database message handler: {e}","messagePattern":"Failed to send query add_trade to database message handler: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/infrastructure/src/sql/cache.rs","lineNumber":1021,"sourceCode":"                    }\n                }\n                Err(e) => {\n                    log::error!(\"Failed to load quotes for instrument {instrument_id}: {e:?}\");\n                    if let Err(e) = tx.send(Vec::new()) {\n                        log::error!(\n                            \"Failed to send empty quotes for instrument {instrument_id}: {e:?}\"\n                        );\n                    }\n                }\n            }\n        });\n        Ok(rx.recv()?)\n    }\n\n    fn add_trade(&self, trade: &TradeTick) -> anyhow::Result<()> {\n        let query = DatabaseQuery::AddTrade(trade.to_owned());\n        self.tx.send(query).map_err(|e| {\n            anyhow::anyhow!(\"Failed to send query add_trade to database message handler: {e}\")\n        })\n    }\n\n    fn load_trades(&self, instrument_id: &InstrumentId) -> anyhow::Result<Vec<TradeTick>> {\n        let pool = self.pool.clone();\n        let instrument_id = instrument_id.to_owned();\n        let (tx, rx) = std::sync::mpsc::channel();\n\n        tokio::spawn(async move {\n            let result = DatabaseQueries::load_trades(&pool, &instrument_id).await;\n            match result {\n                Ok(trades) => {\n                    if let Err(e) = tx.send(trades) {\n                        log::error!(\"Failed to send trades for instrument {instrument_id}: {e:?}\");\n                    }\n                }\n                Err(e) => {\n                    log::error!(\"Failed to load trades for instrument {instrument_id}: {e:?}\");","sourceCodeStart":1003,"sourceCodeEnd":1039,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/infrastructure/src/sql/cache.rs#L1003-L1039","documentation":"add_trade sends a DatabaseQuery::AddTrade over the cache's internal mpsc channel to the database message handler task; the error is produced by map_err when channel send fails. A send fails only when the receiver has been dropped, meaning the background handler is no longer running. The trade data itself is not validated here — the failure is purely internal plumbing.","triggerScenarios":"Calling add_trade (or py_add_trade from Python) when the handler task backing the cache has terminated: adapter shut down, task aborted, or handler exited due to an earlier fatal DB error.","commonSituations":"A live node tears down its database adapter while a strategy callback still records trades; a handler panic from a previous failed write; using a cache instance obtained before reconnection.","solutions":["Confirm the database message handler task is running before calling add_trade","Restart/recreate the cache adapter after any shutdown; do not write through stale handles","Inspect handler logs for the reason the receiver was dropped (panic, pool failure) and fix it","Wrap add_trade calls in error handling if trade persistence is non-critical"],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try:\n    cache.add_trade(trade)\nexcept Exception as e:\n    if \"Failed to send query add_trade\" in str(e):\n        logger.error(\"DB cache handler unavailable\")\n        raise PersistenceError from e","preventionTips":["Do not reuse cache adapter instances across shutdown/restart cycles","Log and alert on handler task termination","Verify adapter startup succeeded before enabling trade writes","Keep DB config valid so the handler never dies at init"],"tags":["rust","channel","database","postgres"],"backgroundTag":"broken-pipe","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"}