Track LLM Costs With n8n: Per-Feature Token Logging and Budget Alerts
Track LLM costs with n8n: log per-feature token spend to Google Sheets and fire a budget alert before month-end. A vendor-neutral, self-hosted build — no paid SaaS.
The LLM bill is the line item nobody watches until it spikes. A summarization workflow runs every 15 minutes, a lead-scoring flow fires on every form submission, an email-drafting agent handles support tickets, and each one quietly burns tokens. The first time anyone looks is when the invoice lands at three times last month's number, and by then there's no data on which workflow caused it.
To track LLM costs with n8n is to put a meter on every model call before the bill surprises anyone. Each LLM node returns its token usage; a workflow captures that, converts it to dollars, tags it with the feature that spent it, and logs it to a sheet. A daily check sums the month-to-date total and alerts the moment it crosses a budget. Vendor-neutral, self-hosted, no cost-tracking subscription required.
The paid tools that do this exist, and they charge a monthly fee to tell you how much you're spending — which is its own small irony. The same job is a handful of n8n nodes and a Google Sheet you already have.
What You Can Automate in LLM Cost Tracking
The cost-control jobs that fit an n8n workflow:
- Capturing token usage from every OpenAI, Anthropic, or Google model call
- Converting tokens to USD using a per-model pricing table you control
- Tagging each cost with the feature or workflow that incurred it
- Logging every call's cost to a Google Sheet as a running ledger
- Summing month-to-date spend on a daily schedule
- Projecting the month-end total from the current burn rate
- Alerting by email or Slack before the budget threshold is crossed
The per-feature tagging is what turns a single scary number into an actionable one. You don't just learn the bill is high; you learn which workflow to fix.
The Cost-Tracking Pipeline
Two workflows cooperate: a logger that runs inline with every LLM call, and a watcher that runs on a schedule.
LLM call → Capture usage → Convert to USD → Tag feature → Append to ledger
Schedule → Sum MTD → Project month-end → Compare to budget → Alert
The watcher in concrete form:
Schedule Trigger v1.2 (cron: 0 9 * * *)
→ Google Sheets v4: read this month's cost rows
→ Code v2 (jsCode): sum MTD, project month-end from daily rate
→ Switch v3: under budget | over threshold
→ Slack v2 + Gmail v2: alert with current + projected totals (over branch)
The split into two workflows is deliberate. The logger has to run wherever an LLM node runs, so it lives as a small sub-workflow you call after each model node. The watcher runs once a day, independent of any LLM traffic. Nesting the watcher inside an LLM workflow creates a loop where the cost check itself makes a model call, which is exactly the kind of self-inflicted spend you're trying to measure.
Model prices change, and a hardcoded rate buried in a Code node goes stale silently — your "costs" drift from the real invoice with no error to tell you. Keep per-model input and output rates in a single Set node or a Google Sheet tab. When a provider changes pricing, you update one place. The conversion math reads the rate from there, never from a literal scattered through the workflow.
Step-by-Step Breakdown
1. Capture usage at the source
Every major LLM node returns token counts. The OpenAI node exposes them in its response payload; the @n8n/n8n-nodes-langchain.openAi v2.1 node surfaces usage at $json.output[0].usage.total_tokens, split into prompt and completion counts. Grab both — input and output tokens are priced differently.
2. Convert to dollars
A Code node reads the per-model rate from your pricing table and multiplies. Input tokens times input rate, output tokens times output rate, summed. Keep the model name flowing through so the right rate gets applied.
3. Tag the feature
Add a feature field naming what spent the money: lead-scoring, summarization, support-draft. This is one line in the Code node and the single most useful column in the whole ledger.
4. Append to the ledger
A Google Sheets append writes timestamp, model, feature, tokens, and cost. One row per LLM call. This sheet is the source of truth — independent of any provider dashboard, with no retention limit you don't control.
5. Watch and alert
The separate daily workflow sums the month so far, projects the month-end figure from the current daily rate, and a Switch node routes the over-budget case to an alert carrying both numbers. The projection is what makes it useful: knowing you'll hit $800 by the 31st on the 12th gives you time to act.
Implementation Patterns That Hold Up
Pattern 1 — Input and output priced separately. A single blended rate is wrong for any model where output costs more than input, which is most of them.
Code v2 (jsCode):
const rate = PRICING[$json.model]; // { in: 0.15, out: 0.60 } per 1M tokens
const usd = (promptTokens / 1e6) * rate.in
+ (completionTokens / 1e6) * rate.out;
return [{ json: { feature: $json.feature, model: $json.model, usd } }];
The PRICING[$json.model] lookup is why the model name has to travel with the usage data. Strip it upstream and you can't pick the right rate.
Pattern 2 — Multi-provider, one ledger. Don't build a separate tracker per provider. OpenAI, Anthropic, and Google all return usage; normalize each into the same { model, promptTokens, completionTokens, feature } shape in a Code node right after the model call, and they all land in one sheet with one pricing table. A single ledger is what lets you compare provider spend honestly.
Pattern 3 — Project, don't just sum. A month-to-date total on the 5th tells you little. Divide it by days elapsed, multiply by days in the month, and the projection tells you whether you're on track to blow the budget. The AgentSpend — LLM Cost Tracker & Budget Alerts template runs this daily: it pulls usage, converts with a built-in pricing table for the major GPT models, logs each snapshot to Google Sheets, and emails the moment daily spend crosses a configurable budget.
n8n Nodes You'll Use Most
| Node | Purpose |
|---|---|
@n8n/n8n-nodes-langchain.openAi | LLM calls that also return token usage |
n8n-nodes-base.code | Token-to-USD conversion, projection math, provider normalization |
n8n-nodes-base.googleSheets | The cost ledger and the pricing table |
n8n-nodes-base.scheduleTrigger | Daily budget-check run |
n8n-nodes-base.switch | Route under-budget vs over-threshold |
n8n-nodes-base.slack | Budget-breach alert to the team channel |
n8n-nodes-base.gmail | Budget alert by email with the projection |
The Code node does the real work here, and the one rule that keeps it honest is reading rates from data, never from literals. A pricing constant typed into the conversion node is a number that will be wrong within a quarter and won't announce it.
Getting Started
- Build the pricing table first. A Google Sheet tab or Set node with per-model input and output rates. Everything downstream reads from it.
- Capture usage on one workflow. Pick your highest-traffic LLM workflow, add the usage-capture and conversion nodes after the model call, and confirm the cost rows look right against a known call.
- Tag the feature. Add the
featurecolumn now, while you remember which workflow is which. Backfilling attribution later is painful. - Roll the logger out as a sub-workflow. Make capture-and-log a reusable sub-workflow you call after every LLM node, so adding tracking to a new workflow is one node, not a rebuild.
- Build the daily watcher separately. Sum, project, compare, alert. Keep it off any LLM-calling workflow.
- Set the threshold below the real ceiling. Alert at 80% of budget, not 100%. An alert that fires the day you blow the budget is too late to do anything about it.
The AgentSpend — LLM Cost Tracker & Budget Alerts template ships this end-to-end: a daily Schedule Trigger pulls OpenAI usage, a Code node converts it with a built-in pricing table for the major GPT models, every snapshot logs to Google Sheets, and an email fires the instant daily spend crosses your configured budget — the watcher half of this workflow, already wired. It's part of The Complete n8n Templates Bundle, a one-time lifetime license to the whole catalog (plus every template added later) if you run more than one of these AI automations.
One detail that catches people: the OpenAI usage endpoint reports with a delay, so a same-day sum built from the API alone lags reality by hours. Logging token counts inline at call time — straight from each node's response — gives you a real-time ledger that the usage endpoint can only confirm after the fact. Trust your own inline log for the live number.
If your LLM workflows are growing fast, the patterns for keeping them reliable live in the n8n OpenAI workflows guide, and the broader agent-orchestration picture is covered in the LLM agent workflows guide. Cost tracking pairs naturally with both — the more model calls you run, the sooner the meter pays for itself.
Build the pricing table and log one workflow's costs first. The moment you see which feature actually drives the bill, the rest of the tracker justifies itself.
See more AI automation templates →Common questions
How do I track LLM token costs in n8n without a paid SaaS tool?
How do I attribute LLM spend to specific features in n8n?
Can n8n alert me before my LLM bill exceeds a budget?
Get the workflow templates this guide is built on
Import-ready n8n JSON, step-by-step setup, and tested end-to-end. One-time payment, own it forever.
Get 3 tested n8n templates, free
The full customer package for three real catalog templates — workflow JSON, step-by-step setup guide, credential checklist. Built through the same live-instance release process as everything we sell. Plus new templates and automation guides in your inbox. No spam, unsubscribe anytime.
- 01Smart To-Do List ManagerPre-built n8n workflow template that automates productivity with OpenAI. Live in about 10 minutes.$14
- 02Email Follow-Up AutomatorPre-built n8n workflow template that automates crm with OpenAI. Live in about 15 minutes.$12
- 03Market Trend AnalyzerPre-built n8n workflow template that automates data processing with OpenAI. Live in about 10 minutes.$14
More automation guides

n8n Backup Automation That Actually Verifies the Backup
A Backup You Never Verified Is a Coin Flip Every n8n backup automation tutorial that ranks does the same thing: schedule an export, push the JSON to Google Drive or S3, done. They back up the data and…

How to Build an n8n Log Alerting Workflow (No Grafana Required)
Most n8n Error Setups Tell You Everything, Which Means They Tell You Nothing An n8n log alerting workflow has one job: surface the failures that need a human and quietly file the ones that don't. The…

n8n Uptime Monitoring with Slack Alerts (Without the Alert Storms)
An Uptime Check That Cries Wolf Gets Muted in a Week The point of n8n uptime monitoring with Slack alerts isn't to detect a single outage. It's to be trusted the next hundred times it fires. Most of t…