Skip to content
Blog
October 24, 2026Architecture8 min readUpdated November 3, 2026

How to track LLM cost per user request with subagents: provider usage APIs vs traces vs a lineage ledger

To track LLM cost per user request when agents spawn subagents, record one row per model call carrying the root request id, the parent id and the delegation depth, then sum with one GROUP BY. Provider usage APIs report by key, project and workspace; trace sums are exact when traces are kept unsampled.

byPleach maintainers

Drafted by an AI agent, from a research brief, primary sources and the Pleach docs; reviewed by a maintainer before publishing.

No @pleach/* package is on npm yet. Each name holds a 0.0.1 placeholder until its first release, so the code here describes the source, not an install that works today. Package status

To track LLM cost per user request when an agent spawns subagents, record one row per model call that carries the root request id, the parent id and the delegation depth, then sum the rows with one GROUP BY on the root id. Provider usage APIs group by API key, project or workspace in time buckets, which makes them the tool for invoice reconciliation. Summing token attributes over a trace gives exact totals when traces are kept unsampled. Baggage carries the request id downstream; a span or row records it.

This post compares the four approaches on the properties that decide a billing number. For the ledger row itself, see adding an audit ledger without rewriting your agent loop. For how a per-call row compares with traces as a record, see hash chain vs append-only table vs OTel traces.

PropertyProvider usage / cost APITrace sum (OTel GenAI)Baggage / context propagationPer-call ledger row with lineage
Finest grainTime bucket × key, project, workspace or modelOne span per inference callNone; it carries an id, it stores nothingOne row per model call
Grouping keyAPI key, project, workspace, modelTrace idKeys you choose, once copied onto a span or rowRoot request id
Survives async or queued subagentsN/A; the provider sees every callOnly if context is injected into the messageOnly if injected into the messageYes, if the id is written on the row
Needs sampling offNoYes, for exact totalsN/ANo; nothing samples it
Query costPaginated API read per time rangeFetch and walk the traceN/AOne flat aggregate per request
Joinable to your billing tablesOnly by key or projectOnly after exportN/AYes, it lives in your database

These approaches sit at different layers, so the comparison isn't like-for-like. Most teams run two of them: a per-request record for attribution, and the provider API to reconcile the invoice.

What do the OpenAI and Anthropic usage APIs report?

Both providers report usage in time buckets, grouped by account-level dimensions such as key, project, workspace and model.

OpenAI's Usage and Cost API cookbook groups completions usage by fields such as model, project_id and user_id. Its bucket_width takes 1m, 1h or 1d, with 1d as the default. The costs endpoint groups by line_item or project_id, and the cookbook's code notes "Currently only '1d' is supported." Both endpoints need an Admin API key.

Anthropic's Usage and Cost API has the same shape. The usage endpoint aggregates into 1m, 1h or 1d buckets. It filters and groups by API key, workspace, model, service tier, context window, data residency and speed. The cost endpoint offers "only daily granularity (1d)" and groups by workspace or description. Data "typically appears within 5 minutes of API request completion."

Anthropic marks that API as legacy and points new integrations to a Usage and Cost Analytics API "with more grouping and filtering dimensions."

The common pattern is one key or one project per tenant, which yields per-tenant spend. Splitting one user request across its subagents happens in your own records. The provider API then serves reconciliation; Anthropic's docs list "cost reconciliation" as a stated use.

Can you sum gen_ai.usage tokens over an OpenTelemetry trace?

Yes, when every span is kept and every call reports usage. The trace id then serves as the request id, and child spans from subagents share it.

The OpenTelemetry GenAI client inference conventions define the attributes. gen_ai.usage.input_tokens is "the number of input tokens reported by the provider for this inference operation." gen_ai.usage.output_tokens is the output-side twin. Both are Recommended, not Required. The input count "SHOULD include cached tokens," and cache reads appear separately as gen_ai.usage.cache_read.input_tokens. The document's status is Development, so names can still change.

The spans hold tokens, not dollars. You apply a price table at query time, which means the price lives outside the record.

Sampling is a deliberate design choice in tracing. OpenTelemetry's sampling page says head sampling decides "as early as possible," before the trace is complete. Tail sampling decides "by considering all or most of the spans within the trace." Unsampled spans are not exported, so exact cost totals need the cost-bearing traces kept.

Probability sampling can attach an adjusted count to each kept span. The spec calls it "an estimate of the number of spans there would be without sampling." That serves aggregate metrics, such as span-to-metrics pipelines.

The sampling page also lists when not to sample. One case is when "regulation or similar requirements prohibit dropping data." Billing a customer from a trace store is close to that case. Run cost traces unsampled, or record cost somewhere that isn't sampled.

How do you carry a request id into subagents?

Propagate it as context, and write it onto every record the subagent produces. Propagation alone records nothing.

Context propagation is "the mechanism that moves context between services and processes." The default propagator uses W3C TraceContext headers. Baggage adds arbitrary key-value pairs, such as a tenant id or a root request id, that travel with that context.

Three points from the docs shape how you use it:

  • Baggage is "unassociated with attributes on spans, metrics, or logs" until you copy it on. Some languages ship a Baggage Span Processor that does this.
  • OpenTelemetry advises reading baggage with caution and keeping sensitive values out of it, since it travels in headers.
  • The W3C Baggage spec sets minimum propagation limits of 64 list members and 8192 bytes. A root id and a tenant id fit well inside that.

Queued and background subagents need one extra step, because in-process context stays in its process. The propagation page says that over a protocol without a metadata field, the receiver must extract the context before processing. So the producer injects the root id into the job payload, and the worker restores it before its first model call.

A subagent that runs after the user's response has streamed is still part of that request's cost. Whether to bill it to that request is a policy choice. Decide it explicitly, and record the choice.

What should a per-call cost row record?

One row per provider dispatch, with the request lineage written at insert time. Three fields carry the lineage:

FieldJobWhat breaks without it
Parent idPoints a subagent's call at the request that spawned itChild calls float free of any user message
Root idNames the depth-0 user request, on every rowRolling up a deep tree needs a recursive query
DepthCounts delegation levels below the requestYou can't see what each fan-out tier cost

A parent pointer alone works in theory. In practice, a three-level tree means a recursive CTE on every billing query. Storing the root on every row turns that into a flat GROUP BY.

Add a tenant id, the tool that caused the call, the model and provider, the token counts, and the cost as computed when the call ran. Write a row for retries and for calls cut off by a timeout, since the provider bills those too.

Why shouldn't missing usage count as zero?

Because a missing count is unknown, and summing it as zero makes an expensive request look cheap.

Usage can be absent from a record in ordinary ways. OpenAI's chat completions reference says streamed chunks carry a usage field "with a null value" except for one final chunk. It adds: "If the stream is interrupted, you may not receive the final usage chunk." A model missing from your price table produces the same gap on the cost side.

SUM() in SQL skips NULL, so the total silently becomes a floor. Count unknown-cost calls in their own column. Treat any request with a non-zero count as a lower bound, not a final number.

When to use each

  • You need monthly spend per tenant and can issue one key or project per tenant: the provider usage API is enough.
  • You need to reconcile your records against the invoice: the provider cost API, compared against your own totals each day.
  • You want latency and token debugging per request, and sampling is acceptable: sum gen_ai.usage.* over the trace.
  • Subagents run in other processes or on a queue: propagate the root id in context and in the job payload, and write it onto every record.
  • You bill customers per request or need cost at each delegation depth: a per-call ledger row with root id, parent id and depth.

How Pleach does it

Pleach's audit ledger takes the per-call row approach. With an AuditEmitter registered, every LLM call in @pleach/core writes one AuditableCall row through a ProviderDecisionLedger. The default emitter is a no-op; rows land once the host registers an emitter, which the quickstart does. See packages for package status.

The lineage columns

The AuditableCall row reference spells the fields:

FieldMeaning
turnIdStable across retries within a turn. On a subagent row, the subagent's own sub-turn key
parentTurnIdSubagent rows only: the spawning user turn's key. Unset on a root row
(derived root turn)Own turnId on a root row, else the spawning user turn
subagentDepth0 on a root row, 1 for a direct child, 2 for a grandchild
toolNameThe tool whose execution caused the call. On a subagent row, the tool that spawned it

Per-call rows carry a modelCall slot in the payload JSONB with inputTokens, outputTokens, cachedInputTokens, and costUsd. Every provider dispatch gets its own row, retries included, with no sampling. A call cut off by Stop or a timeout still gets its row, per the subagents page.

The rollup query

This follows the query in the lineage columns section:

Ask the call ledger for one result per user turn, grouped on the root turn and filtered to one tenant and to per-call rows only (one per dispatch). For each root turn, return the call count, the deepest delegation depth, the sum of known cost, and the count of calls with an omitted cost.

A missing costUsd is an unknown cost, never $0. Group on the subagent depth or the tool name instead to see which tier or tool drove spend. The tenant is the per-customer axis, covered in multi-tenant.

Rows written before the lineage columns existed have no root turn. Across mixed history, group on the root turn, falling back to the parent turn and then the turn itself.

The in-process read

runtime.getTurnCostRollup() on the root runtime returns self, descendants, and total buckets for one turn, plus partial and truncated flags. It keeps the 32 most recently recorded turns and excludes background async.spawn tasks. The subagents page lists its other limits. Use it for live UI and budget checks; use the ledger query for reporting.

With hashChain: true, PostgresProviderDecisionLedger also chains the rows, so edits to the cost record are detectable. The hash chain page covers verification and its limits. The landscape page places this next to other approaches.

Key takeaways

  • Provider usage APIs report at the account layer. OpenAI and Anthropic group by key, project, workspace and model, in 1m to 1d buckets, with daily cost.
  • Trace sums are exact when cost traces are kept unsampled. The GenAI token attributes are Recommended and in Development status.
  • Propagation carries the id; it doesn't record it. Copy baggage onto spans or rows yourself, and inject it into queued jobs.
  • Store the root id on every row. A flat GROUP BY replaces a recursive tree walk at any delegation depth.
  • Unknown cost is not zero. Count calls with missing usage or price apart, and report the total as a floor.

References

  1. OpenTelemetry. GenAI semantic conventions: Client Inference.
  2. OpenTelemetry. Sampling.
  3. OpenTelemetry. TraceState: Probability Sampling.
  4. OpenTelemetry. Context propagation.
  5. OpenTelemetry. Baggage.
  6. W3C. Propagation format for distributed context: Baggage.
  7. OpenAI. How to use the Usage API and Cost API to monitor your OpenAI usage.
  8. OpenAI. Create chat completion: API reference.
  9. Anthropic. Usage and Cost API.

Frequently asked

How do I track LLM cost per user request when an agent spawns subagents?

Write one row per model call that names the user request it belongs to. Each row carries a root request id, a parent id and a delegation depth, plus the call's tokens and cost. One GROUP BY on the root id then sums the request at any depth. Provider usage APIs complement this: they group by API key, project or workspace in time buckets, which suits invoice reconciliation.

What do the OpenAI and Anthropic usage APIs report?

Token usage in time buckets of 1m, 1h or 1d, and cost in daily buckets. OpenAI groups completions usage by fields such as model, project_id and user_id, and cost by line_item or project_id. Anthropic's usage endpoint groups by API key, workspace, model, service tier and more. Both are account-level reports, built for monitoring spend and reconciling it against the invoice.

Can I sum gen_ai.usage.input_tokens over an OpenTelemetry trace to get request cost?

Yes, if every span in the trace is kept and every call reports usage. The GenAI conventions define gen_ai.usage.input_tokens and gen_ai.usage.output_tokens per inference operation, and their status is Development. For exact per-request totals, keep cost traces unsampled; adjusted counts from probability sampling are designed for estimating volume across many traces.

How do I carry a request id into subagents that run on a queue?

Put it in the message, not only in the in-process context. OpenTelemetry's default propagator uses W3C TraceContext headers, and baggage carries arbitrary key-value pairs. Neither crosses a queue when the producer injects it into message metadata and the consumer extracts it. Baggage is a separate store from span attributes, so read it and set it as an attribute yourself.

Is a missing token count the same as zero cost?

No. A missing count is unknown, not zero. With streaming, OpenAI delivers total usage in one final chunk, so a stream that ends early may carry no usage figure. Summing that call as zero understates the request. Count calls with no usage or no price separately, and report the total as a floor when that count is above zero.

How does Pleach attribute subagent cost to the user turn?

Each model call writes its own audit row with its parent turn, root turn and subagent depth. The root turn names the depth-0 user turn on every row, so one group-by-root-turn query over the call ledger sums a turn at any delegation depth. A missing costUsd is counted as unknown, never $0. runtime.getTurnCostRollup() gives an in-process read of the same turn.

llm cost trackingsubagentscost attributionopentelemetrymulti-agenttoken usage

Related posts