How to Track and Allocate OpenAI & Anthropic API Costs Per User (2026 Architecture Guide)
A developer guide to tracking LLM token consumption per user and workspace in your own app. Includes TypeScript code, reverse proxy patterns, prompt caching math, streaming token attribution, and Redis circuit breakers.
Engineering teams deploying AI applications often encounter unexpected billing spikes.
A company launches an automated research assistant or document processing agent. Usage grows quickly, and customer sign-ups increase on payment gateways.
Illustrative example: weeks later, the company receives these invoices:
- Anthropic Claude API: Monthly charge of $8,420.00
- OpenAI API: Monthly charge of $6,190.00
Checking the OpenAI Usage Dashboard or the Anthropic Console shows aggregate token spikes. However, provider consoles cannot answer an essential operational question: which workspace, customer account, or feature caused the expense?
Standard provider dashboards lack multi-tenant reporting. Teams cannot tell whether costs came from:
- An autonomous agent stuck in a recursive loop calling Claude.
- A single high-volume subscriber on a $29 monthly plan processing large documents.
- Broad adoption across paying customers.
Tracking model expenses per tenant is necessary to maintain healthy unit economics.
This guide provides architectural patterns, database schemas, and TypeScript code to track token costs per customer, handle prompt caching, capture streaming usage, and enforce Redis spending limits.
1. The Multi-Tenant Attribution Problem
Standard provider dashboards serve organizational administrators rather than multi-tenant software architectures:
┌────────────────────────────────────────────────────────────────────────┐
│ THE MULTI-TENANT ATTRIBUTION BLIND SPOT │
├────────────────────────────────────────────────────────────────────────┤
│ What the OpenAI / Anthropic Console Shows: │
│ • Total Tokens Consumed: 142,850,000 tokens │
│ • Total Invoice: $1,428.50 │
│ • Model Breakdown: 70% Claude / 30% OpenAI │
│ │
│ What You ACTUALLY Need to Know: │
│ • Workspace #812 (Acme Corp on $290 plan): $18.40 (93.6% Margin) │
│ • Workspace #419 (Beta Tester on $29 plan): $940.20 (-3,142% Loss!) │
│ • Feature Attribution: 65% Search Agent / 35% Chat Copilot │
│ • Cache Efficiency: Did Acme Corp hit 90% prompt cache discounts? │
└────────────────────────────────────────────────────────────────────────┘
Relying solely on native provider consoles presents three major challenges:
- Aggregated Usage Data: Provider consoles aggregate usage across entire API keys. They cannot associate tokens with internal PostgreSQL
workspace_idrecords. - Delayed Metrics Reporting: Provider usage reports can lag behind live traffic. Teams cannot detect runaway loops through delayed dashboards.
- No Direct Revenue Correlation: Raw token exports do not show whether an account generates a profit. Understanding unit economics requires matching compute costs against subscription revenue from payment gateways like Stripe, Paddle, or Lemon Squeezy.
To solve these issues, applications must record token telemetry directly in software.
2. Three Architectural Patterns for LLM Cost Tracking
Engineers use three primary architectural patterns to track model expenses:
PATTERN 1: IN-APP DIRECT TAGGING
App Server ──► Provider SDK (with user tag) ──► OpenAI / Anthropic
(Simple setup, lacks real-time local analytics)
PATTERN 2: REVERSE PROXY GATEWAY (RECOMMENDED)
App Server ──► LLM Gateway (LiteLLM / Helicone) ──► Provider API
│
▼ (Async log to ClickHouse / Redis)
PATTERN 3: ASYNC TELEMETRY WORKER
App Server ──► OpenAI / Anthropic ──► Return response to user
│
└──► BullMQ / Kafka ──► Worker logs to Postgres / Analytics
Pattern 1: Native Request Tagging
OpenAI and Anthropic provide parameters to tag requests with user identifiers.
OpenAI: The user Parameter
OpenAI accepts an optional user string in completion requests:
// openai-client.ts
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
export async function generateCompletion(prompt: string, workspaceId: string) {
return await openai.chat.completions.create({
model: process.env.OPENAI_MODEL!, // the OpenAI model you use
messages: [{ role: "user", content: prompt }],
user: `workspace_${workspaceId}`,
});
}
Anthropic: The metadata.user_id Parameter
Anthropic accepts a metadata object with a user_id string:
// anthropic-client.ts
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
export async function generateClaudeResponse(prompt: string, workspaceId: string) {
return await anthropic.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }],
metadata: {
user_id: `workspace_${workspaceId}`,
},
});
}
- Advantages: Requires no new infrastructure and minimal code changes.
- Limitations: Tags do not appear as grouped cost summaries in provider dashboards. You need to log usage yourself to add up costs by tenant. Anthropic uses
metadata.user_idto help detect abuse and asks for an opaque ID, never a name or email.
Pattern 2: The Reverse Proxy Gateway
In production applications handling large request volumes, teams often route traffic through a reverse proxy gateway like LiteLLM Proxy or a custom Cloudflare Worker:
┌────────────────────────────────────────────────────────────────────────┐
│ LLM REVERSE PROXY ARCHITECTURE │
│ │
│ ┌────────────────┐ Request with Tenant Headers │
│ │ App Server │──────────────────────────────────┐ │
│ └────────────────┘ │ │
│ ▼ │
│ ┌──────────────────────┐ │
│ │ LLM REVERSE PROXY │ │
│ │ (LiteLLM / Custom) │ │
│ └──────────┬───────────┘ │
│ │ │
│ ┌─────────────────────────────┴──────┐ │
│ ▼ ▼ │
│ ┌────────────────────┐ ┌──────────────────┐ │
│ │ Upstream Providers │ │ Async Telemetry │ │
│ │ • OpenAI │ │ • Redis Spend │ │
│ │ • Anthropic │ │ • ClickHouse Log │ │
│ │ • Google Vertex │ │ • PostgreSQL DB │ │
│ └────────────────────┘ └──────────────────┘ │
└────────────────────────────────────────────────────────────────────────┘
The gateway manages requests and responses:
- Checks whether the workspace has exceeded its spend limit in Redis.
- Forwards the request to the upstream provider with configured credentials.
- Parses returned token usage, calculates cost, and logs metrics asynchronously.
- Advantages: Centralized rate limiting, model failover support, and per-tenant audit records.
- Limitations: Adds a network hop, which is usually small next to model generation time. Measure it on your own traffic.
Pattern 3: Application-Level Wrapper
Teams can also wrap official provider SDK clients in application code.
The wrapper extracts token usage from completion promises, calculates dollar expenses, logs data asynchronously, and updates spend counters in Redis.
3. Pricing Catalogs and Prompt Caching Calculations
Accurate cost tracking requires maintaining an updated model pricing registry.
Calculating expenses in 2026 requires accounting for Prompt Caching discounts, which reduce input costs significantly.
Claude Pricing Reference
| Model Name | Input Tokens (per 1M) | Output Tokens (per 1M) | Cache Write (per 1M) | Cache Read (per 1M) |
|---|---|---|---|---|
| Claude 3 Opus | $15.00 | $75.00 | $18.75 (+25%) | $1.50 (90% discount) |
| Claude 3.5 Sonnet | $3.00 | $15.00 | $3.75 (+25%) | $0.30 (90% discount) |
| Claude 3.5 Haiku | $0.80 | $4.00 | $1.00 (+25%) | $0.08 (90% discount) |
Claude prices are from Anthropic's pricing page, as of November 2026. Cache writes use the 5-minute rate. For OpenAI models, take current prices from OpenAI's pricing page on the day you build your price table. OpenAI applies prompt caching automatically and bills cached input at a lower rate. |
Prompt Caching Economics
On Anthropic Claude 3.5 Sonnet, standard input costs $3.00 per million tokens, while cache read tokens cost $0.30 per million tokens.
When an application uses large system instructions or retrieval context, hitting prompt caches reduces input costs by 90%.
Tracking scripts that ignore cache hit tokens (cache_read_input_tokens) overestimate real API expenses.
TypeScript Cost Calculation Function
The code below calculates exact request costs with prompt cache support:
// llm-pricing.ts
export interface ModelPricing {
inputPerMillion: number;
outputPerMillion: number;
cacheWritePerMillion?: number;
cacheReadPerMillion?: number;
}
// Claude prices per million tokens, from https://platform.claude.com/docs/en/about-claude/pricing (as of November 2026).
// Cache writes use the 5-minute rate. Check the pricing pages before you rely on these numbers.
export const MODEL_PRICING_REGISTRY: Record<string, ModelPricing> = {
"claude-3-opus-20240229": {
inputPerMillion: 15.00,
outputPerMillion: 75.00,
cacheWritePerMillion: 18.75,
cacheReadPerMillion: 1.50,
},
"claude-3-5-sonnet-20241022": {
inputPerMillion: 3.00,
outputPerMillion: 15.00,
cacheWritePerMillion: 3.75,
cacheReadPerMillion: 0.30,
},
"claude-3-5-haiku-20241022": {
inputPerMillion: 0.80,
outputPerMillion: 4.00,
cacheWritePerMillion: 1.00,
cacheReadPerMillion: 0.08,
},
// Add each OpenAI model you call, with prices from https://openai.com/api/pricing/
// "<openai-model-id>": { inputPerMillion: 0, outputPerMillion: 0, cacheReadPerMillion: 0 },
};
export interface TokenUsagePayload {
model: string;
promptTokens: number; // all input tokens with cache reads included (OpenAI: prompt_tokens; Anthropic: input_tokens + cache_read_input_tokens)
completionTokens: number;
cachedTokens?: number;
cacheWriteTokens?: number;
}
export function calculateCostUSD(usage: TokenUsagePayload): number {
const pricing = MODEL_PRICING_REGISTRY[usage.model];
if (!pricing) {
throw new Error(`No price for model ${usage.model}. Add it to MODEL_PRICING_REGISTRY.`);
}
const cachedCount = usage.cachedTokens || 0;
const cacheWriteCount = usage.cacheWriteTokens || 0;
const basePromptCount = Math.max(0, usage.promptTokens - cachedCount);
const baseInputCost = (basePromptCount * pricing.inputPerMillion) / 1_000_000;
const outputCost = (usage.completionTokens * pricing.outputPerMillion) / 1_000_000;
const cacheReadCost = pricing.cacheReadPerMillion
? (cachedCount * pricing.cacheReadPerMillion) / 1_000_000
: 0;
const cacheWriteCost = pricing.cacheWritePerMillion
? (cacheWriteCount * pricing.cacheWritePerMillion) / 1_000_000
: 0;
const totalCost = baseInputCost + outputCost + cacheReadCost + cacheWriteCost;
return Math.round(totalCost * 1_000_000) / 1_000_000;
}
4. PostgreSQL Schema for Multi-Tenant Accounting
Recording request data without degrading API performance requires normalized tables paired with daily aggregation rollups:
-- 1. Main Table: Stores individual completion records
CREATE TABLE workspace_llm_requests (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
workspace_id UUID NOT NULL,
user_id UUID,
feature_name VARCHAR(64) NOT NULL,
provider VARCHAR(32) NOT NULL,
model VARCHAR(64) NOT NULL,
prompt_tokens INTEGER NOT NULL DEFAULT 0,
completion_tokens INTEGER NOT NULL DEFAULT 0,
cached_tokens INTEGER NOT NULL DEFAULT 0,
total_tokens INTEGER GENERATED ALWAYS AS (prompt_tokens + completion_tokens) STORED,
cost_usd NUMERIC(10, 6) NOT NULL DEFAULT 0.000000,
latency_ms INTEGER,
status_code SMALLINT NOT NULL DEFAULT 200,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_llm_requests_workspace_date
ON workspace_llm_requests (workspace_id, created_at DESC);
CREATE INDEX idx_llm_requests_feature
ON workspace_llm_requests (feature_name, created_at DESC);
-- 2. Daily Summary Table
CREATE TABLE daily_workspace_llm_rollups (
workspace_id UUID NOT NULL,
date DATE NOT NULL,
total_requests INTEGER NOT NULL DEFAULT 0,
total_prompt_tokens BIGINT NOT NULL DEFAULT 0,
total_completion_tokens BIGINT NOT NULL DEFAULT 0,
total_cached_tokens BIGINT NOT NULL DEFAULT 0,
total_cost_usd NUMERIC(12, 4) NOT NULL DEFAULT 0.0000,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (workspace_id, date)
);
CREATE INDEX idx_rollups_date ON daily_workspace_llm_rollups (date DESC);
Atomic Daily Upsert Query
When a completion completes, record the raw request and execute this atomic upsert into the daily summary table:
INSERT INTO daily_workspace_llm_rollups (
workspace_id, date, total_requests, total_prompt_tokens,
total_completion_tokens, total_cached_tokens, total_cost_usd, updated_at
)
VALUES ($1, CURRENT_DATE, 1, $2, $3, $4, $5, NOW())
ON CONFLICT (workspace_id, date) DO UPDATE SET
total_requests = daily_workspace_llm_rollups.total_requests + 1,
total_prompt_tokens = daily_workspace_llm_rollups.total_prompt_tokens + EXCLUDED.total_prompt_tokens,
total_completion_tokens = daily_workspace_llm_rollups.total_completion_tokens + EXCLUDED.total_completion_tokens,
total_cached_tokens = daily_workspace_llm_rollups.total_cached_tokens + EXCLUDED.total_cached_tokens,
total_cost_usd = daily_workspace_llm_rollups.total_cost_usd + EXCLUDED.total_cost_usd,
updated_at = NOW();
5. Capturing Token Counts in Streaming Responses
Streaming API responses emit text deltas in real time. Standard chunks omit the final usage metadata block unless configured properly.
OpenAI sends usage on a stream only when you ask for it. Anthropic always includes it.
Streaming Usage on OpenAI
To receive token counts on an OpenAI stream, pass stream_options: { include_usage: true }:
// openai-streaming.ts
import OpenAI from "openai";
import { calculateCostUSD } from "./llm-pricing";
const openai = new OpenAI();
export async function* streamOpenAIResponse(prompt: string, workspaceId: string) {
const stream = await openai.chat.completions.create({
model: process.env.OPENAI_MODEL!, // the OpenAI model you use
messages: [{ role: "user", content: prompt }],
stream: true,
stream_options: {
include_usage: true,
},
user: `workspace_${workspaceId}`,
});
let finalUsage = null;
for await (const chunk of stream) {
const textDelta = chunk.choices[0]?.delta?.content;
if (textDelta) {
yield textDelta;
}
if (chunk.usage) {
finalUsage = chunk.usage;
}
}
if (finalUsage) {
const costUSD = calculateCostUSD({
model: process.env.OPENAI_MODEL!,
promptTokens: finalUsage.prompt_tokens,
completionTokens: finalUsage.completion_tokens,
cachedTokens: finalUsage.prompt_tokens_details?.cached_tokens || 0,
});
// Log costUSD asynchronously to your database
}
}
Streaming Usage on Anthropic Claude
The Anthropic SDK's finalMessage() returns the full usage once the stream ends:
// anthropic-streaming.ts
import Anthropic from "@anthropic-ai/sdk";
import { calculateCostUSD } from "./llm-pricing";
const anthropic = new Anthropic();
export async function* streamClaudeResponse(prompt: string, workspaceId: string) {
const stream = anthropic.messages.stream({
model: "claude-3-5-sonnet-20241022",
max_tokens: 2048,
messages: [{ role: "user", content: prompt }],
metadata: { user_id: `ws_${workspaceId}` },
});
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
yield event.delta.text;
}
}
const { usage } = await stream.finalMessage();
const cacheRead = usage.cache_read_input_tokens ?? 0;
const costUSD = calculateCostUSD({
model: "claude-3-5-sonnet-20241022",
// Anthropic's input_tokens leaves out cached tokens. Add cache reads back,
// because calculateCostUSD subtracts them from promptTokens.
promptTokens: usage.input_tokens + cacheRead,
completionTokens: usage.output_tokens,
cachedTokens: cacheRead,
cacheWriteTokens: usage.cache_creation_input_tokens ?? 0,
});
// Log costUSD asynchronously to your database
}
6. Circuit Breakers and Real-Time Spending Limits
Recording expenses in a database provides historical data. It does not stop an active loop from consuming budget during an unexpected event.
A reliable architecture enforces three protection tiers:
- Per-Request Bounds: Set strict
max_tokenslimits on all calls. - Concurrency Limits: Restrict parallel active requests per workspace to prevent scraping attacks.
- Spend Limits in Redis: Track daily and monthly spend in Redis. When an account exceeds its limit, return an HTTP
429 Too Many Requestsstatus or route to a smaller model.
┌────────────────────────────────────────────────────────────────────────┐
│ REDIS CIRCUIT BREAKER WORKFLOW │
│ │
│ Incoming LLM Request (Workspace #419) │
│ │ │
│ ▼ │
│ Check Redis Daily Spend Key │
│ `GET ws:419:spend:2026-11-20` │
│ │ │
│ ┌───────────┴───────────┐ │
│ ▼ ▼ │
│ Spend < $10.00 Spend >= $10.00 │
│ │ │ │
│ ▼ ▼ │
│ Execute Upstream TRIP CIRCUIT BREAKER │
│ OpenAI / Claude API • Reject with HTTP 429 │
│ │ • Send Alert Email to Founder & User │
│ ▼ • Fall back to a smaller model │
│ Atomic Increment │
│ `INCRBYFLOAT ...` │
└────────────────────────────────────────────────────────────────────────┘
Redis Budget Guard Implementation
// llm-budget-guard.ts
import { Redis } from "ioredis";
const redis = new Redis(process.env.REDIS_URL || "redis://localhost:6379");
export interface BudgetConfig {
dailyHardCapUSD: number;
monthlyHardCapUSD: number;
}
export async function checkBudgetGuard(
workspaceId: string,
config: BudgetConfig
): Promise<{ allowed: boolean; currentDailySpend: number; reason?: string }> {
const today = new Date().toISOString().split("T")[0];
const month = today.substring(0, 7);
const dailyKey = `ws:${workspaceId}:spend:${today}`;
const monthlyKey = `ws:${workspaceId}:spend:${month}`;
const [dailySpendRaw, monthlySpendRaw] = await redis.mget(dailyKey, monthlyKey);
const dailySpend = parseFloat(dailySpendRaw || "0");
const monthlySpend = parseFloat(monthlySpendRaw || "0");
if (dailySpend >= config.dailyHardCapUSD) {
return {
allowed: false,
currentDailySpend: dailySpend,
reason: `Daily spend limit of $${config.dailyHardCapUSD.toFixed(2)} reached.`,
};
}
if (monthlySpend >= config.monthlyHardCapUSD) {
return {
allowed: false,
currentDailySpend: dailySpend,
reason: `Monthly spend limit of $${config.monthlyHardCapUSD.toFixed(2)} reached.`,
};
}
return { allowed: true, currentDailySpend: dailySpend };
}
export async function recordSpendAtomic(workspaceId: string, costUSD: number): Promise<void> {
const today = new Date().toISOString().split("T")[0];
const month = today.substring(0, 7);
const dailyKey = `ws:${workspaceId}:spend:${today}`;
const monthlyKey = `ws:${workspaceId}:spend:${month}`;
const pipeline = redis.pipeline();
pipeline.incrbyfloat(dailyKey, costUSD);
pipeline.expire(dailyKey, 172800); // 48 hours
pipeline.incrbyfloat(monthlyKey, costUSD);
pipeline.expire(monthlyKey, 5184000); // 60 days
await pipeline.exec();
}
This check is not atomic. Requests that start at the same time all see the old total, and spend is recorded only after each request finishes. Combine it with the concurrency limit above, or reserve an estimated cost with INCRBYFLOAT before the call and correct it with the real cost afterwards.
7. Checking Your Logs Against Provider Bills
Application-level metrics track individual API calls. However, internal database logs often differ from provider invoices due to:
- Failed requests that consumed input tokens before encountering timeouts.
- Staging environments and internal team testing on primary API keys.
- Cache creation write surcharges (+25%).
- Minimum monthly platform charges.
Your logs tell you which tenant used what. RealMRR works one level up: it reads what each provider billed, through the provider's API, and puts it next to revenue for each product. If your logged total for a product is far from the provider's figure, your logging is missing something.
┌─────────────────────────────────────────────────────────────────┐
│ ILLUSTRATIVE EXAMPLE: ONE PRODUCT IN REALMRR │
│ │
│ Revenue (Stripe, Paddle or Lemon Squeezy): $32,400.00 │
│ AI costs (OpenAI + Anthropic): -$8,940.00 │
│ Hosting & database costs: -$2,180.00 │
│ ─────────────────────────────────────────────────────────── │
│ Profit: $21,280.00 │
│ Margin: 65.7% │
└─────────────────────────────────────────────────────────────────┘
Founders connect OpenAI and Anthropic with an organization Admin key in the RealMRR workspace. RealMRR maps OpenAI spend by project and Anthropic spend by workspace to your products. Anything it can't map shows as "Unassigned".
RealMRR reads revenue from Stripe, Paddle or Lemon Squeezy and shows revenue, costs and profit for each product. It syncs every 6 hours on the Free plan and every hour on Plus and Scale. RealMRR does not track cost per user or per customer: that part stays in your own logs.
8. Production Readiness Checklist
Review this checklist before deploying AI features:
1. Request Attribution
- OpenAI calls pass the
user: "ws_${workspace.id}"parameter. - Anthropic calls pass
metadata: { user_id: "ws_${workspace.id}" }. - Staging and test environments use isolated API keys with strict spend limits.
2. Token Measurement
- Streaming requests pass
stream_options: { include_usage: true }on OpenAI. - Anthropic streaming handlers read usage from
stream.finalMessage()and add cache reads back into input tokens. - Cost calculations account for prompt cache discounts.
3. Circuit Breakers
- Requests include explicit
max_tokensboundaries. - A Redis rate limiter tracks daily and monthly spend per workspace.
- Accounts reaching budget limits return HTTP 429 status codes.
4. Financial Reconciliation
- Connect your payment and AI providers to RealMRR to see what each provider billed for each product, and compare it with your own logs.
Managing AI Unit Economics
Sustainable AI products require clear visibility into per-user compute costs.
Measuring token consumption, applying prompt caching, and using circuit breakers protects operating runway.
To verify margins and reconcile cloud expenses:
- Connect your accounts on RealMRR. The Free plan is $0 for workspaces averaging up to $3,000 a month in net revenue, and every plan includes unlimited products.
- Browse products ranked by MRR, profit and expenses in the RealMRR directory.
Related Reading
- Why $20k MRR Can Still Leave You Broke: The Broken Unit Economics of AI Wrappers
- RealMRR vs Baremetrics vs ProfitWell: Why Subscription Analytics Fail Modern AI Apps
- Stripe vs Paddle vs Lemon Squeezy: The Real Cost After Fees, FX, and Taxes (2026)
- The True Cost of a $100 SaaS Sale: Stripe vs Paddle vs Lemon Squeezy vs Polar vs Dodo
- Where to Sell a Micro-SaaS in 2026: Acquire.com vs TrustMRR vs Flippa vs RealMRR
Know your real profit today.
Connect your payment gateway and cloud bills to get verified profit rankings, automated bookkeeping, and zero guesswork.