Tips > Data, APIs & Webhooks

Track API Usage by Logging Calls with Timestamps, Endpoints, and Token Counts

You cannot optimize what you do not measure.

Track API usage by adding a logging step after every paid API call that records the timestamp, endpoint, model, token counts, and estimated cost. A Code node computes the cost from the response's token usage and per-model pricing; write each entry to a Google Sheet or a Postgres table, then run a weekly query to find your most expensive workflows and optimize them first.

Why log every paid API call?

You cannot optimize what you do not measure. Add a lightweight logging step to every workflow that calls paid APIs. Track the timestamp, endpoint, model used, token count, and estimated cost. Review this log weekly to find your most expensive workflows and optimize them first.

Real-world example: A team runs 15 workflows that call OpenAI, Anthropic, and various SaaS APIs. Without tracking, they discover a $2,000 monthly bill but do not know which workflows are responsible.

How do you log API usage and cost in a Code node?

// Code node: "Log API Usage" -- place after every paid API call
const apiResponse = $input.first().json;

// Extract token usage from OpenAI response format
const usage = apiResponse.usage || {};

// Pricing per 1K tokens (update these as prices change)
const pricing = {
  'gpt-4o': { input: 0.0025, output: 0.01 },
  'gpt-4o-mini': { input: 0.00015, output: 0.0006 },
  'claude-sonnet-4': { input: 0.003, output: 0.015 },
  'claude-3-5-haiku': { input: 0.0008, output: 0.004 }
};

const model = apiResponse.model || 'unknown';
const modelPricing = pricing[model] || { input: 0, output: 0 };

const inputTokens = usage.prompt_tokens || 0;
const outputTokens = usage.completion_tokens || 0;
const estimatedCost = (
  (inputTokens / 1000) * modelPricing.input +
  (outputTokens / 1000) * modelPricing.output
);

const logEntry = {
  timestamp: new Date().toISOString(),
  workflow_name: $workflow.name,
  execution_id: $execution.id,
  node_name: $prevNode.name,
  model: model,
  endpoint: 'chat/completions',
  input_tokens: inputTokens,
  output_tokens: outputTokens,
  total_tokens: inputTokens + outputTokens,
  estimated_cost_usd: Math.round(estimatedCost * 10000) / 10000,
  success: !apiResponse.error
};

return [{
  json: {
    ...apiResponse,
    _usage_log: logEntry
  }
}];

How do you store and analyze the usage log?

Write the log to a Google Sheet or database:

-- Postgres: Create the tracking table
CREATE TABLE api_usage_log (
  id SERIAL PRIMARY KEY,
  timestamp TIMESTAMPTZ NOT NULL,
  workflow_name TEXT NOT NULL,
  execution_id TEXT,
  node_name TEXT,
  model TEXT,
  endpoint TEXT,
  input_tokens INTEGER DEFAULT 0,
  output_tokens INTEGER DEFAULT 0,
  total_tokens INTEGER DEFAULT 0,
  estimated_cost_usd NUMERIC(10, 6) DEFAULT 0,
  success BOOLEAN DEFAULT true
);

-- Weekly cost analysis query
SELECT
  workflow_name,
  model,
  COUNT(*) as call_count,
  SUM(input_tokens) as total_input_tokens,
  SUM(output_tokens) as total_output_tokens,
  SUM(estimated_cost_usd) as total_cost,
  ROUND(AVG(estimated_cost_usd)::numeric, 6) as avg_cost_per_call
FROM api_usage_log
WHERE timestamp > NOW() - INTERVAL '7 days'
GROUP BY workflow_name, model
ORDER BY total_cost DESC;

Build a monitoring dashboard workflow:

# Scheduled workflow: "Weekly API Cost Report"

# Runs every Monday at 9am

[Schedule Trigger: Monday 9am]
  --> [Postgres: Run weekly analysis query]
  --> [Code: Format report]
  --> [IF: Total cost > $100 threshold]
      True:  [Slack: Send alert with breakdown]
      False: [Slack: Send normal summary]
Sample report output:
  Total API spend this week: $47.23

  Top workflows by cost:
  1. Customer Support Classifier  - $18.50 (392 calls, gpt-4o)
  2. Product Description Generator - $12.30 (41 calls, gpt-4o)
  3. Email Summarizer              - $8.90 (890 calls, gpt-4o-mini)
  4. Lead Enrichment               - $4.20 (420 calls, clearbit)
  5. Translation Pipeline          - $3.33 (111 calls, gpt-4o-mini)

  Recommendation: Switch "Customer Support Classifier" to gpt-4o-mini
  (estimated savings: $16.50/week)

This visibility lets you make data-driven decisions about which workflows to optimize first and measure the impact of changes.

Related: Use Structured Output (JSON Mode) for Parseable Responses · Configure Payload Size and Binary Data Mode for Large Files

Showcase builds

19 complete workflows from my own projects, each with its n8n workflow JSON to import. Showcase entries link the file at the end of the article.

See the showcase builds

Keep reading

190 entries grouped by topic, from first workflow to queue mode. Free, no signup.

Browse the encyclopedia

Need it built?

I design, build and run n8n systems for clients. Every engagement starts with a $1,500 diagnostic audit, credited toward the build.

Book an introductory call