惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Security Latest
Security Latest
Recorded Future
Recorded Future
人人都是产品经理
人人都是产品经理
S
SegmentFault 最新的问题
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
P
Privacy & Cybersecurity Law Blog
WordPress大学
WordPress大学
Know Your Adversary
Know Your Adversary
Spread Privacy
Spread Privacy
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
量子位
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tor Project blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
阮一峰的网络日志
阮一峰的网络日志
V
Visual Studio Blog
T
Threatpost
T
Tenable Blog
有赞技术团队
有赞技术团队
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
C
Cisco Blogs
H
Heimdal Security Blog
Attack and Defense Labs
Attack and Defense Labs
A
About on SuperTechFans
Last Week in AI
Last Week in AI
N
News and Events Feed by Topic
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
I
Intezer
V
V2EX
Cyberwarzone
Cyberwarzone
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
B
Blog RSS Feed
V
Vulnerabilities – Threatpost
N
Netflix TechBlog - Medium
T
The Blog of Author Tim Ferriss
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
PCI Perspectives
PCI Perspectives
P
Privacy International News Feed
D
Docker

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Monitoring LLM costs in production: tokens, tenants, and alerts
Amit Nabarro · 2026-06-23 · via DEV Community

Originally published on 475 Cumulus


A practical guide to LLM cost observability: structured logging, Langfuse dashboards, OpenTelemetry metrics, per-tenant budgets, and the unit economics finance actually needs.


The copilot launched. Usage climbed. Three weeks later finance forwards the OpenAI invoice and asks a simple question nobody can answer: which customers, which features, and which workflows drove the spend?

Provider dashboards show account totals. They do not show that tenant ACME's support copilot costs $0.42 per resolved ticket while tenant Beta burns $3.10 per draft because retrieval returns forty chunks nobody trimmed. Invoice-level visibility is too late and too coarse. Cost monitoring belongs in your LLM middleware, tagged like any other multi-tenant metric.

What this guide covers

This is the cost and spend layer of LLM observability. For trace structure, prompt versioning, and eval workflows, see Langfuse for LLM observability. For where middleware sits in the stack, see LLM middleware explained.


What to measure (and what to ignore)

Total monthly tokens is a lagging indicator. Production teams track unit economics tied to user outcomes:

Metric Why it matters
Tokens per successful action Cost per draft accepted, ticket summarized, or search answered
Spend by tenantId Multi-tenant fairness, abuse detection, customer profitability
Spend by feature Copilot vs classifier vs RAG assist: where to optimize first
Input vs output tokens Bloated context assembly shows up as high input; rambling models as high output
Retrieval + embed cost RAG has a bill before the LLM runs; trace it separately
Failed / timeout requests You still pay for many partial generations; track outcome

Example: support copilot unit economics

Suppose last week your middleware logged:

  • 12,400 copilot requests across 85 tenants
  • 48.2M total tokens ($612 estimated at blended rates)
  • 9,100 requests where the agent clicked "insert draft" (outcome: success with downstream accept event)

Blended cost per request: $612 ÷ 12,400 ≈ $0.049

Cost per accepted draft: $612 ÷ 9,100 ≈ $0.067

That second number is what product and finance can reason about. If ACME alone ran 2,200 requests but only 180 accepted drafts, their effective cost per useful action is $3.40, not the tenant-average $0.07. Without tenant and outcome dimensions, you would never see the gap.

Provider invoices are reconciliation, not monitoring

Use OpenAI, Anthropic, or Google Cloud billing exports to reconcile your estimates monthly. Day-to-day decisions run on middleware metrics you control: per tenant, per feature, per model, per hour.


Where to instrument

Every model call should pass through one server-side path (middleware) that already handles auth and rate limits. Cost data is recorded there, on the same boundary as tracing.

Client  →  your API  →  LLM middleware  →  provider
                              │
                    log tokens + estimated cost
                    enforce tenant budget
                    emit trace (Langfuse) + metrics (OTel)

Never rely on the browser to report usage. Never infer spend from unstructured console.log lines without consistent fields.

Request flow through LLM middleware

┌──────────────────────────────┐
│          Client UI           │
│   Copilot, search, actions   │
└──────────────┬───────────────┘
               │ Existing auth session
               ▼
┌──────────────────────────────┐
│          Your API            │
└──────────────┬───────────────┘
               │
               ▼
┌──────────────────────────────────────────────┐
│              LLM Middleware                  │
│                                              │
│  ✓ Auth & rate limits                        │
│  ✓ Inject tenant-scoped context              │
│  ✓ Enforce tool permissions                  │
│  ✓ Record tokens & latency                   │
│  ✓ Structured logging                        │
└──────────────┬───────────────────────────────┘
               │
               ▼
┌──────────────────────────────┐
│        Model Provider        │
│   OpenAI, Anthropic, etc.    │
└──────────────────────────────┘

Every model call passes through your stack — not around it.


Layer 1: Structured logging (minimum viable)

Before dashboards, emit one structured log line per model call with fixed fields. This alone answers most "who spent what" questions if you ship to Datadog, CloudWatch, Grafana Loki, or similar.

Required fields:

  • feature, tenantId, userId (hashed if policy requires)
  • model, inputTokens, outputTokens
  • latencyMs, outcome (success, timeout, rate_limited, error)
  • requestId or trace ID for correlation with support tickets
import logging
from dataclasses import dataclass

logger = logging.getLogger("llm.middleware")

@dataclass(frozen=True)
class LlmUsage:
    input_tokens: int
    output_tokens: int
    model: str

def log_llm_request(
    *,
    feature: str,
    tenant_id: str,
    user_id: str,
    usage: LlmUsage,
    latency_ms: int,
    outcome: str,
) -> None:
    logger.info(
        "llm.request",
        extra={
            "feature": feature,
            "tenant_id": tenant_id,
            "user_id": user_id,
            "model": usage.model,
            "input_tokens": usage.input_tokens,
            "output_tokens": usage.output_tokens,
            "total_tokens": usage.input_tokens + usage.output_tokens,
            "latency_ms": latency_ms,
            "outcome": outcome,  # success | timeout | rate_limited | error
        },
    )

Datadog example query (adapt field names to your schema):

sum:llm.tokens{feature:copilot} by {tenant_id}.as_count()

Grafana Loki / LogQL example:

sum by (tenant_id) (
  rate({app="api"} |= "llm.request" | json | input_tokens + output_tokens [1h])
)

Set an alert when a single tenant_id exceeds 2× its seven-day baseline. That catches runaway agents and abuse before the invoice closes.


Layer 2: Estimated cost per request

Providers bill in tokens; finance thinks in dollars. Middleware should compute an estimated costUsd on every completion using a pricing table you refresh when providers change rates.

# USD per 1M tokens — refresh from provider pricing pages
MODEL_PRICING = {
    "gpt-4.1-mini": {"input": 0.40, "output": 1.60},
    "claude-sonnet-4": {"input": 3.00, "output": 15.00},
}

def estimate_cost_usd(model: str, input_tokens: int, output_tokens: int) -> float:
    rates = MODEL_PRICING[model]
    return (
        (input_tokens / 1_000_000) * rates["input"]
        + (output_tokens / 1_000_000) * rates["output"]
    )

Store the estimate on the log line and trace:

{
  "feature": "copilot",
  "tenantId": "tenant_acme",
  "model": "claude-sonnet-4",
  "inputTokens": 4200,
  "outputTokens": 380,
  "costUsd": 0.0183,
  "outcome": "success"
}

Langfuse can display cost on generations when you pass usage and cost details. That lets you filter traces by expensive tenants and compare prompt versions side by side.

cost_usd = estimate_cost_usd(
    model=response.model,
    input_tokens=response.usage.input_tokens,
    output_tokens=response.usage.output_tokens,
)

with langfuse.start_as_current_observation(
    as_type="generation",
    name="copilot-completion",
    model=response.model,
    input=messages,
) as generation:
    generation.update(
        output=response.text,
        usage_details={
            "input": response.usage.input_tokens,
            "output": response.usage.output_tokens,
        },
        cost_details={
            "input": cost_usd * 0.3,   # optional split for dashboards
            "output": cost_usd * 0.7,
            "total": cost_usd,
        },
        metadata={"feature": "copilot", "tenantId": tenant_id},
    )

In the Langfuse UI:

  1. Open Traces → filter metadata.tenantId = tenant_acme and tags contains copilot
  2. Switch to Analytics → group by userId or custom metadata feature
  3. Compare cost per trace before and after a prompt change tagged promptVersion: v4

See Langfuse for LLM observability for full tracing setup.


Layer 3: OpenTelemetry metrics (SRE-friendly)

If your platform team already runs OpenTelemetry into Datadog, Honeycomb, Grafana Cloud, or Prometheus, export counters from middleware rather than building LLM-only silos.

from opentelemetry import metrics

meter = metrics.get_meter("llm.middleware")
token_counter = meter.create_counter(
    "llm.tokens",
    description="LLM tokens by tenant and feature",
)
cost_counter = meter.create_counter(
    "llm.cost_usd",
    description="Estimated LLM spend in USD",
)

def record_otel_cost(attrs: dict, usage, cost_usd: float) -> None:
    labels = {
        "feature": attrs["feature"],
        "tenant_id": attrs["tenant_id"],
        "model": usage.model,
        "outcome": attrs["outcome"],
    }
    token_counter.add(usage.input_tokens + usage.output_tokens, labels)
    cost_counter.add(cost_usd, labels)

Example Datadog monitor:

  • Metric: sum:llm.cost_usd{*}.rollup(sum, 86400) by {tenant_id}
  • Alert: daily spend > $50 for any tenant not on the enterprise AI tier

Example Grafana panel:

  • Stacked bar: sum(rate(llm_cost_usd[1h])) by (feature)
  • Table: top 10 tenant_id by sum(increase(llm_tokens[24h]))

Langfuse's OpenTelemetry exporter can dual-write: LLM-native traces in Langfuse for debugging, aggregated llm.cost_usd in your existing stack for paging and executive dashboards.


Layer 4: Per-tenant budgets and enforcement

Observability without enforcement is a report card nobody acts on. For multi-tenant SaaS, add budget checks in middleware before the provider call.

Pattern:

  1. Read today's accumulated spend for tenantId from Redis (or your rate-limit store)
  2. Compare against plan limit (starter: $5/day, pro: $50/day, etc.)
  3. If over budget: return 429 or a degraded response ("AI assist temporarily unavailable")
  4. After a successful call: increment spend by costUsd
from datetime import date
import redis

redis_client = redis.Redis.from_url(os.environ["REDIS_URL"])

def daily_spend_key(tenant_id: str) -> str:
    return f"llm:spend:{tenant_id}:{date.today().isoformat()}"

def check_tenant_budget(tenant_id: str, budget_usd: float) -> None:
    spent = float(redis_client.get(daily_spend_key(tenant_id)) or 0)
    if spent >= budget_usd:
        raise TenantBudgetExceeded(tenant_id, spent, budget_usd)

def record_tenant_spend(tenant_id: str, cost_usd: float) -> float:
    key = daily_spend_key(tenant_id)
    return float(redis_client.incrbyfloat(key, cost_usd))

Pair soft limits with rate limits (requests per minute) to stop runaway loops and agent retries from burning budget in minutes. See Prompt injection and LLM security for SaaS for abuse patterns that inflate token spend.

Provider-side guardrails (belt and suspenders)

Use these in addition to middleware, not instead of it:

Tool What it does
OpenAI Project-level budgets, separate API keys per environment, usage limits per key
Anthropic Workspaces with distinct keys; monitor usage in Console
Google Vertex / Gemini Cloud Billing budgets and alerts on the GCP project
Langfuse Cloud Trace volume and cost analytics; self-hosted for data residency

Provider limits catch catastrophes. Middleware limits catch tenant-level fairness your provider will never enforce for you.


Dashboards worth building on day one

You do not need twenty charts. Ship these four before GA:

1. Spend by feature (stacked daily)

Answers: "Is the copilot or the classifier driving growth?"

2. Top tenants by cost (table, 24h / 7d)

Answers: "Who would we call if we need to throttle or upsell?"

3. Tokens per successful action (trend)

Requires joining middleware logs with a product event (draft_accepted, ticket_resolved). Answers: "Are we getting more efficient or just busier?"

4. Cost by model (pie or bar)

Answers: "Did last week's routing change actually shift traffic to the cheaper model?"

Production readiness checklist

[ ] Server-side auth         — all model calls go through server middleware
[ ] Tenant-scoped context    — tenant ID from session, not client input
[ ] Structured logging       — audit trail on all tool calls and retrievals
[ ] Cost per action          — token budget enforced in middleware
[ ] Eval pipeline            — adversarial cases run in CI
[ ] Provider fallback        — failover configured and tested
[ ] Feature flags            — kill switch per feature, per tenant, global
[ ] Audit on tool calls      — who called what, when, with what outcome

Use this as a gate before calling an AI feature GA — not as a post-launch backlog.


Alerts that prevent surprises

Alert Condition Action
Tenant spike Tenant daily cost > 2× 7-day avg Notify CS + auto-throttle AI features
Feature regression tokens_per_success up 40% WoW after deploy Roll back prompt version; check Langfuse promptVersion filter
Error burn outcome:error rate > 5% and tokens still rising Often retry storms; tighten timeouts and max retries
Budget threshold 80% of monthly org budget in week one Page platform; enable kill switch for non-critical features
Embed surge RAG embed tokens > generation tokens Chunking or re-index job run amok; check batch pipelines

Wire critical alerts to the same channel as payment or export failures. LLM spend is a reliability and revenue issue, not only a finance report.


Reducing cost without guessing

Once you can see spend by tenant and feature, optimization is measurable:

Route by task complexity

Use smaller models for classification and extraction; reserve large models for multi-turn copilots. Middleware selectModel(feature, tenantId) centralizes this. See When not to use RAG: many "AI" tasks do not need the biggest model or retrieval at all.

Trim context assembly

High input token counts usually mean the context builder sends too much: full thread history, unstripped HTML, duplicate records. Fix the builder; do not only switch models.

Cache stable work

Cache embeddings for unchanged documents. Cache FAQ or policy answers keyed by (tenantId, questionHash) with short TTL. Log cache_hit: true so dashboards separate fresh spend from cache savings.

Cap agent loops

Agents that retry tools or loop on errors can multiply cost per session. Enforce maxSteps, per-session token budgets, and timeouts. See Build an agent with LangChain.

Eval before expensive architecture

Running evals costs tokens, but cheaper than shipping retrieval or a larger model to every tenant without proof. See Eval pipelines for LLM features.


Common mistakes

Waiting for the invoice. By then the damage is done and you cannot attribute it.

Logging tokens without tenantId or feature. Aggregates are useless in SaaS.

Cost per API call only. A copilot that takes three model calls to produce one draft looks cheap per call and expensive per outcome.

Ignoring embed and re-rank costs. RAG bills start at the vector store and embedding API, not only the final chat completion.

Budgets in config files nobody updates. Tie limits to plan tier in your billing system or tenant settings table.

Alerts with no kill switch. Observability plus a runbook entry "disable feature=copilot via flag" beats a Slack message nobody can act on at 2 a.m.


Rollout order

  1. Structured log with tokens, model, tenant, feature, outcome
  2. Cost estimate on every completion; reconcile monthly with provider billing
  3. Langfuse (or equivalent) for trace-level drill-down and prompt version comparison
  4. OTel metrics into your existing observability stack for alerts
  5. Per-tenant budgets enforced in middleware before GA to external tenants
  6. Unit economics dashboard joined to product success events

Incremental rollout phases

Phase 1: Internal   → Eng team + CS
Phase 2: Canary     → 5–10% of tenants
Phase 3: Gradual    → 25% → 50% → 100%
Phase 4: GA         → Default on

Measure quality, cost, and support load at each stage before expanding.


Putting it together

LLM cost monitoring is not a finance spreadsheet exercise. It is middleware instrumentation: the same boundary where you already enforce auth, assemble context, and route models. Log consistently, estimate cost per request, aggregate by tenant and feature, alert on spikes, and enforce budgets before the provider charges you.

If you cannot answer "what did tenant X spend on copilot yesterday" from your own metrics, you are not ready to scale AI traffic, regardless of how good the demo looks.


Scoping AI features for your product? Describe the workflow and we will map middleware, cost tagging, budgets, and dashboards for your stack and tenant model.