Chat Usage and Cost #
What to do when a tofu Web chat usage monitor fires. Everything here reads tofu-web’s structured log events (@event:chat_usage.*, @event:ai.turn.finished). No message text is logged.
- Dashboard: tofu Web Chat, groups Usage and cost, Allowance health and Accounting health.
- The dashboard and monitors live in Datadog only; change them there. Find the monitors by the tag
ticket:eng-9356. - Filter the dashboard by environment with
$env(production,dev_aws). It filters on the@envlog attribute; these logs carry noenvtag.
How the accounting works #
- Before each model call, tofu-web reserves an estimate in Redis (
reserved). - After the call it settles to the real total (
chat_usage.settled, withreserved,tokens,inputTokens,outputTokens,model,plan,agent,period). When Redis refused the reservation, the event also carriesreserveFailed: trueandreservedis 0. - A call that is aborted or fails after producing output keeps its estimate (
chat_usage.kept). A call refused before any output gives it back (chat_usage.refunded). - A System One call (the judge, command search), which reports no tokens, is charged an estimate (
chat_usage.charged, withtokens,inputTokens(all of it),plan,periodandmodel: jev). It is logged even when the charge was not counted, withchargeFailed: true: Redis refused it, or there was no recent allowance check to count it against (then the event has noplanorperiod). - At 80 percent of its cap, an org (or a member below the org’s share) is warned once a period (
chat_usage.warning, withscope,plan,tokens,cap,percent,period). - Every allowance check that finds an org or member at its cap logs
chat_usage.budget_hit, with the same fields. That is each chat leg and each command search while stopped, so it counts refused checks, not refused messages. - bonsai-housekeeping calls
/api/chat-usage-flushevery 10 minutes. The first call in an hour writes dirty counters back to Clerk (chat_usage.flush, withdirty,written,failedandrateLimited); later calls that hour are skipped and log nothing. A pass that fails or is rate-limited releases the hour, so the next call 10 minutes later retries. - A Redis key that is missing is seeded from Clerk (
chat_usage.restore).
period is the day the org’s allowance period started (2026-11-01), so per-period tables group by org and period.
Monitors #
| Monitor | Fires when | Section |
|---|---|---|
| One org refused by its chat allowance more than 10 times in an hour | budget_hit per @env and @orgId > 10 in 1 h |
Hard stops |
| More than 50 refused chat allowance checks across orgs in a day | budget_hit per @env > 50 in 24 h |
Hard stops |
| Chat usage restored from Clerk more than 20 times in an hour | restore per @env > 20 in 1 h |
Restores |
| Chat usage write-back to Clerk failed for an org | sum of @failed per @env > 0 in 2 h, rate-limited runs left out |
Write-back |
| Clerk rate-limited every chat usage write-back retry for an hour | 6 or more @rateLimited:true runs per @env in 1 h |
Write-back |
| Chat usage write-back to Clerk did not run for 3 hours | no flush per @env in 3 h |
Write-back |
| Chat token estimate off by more than 30% | abs((reserved − tokens) / tokens) > 0.3 per @env and model over 1 d, Redis misses left out |
Drift |
| Chat provider cost above $25 in a day (production) | list-price cost in production > $25 in 24 h | Cost |
| Production chat tokens on a model the cost figures do not price | any production settled tokens on another model in 24 h |
Cost |
Owner: AI chat (team:front-end). None of them pages on-call.
- Every monitor except the two cost ones runs per environment (
productionanddev_aws). - A production alert from hard stops, restores or write-back goes to
#eng-prod-alerts; the same alert from dev goes to#eng-dev-alerts. - Drift and both cost monitors always go to
#eng-dev-alerts. - The cost monitors watch production only, because the dev models are not priced.
Hard stops #
An org (or a member, when their share is below the org’s) used its allowance for the period and is refused. The counts are refused checks: one chat message can be checked once per leg, and the command palette checks on each search.
- Allowance health: is it one org or many, and which plan and scope?
- One org with many stops in an hour: check Top orgs by tokens settled. If the org really reached its cap, look for a client or user retrying (
@event:ai.turn.dispatched @orgId:<id>). If it did not, the estimate stops it too early; see Drift. - Many orgs on one plan: compare Measured tokens per model call with the plan’s
max_token(M1.1). The plan’s allowance may be too small for real use.
Restores #
Each restore is a Redis miss for a usage key. A few a day are normal (new periods, new orgs). A burst means Redis lost the keys.
- Check the ElastiCache instance for a restart, failover or evictions.
- Usage since the last write-back is gone, so orgs may get extra headroom until the next period. Confirm on Write-back to Clerk that the last runs succeeded.
- Nothing to repair by hand: each key is seeded once per period, then counting continues.
To test in dev: delete the usage keys in the dev Redis and send a chat message. Restores from Clerk shows the spike. The restore monitor’s dev_aws group fires once more than 20 counters are restored in an hour, so delete keys for more than 20 orgs or members.
Write-back #
The write-back writes each dirty org and member counter to Clerk metadata once an hour. bonsai-housekeeping calls it every 10 minutes, and a failed or rate-limited pass is retried 10 minutes later.
- Failed for an org: search
service:tofu-web label:chat-usage status:(warn OR error)around the run. A Clerk 429 stops the pass early, and the next run retries the same orgs. Repeated failures point at Clerk or at a bad org record. - Did not run: check the bonsai-housekeeping job ran. If it logs “skipping the chat usage write-back”,
TOFU_WEB_INTERNAL_HOSTorTOFU_WEB_CRON_SECRETis unset in its environment (Doppler). A 401 from/api/chat-usage-flushmeans the two services hold different secrets.
Drift #
Drift is (reserved − tokens) / tokens per model. Negative means the estimate is too low: between calls, an org can go past its allowance by the difference. Positive means it is too high, so orgs are stopped early.
- Reserve-versus-settle drift shows which model moved and since when (a prompt, tool or model change).
- Measured tokens per model call gives the real mean and p95 to tune against.
- Re-tune
estimateTokensinapps/tofu-web/src/server/ai/limits/allowance.ts.
On 2026-11-30, production drift over 30 days was −51% for claude-opus-4-7, −31% for claude-sonnet-4-6 and −7% for gpt-5.4-mini, so this monitor fires as soon as it is published.
Cost #
Cost is computed on the dashboard from inputTokens and outputTokens at list price (USD per million tokens), without cache discounts, so it is an upper bound:
| Model | Input | Output |
|---|---|---|
| claude-opus-4-7 | 5 | 25 |
| claude-sonnet-4-6 | 3 | 15 |
| gpt-5.4-mini | 0.75 | 4.5 |
| jev (TypeSafe System One: judge, command search) | 0.042 | 0 |
A model not in this table is not counted. When production starts using a new model, add it to Cost per day, Cost per plan and the cost monitor.
- Cost per day by model and Top orgs by tokens: one org, or everyone?
- Everyone: check Tokens per message under Usage per message for a prompt or tool change.
- Expected growth: raise the ceiling in the monitor.
Orgs nearest their cap takes the highest percent from each org’s warnings and hard stops in one allowance period, so an org shows up only once it passes 80 percent. Above 100 percent means usage went past the cap between the check and the settle, which is the drift above.
Sales role under Usage and cost shows the sales role’s tokens (@agent:sales). Allowance stops cannot be split by role: the gate refuses a message before the judge picks one, so a stopped turn logs role: none.