Tracking LLM cost per user and session in Langfuse

Attribute LLM spend and quality to customers, users and conversations in self-hosted Langfuse, and learn which identifiers to send, how to set them and what to confirm before you rely on per-user totals.

On this page

Tracking LLM cost per user and session in Langfuse starts with identifiers

Per-user and per-session cost in Langfuse depends on identifiers that your application sends with each trace. Langfuse does not infer who a user is or which conversation a model call belongs to, so if your code does not attach those values, the spend exists but cannot be attributed. Teams usually need this when they price usage by customer or seat, enforce rate limits or budgets per user, or investigate a support ticket that asks why one account's answers or bills looked wrong. The same codebase runs in Langfuse Cloud and in self-hosted deployments, and the feature is part of the MIT-licensed open source version, so it does not require an Enterprise license key according to the supplied facts.

Before writing any instrumentation, decide what a user and a session mean in your product. A user is usually a stable internal account or tenant identifier, not an email address or a name, because identifiers that carry personal data also spread personal data into every trace, export and backup. A session is usually one conversation or one workflow run. Confirm with your privacy and security teams which values are acceptable in trace metadata, and agree on one format per identifier across all services, since two spellings of the same customer will split its cost into two rows in every report. Check whether your SDK version and integration pass these fields through unchanged, and confirm the exact parameter names in the Langfuse documentation for your SDK version.

Test the attribution before you rely on it for pricing or limits. Send a few traces from a test account, open them in the self-hosted instance, and confirm that the user and session values appear on each generation and that the cost total for that account matches the model calls you made. Also test the paths that are easy to miss, such as background jobs, retries, streaming responses and calls made through a gateway, because an untagged call will show up as unattributed spend. Record who owns the identifier contract, since a later change to one service's naming will quietly move spend out of existing reports.

How userId and sessionId flow from your application into cost reports

The request starts in your application, which attaches a user and session identifier to each trace before calling the model provider. The trace leaves your infrastructure over OpenTelemetry or an SDK and reaches the Langfuse Web ingestion endpoint, which hands events to the Worker for processing into ClickHouse. Dashboards, the Metrics API and per-user reports then read from ClickHouse. Check that the same identifiers appear on the trace at every hop, because a missing userId or sessionId at ingestion cannot be recovered in later reports.

Identifiers travel with each trace from the application to per-user cost reports.

Which identifiers to send and when each one fits

This table compares four attribution options for Langfuse traces: user, session, customer or tenant grouping, and free-form metadata. For each one it shows the question it answers, the privacy exposure it adds, and what breaks when it is missing or inconsistent across services. Use it to decide which identifiers to standardize before writing instrumentation code.

IdentifierQuestion it answersPrivacy exposureWhat breaks if missing or inconsistent
User identifierWhich individual user generated this spend, and how often do they call the model?High if the value is an email address or name. Lower if it is an opaque internal ID that your team can map back.Per-user cost reports split into unknown buckets, and rate limit or abuse checks miss users who appear under several spellings.
Session or conversation identifierWhich multi-turn conversation or workflow run did this call belong to, and what did it cost end to end?Moderate. A session ID can reveal conversation activity, so treat it as personal data when it links back to a person.Session replay shows fragments of a conversation, and cost per conversation overstates or understates totals when one service sends the ID and another does not.
Customer or tenant groupingWhich paying customer or account should carry this cost for billing, chargeback or pricing reviews?Low to moderate. Account identifiers are usually less sensitive than user data, but they still reveal who your customers are.Invoices and internal chargeback reports do not reconcile, and a customer with several accounts appears as several unrelated spenders.
Free-form metadata (feature, environment, release)Which product feature, environment or version produced this spend or score?Low when values are fixed labels such as feature names. Rises quickly if teams put user content or free text here.Dashboards split by feature or environment show gaps, and staging traffic mixes into production totals when the environment tag is missing on some services.
Shared naming conventionDo all services use the same key names and value formats for the identifiers above?Neutral, but a shared convention lets you review and restrict what personal data reaches traces.Two services that write the same user as different strings or key names produce two users, and per-user totals become wrong without any error being raised.
Trace-level versus observation-level placementIs the identifier set on the whole trace or only on individual model calls and spans?Neutral, but values set on observations may be stored on each child record, widening where personal data appears.Cost reports grouped by user miss generations that carry the value only at the trace level or only at the observation level, so confirm placement before you rely on it.
Confirm field names in Langfuse OpenTelemetry documentationDo the attribute names and their trace or observation scope match the version you run?Neutral. Confirm the exact names before rollout so that personal data is not written to fields you did not intend.Renamed or misplaced attributes are silently ignored, so cost grouping looks correct in code review but returns empty groups in the UI.

Choosing between per-user reports, session replay and rate limits

Finance and product pricing teams use per-user cost reports to see which customers or user groups drive model spend, compare that spend against plan prices, and test whether a pricing tier or usage allowance would hold margin. Attribution data is good for ranking accounts and spotting outliers over a period. It is not reliable for invoice-grade billing on its own, because cost depends on how each generation's usage and price were recorded, and because traces can be missing or late when an application fails to send them. Before building, decide which customer identifier becomes userId (a stable internal ID, never an email address), which tenant grouping rolls users up to billable accounts, the reporting period, and how unattributed spend is handled. Ask whether the cost figures will be reconciled against provider invoices before anyone quotes them to a customer.

  • Pick the billing unit first: decide whether reports roll up by user, workspace or account, and map each user to exactly one account.
  • Plan for unattributed spend: background jobs, retries and system calls often carry no user, so report them as a separate line.
  • Set a reconciliation step: compare monthly totals with provider invoices before pricing decisions depend on them.
  • Agree on cost definitions: confirm with the team whether reported cost is ingested or inferred for each model.
  • Keep personal data out of identifiers: use pseudonymous IDs so reports do not spread personal data further.

Before relying on these numbers, check that the attribution coverage and the reconciliation method are written down.

Propagating userId and sessionId from your application

This sequence turns user and conversation identifiers into a consistent attribution key on every model call, so per-user and per-session cost and quality can be checked against your own test data and your provider invoices before anyone relies on the numbers.

  1. Agree the identifier schema with owners

    Product, engineering and privacy owners agree which identifiers go on each trace: a userId for the customer or account, a sessionId for one conversation, and optionally tenant or feature tags. Write the format, the maximum length, the allowed characters and the owner of each field in a short schema document. The step is done when every owner has signed off on that document and nobody can name a field that is missing from it.

  2. Decide on pseudonymous internal identifiers

    Choose internal, opaque IDs (for example, a random account key from your own database) rather than email addresses, names or phone numbers, because Langfuse stores these values in traces and reports. Confirm with privacy and legal owners how the mapping from internal ID to a person is kept and who can reverse it, and confirm your retention and masking settings for trace data. The step is done when the mapping location and access list are documented and no direct personal identifier is in the schema.

  3. Instrument the application for every model call

    Engineers pass userId and sessionId from the request context into every LLM call, including retries, tool calls and background jobs that run on behalf of a user, so the identifiers travel with the generation rather than being attached only at the HTTP layer. Use the Langfuse SDK or the OpenTelemetry instrumentation your stack already uses, and set the values in one shared helper so no call site is missed. The step is done when a code search or test run shows every model call path passes both identifiers.

  4. Point the exporter at your self-hosted endpoint

    Configure the tracing integration or OpenTelemetry exporter to send traces to your self-hosted Langfuse host, using the OTLP path at the /api/public/otel endpoint if you export through OpenTelemetry. Set the public and secret keys through your secret store, not in source code. The step is done when a single test request appears in the self-hosted UI under the expected project and carries the identifiers you set.

  5. Run a two-user, two-session test

    Run scripted conversations with two test users, each holding two separate sessions, and record the expected number of generations per conversation and the expected token counts from your own logs. Include one call that fails or is retried so you can see how retries are attributed. The step is done when your test log lists every conversation with its identifiers and call count, ready to compare against Langfuse.

  6. Match sessions to their generations

    Open each test session in the Langfuse UI and confirm it contains exactly the generations from your log, with no generation attached to the wrong user or session and no blank identifiers. Check the background job path too, since calls made outside the request can drop context. The step is done when every test session matches your log by count and identifier, and any gap has a recorded cause and fix.

  7. Reconcile per-user totals with invoices

    Compare the per-user and per-session cost and token totals shown in the UI and returned by the API with the provider invoice or usage export for the same test window, using the same time zone and model names. Explain any difference, such as cached tokens, unpriced models or calls made outside the test window. The step is done when the differences are small and explained in writing, and the team agrees the figures can be used for internal reporting or pricing analysis.

  8. Confirm totals in the UI and API

    Repeat the per-user and per-session totals check through the dashboard and through the API that your reports will use, and confirm both return the same values for the same filters. Record the query used so the report can be rerun after any change. The step is done when UI and API totals agree for the test set and the query is saved in your runbook for future reconciliation.

Privacy, access and data handling for user identifiers in traces

Per-user cost and session views only work if the identifiers attached to traces are handled deliberately. The cards below cover what goes into userId and sessionId, who can see the resulting views, how long those traces live, and what the audit trail should show.

Use pseudonymous internal IDs

Set userId to an internal account identifier, such as a random key your application maps to a customer record, rather than an email address or full name. Cost reports then group spend by account without copying direct identifiers into every trace. The mapping table stays in your systems under your own access controls. Check that no other attribute, such as metadata, tags or session names, carries an email or name by accident.

Limit who sees per-user views

Per-user and session pages expose the prompts and completions behind each account, which is more sensitive than the cost totals alone. Project-level RBAC roles, which need an Enterprise license key on self-hosted Langfuse, let you separate people who read cost dashboards from people who open raw traces. Without them, confirm which staff can open any project and document who approved that access.

License key docs

Set retention for identifier-bearing traces

Traces that carry userId and sessionId persist until your retention settings remove them. Data retention policies are an Enterprise feature on self-hosted Langfuse. Decide how long cost history must survive for billing or chargeback, how long raw conversations are needed for support or quality review, and whether deletion requests from users can be carried out in the trace store and the blob storage.

Mask sensitive content server-side

Server-side data masking is an Enterprise feature that can redact sensitive values before they are stored or shown. It helps when users type personal data into prompts, but it does not cover every case. Test masking with realistic but synthetic conversations, confirm that masked fields still allow cost attribution, and confirm what the masking rules do to fields used for session replay.

Audit exports and API reads

Exports of per-user data, whether through the UI, the API or downstream pipelines, move personal information out of Langfuse. Audit logs are an Enterprise feature on self-hosted deployments. Ask whether your edition records who exported or queried user-level data, when, and with which filters, and send those records to the central log store your security team reviews.

Prompts still carry personal data

Identifier choice does not settle the privacy question. Prompts and completions can contain names, contact details, health or financial information typed by the user, even when userId is pseudonymous. Your GDPR analysis and internal data policy must cover the content of traces, not only the metadata. Confirm the lawful basis, retention period and deletion process with your privacy and legal teams before enabling per-user tracing for production traffic.

Using per-user cost for rate limits and pricing decisions

Attribution data is only useful for decisions if the team knows when the numbers arrive and who enforces the limits. The enforcement point must sit in your application or an AI gateway, not in Langfuse reports. Langfuse records usage and cost after the model call has been traced and processed, so a report that shows a user over budget may reflect calls made minutes or more earlier. Before setting a cap, measure the delay in your own environment by sending a known test call with a fixed userId, then checking how long it takes to appear in the UI and in the Metrics API. Confirm how aggregation behaves at the boundaries of a day or billing period as well, because a cutoff that runs on ingestion time can differ from one that runs on the time of the call.

Use Langfuse for the decisions that tolerate lag: spotting outlier users and sessions, reviewing which features drive spend, and deciding whether a tenant should move to a higher pricing tier. A per-user report that shows one account generating far more cost per session than its peers is a signal to inspect prompts, retries or agent loops, and it is usually worth investigating before any cap is introduced. If you use LiteLLM as your gateway, its virtual keys and budgets can enforce hard limits at request time, while Langfuse provides the review trail. Keep the two systems' user identifiers aligned so that a cap in the gateway and a report in Langfuse refer to the same customer.

Before any figure from Langfuse goes into an invoice or a usage-based price, verify it. Cost fields can be ingested from the model provider's response or inferred from model pricing definitions, and the two can diverge when a model is missing a price, when cached tokens are billed differently, or when a custom model has no matching price. Reconcile a sample of traces and the period totals against your provider invoices, and record which cost source each generation used. Ask your DeployOpen team to include this reconciliation step in the scope so that billing rules, caps and the reporting queries are tested together before customers see charges.

Limits to confirm before you rely on per-user totals

Per-user cost figures are only as complete as the identifiers attached to each trace and the version that produced the reports. The items below are what to check against the Langfuse release you run before you use these totals for limits or pricing. Confirm each one on your own instance, and check the current version on the releases page first.

Identifier fields accepted by your SDK mapping

Confirm that the SDK or OpenTelemetry mapping you use passes userId and sessionId into the trace fields that Langfuse reports on, not into metadata that the aggregation views may ignore. Send a test trace with known identifiers from each application and framework, then check that it appears under the expected user and session. Do this for every language SDK and every OTLP-based framework in use, since mappings differ between them.

Langfuse releases

Session replay and per-user views in your version

Confirm that session replay and the per-user views you plan to use exist in the release you run, and that they behave as the documentation describes. Views for users and sessions have changed across releases, so a screenshot from the docs or a colleague's instance may not match yours. Record the version you tested against, so that a later upgrade can be checked against the same cases.

Self-hosting docs

Historic traces without identifiers

Traces recorded before identifiers were propagated will not carry a userId or sessionId. Find out how your reports group these traces, whether they appear as an unattributed total or are dropped from per-user figures, and whether that changes the totals you quote. Ask a team member to reconcile one day of historic spend against the provider invoice before you use per-user totals for pricing or limits.

Backfill headroom during a v3 to v4 upgrade

The v3 to v4 guide moves ClickHouse to an observations-first data model, and it advises about 3x ClickHouse disk headroom when backfilling historic data. Confirm the free disk on your ClickHouse nodes before you start the backfill, and confirm with your own team how long user-level figures stay incomplete during the migration. Plan to re-run the per-user cost test from the previous card after the upgrade completes.

v3 to v4 guide

Dimensions exposed by the Metrics API

Check whether the Metrics API returns cost and usage grouped by the user and session dimensions you need, and whether filters and granularity cover your reporting period. If it does not, your chargeback or rate-limit job will need to join data from another source. Confirm this against the API version your release supports before you write the integration, and do not assume that a dashboard view is available through the API.

Questions teams ask before tracking cost per user

What drives the effort of rolling out per-user cost tracking in Langfuse?

The effort depends mostly on how many applications send traces, how consistently they already pass a stable user identifier and session identifier, and how many model providers and custom models need pricing. Each application needs its trace calls changed to carry userId and sessionId, and the team must agree on what those identifiers are and how they map to customers or accounts. Work also grows with the number of teams that will read the reports, since each audience needs its own views and checks against provider invoices. Ask for a written scope that lists each application, each identifier rule and each report before accepting a quote.

Can our own team set this up without outside help?

Yes, many teams can attribute cost per user with their own engineers, because the core Langfuse features and APIs are available in the MIT-licensed open source version. The parts that usually need more experience are the self-hosted infrastructure, which runs Langfuse Web, Langfuse Worker, PostgreSQL, ClickHouse, Redis or Valkey and S3-compatible storage, and the consistency work across services. A partner is most useful when several teams must agree on identifiers quickly, when the platform must be sized and backed up to a standard your reviewers accept, or when capacity is limited. Compare the internal effort with a written scope before deciding.

How long does a pilot take and what does it depend on?

A pilot's length depends on the number of applications in scope, whether tracing is already in place, and whether the platform must be deployed before any data can flow. Teams with an existing self-hosted instance and one application can start faster than teams that must first build the infrastructure. Other factors are how quickly identifier rules are approved, how many model prices need custom definitions, and how much validation against provider invoices is required. DeployOpen does not state a fixed duration here; the timeline is agreed in the written scope, which lists the milestones and the dependencies your side must meet.

What do our engineers and product owners need to provide?

Engineers need access to the services that emit traces, a way to deploy changes to them, and enough time to add identifier propagation and review the results. Product owners need to define what counts as a user, a customer and a session, and which reports leadership or finance will use. Both groups should agree on how long sessions run and how users who are not logged in are represented. Without these decisions, the cost reports will be accurate in totals but hard to act on, so ask for a list of required inputs in the proposal.

Do user identifiers in traces create privacy obligations?

They can. A userId that maps to a real person or an email address is personal data, and it can be copied into trace metadata, so the GDPR obligations that apply to that data also apply to the trace store. Choose opaque, pseudonymous identifiers where possible, and document where the mapping to a real person is kept. Self-hosted Langfuse gives you control over where data lives, but retention, deletion and masking features that help with these obligations are governed by the license tier, so confirm which of them your plan includes. Your privacy or legal team should review the identifier design before rollout.

How does this relate to the Enterprise license?

Per-user and per-session tracking uses core features, so it does not require an Enterprise license key on its own. The Enterprise license key unlocks specific features such as project-level RBAC roles, data retention policies, audit logs, server-side data masking and SCIM provisioning. If your reviewers require retention, deletion or masking controls over user-level data, those controls may need the Enterprise license key, so check the license key documentation and the current pricing page before you finalize the design. Confirm the license terms with Langfuse directly, since DeployOpen does not set those terms.

What does a fixed-scope engagement typically cover for this work?

A fixed-scope engagement covers the agreed items in writing before work starts, such as the identifier design, the code changes to propagate userId and sessionId, the report definitions, and the validation steps. It may also cover the self-hosted deployment and sizing if that is in scope, along with handover documentation and a retest of agreed fixes. Items outside the written scope, such as new applications or additional reports, are handled through a change to that scope. Ask for a quote that lists each deliverable, each assumption about your environment and each acceptance check.

How DeployOpen scopes and delivers user-level cost tracking

DeployOpen plans and implements user and session attribution for Langfuse inside your own infrastructure, from how your application passes identifiers to how your teams read per-user spend. Engagements are fixed-scope, with the scope, deliverables and timeline agreed in writing before work starts.

How we scope

  • We map which customer, tenant, user and conversation identifiers your application already holds and which ones are safe to send to Langfuse.
  • The written scope lists the instrumentation points, session boundaries and reports covered, so pricing and rate-limit decisions have a defined data source.
  • We confirm with your privacy and security teams which identifiers count as personal data and how long attributed traces should be kept.

How we build

  • We propagate userId and sessionId through your services and confirm they appear on generations in a self-hosted Langfuse test instance.
  • We check that per-user cost totals reconcile with provider invoices for a sample period, and document any gaps caused by missing usage fields.
  • We test session replay, per-user reports and any export or rate-limit hook against representative traffic, including unattributed requests.

How we hand over

  • You receive the attribution specification, the identifier mapping, and the code or configuration changes, with a record of what was tested.
  • We document how to read per-user and per-session cost in the UI and through the API, and which fields are required for reports to be complete.
  • We walk your engineering, finance and compliance owners through the runbook so the attribution keeps working after the engagement ends.

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers, including checks after Langfuse version changes and SDK updates.
  • We can review attribution coverage periodically, flagging requests that arrive without a user or session identifier.
  • Retainer scope, response expectations and any support SLA are agreed in writing, and we confirm them with you before the retainer starts.

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.