lucidity.sh platform
← All posts

Per-Customer AI Cost Tracking for Multi-Tenant SaaS: Keys, Metering and Budgets

If you sell an AI feature to other businesses, you need to know what each customer costs you, stop one customer from spending everyone's balance, and price with a margin. This is how to do all three on Synth 2.5.

Short answer: create one API key per customer and also log every response in your own database. Record the model that answered and the usage token counts, and price each request at that model's rates. Then the platform's Usage page and your log are two independent records you can reconcile. The platform has no per-key spending caps, so enforce each customer's budget in your code before the call, and downgrade to synth-2.5-flash as a soft limit before you block.

How the platform bills a request

Everything below follows from four billing facts:

  • Per token, prepaid. Each request is charged input tokens × input rate plus output tokens × output rate, from one account balance. Synth 2.5 Pro is $0.10 / $0.20 per million tokens; Synth 2.5 Flash is $0.03 / $0.10. No monthly fee.
  • The served model sets the rate. A request for synth-2.5-pro can be answered by synth-2.5-flash when Pro is over its shared limit of 5 requests per minute. It is then billed at Flash rates, and the response's model field says so.
  • The response tells you what you paid for. On a normal (non-streamed) response, usage.prompt_tokens and usage.completion_tokens are the numbers billed. usage.estimated is true when the model server reported no counts and the platform estimated them at about three characters per token.
  • Every key shares the balance. When it runs out, every key gets 402 at once. One runaway customer can take the feature down for all of them unless you stop it first.

Fallback, retries and per-request cost for a single integration are covered in the Synth 2.5 production guide. This post is about splitting that cost across many customers.

Key per tenant or shared key

SetupYou getYou give up
One key per tenantPer-tenant totals in the Usage page and CSV; pause one tenant without touching others; a leaked key exposes one tenantMore keys to store; you create them in the dashboard
One key per environment, tenant in your DBFewest secrets; simplest setupThe platform cannot split cost by tenant; your own log is the only record
Both: key per tenant, plus your own logTwo independent records you can reconcileSlightly more work up front

Use both. A key per tenant costs little, and it pays off the first time a customer disputes a bill or a key leaks. On the LuciditySH Platform:

  • The Usage page filters by key and groups by key or model over 7 days, 30 days or month to date. Export CSV writes one row per day with total cost, requests, tokens and one cost column per key.
  • Pausing a key makes its requests fail with 401 right away; resuming restores it. Use it for a customer who stops paying, without deleting anything.
  • Revoking a key keeps its past usage. Daily usage is stored with the key's name at the time, so history survives the key.
  • Key names can be up to 64 characters. Use a stable id, such as tenant-4821-prod, rather than a company name that might change, and don't rename keys mid-month.

Store each tenant's key encrypted, like any credential. The full secret is shown once, when you create it.

Meter every response

The platform's Usage page is daily and per key. Your product needs more: cost per feature, per user inside a tenant, per request. So log each call yourself. If your calls go through LangChain, LiteLLM or the Vercel AI SDK, the same fields are available there; see our framework setup guide. A table that covers it:

CREATE TABLE llm_usage (
  id                BIGSERIAL PRIMARY KEY,
  tenant_id         TEXT        NOT NULL,
  feature           TEXT        NOT NULL,          -- 'chat', 'blurbs', ...
  requested_model   TEXT        NOT NULL,
  served_model      TEXT        NOT NULL,          -- response "model" field
  prompt_tokens     INTEGER     NOT NULL,
  completion_tokens INTEGER     NOT NULL,
  estimated         BOOLEAN     NOT NULL DEFAULT false,
  cost_usd          NUMERIC(12,8) NOT NULL,
  created_at        TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX llm_usage_tenant_month ON llm_usage (tenant_id, created_at);

And a wrapper that every Synth call goes through. The two lines that matter are pricing by data.model rather than the model you asked for, and keeping the estimated flag:

const BASE = 'https://platform.lucidity.sh/v1'
// USD per 1M tokens. Keep in step with the platform's Models page.
const RATES = {
  'synth-2.5-pro':   { in: 0.10, out: 0.20 },
  'synth-2.5-flash': { in: 0.03, out: 0.10 },
}

export async function completeForTenant(tenant, feature, body) {
  const model = await pickModel(tenant, body.model)          // budget check, below
  const res = await fetch(`${BASE}/chat/completions`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${tenant.lucidityKey}`,      // one key per tenant
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ ...body, ...model }),
  })
  if (!res.ok) throw new Error(`LuciditySH ${res.status}`)
  const data = await res.json()

  const served = data.model                                  // may be Flash after a fallback
  const { prompt_tokens: pin, completion_tokens: pout, estimated } = data.usage
  const rate = RATES[served]
  const cost = (pin * rate.in + pout * rate.out) / 1e6

  await db.query(
    `INSERT INTO llm_usage (tenant_id, feature, requested_model, served_model,
       prompt_tokens, completion_tokens, estimated, cost_usd)
     VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`,
    [tenant.id, feature, body.model, served, pin, pout, Boolean(estimated), cost],
  )
  return data
}

Keep the rate table in one place and date it. If prices change, you want old rows priced at old rates, which is why the table stores cost_usd per row instead of computing it at report time.

Streaming responses

A streamed response carries no usage unless you ask for it. Send "stream_options": {"include_usage": true} and the last chunk before [DONE] has the token counts. Streams need two extra cases:

let usage = null, chars = 0
for await (const chunk of stream) {           // OpenAI SDK, stream: true
  if (chunk.usage) usage = chunk.usage          // last chunk, needs include_usage
  chars += chunk.choices[0]?.delta?.content?.length ?? 0
}
// Client hung up before the usage chunk? Estimate the way the platform does.
const pout = usage?.completion_tokens ?? Math.ceil(chars / 3)
  • The user closes the tab. The platform bills the tokens already delivered, and you never see the usage chunk. Estimate from the characters you received, as above, and set estimated.
  • Small differences are normal. Streamed requests are metered with the platform's character-based estimate, so your log and the platform's total can differ by a few percent on streaming-heavy tenants. Reconciliation, below, absorbs this.

Read the served model from the chunks' model field. Fallback on a stream only happens before the first byte, so it is the same in every chunk.

Per-tenant budgets and soft limits

The platform enforces one limit, the account balance, and it is shared. Per-customer limits are yours to build, and your usage log already holds what you need:

const MONTH_SPEND = `SELECT COALESCE(SUM(cost_usd), 0) AS spent FROM llm_usage
  WHERE tenant_id = $1 AND created_at >= date_trunc('month', now())`

async function pickModel(tenant, requested) {
  const { rows } = await db.query(MONTH_SPEND, [tenant.id])
  const used = Number(rows[0].spent) / tenant.monthlyBudgetUsd

  if (used >= 1) throw new BudgetExceeded(tenant.id)          // hard stop: show an upgrade prompt
  if (used >= 0.8 && requested === 'synth-2.5-pro') {
    return { model: 'synth-2.5-flash' }                       // soft limit: about a third of the cost
  }
  return { model: requested }
}
  • Soft limit first. At 80% of budget, move the tenant from Pro to Flash. Flash costs 30% of Pro on input and half on output, and the feature keeps working. It is the same trade the platform's own fallback makes.
  • Hard stop at 100%, with an in-product message and an upgrade path, not a raw 402 surfacing as a generic error.
  • Rate limits per tenant, too. Synth 2.5 Pro's 5 requests per minute is shared by every caller of the model, including all your tenants. A tenant running a bulk job on Pro takes Pro slots from everyone else and pushes their requests to Flash. Route bulk features to synth-2.5-flash directly, and queue per tenant.
  • Watch your balance. Sum your own log against your top-ups so you know your remaining balance between dashboard visits, and treat any 402 as an alert, not a retry.

From cost to price

Cost per tenant at 2,000 input and 300 output tokens per chat turn, a typical turn with history:

TenantTurns per monthAll ProAll Flash90% Pro, 10% Flash
Small tenant5,000 turns$1.30$0.45$1.22
Mid tenant40,000 turns$10.40$3.60$9.72
Large tenant250,000 turns$65.00$22.50$60.75

Three things decide whether a seat price holds up:

  • Input dominates chat cost. In the example, 2,000 input tokens are 77% of a Pro turn's cost. History length is the variable to watch per tenant. A tenant whose users keep 20,000-token conversations costs about eight times as much per turn. Cap or summarize history, and price heavy tiers on it.
  • Price in usage bands, not unlimited. A flat seat price with no ceiling lets your heaviest customer set your margin. Include a turn allowance per plan, and enforce it with the budget check above.
  • Moderation calls cost money too. If you run a guard model on input and output, that is two extra calls per turn. Add them to the per-turn cost before you set prices. Our guide to writing moderation policies covers where those checks go.

Reconcile every month

  1. Export the Usage page CSV for month to date, grouped by key.
  2. Sum cost_usd per tenant from your log for the same UTC dates. The page uses UTC and can be up to five minutes behind.
  3. Compare per tenant. Within a few percent is normal; streaming and estimated rows explain most of it.
  4. A bigger gap means a code path is calling the API without your wrapper, a key is shared between tenants, or a key has leaked. Pause the key and check.

Bill your customers from your own log, since it has the feature and user detail the platform doesn't. Use the platform total as the check on it.

Per-customer cost tracking FAQ

How do I track LLM API costs per customer?

Give each customer its own API key, and also log every response's served model and token usage against the customer in your own database. Multiply tokens by the per-million rates of the model that actually answered. The key gives you an independent per-customer total in the provider's usage dashboard to reconcile against.

Should each tenant get its own API key?

For a B2B product, yes. On the LuciditySH Platform a per-tenant key shows up as its own series on the Usage page and in the CSV export, can be paused alone, and keeps its usage history after you revoke it. Name keys with a stable tenant id, such as tenant-4821-prod, and avoid renaming them.

Can I set a spending limit per API key on LuciditySH Platform?

There are no per-key spending caps. All keys draw on one prepaid account balance, and a request returns 402 when the balance is empty. Enforce per-tenant budgets in your own code by checking each tenant's month-to-date spend before a call.

Why does my cost log differ slightly from the platform's usage page?

Usually one of three things: a fallback served the request on Synth 2.5 Flash and you priced it at Pro rates, the usage was estimated from text length because the model server did not report token counts, or a stream ended before its usage chunk arrived. The Usage page is also in UTC and up to five minutes behind.

How much does Synth 2.5 cost per tenant?

At 2,000 input and 300 output tokens per chat turn, a turn costs about $0.00026 on Synth 2.5 Pro and $0.00009 on Synth 2.5 Flash. A tenant with 40,000 turns a month costs about $10.40 on Pro or $3.60 on Flash, before your margin.

Sources

Create an account, make one key per customer, and your usage log starts with the first request. Prepaid, per token, no monthly fee.

Create an account