LLM token and cost tracking in Langfuse

Langfuse records token usage and cost on each generation, but totals are only as good as the usage data and prices behind them. This page explains how to capture both correctly in infrastructure you control and how to check them against provider invoices.

On this page

LLM token and cost tracking in Langfuse: what each generation records

A team running LLM features needs to know what each model call costs and which product, user or team drives that spend. Langfuse is the self-hosted place where that record lives. For each generation, Langfuse can store the model name, the prompt and completion token counts, and a cost, so spend can be broken down by model, feature, user or session. Token and cost tracking covers that record end to end: how usage is captured, how a price is attached to it, and how totals are read back out. Teams usually need it for four reasons: chargeback to internal business units, budget control and rate limits, pricing decisions for their own AI features, and reconciliation with the invoices their model providers send at the end of each billing period.

The core features of Langfuse, including tracing and cost tracking, are available in the MIT-licensed open source version, so a self-hosted deployment does not require an Enterprise license key for this work. A self-hosted deployment runs on the same codebase as Langfuse Cloud, which means the behavior described in the Langfuse documentation for cloud applies to your instance as well. Before you rely on any field name, usage type or cost calculation, confirm it against the documentation for the exact release you deploy. Langfuse releases change the data model and API surface, and a v4 deployment may differ from older versions in ways that affect how totals are queried.

Your first decision is where the cost number comes from. A generation can carry a cost that your application or integration reports, or a cost that Langfuse infers from the token counts and a price definition that you maintain. Those two sources can disagree, so decide which one is authoritative for each model before you build dashboards on top of it. Then run a reconciliation on a small sample of real traffic: compare the token counts and cost totals Langfuse reports for one billing period against the provider's invoice line items for the same models, and record any gap. The Langfuse self-hosting documentation is the place to confirm how your release handles these fields before you start.

What Langfuse stores on each generation

Each generation in Langfuse is a record with four parts that together determine whether a cost figure is trustworthy. The model identifier decides which price applies, the usage counts decide how many tokens are billed, the cost value shows where the number came from, and the attribution metadata decides who or what the spend is charged to. Check all four in your own traces before you trust a dashboard total.

Model and identifier

The model field records which model name Langfuse received for the generation, and that name is what Langfuse matches against its price definitions. Provider responses often return a dated or versioned identifier that differs from the alias your application requested, so one model can appear under several names. Confirm in a sample of traces that the stored model name matches a price entry, and note any generation with an empty or unrecognized model, because it will carry no inferred cost. Custom and self-hosted models usually need their own definitions, covered in the sibling topic on adding custom model definitions and prices.

Usage counts and usage types

Usage holds the token counts for each generation, broken into types such as input, output and, where the provider reports them, cached tokens. Pricing is applied per usage type, so a missing cached-token count can overstate spend while a double-counted input can understate it. Compare the usage object for a few generations against the raw provider response to see whether counts are copied or recalculated. Reasoning tokens and other provider-specific categories need the same check before you rely on totals.

Self-hosting docs

Cost value and its source

The cost fields hold a monetary value for the generation, and Langfuse distinguishes between a cost you send with the event and a cost it calculates from the model price and usage. A sent cost reflects what your integration or provider reported, while an inferred cost reflects the price definition in your Langfuse project at the time of ingestion. Confirm which path each integration uses, because the two can diverge when prices change or a model is missing from the price list. Record the source in your reconciliation notes so that a later invoice mismatch can be traced.

Attribution metadata

Attribution fields carry the identifiers that connect a generation to a user, session, environment, tags and custom metadata. Without them, spend appears only as a project total, which cannot be split by team, feature or customer. Check that user and session identifiers are populated on every generation, and that they are stable pseudonymous IDs rather than raw email addresses if your data handling rules require it. Missing or inconsistent identifiers are the most common reason per-customer cost reports fail, and the sibling topic on tracking cost per user and session covers how to propagate them.

How usage data travels from your application to Langfuse dashboards

Usage data starts in your application, where an instrumented SDK or OpenTelemetry exporter sends traces to the Langfuse Web container. Web accepts the events and hands them to Redis or Valkey, and the Langfuse Worker picks them up for asynchronous processing before the data lands in ClickHouse and PostgreSQL. The UI and API then read from those stores. Blob storage sits alongside as a separate component, and everything inside the dashed boundary is yours to check, size and back up.

Path of a usage event through the self-hosted Langfuse components inside your infrastructure.

Ingested or inferred cost: choosing how each price gets set

This table compares the three ways a Langfuse generation can get a cost value: reported by the application at ingestion, inferred from a built-in model price definition, or inferred from a custom definition you maintain. Read each row against your own model mix, and treat the last column as the checklist to confirm in the Langfuse docs before you rely on the numbers.

Cost sourceWhen it fitsWho maintains pricesWhat breaks and what to confirm
Reported at ingestionYour application or gateway already computes cost per call, or you need the provider's billed figure to match invoicesYour team, through the code or gateway that sends the costCost is only as accurate as the value sent. Confirm which cost fields Langfuse accepts on generations and how they override inferred values.
Inferred from a built-in model definitionMainstream hosted models whose names Langfuse already recognizes and whose prices it tracksLangfuse maintains the default definitions, you consume themA renamed or versioned model name can stop matching and leave cost empty. Confirm the match pattern and the model name your SDK sends.
Inferred from a custom model definitionSelf-hosted, fine-tuned or privately served models, or hosted models with negotiated pricesYour team, who owns each price and its effective periodOld traces do not reprice when a price changes, and unmatched names fall back to no cost. Confirm how definitions are versioned and how prices per usage type are set.
Mixed approach per modelA portfolio that combines hosted models with private ones and needs invoice reconciliationSplit between Langfuse defaults and your custom definitionsOverlaps and gaps appear at the boundary. Confirm precedence rules when a reported cost and a definition both exist.
Gateway-supplied costYou route calls through a gateway that already records spend per key or teamThe gateway team, with prices set in the gatewayGateway prices can differ from provider invoices. Confirm whether the gateway cost or a Langfuse inferred cost feeds your reports.

Which integration captures token usage automatically

The Langfuse Python and JS/TS SDKs wrap model calls and send generation events that carry the model name, inputs, outputs and usage. The Python SDK v5 and the JS/TS SDK v6 need Langfuse v4.59.0 or later, so confirm the server version in each environment before upgrading client code.

  • Usage fields: Input, output and cached token counts for each generation, as long as the provider response returns them. Whether a field is populated depends on the provider and the wrapper you use.
  • Model name: The model string must match a model definition in Langfuse before cost can be inferred. Unmatched names leave the cost field empty.
  • Manual work: Wrap every call site, including retries, background jobs and streaming paths. Pass usage yourself where a wrapper does not read it from the response.
  • Version control: Pin SDK versions in lockfiles and record the server version alongside them, so a client upgrade does not change how usage is recorded.

Check a test trace for a generation with non-zero input and output counts, the expected model name and a cost value that matches your own rate card for that model.

Why Langfuse totals drift from provider invoices

A gap between Langfuse cost totals and a provider invoice usually comes from how cost is computed, not from the token counts themselves. The most frequent cause is a model name that does not match a price definition. Langfuse infers cost by matching the model name on each generation against its price table, so a dated snapshot, a region prefix or a custom deployment name can fall through to no price at all. Those generations then show tokens but little or no cost, and the total runs low. The reverse also happens: an alias that matches the wrong price definition inflates the total. Check the model names your integrations send against the definitions in your project, and confirm which definition each high-volume model resolves to.

A second group of causes sits in usage. If the price table has no price for a usage type that the provider bills, such as cached input tokens, reasoning tokens or audio tokens, those tokens are counted but not priced, and the invoice will be higher than the total. Retries and duplicated traces push the other way: a client that retries a failed call after the provider has already billed it can produce two generations for one charge, while a retry that the provider never billed produces a generation with no invoice line. Traces that never reached the server, because of network failures, dropped batches or a crashed process before flush, make the total lower again. Compare trace counts against request logs from your own gateway or application for a sample window before you trust either number.

Time windows and currency account for most of the remaining difference. Provider invoices follow the billing period and sometimes a timezone of the provider's choosing, while Langfuse filters by the timestamp recorded on each trace, so the first and last days of a month rarely line up exactly. Prices in the table are also per unit and in a single currency, so any conversion or tax on the invoice must be reconciled separately. The specific behavior of each cause depends on the integration and the Langfuse version you run, so confirm every one of them in a test environment that sends known requests before you use Langfuse totals for chargeback or billing.

Usage types to confirm before you trust a total

Langfuse calculates cost per generation by multiplying each usage type in a response by a price in the model definition. A total is only as reliable as the match between the usage types a provider reports and the prices Langfuse holds for each of them. The four cards below cover the usage types you are most likely to meet and the checks that show whether your numbers line up with an invoice.

Input tokens

Input tokens are the prompt, system message, tool definitions and prior conversation turns the provider bills as input. They are usually the largest share of a long chat or retrieval request, so a small error in the input price or a missing prompt segment shows up quickly in the total. Check that the model definition has an input price and that a sample trace records the same input count the provider returned for that call. Confirm that your integration does not truncate or reshape the prompt before it is sent.

Langfuse self-hosting docs

Output tokens

Output tokens are what the model generates, and providers often price them differently from input tokens. Reasoning or thinking output may be billed as output even when it is not shown to the user, which can make a visible answer look cheaper than the invoice. Check whether your provider includes reasoning tokens in the output count, and confirm in a sample trace that the recorded output count matches the response metadata for the same call. Streamed responses are a common place where the final usage block is missing.

Cached tokens

Cached tokens are input tokens the provider served from a prompt cache, and many providers bill them at a different rate than uncached input. If your model definition prices cached input at the standard input rate, the total will overstate spend for cache-heavy workloads. Confirm in the Langfuse docs whether the model definition has a separate price for this usage type, then send a repeated prompt and check that the cached count appears in the trace and that the cost changes as expected.

Provider-specific usage types

Some providers return usage types that do not map to input or output, such as audio, image, web search or tool-call units, or cache writes that are billed separately from cache reads. Langfuse only prices a usage type when the model definition names it, so an unmatched type can be dropped from the total without any error. Compare the raw usage object from the provider with the usage and cost fields on a sample generation, and reconcile a day of traffic against the provider's invoice line items before you rely on the totals.

Setting up token and cost capture in a self-hosted Langfuse

This sequence takes a self-hosted Langfuse from version checks to verified token and cost capture for one application, then to a planned rollout across services. The result is a generation whose usage and cost you have checked against the provider response and invoice.

  1. Confirm versions against releases and v4 requirements

    The platform team checks the current release on the Langfuse releases page and compares it with the version you plan to run. If you are moving to v4, confirm ClickHouse 25.12 or later (26.4 recommended), PostgreSQL 15 or later and Redis 7.0 or later. Pin the Python SDK v5 or JS/TS SDK v6 only against Langfuse v4.59.0 or later. Done when you have a written version matrix covering the server, each data store and each SDK in use.

  2. Deploy or confirm the self-hosted stack

    Confirm that Langfuse Web, Langfuse Worker, PostgreSQL, ClickHouse, Redis or Valkey and S3-compatible blob storage are running in your infrastructure and meet the minimum resources in the scaling guide. A single VM with Docker Compose suits testing only, since it has no high availability. Sign in, create a project and generate the public and secret API keys for the test application. Done when the UI loads and each component reports healthy.

  3. Instrument one application with a single model call

    Choose one capture path for the first test: an SDK integration or an OpenTelemetry exporter that sends OTLP traces to the /api/public/otel endpoint of your instance. Add the instrumentation to one small application that makes a single call to one provider model. Set the project keys as environment variables, not in code. Done when the script runs, returns the provider response and reports no errors on the client side.

  4. Send a test trace through the chosen path

    Run the application once and open the project in the Langfuse UI. Ingestion is asynchronous, so allow the worker time to process the event before you look for it. Confirm that the trace contains one generation with the model name, input and output. If nothing appears, check the Langfuse Worker logs and the API keys before changing the application. Done when one trace with one generation is visible in the correct project.

  5. Check stored usage and cost on the generation

    Open the generation and compare the stored input, output and cached token counts with the usage block in the provider response for the same call. Note whether the cost fields were ingested from the SDK or inferred by Langfuse from the model definition. Record both values in your test log. Done when the stored token counts match the provider response and you know which source produced each cost figure.

  6. Confirm the model definition matches the provider name

    Compare the model name on the generation with the provider's exact model identifier, including any version or date suffix, as listed in the provider's documentation. If the model is missing from Langfuse's definitions, or the inferred cost is absent or zero, add a custom definition with a match pattern and prices per usage type. Done when the generation shows a price source you can explain and the cost matches the price you expect for that model.

  7. Enable capture across services with a rollout plan

    Roll out capture one service at a time, each with a named owner, a test trace and a reconciliation of Langfuse totals against the provider invoice for an agreed period. Scale langfuse-worker on CPU load, and split langfuse-web into ingestion and UI deployments if ingestion becomes heavy. Record which services are live and who reviews their totals. Done when every service's totals reconcile on the review cycle you agreed.

Checking Langfuse totals against a provider invoice

Reconcile a billing period by fixing the window first. Set the same start and end timestamps, in the same time zone, on the provider invoice and on the Langfuse query, and confirm which time zone the invoice uses before comparing any figures. Then group both sides the same way: by model and by provider account or API key, because a single Langfuse project often receives traffic from several keys, and a mismatch in one account is easier to trace than a gap in the grand total. Keep the usage types separate as well. Input, output, cached and reasoning tokens are billed at different rates, so a total that merges them can match by accident while the line items do not. Check that the model names recorded in Langfuse map to the invoice line items, since an unrecognized model name is a common reason for cost to appear as zero or as an inferred estimate.

Expect small differences and treat them as a finding, not a failure. Provider invoices are often rounded, may include taxes, credits or discounts, and may bill requests that failed after the provider began processing them. Langfuse records only the traces your application sent, so calls made from scripts, tools or teams that bypass the instrumentation will appear on the invoice and not in Langfuse. Write each remaining gap in a reconciliation log with its amount, its direction, the model and account involved, and a stated cause. Confirm with the provider and your own engineers which causes apply to your setup, and do not assume a cause the evidence does not support. Ask the provider for an itemized usage export with the same window and granularity you used, and ask your team which Langfuse fields, such as ingested cost or the model definition in use, drove each figure.

Langfuse does not issue audit reports, attestations or certifications for these figures. Any formal finance review, including confirmation that spend was recorded correctly for accounting purposes, remains with your own finance function and independent auditors, and the reconciliation log is the evidence you hand them. The Metrics API, which pulls aggregated usage and cost for reporting, is covered on a sibling page, so this section only covers the manual comparison.

Security, operational limits and what to confirm

Token and cost data is only useful if it is governed like the traces it sits beside. The cards below cover what the records contain, who can read them, how long they live and what load they put on the platform. Each one names what to confirm in your environment before you rely on the numbers.

Trace content and personal data

Generations store the full prompt and completion text alongside token counts, so a usage record can carry personal data, customer records or secrets pasted into a prompt. Confirm what your applications send before enabling capture, and decide whether metadata-only logging is acceptable for cost reporting. Check whether your data masking approach must run on the client side before data reaches Langfuse, since server-side masking requires an Enterprise license key.

License key docs

Access to cost reports by project

Cost and usage dashboards expose spend per model, user and session, which many organizations treat as business-sensitive. Project-level access control is a feature that requires an Enterprise license key, so confirm who can view cost data in each project before onboarding teams. Also check whether finance, engineering and product users need different roles, and whether shared API keys can write traces into projects they should not see.

License key docs

Retention of usage records

Usage and cost records persist for as long as the platform keeps the underlying traces, so retention settings decide how far back finance can reconcile spend. Data retention policies require an Enterprise license key on self-hosted deployments. Confirm the retention period your finance and privacy teams agree on, and check whether it differs from the period your provider invoices require you to keep for your own records.

License key docs

Audit trail for cost configuration

Changes to model prices and match patterns alter every cost figure computed afterward, so an unexplained edit can shift reported spend without any change in traffic. Audit logs require an Enterprise license key. Confirm who may edit model definitions and prices, and record the source of each price so a later reviewer can trace why a number changed.

Worker and ClickHouse load at high ingestion

Cost is computed asynchronously by the worker and stored in ClickHouse, so a burst of generations raises the load on both before dashboards show the new totals. Langfuse recommends scaling workers on CPU load and, under heavy ingestion, splitting the web container. Confirm your peak generation rate and the lag you accept between a provider call and its cost appearing, and size ClickHouse memory and disk for that volume.

Scaling guide

Ingestion gaps that hide spend

Traces that fail to reach Langfuse, or that arrive without usage fields, make totals look lower than provider invoices. Queued events can also be dropped during outages if the pipeline has no buffer or monitoring. Confirm how you detect missing traces, for example by comparing daily request counts with provider logs, and assign an owner to investigate any gap before month-end close.

Questions teams ask before setting up cost tracking

How much effort does setting up Langfuse cost tracking take?

The effort depends on how many applications send traces, which frameworks they use, how many models need custom prices and how far the reconciliation goes. A single application on one supported provider with standard model names is a small piece of work. Each additional service, each framework with its own instrumentation, each self-hosted or fine-tuned model and each provider invoice you want to match adds configuration and verification steps. Ask any partner to break the quote into these drivers so you can see which ones you are paying for and which you can drop or do later.

Can our internal team set up cost tracking without a partner?

Yes, if you have engineers who can instrument applications, maintain a price table and read provider invoices. Langfuse's core features and APIs are available in the MIT-licensed open source version without limits, so the tracing and cost features do not depend on a commercial license. The risks are ownership and time: cost numbers are only as good as the prices and usage types behind them, and someone must keep those current when providers change models. Decide early who owns that work after go-live, because most cost errors appear later, not during the first setup.

What do we need to provide for the work to start?

Expect to provide four things: read access to a representative set of traces so the work can confirm which usage fields each integration sends, a sample of provider invoices for the same period so totals can be compared, a test environment where instrumentation changes can be tried without touching production traffic, and a named owner who approves the price table. The owner matters most. Model prices, cached token rates and tiered pricing need a decision-maker, and without one the setup stalls at the first unknown model. Confirm these inputs in the written scope before work begins.

How long does the setup take for different scopes?

No duration can be stated here without a scoped plan, so treat any figure you see without its basis with caution. Timing follows the same drivers as effort: the number of applications and frameworks, the count of custom or self-hosted models, the number of provider accounts to reconcile and whether the Langfuse instance is already running in your environment. A narrow scope with one integration and standard models can be planned as a short, fixed engagement. A broader scope that includes invoice matching across several providers usually needs more verification time. Ask for a timeline that lists the milestones and the approval points you must meet.

Does Langfuse calculate cost for self-hosted or fine-tuned models?

Langfuse calculates cost from a model price table that matches each generation to a model definition. Models that are not in the built-in list, including self-hosted and fine-tuned models, need a custom definition with match patterns and prices per usage type before cost appears. If a model has no price, the trace still records token usage, but the cost is missing or inaccurate. For GPU-served models there is no per-token invoice, so the cost is an internal estimate based on your own compute assumptions. Confirm with your own cost model how those figures will be used, and confirm the exact model-matching behavior in the current Langfuse documentation for your version.

What should a quote for cost tracking include?

A useful quote lists the scope in writing: which applications and frameworks are instrumented, which models get custom prices, and which provider invoices are reconciled and for which periods. It should name the deliverables, such as instrumentation changes, the price table, a reconciliation report and a short handover to your owner. It should state what you must provide, the test environment, the approval steps and the assumptions behind each item. Ask which costs are one-time and which recur, such as keeping prices current after provider changes or retesting after a Langfuse upgrade. Ask how changes to scope are priced. DeployOpen does not publish a price list, and a quote follows from the written scope.

How DeployOpen scopes and delivers token and cost tracking

DeployOpen plans, implements, configures and documents self-hosted Langfuse inside your own infrastructure, including how it records token usage and cost per generation. Engagements are fixed-scope, so the scope, deliverables and timeline for your cost tracking are agreed in writing before work starts.

How we scope

  • We inventory which model providers, gateways and SDKs send generations to your Langfuse instance today.
  • We agree which usage types, such as cached tokens, your totals must include, and which models need custom prices.
  • The written scope names the invoice reconciliation method, the reports and the owners who sign off on totals.

How we build

  • We configure ingestion so usage and cost are captured as the provider reports them, and inferred where it is not.
  • We define custom model definitions and prices for self-hosted or fine-tuned models and test their match patterns.
  • We run test generations through each integration and compare recorded totals with the provider's usage data before go-live.

How we hand over

  • You receive a written record of each integration, its usage fields, price sources and known gaps in recorded cost.
  • We document the reconciliation procedure so your finance or platform team can repeat the invoice comparison each billing period.
  • We walk your team through the dashboards and Metrics API queries agreed in scope, with the configuration stored in your repositories.

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers after handover.
  • A retainer can cover re-checking totals when providers change prices, models or usage reporting.
  • Major Langfuse upgrades that affect the data model are planned as separate, scoped work with their own migration review.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.