How the Langfuse Metrics API answers usage and cost questions
The Langfuse Metrics API returns aggregated usage, cost, latency and scores from your self-hosted instance, so a finance, platform or data team can get per-team or per-model spend without exporting raw traces. Teams usually need it when the numbers leave Langfuse: chargeback to internal cost centers, billing that depends on usage data, or BI tools that join LLM spend with other business data. If the question is answered by looking at a chart, the Langfuse dashboards are usually enough, and the API adds a second system to maintain.
Before building anything, confirm the exact endpoint names, query parameters, dimensions, filter syntax and response fields against the current API reference, since the research behind this page did not cover them. Also confirm which Metrics API version your Langfuse release exposes, and whether the endpoints you plan to use are the current ones or the deprecated metrics endpoints that the migration guide covers. Check the authentication model for API keys and which project each key can read, because a query returns only the data that its credentials can see.
Decide early what a 'team' or 'model' means in your data. Cost totals depend on how traces were tagged and whether prices were ingested or inferred, so a chargeback report is only as reliable as the metadata behind it. Ask your platform team to test one month of aggregated results against your provider invoices before any finance process relies on the numbers, and record which Langfuse version produced them so later upgrades do not silently change your totals.
Query options and when each fits
This table compares the metric families, dimensions, filters, time granularity and paging options you can choose from when querying Langfuse usage and cost. Read each row by the reporting question it answers, then check the trade-off before you build a recurring export. Options marked for confirmation have exact names and behavior that you should verify in the API reference for your Langfuse version.
| Option | Reporting question it serves | Trade-off | Confirm in API reference |
|---|---|---|---|
| Usage and token volume | How many input, output and cached tokens each model or feature consumed | Totals only match provider invoices if usage was captured completely at ingestion | Exact metric names for each usage type |
| Cost totals | What each team, model or feature spent in a billing period | Inferred cost depends on model definitions, so unknown models may show no cost | Which cost fields are returned and how currency is represented |
| Latency percentiles | Which features are slow at the median and at the tail | Averages hide slow requests, so percentile support matters for user-facing reports | Available percentile aggregations and their units |
| Score aggregates | Whether output quality holds steady after a model or prompt change | Scores exist only where evaluations or user feedback were recorded | Score data types and supported aggregation functions |
| Dimensions such as model, environment, tags, user and session | Chargeback by team, product feature or customer | High-cardinality dimensions like user and session increase response size and query load | Exact dimension names and which dimensions each metric family supports |
| Filters on time range, model, environment or tag | Limiting a report to one billing period or one product | Tag filters only work if tags were set consistently during tracing | Filter operators and the timestamp field used for time range |
| Time granularity | Daily trends for operations or monthly totals for billing | Finer granularity returns more rows and may be limited by the range requested | Supported granularities and the maximum range per query |
| Paging and row limits | Exporting a full history into a warehouse or BI tool | Large exports need paging, retries and a schedule that avoids peak load | Page size limits, rate limits and any response size caps |
How aggregation depends on the v4 data model
Aggregated results from the Metrics API are only as complete as the observations, usage and cost values stored underneath them, and Langfuse v4 changes how those are stored. With v4, Langfuse moves to an observations-first ClickHouse data model, so the unit that carries tokens, cost and latency is the observation (a generation or span), not the trace. Before you build a chargeback or billing query, confirm which fields your instance populates at the observation level, because a query that sums usage across observations will only be correct if every billable call was recorded as an observation with its usage attached.
Totals from the Metrics API can differ from what you see when you open individual traces in the UI, and the gap usually has a traceable cause. Common causes are observations that were never ingested because an SDK or OpenTelemetry exporter dropped them, usage that was not captured by the integration, cost that was not inferred because the model name did not match a price definition, and historic data that was not fully backfilled during the v3 to v4 migration. The v4 migration guide advises about 3x ClickHouse disk headroom when backfilling, so plan the backfill window and check that it finished before you trust historic aggregates. Ask your operations team which of these conditions apply to your instance and record the answer alongside the query.
Before any Metrics API output feeds an invoice, reconcile a sample of query results against the provider invoices for the same period. Pick several models, several days and at least one feature with a known volume, compare input, output and cached token counts and the resulting cost with what the provider billed, and document the variance and its explanation. Repeat the check after each Langfuse upgrade or pricing change, because a new data model or a changed price definition can shift totals without any visible error. Treat a reconciled sample as the acceptance test for the query, not as proof that every record is correct.
Set up a first reporting query
This sequence takes a self-hosted Langfuse instance from a version check to a first aggregated usage and cost query that matches the Langfuse UI for a window you have already counted. The result is one reconciled baseline that any chargeback, billing or BI pipeline can be checked against later.
Confirm the Langfuse version
The platform engineer checks the running self-hosted version against the Langfuse releases page on GitHub. Current Python SDK v5 and JS/TS SDK v6 need Langfuse v4.59.0 or later, and v4.63.0 is the latest release listed at the time of writing. Done when the instance runs v4.59.0 or later and the SDK versions in your query client are on the supported pairing.
Confirm the auth method in current docs
Before creating any credentials, the person running the query checks the current Langfuse API authentication documentation for the version you run. Authentication details are the kind of thing to confirm against your own version rather than rely on from memory. Note the key format and header the docs specify, and whether the key is tied to a project. Done when you can state the auth method in one sentence and you have the docs page open for reference.
Create a project-scoped API key
A project owner or organization admin creates an API key in the project that holds the traces you want to report on. Store the public and secret parts in your secrets manager and give the reporting job only that key. Done when the key appears in the project settings and a simple read request with it succeeds, while a request for a second project's data with the same key is refused.
Pick a known time window
Choose a window whose trace volume you can count, for example (illustrative) one day from a test application that you have already reviewed. Record the start and end timestamps in UTC, the project name, the number of generations you expect and the models you expect to see. Done when these expectations are written down before you send any query, so the result is checked against them rather than shaped to fit.
Send the first aggregated query
Send one aggregated request for usage, cost and generation count over the window. Group by a single dimension such as model, and add no filters beyond the time range and project. Keep the request body in version control so the query can be rerun unchanged. Done when the response contains a row for each expected model and totals for tokens and cost across the window.
Compare totals with the UI
Open the same project in the Langfuse UI, set the same time range and model filter, and read the generation count, token total and cost. Gaps usually come from timezone handling, a filter that was applied in one place but not the other, or a model priced differently in the two views. Trace each difference to one of those causes before going further. Done when the counts match exactly or every difference has a named cause.
Record the query as a baseline
Save the request, the response for the reconciled window and the UI figures together, along with the Langfuse version and SDK versions in use. Keep this record in the same repository as the reporting job so later output can be compared with it. Done when the baseline and the reconciliation notes are committed, and anyone on the team can rerun the query and get the same totals.
How a reporting request moves from SDK to BI tool
The flow starts in your instrumented applications, which send traces through the Langfuse SDK or the OTLP endpoint at /api/public/otel. Langfuse Web and Langfuse Worker process those events, store them in ClickHouse, and the Metrics API reads aggregates back out for a chargeback job or BI tool. The trust boundary sits around the API key and the infrastructure you control, so check that the reporting client holds only a read-scoped key and that every hop stays inside your network.
Telemetry flows in, aggregates flow out, with the API key boundary around reporting.
Which reporting path fits chargeback, billing and BI
Internal chargeback allocates LLM spend to business units, product lines or cost centers so each group pays for what it uses. The query should return cost and token usage grouped by the attribute your organization uses to map traces to a unit, for a fixed billing period. Finance or the platform team usually reviews the output on the close calendar, and unit owners should see their own lines before any internal invoice is issued.
- Dimension mapping: agree which trace metadata field maps to a cost center and name the owner of the mapping table.
- Untagged spend: decide whether traffic without a unit goes to a shared pool, a default unit or back to the team that generated it.
- Period boundaries: match the query window and time zone to the finance close calendar.
- Invoice reconciliation: compare Langfuse totals with provider billing exports for the same window and document known gaps.
- Change control: record model price and mapping changes so restated periods can be explained.
Before the first chargeback run, confirm that the allocated lines add up to the reconciled total, because unallocated spend is where disputes start.
Customer billing charges end customers for an AI feature, often with a markup, included allowance or credits. The query must return usage keyed to each customer identifier for the billing cycle, filtered to the feature that is being sold. Finance and the account owners review it, and many teams also run lighter checks more often to catch heavy usage before the invoice date. Because the output affects what a customer is charged, the mapping from application identifiers to billing accounts needs to be verified first.
- Identifier propagation: confirm that every billable request carries the customer identifier, including background jobs and retries.
- Cost basis: decide whether invoices use provider-reported cost, Langfuse-computed cost or a contracted rate, and test that choice on sample accounts.
- Failed and retried calls: define whether these are billable and filter them consistently.
- Allowances and credits: keep free tiers and promotional credits outside the usage total or track them separately.
- Currency and rounding: agree the currency, rounding rules and markup logic with finance before go-live.
For illustrative purposes, a team could sample five customer accounts each cycle and compare the query output with its own billing logs before issuing any invoice.
BI reporting loads Langfuse usage and cost into a warehouse that already holds CRM, product, HR or finance data, so analysts can join LLM spend with business measures. The query should return aggregates at the grain the warehouse needs, on a schedule the data team sets. Data engineers own the pipeline, and analysts or finance partners own the metric definitions. Confirm the output format and pagination behavior in the Metrics API reference before designing the load, since the pipeline depends on them.
- Metric definitions: write down what counts as cost, tokens and latency, and whether they match the Langfuse dashboards that stakeholders already use.
- Grain and keys: choose a grain, such as day by model and feature, that joins cleanly to warehouse dimensions.
- Time zones: store timestamps in one time zone and document it for analysts.
- Idempotent loads: plan how late-arriving data and reruns avoid double counting.
- Schema drift: track changes in the API response and in self-hosted Langfuse versions, and test the pipeline after each upgrade.
Before the first load, compare a sample day in the warehouse with the Langfuse interface, because a pipeline that matches its source is far easier to trust than one that has only been checked once.
Migrating from the deprecated metrics endpoints
Start by inventorying every script, scheduled job, dashboard and BI connection that calls a Langfuse metrics endpoint, because the migration can only be as complete as that list. For each caller, record the endpoint path, the query parameters it sends, the fields it reads from the response, the project and API keys it uses, and who owns the output. Dashboards built in the Langfuse UI and exports pulled into finance or chargeback spreadsheets are easy to miss, so ask the teams that consume the numbers, not only the engineers who wrote the code. Then map each call to its equivalent in the Metrics API v2 reference and note every field that has no direct counterpart, such as a dimension or filter that must be rebuilt or a unit that changed. Confirm each mapping against the current reference rather than against memory of the old endpoint.
Run the old and new calls side by side for a reconciliation window before switching any consumer over. Pull the same time range from both, for the same project, and compare totals for cost, token usage, request counts and latency percentiles. Differences usually come from time zone boundaries, how incomplete recent data is treated, or filters applied on one side only, so document each gap and its cause before accepting it. Agree in writing with finance or the chargeback owner which figures are authoritative during the window and how long the window runs. Do not make the window length a guess: set it from the reporting cycle that the numbers feed.
The platform change is governed separately. The Langfuse v3 to v4 upgrade guide covers the ClickHouse, PostgreSQL and Redis version floors and the observations-first data model, and it advises about 3x ClickHouse disk headroom when backfilling historic data. Plan that disk capacity before you upgrade, not during reconciliation. If your deployment uses the Helm chart with bundled data stores, the chart must move from v1 to v2 before Langfuse moves to v4, so sequence that upgrade first and test it in a non-production environment. Confirm which Langfuse version your instance runs and which SDK versions your applications use, since the Python SDK v5 and JS/TS SDK v6 need Langfuse v4.59.0 or later.
Security and access controls for metrics data
The Metrics API hands out aggregated usage, cost and user-level attributes to whoever holds a valid key, so access control sits at the key, network and data-export layers. In a self-hosted Langfuse, your team owns each of these controls, and the cards below cover the decisions to make before reporting queries reach a BI tool.
Scope keys to one project
Langfuse API keys are issued per project, so a key that can read one project's usage cannot read another's. Create a dedicated key for each reporting job rather than reusing the keys your applications send traces with. Check which project each existing key belongs to before a chargeback or BI extract goes live. Confirm with your Langfuse administrator whether any role on your instance can create keys that span projects.
Store keys in a secrets manager
A reporting key that sits in a notebook, a cron file or a BI connection string is easy to leak and hard to trace. Keep the key in the secrets manager your organization already runs, such as OpenBao or your cloud provider's service, and inject it at runtime. Restrict which service accounts can read the secret and audit those reads. Never commit the key to a repository used for dashboards or reports.
Restrict network access to the API
Your self-hosted Langfuse Web container serves the Metrics API, so the reachable path is part of the access model. Expose the API only on the internal network or through the reverse proxy your BI and finance systems use, and block it from the public internet unless you need it. Confirm which hosts are allowed to reach the API and document the rule in your network policy. Review the rule whenever the ingress configuration changes.
Log who runs reporting queries
Metrics queries can reveal spend by team, model and user, so you need to know which key and which job ran each one. Record requests at your reverse proxy or gateway, with the key identifier, source host and time. Keep the logs in your central log store with a retention period set by your policy. Audit logs inside Langfuse are an Enterprise feature, so confirm whether your plan includes them before you rely on them.
Handle personal data in exports
Trace metadata can contain user identifiers, emails or customer names that developers attached to a trace. When a Metrics result is exported into a BI tool, that data travels with it into a system with its own access list and retention. Aggregate on identifiers you have pseudonymized, drop free-text metadata fields from reporting queries, and confirm the data handling rules with your privacy team. Illustrative example: a per-user cost table keyed on a hashed ID instead of an email address.
Rotate keys on a schedule
Reporting keys should be rotated on a fixed schedule and immediately after a team member with access leaves or a host is decommissioned. Plan the rotation so the old key is revoked only after the BI connection is updated, which avoids a broken dashboard during a finance close. Record each rotation in your change log. Ask your Langfuse administrator how keys are revoked in your version, since the procedure can differ between releases.
Questions teams ask before building metrics reporting
How much does it cost to build Langfuse usage and cost reporting?
Cost depends on the written scope, and DeployOpen does not publish a price list, so a quote follows from the agreed deliverables. The main cost components are the design work (defining dimensions, filters and granularity), the pipeline that pulls data into your chargeback or BI system, and reconciliation against provider invoices. Infrastructure is a separate, recurring cost because ClickHouse, PostgreSQL, Redis or Valkey and blob storage run in your environment. The biggest drivers are the number of Langfuse projects, how many dimensions finance or product teams need, and how much reconciliation your invoices require. Ask for a quote that lists each deliverable, the environments covered, the assumptions about data volume and the items you must provide, such as API access and a named finance contact.
How long does a Metrics API reporting project take?
No researched duration applies to this work, so the timeline should come from your written scope rather than from a general estimate. The schedule depends on how many projects feed the report, how many dimensions and filters you need, and whether the destination system already exists. Platform readiness can add time. Langfuse v4 requires ClickHouse 25.12 or later (26.4 recommended), PostgreSQL 15 or later and Redis 7.0 or later, so an older stack must be upgraded first. Reconciliation with invoices usually takes longer than the query work itself, because each billing period needs checking. Confirm with your provider which steps are in scope and which depend on your change calendar.
Should we use Langfuse dashboards or the Metrics API first?
Start with the Langfuse dashboards to confirm the questions and the numbers, then move to the Metrics API when reports must run on a schedule or feed another system. Dashboards let product and finance users explore cost by model, feature or user without writing code, so they are the fastest way to check that the definitions match what your organization expects. The API suits chargeback pipelines, scheduled exports, joins with billing or HR data, and BI tools that already hold the rest of your figures. Both read the same underlying usage and cost data, so any total that differs between them points to a filter, time window or definition problem. Settle those definitions in the dashboards before you hard-code them into a pipeline.
What does our team need to provide for this work?
You need to provide decisions and access that only your organization can give. Name an owner for cost definitions, including which models, projects and time zones count toward a chargeback period. Agree naming conventions for projects, environments and user or session identifiers, because they become the filters in every report. Provide a scoped API key for the Langfuse project, a destination such as a data warehouse or BI tool, and read access to the ClickHouse and PostgreSQL instances if they are operated by your platform team. Finance should name a contact who can confirm which provider invoices and cost centers each report must match. Missing decisions on definitions cause more rework than missing technical access.
Can our own team build Metrics API reporting without a partner?
Yes, a team with Langfuse operations experience, data engineering skills and a finance contact can build this in-house. The query work is not the hard part. The harder parts are agreeing cost definitions, keeping filters stable as projects change, and reconciling totals with provider invoices each period. Plan for ongoing ownership after launch, because Langfuse upgrades, new models and changes to pricing definitions will alter the numbers. If your team lacks capacity or has no one who has run a ClickHouse-backed platform, a fixed-scope engagement can cover the design, build and handover. Either way, document the definitions and the reconciliation method so a future owner can repeat them.
How much ClickHouse disk do we need for historic backfills?
The Langfuse v3 to v4 upgrade guide advises about 3x ClickHouse disk headroom when backfilling historic data, so a backfill needs roughly three times the disk space of the data being moved. The scaling guide lists minimum resources of 2 CPU and 8 GiB for ClickHouse, with at least 16 GiB of ClickHouse memory for larger deployments. The actual size depends on how much trace history you keep and how many events each day produce, so measure your current ClickHouse volume before you plan the backfill window. Confirm storage growth, replication and backup arrangements in your own environment, and verify that the disk headroom exists before starting the backfill. Metrics reporting over historic periods will not be accurate until that backfill finishes.
Does Metrics API reporting need a Langfuse Enterprise license?
The Langfuse docs list the features that need an Enterprise license key, including project-level RBAC roles, data retention policies, audit logs, server-side data masking, the org management API with SCIM and the instance management API. Those lists do not place the Metrics API on the same list in the sources available to us, but you should confirm that for your Langfuse version before you rely on it. Core features and APIs are described as available in the MIT-licensed open source version. The enterprise code under the ee/ directories is licensed separately, so check the license terms that apply to any component you plan to use. Ask Langfuse to confirm in writing which license covers each reporting feature you need.
How do we check API totals against provider invoices?
Compare totals by model, project and billing period, using the same time zone and window as the provider invoice. Most gaps come from a small set of causes: cached or other usage types billed at different rates, model names that do not match a pricing definition, traces that were never ingested, and events that arrived after the period closed. Each of these should be listed as a known difference in your reconciliation method, with an owner for each one. Record which Langfuse version and pricing definitions produced each report, because a later change to a price or match pattern will change historic totals. Ask the vendor to confirm how ingested cost and inferred cost are reported in your version before you agree on a tolerance.
Limits to confirm in your environment
The Metrics API v2 behaves differently across Langfuse versions, deployments and data age, so the limits below should be checked against your own instance before a chargeback or billing pipeline depends on them. Each item names where to confirm it.
Rate limits and result sizes
Confirm the request rate your reporting jobs can send and the maximum number of rows or time buckets a single query returns. Langfuse's API limits are set per deployment and version, so a nightly export that works in testing can paginate differently in production. Run a full month of data for your largest project and time how long it takes. Ask your Langfuse administrator whether the limits are changed in your configuration, and build retry and pagination into the export job from the start.
Scaling guideDimensions and filters in your version
The set of group-by dimensions and filter fields is tied to the release you run. Before you write a report, list the dimensions your version exposes, such as model, user, session, tags and environment, and confirm that each one you need can be combined with the metrics you need, such as cost, latency and scores. Check the Metrics API reference in your own instance after each upgrade, since a dimension that works on v3 may be unavailable or renamed on v4.
- Latest release listed
- v4.63.0
Cost for self-hosted and custom models
Cost appears in results only when Langfuse can match a model to a price. Self-hosted, fine-tuned and GPU-served models often have no built-in price, so their cost may be zero or missing in aggregated results. Test one query per custom model and compare the totals with your own cost calculation. Confirm how your version handles ingested cost versus inferred cost, and decide before rollout whether missing prices are reported as gaps or excluded from chargeback.
Timestamp and timezone handling
Confirm whether the API returns timestamps in UTC and how time buckets are aligned to day boundaries. A monthly invoice cut at local midnight will not match a UTC-based report if the boundaries differ, and the gap is most visible for requests near midnight. Pick a fixed reporting timezone, run one day of traffic through both the API and the UI, and record the difference. Document the boundary rule in the chargeback methodology so finance can reproduce the totals.
Retention effects on historic queries
Data retention policies, which need an Enterprise license key on self-hosted deployments, can delete traces that a report expects to read. A query for last year's cost will return partial totals if older data has been removed, and the API will not warn you about the gap. Confirm the retention setting on each project, decide whether finance needs a separate archive of aggregated totals, and export monthly figures before deletion windows apply.
License key docsResults during a v4 backfill
The v3 to v4 upgrade moves to an observations-first ClickHouse data model and can backfill historic data. Until the backfill completes, queries over older periods may return incomplete or changing totals, and reports run during the window may not match later runs. Ask your operator when the backfill finishes, plan the ClickHouse disk headroom the migration guide advises, and rerun critical reports after the backfill to confirm they are stable.
- Disk headroom advised
- 3x
How DeployOpen scopes and delivers Langfuse reporting
DeployOpen approaches Metrics API v2 reporting as a defined piece of work inside your self-hosted Langfuse, planned against your chargeback, billing or BI requirements. We confirm the version, data model and query needs first, then build, test and document the extraction so your team can run it afterward.
How we scope
- We list the reports you need: usage, cost, latency and scores, with the dimensions, filters and granularity each one requires.
- We confirm your Langfuse version and whether you are on v4, since the v4 data model affects which queries and fields apply.
- Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts.
- We identify whether any legacy metrics endpoints are in use and include their migration in the written scope.
How we build
- We write the query definitions and client code that pull aggregated usage and cost from the Metrics API v2 into your reporting pipeline.
- We set up authentication with project API keys scoped to the reporting account, stored in your secrets management.
- We test totals against a sample of provider invoices and against Langfuse dashboards before anything feeds billing.
- We build pagination, retry and rate handling so scheduled jobs do not silently drop data.
How we hand over
- You receive the query catalog, extraction code, configuration and a runbook describing each report and its expected output.
- We document the reconciliation steps your finance or data team uses to check totals each reporting period.
- We walk your engineers through how to add a dimension, change a filter or adjust granularity without breaking existing reports.
- Handover includes a written record of the decisions made during scoping, including known gaps in cost data.
How we support
- Ongoing support, upgrades and continuous testing are available as retainers, including checks after Langfuse version changes.
- We can retest reports after a Langfuse upgrade, especially when the v4 data model or SDK versions change field names or behavior.
- Confirm with DeployOpen during scoping which reports, environments and support hours a retainer would cover.

