Track and Cap LLM Cost per Customer (With Real Numbers)

OpenRouter ·

Track and Cap LLM Cost per Customer (With Real Numbers)

When you charge customers a flat monthly fee for an AI product, they all pay the same price, but they don’t necessarily cost you the same amount. One customer might send short requests to a smaller model, while another sends long documents to a more expensive one. That difference can significantly affect your margins, even before you consider whether you’re using the most cost-effective model for each task.

We tested this with three simulated customers, each making ten requests. The most expensive customer’s requests cost 225 times as much as the cheapest’s. We also checked the costs against three reporting sources and tested what happens when an API key reaches its spending limit.

In this article, we’ll show you how to track LLM cost per customer by tagging requests with customer IDs, recording actual charges, and verifying your totals match. We’ll also look at how to enforce spending limits in your application or through individual OpenRouter API keys, including what happens when those limits are reached.

Tl;dr

  • Request count alone doesn’t tell you what a customer costs. In our test, ten requests per customer cost between $0.0030792 and $0.693814.
  • Pass a stable customer ID in the user field and record usage.cost from each response instead of estimating charges from token counts.
  • Check your totals against generation records and Broadcast. All 30 requests in our test matched once reporting caught up.
  • For customers sharing one API key, enforce spending limits in your application. Use per-customer API key limits when customers have separate keys.
  • A $0.02 key limit blocked our 15th request, while another key accumulated $0.067792 against a $0.05 limit before the next request was rejected.

Why does LLM cost vary so much between customers?

LLM cost depends on how many tokens a request uses and the price of the model handling it. Two customers can make the same number of requests and end up with very different bills.

On October 28, 2026, we tested a support-ticket summarization workload with three simulated customers on the same flat-price plan. Each made ten requests with max_tokens set to 2000. Two used Claude Haiku 5.5, while the customer generating detailed reports used Claude Sonnet 5.5.

CustomerModelWorkloadInput tokensOutput tokensTotal cost
cust_globexClaude Haiku 5.5Three-bullet summary of 5 tickets5,1625,126$0.0030792
cust_initechClaude Haiku 5.5Five-bullet summary of 60 tickets59,51516,761$0.014332
cust_acmeClaude Sonnet 5.5Detailed report on 250 tickets246,90720,000$0.693814

For the same ten requests, Acme cost about 225 times as much as Globex and 48 times as much as Initech, largely because it processed more text and used a more expensive model. Acme consumed nearly 48 times as many input tokens as Globex and generated almost four times as many output tokens, with every response reaching the 2,000-token limit. It also used Claude Sonnet 5.5, which cost 20 times as much per input or output token as Claude Haiku 5.5 at the rates used in our October 28 test, so allowing longer reports could have increased the cost further.

How to attribute each request to a customer

Pass a stable internal customer identifier in the user field of your Chat Completions request. This lets us associate the generation with the customer who triggered it, even when several customers share one API key.

Use identifiers such as cust_globex or customer_abc123, not email addresses or other personal information. Keep the same identifier across requests.

The following Python example sends a request, reads its cost, and saves a record to a local SQLite database. You’ll need requests installed and your OPENROUTER_API_KEY environment variable configured.

import os
import sqlite3
from decimal import Decimal

import requests

customer_id = "cust_globex"

response = requests.post(
    "https://openrouter.ai/api/v1/chat/completions",
    headers={
        "Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}"
    },
    json={
        "model": "anthropic/claude-haiku-5.5",
        "user": customer_id,
        "messages": [{
            "role": "user",
            "content": (
                "Summarize these support tickets in three bullets: "
                "Login fails; duplicate invoice; password reset; "
                "delayed email; incorrect billing address."
            )
        }],
        "max_tokens": 2000,
    },
    timeout=60,
)

response.raise_for_status()
data = response.json(parse_float=Decimal)

if data.get("error") or not data.get("choices"):
    raise RuntimeError(f"Completion failed: {data.get('error')}")

cost = data.get("usage", {}).get("cost")

with sqlite3.connect("customer_costs.db") as db:
    db.execute("""
        CREATE TABLE IF NOT EXISTS costs (
            generation_id TEXT PRIMARY KEY,
            customer_id TEXT NOT NULL,
            model TEXT NOT NULL,
            cost_usd TEXT,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP
        )
    """)
    db.execute(
        "INSERT INTO costs "
        "(generation_id, customer_id, model, cost_usd) "
        "VALUES (?, ?, ?, ?) "
        "ON CONFLICT(generation_id) DO UPDATE SET cost_usd = excluded.cost_usd "
        "WHERE costs.cost_usd IS NULL AND excluded.cost_usd IS NOT NULL",
        (data["id"], customer_id, data["model"], None if cost is None else str(cost)),
    )

if cost is None:
    raise RuntimeError(f"Request cost unavailable for {data['id']}; reconcile later")

print(f"{customer_id}: ${cost}")

The code stores each generation ID as a unique record, preventing the same response from being counted twice if you retry the logging operation. We also store the returned cost as a decimal string to avoid floating-point rounding errors when summing requests and reconciling the totals later.

This is a small accounting example, not a complete billing system. In production, you would connect the customer ID to your authenticated account or tenant, store the record in your application database, and aggregate it over your billing period.

Diagram showing per-customer cost tracking: app tags requests with a user ID, OpenRouter returns usage.cost to a usage ledger, and spend is capped by an app-level soft cap and a key-level credit limit.

Our User Tracking cookbook explains the identifier behavior. We don’t forward the raw user string to model providers. Where a provider requires an identity, we incorporate it into the hashed identifier sent upstream. This also helps isolate provider abuse blocks between your customers.

How to get the exact cost of each request

Read usage.cost from the response rather than calculating cost yourself from token counts. OpenRouter includes usage accounting in completed API responses. Alongside the token counts, the usage object includes the amount charged to your account and a cost_details breakdown where available.

In a separate probe request, the usage object included the following cost details:

{
  "cost": 0.0000033,
  "cost_details": {
    "upstream_inference_prompt_cost": 0.0000013,
    "upstream_inference_completions_cost": 0.000002
  }
}

Use usage.cost to record the amount charged to your OpenRouter account. The cost_details fields provide a breakdown of the upstream inference costs, which can be useful when auditing charges but shouldn’t be counted as additional customer spending.

You can also retrieve the stored record using the generation ID:

curl -G "https://openrouter.ai/api/v1/generation" \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  --data-urlencode "id=YOUR_GENERATION_ID"

The generation lookup returns fields including external_user, total_cost, model, and provider_name. In our probe, the stored record returned external_user: “customer_probe” and total_cost: 0.0000033, matching the original response.

Don’t use GET /api/v1/key as your per-request cost meter. It reports key-level usage and remaining limits, but the counter can lag.

We saw why this matters when testing a capped key. After 14 completed requests, the sum of their returned costs was $0.0198737, but GET /api/v1/key still reported $0.0127335. An earlier read had even returned a lower amount than the previous one. We couldn’t establish why those readings moved backward, so we wouldn’t use this endpoint to attribute individual request costs.

Instead, record usage.cost as each request finishes and use the key endpoint to inspect the key’s overall usage and remaining limit.

How to check and reconcile your customer cost totals

A reliable cost ledger should agree with the records OpenRouter keeps. We compared three sources: the sum of usage.cost from our responses, the stored generation records, and the costs exported through OpenRouter Broadcast.

Here’s how the totals compared across all three sources:

CustomerResponse costsGeneration lookupBroadcast
cust_globex$0.0030792$0.0030792$0.0030792
cust_initech$0.014332$0.014332$0.014332
cust_acme$0.693814$0.693814$0.693814

All three sources matched in our test, although the generation lookup took longer to return the complete records. When we first checked within about a minute of the requests, Acme’s lookup total was only $0.416382 instead of $0.693814. By our next check roughly a minute later, the missing records had appeared, and all three totals agreed.

Broadcast also delivered records for all 30 requests in this test. It can export customer identifiers and generation costs to your configured observability or analytics destination without requiring you to write a separate exporter. The exact field names depend on the destination; our exported traces used user.id and gen_ai.usage.total_cost.

For complete reconciliation, configure Broadcast to send all requests rather than sampling only a percentage. You can enable Privacy Mode on a destination to exclude prompts and completions while preserving usage and cost metadata.

Record usage.cost when each request finishes, then use the generation lookup and Broadcast to reconcile your totals. If a generation record is missing, retry the lookup before treating the difference as an accounting error.

How to cap a customer’s LLM spend

You can enforce customer limits in your own application or assign each customer a separate OpenRouter API key with a credit limit.

The right approach depends largely on how your customers use the product.

Application-level limits for customers sharing a key

If thousands of customers use your product through one backend API key, maintain a month-to-date total for each customer in your database.

Before making a request, check the customer’s remaining budget. For a soft limit, you can reject the request or switch to a cheaper model once spend reaches the cap.

For a hard cap, checking only whether the cap has already been reached isn’t sufficient—even with a single request in flight, a request that could cost $0.03 would slip through when $0.01 remains, and concurrent requests can each pass a simple balance check before any cost is recorded. Before sending a request, compute a maximum-cost reservation from the prompt size, the highest eligible route or fallback pricing (or constrain routing and fallback prices to fit), max_tokens, and any additional charges your workload uses, and verify atomically that the reservation fits the remaining balance. Once the response returns usage.cost, replace the reservation with the actual charge and release the difference.

Key-level limits for customers with separate keys

For large business customers or integrations that warrant separate credentials, create an API key for each customer and set a spending limit.

You can configure limits in the dashboard or use the API Keys Management API. For example, the following creates a test key with a $0.02 monthly limit:

curl -X POST "https://openrouter.ai/api/v1/keys" \
  -H "Authorization: Bearer $OPENROUTER_MANAGEMENT_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "cust_initech_test",
    "limit": 0.02,
    "limit_reset": "monthly"
  }'

The Management API requires a management key. When the request succeeds, the response includes the new API key in the key field and its configuration in data. Save the plaintext key securely, since it cannot be retrieved later. You can configure limits to reset daily, weekly, or monthly, or have no reset, with scheduled resets occurring at midnight UTC.

We tested a key with a $0.02 limit by sending Claude Haiku 5.5 requests with max_tokens set to 2000. The first 14 requests succeeded and cost $0.0198737, but the fifteenth returned HTTP 402 with error.metadata.limit_source set to openrouter_key_limit.

The error showed why the request was rejected:

{
  "error": {
    "code": 402,
    "message": "This request requires more credits, or fewer max_tokens. You requested up to 2000 tokens, but can only afford 252.",
    "metadata": {
      "limit_source": "openrouter_key_limit"
    }
  }
}

Although the key hadn’t spent its full $0.02 allowance, the remaining credit wasn’t enough for the requested output limit. Reducing max_tokens could have allowed a smaller request through.

In a separate test on November 3, 2026, we ran an agent using Claude Sonnet 5.5 against a key limited to $0.05. Three requests completed and accumulated $0.067792, about 36% over the limit, before the fourth was rejected. The requests ran sequentially, but the result suggests the completed charges weren’t fully reflected when later requests were checked. We observed the overshoot, although we’d need the underlying accounting timestamps to confirm exactly where the delay occurred.

These tests show that key limits can help control spending, but they aren’t enough on their own when you need to enforce an exact customer budget. In that case, combine application-level accounting and spending reservations with a conservative key limit rather than relying on the key’s usage counter alone.

Organization Guardrails provide additional controls for member or key budgets, but they don’t replace application-level cost attribution for customers sharing a single key.

Next steps

Start by tagging requests with a stable customer ID and saving their returned costs. Reconcile those records against generation metadata or Broadcast, then choose whether your customers need application-level budgets, separate key limits, or both.

Our User Tracking and Usage Accounting cookbooks cover the request fields and cost records, while the API key documentation explains how to configure limits.

Frequently asked questions

Does the user field get sent to the model provider?

We don’t forward the raw user value to model providers. When a provider needs an end-user identity, we incorporate it into a hashed identifier. On the Responses API, safety_identifier controls the identity used for upstream abuse isolation, but it doesn’t attribute requests to a customer. Continue sending user for cost tracking, and use a stable, non-personal identifier.

How do I set a monthly limit per customer?

You can create a separate API key for each customer and configure its limit in USD with limit_reset set to monthly. For customers sharing a key, calculate each customer’s monthly spend from usage.cost records and enforce the limit in your application before submitting more requests.

Why was my request rejected before the key’s limit was reached?

OpenRouter checks whether the remaining credit can cover the estimated cost of a request, including the maximum allowed output tokens. A request may therefore receive a 402 even when some credit remains. Reducing max_tokens can allow a smaller request through, provided the remaining balance is sufficient.

Can I see cost per customer without writing code?

Yes. If your requests include customer IDs, you can use Activity Explore to view spending grouped by custom user ID without building your own reporting dashboard. For more detailed analysis or exporting costs to a warehouse, you can also enable Broadcast under Settings > Observability and connect a supported destination such as PostHog, Langfuse, or Snowflake. You’ll still need application logic to enforce budgets when multiple customers share one API key.

By subscribing you agree to receive the OpenRouter newsletter: model usage data, product updates, and research reports, about one email a week. Unsubscribe anytime via the link in every email. See our Privacy Policy.