如何防止 n8n 的 AI 智能體凌晨 3 點向 400 名客戶發送電郵:預算上限、冪等性與緊急停止開關
How to Stop an AI Agent From Emailing 400 Customers at 3AM: Budget Caps, Idempotency & a Kill Switch in n8n
文章提出在 n8n 每次 LLM 呼叫及對外操作前加入防護步驟,以冪等鍵、Postgres 記錄、每位客戶本月至今的 LLM 開支上限及每小時操作上限,攔截重複操作及失控執行。
Short answer: put one guard step in front of every LLM call and every outbound action. The guard hashes the action into an idempotency key, checks a Postgres ledger for duplicates, checks the client's month-to-date LLM spend against a cap, checks an actions-per-hour limit, and stops the workflow with an alert if any check fails.
Why this keeps happening (this week's threads)
- A dev.to post titled "I let an agent run unattended overnight. At 3am it emailed 400 customers the wrong thing." drew 48 comments.
- On r/automation, "My automation opened 83 tickets while I was asleep" drew 13 comments.
- On r/n8n, a thread asks how to log the token cost of every LLM call to Postgres, tagged by client and project, and stop the workflow when a monthly budget is hit.
- Another r/n8n thread asks how to monitor a large number of n8n workflows in production.
The common root causes are retries without idempotency, loops with no rate ceiling, and no per-client spend ledger.
The guard pattern (4 checks)
| Check | What it blocks | How |
|---|---|---|
| Idempotency key | Duplicate emails, tickets, payments on retry | SHA-256 of client, action type, recipient, payload |
| Monthly budget | Runaway token spend per client |
SUM(cost_usd) by client and month vs cap |
| Rate cap | Overnight loops |
COUNT(*) of actions in last hour vs cap |
| Kill switch | Everything above | Slack alert, then Stop and Error node |
Ledger schema
CREATE TABLE IF NOT EXISTS guard_actions (
idempotency_key CHAR(64) PRIMARY KEY,
client_id TEXT NOT NULL,
project TEXT,
action_type TEXT,
month CHAR(7) NOT NULL,
cost_usd NUMERIC(12,6) DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT NOW()
);
Cost estimate formula
Estimated cost per call is (input_tokens x input_price + max_tokens x output_price) / 1,000,000, with input tokens approximated as characters divided by 4. Replace it with the provider's returned usage after the call for exact accounting.
Where to run it for $0 to $5
- Self-host n8n plus Postgres on Railway or a small Hetzner box, or start on n8n Cloud.
- If you prefer a visual builder, the same pattern works in Make.com with a Data Store as the ledger.
FAQ
Does this add latency? One indexed Postgres read and one insert per action, typically a few milliseconds on the same host.
Does it work with agents (LangChain, CrewAI)? Yes, call the guard as a tool or HTTP webhook before any side-effecting tool.
Disclosure: Some links are affiliate links — I may earn a commission at no extra cost to you.
來源:DEV Community · dev.to