cusage

Developers

The compiler is a Rust library. Servers embed it and load the schema at startup, with no generated server code: change the schema, restart, done. Your services call one gRPC API through clients generated from the same schema.

The schema

pricing.usage

Structs, types, rate tables, meters, metrics, plans and tests.

usage-core

Rust compiler and engine

lexerparsercheckerenginestoreclient generators

Exact decimals, unit checks, quotas with atomic holds.

usage-serverRust · gRPC with tonic
usage-server-goGo · the same engine through cgo
This websiteWebAssembly in your browser
Your servicea C ABI, JSON in and out

Both servers give the same answers: the demo checks their invoices match to the cent.

Typed clients

Generated for Python, Go and TypeScript. Wrong values don't compile.

cusage gen-client writes a method per struct, and the schema’s types and plans as types: a model the schema doesn’t sell is a compile error in Go and TypeScript and a ValueError in Python. Fields with defaults are optional.

cusage gen-client pricing.usage --lang python --out usage_client.py
cusage gen-client pricing.usage --lang go     --out usage/usage.go --package usage
cusage gen-client pricing.usage --lang ts     --out usage.ts
Generate one in the playground
for the AI platform example
const usage = new UsageClient("localhost:50051");

// size is "512" | "1024" | "2048": any other value won't compile
await usage.imageGen("cus_acme", { size: "1024", user_id: "ben" });

const invoice = await usage.invoice("cus_acme", "starter", { start, end });

Recording usage

Send events, typed by the schema. Retries are safe; billing is never refused.

Every struct becomes a method. Events carry an id, so a batch that’s sent twice is counted once.

Usage that already happened is always recorded, even over a limit, so invoices stay right; it shows up as over the limit. Pass enforce when the event is the work itself and it should only count if there’s room.

service.py

# One event, typed by the schema.
usage.llm_call("cus_acme", model=Model.SMALL, input_tokens=2_000, output_tokens=500, user_id="ana")

# A batch with ids: if it's sent again, it's counted once.
usage.track("cus_acme", *batch, ids=batch_ids)

# Recorded only if every limit has room, checked and recorded in one step.
usage.track("cus_acme", ApiRequest(route="/v1/chat", status=200), enforce=True)

Quotas

A cap of 4 never becomes 5. Not even with many replicas asking at once.

A limit counts what is recorded in its window plus every open hold. A reservation checks and holds in one atomic step, so two callers can never both take the last unit. Holds expire (60 seconds by default, at most an hour), so a crashed service can’t keep quota, and a reserve with a hold_id is safe to retry.

Exact: reserve, do the work, commit. For seats, workspaces, API keys and spend caps. Reservations run through the schema’s own meters, so a distinct-count seat limit refuses a fifth person while four keep working.

Fast: a limiter leases a block of units and admits locally, for requests and other high-volume work. The server never leases more than is left, so the limit still holds; the gap is units sitting in other replicas’ leases.

workspaces.py · exact

# Holds a slot, or raises QuotaExceeded when the plan is full.
with usage.reserve("cus_globex", WorkspaceChange(workspace_id="ws-7", delta=1)) as slot:
    provision_workspace("ws-7")
    slot.commit()  # if provisioning raises instead, the slot is released

llm.py · hold the worst case, commit what happened

# An LLM call costs what it costs only afterwards: hold the most it can cost.
worst = LlmCall(model=Model.GPT_4O, input_tokens=prompt_tokens, output_tokens=max_tokens, user_id=user)
with usage.reserve(customer, worst) as hold:
    reply = call_model(max_tokens=max_tokens)
    hold.commit(LlmCall(model=Model.GPT_4O, input_tokens=prompt_tokens,
                        output_tokens=reply.output_tokens, user_id=user))

gateway.ts · leased

const gate = usage.limiter(customer, {
  type: "api_request", data: { route: "/v1/chat", status: 200 },
}, { lease: 50 });

// Admits from the lease: an RPC only when it runs out.
if (!(await gate.allow())) return reply.code(429).send();
gate.record({ type: "api_request", data: { route, status } });

Errors and exceptions

Errors you can act on. Every one says what, where, and what to do.

A limit said no. QuotaExceeded in Python and TypeScript, *QuotaExceededError in Go. It carries the limits that blocked (what was used, reserved and allowed, and the window) and when to retry: retry_at, retryAt or RetryAt(), ready for a Retry-After header. A limit without a window has no retry time: only less usage frees it.

The server refused events. UsageRejected in Python, RejectedError in TypeScript and Go, with each event’s index and reason. It usually means the client and the server run different schemas.

A schema that doesn’t compile is reported like rustc does, with the place and a hint. Servers refuse to start on one, and on a failing test.

Python

try:
    slot = usage.reserve("cus_globex", WorkspaceChange(workspace_id="ws-8", delta=1))
except QuotaExceeded as e:
    e.blocked    # the limits that said no: quantity, used, reserved, limit, window
    e.retry_at   # when every blocking window starts over; None if one has no window
    raise HTTPException(429, str(e))  # quota exceeded for cus_globex: workspaces: 3 used + 0 reserved of 3 workspace

TypeScript

try {
  await usage.track(customer, event, { enforce: true });
} catch (e) {
  if (!(e instanceof QuotaExceeded)) throw e;
  const wait = e.retryAt ? Math.ceil((e.retryAt.getTime() - Date.now()) / 1000) : 60;
  return reply.code(429).header("Retry-After", wait).send(e.message);
}

Go

var quota *nimbus.QuotaExceededError
if errors.As(err, &quota) {
	if at := quota.RetryAt(); !at.IsZero() {
		w.Header().Set("Retry-After", strconv.Itoa(int(time.Until(at).Seconds())+1))
	}
	http.Error(w, quota.Error(), http.StatusTooManyRequests)
	return
}
error: table `input_rate` has no rate for "small"
 --> pricing.usage:5:7
  |
5 | table input_rate[Model]: credit/token {
  |       ^^^^^^^^^^
  = hint: every Model needs a rate: add it, or a default

Status codes

What the servers answer when a call can’t be done. The messages below are the engine’s own, for the AI platform example.

INVALID_ARGUMENTAn event or a request the schema doesn't allow.line 1: data.input_tokens must be an integer
INVALID_ARGUMENTA value outside a type.line 1: data.model must be one of "gpt-4o", "claude-sonnet", "small"
NOT_FOUNDA plan the schema doesn't have, or a hold that expired with nothing to record.unknown plan "gold"
FAILED_PRECONDITIONA subject with no plan, when none is passed.cus_acme has no plan: pass one, or subscribe the subject to a plan first

The gRPC API

One API for every schema. usage.v1.UsageService doesn't change when the schema does.

Event fields travel as map<string, Value> (string, int64, decimal as a string, bool), so the server needs no code per schema. Clients send the hash of the schema they were generated from; servers log a warning on a mismatch, and GetSchema lets a client check at startup.

RPCTakesWhat it does
Ingestevents, schema_hashValidates each event against the schema. Repeated ids count as duplicates, not usage.
GetUsagesubject, start, endEvery meter and metric, with by breakdowns.
GetInvoicesubject, plan, start, endPriced lines with a readable detail, subtotal and total.
GetSchemaThe hash, structs, plans and a JSON description of the running schema.
Subscribesubject, plan, limitsPuts a subject on a plan, with its own caps on that plan's limits.
CheckLimitssubject, plan, atEach limit's used, reserved, remaining and reset time; allowed if all have room.
Reservesubject, events, count, partial, ttl, commitChecks and holds room in one atomic step: granted, or the blocked limits.
Commithold_id, eventsRecords what the work did and releases the hold.
Releasehold_idGives a hold back unused.
Estimatelines, plansPrices made-up usage on each plan without recording it.

Embedding the engine

Run the compiler in your own process. Rust, Go, anything with a C FFI, and the browser.

Rust · usage-core

let schema = Schema::compile_file(&std::fs::read_to_string("pricing.usage")?, "pricing.usage")?;
let event = schema.parse_event(&json!({ "id": "e1", "type": "llm_call", "subject": "cus_acme",
    "time": "2026-11-02T10:00:00Z",
    "data": { "model": "gpt-4o", "input_tokens": 12000, "output_tokens": 3000, "user_id": "ana" } }))?;
let ev = schema.evaluate(&[event], Some("pro"), time::parse_ms("2026-11-01"), time::parse_ms("2026-12-01"))?;
let invoice = ev.invoice.unwrap();
println!("{} {}", invoice.money(invoice.total), invoice.currency); // 99.00 USD (the plan minimum)

Go · cgo over libusage_ffi.a

schema, err := usage.Compile(string(src), "pricing.usage") // the Rust compiler, through cgo
if err != nil {
	log.Fatal(err) // the same rustc-style report
}
defer schema.Close()

ev, err := schema.Evaluate(eventsJSON, "pro", "2026-11-01", "2026-12-01")
fmt.Println(ev.Invoice.Total, ev.Invoice.Currency) // 99.00 USD

The browser · usage-wasm (this website runs it)

import init, { analyze, Engine } from "./usage.js"; // scripts/wasm.sh builds it
await init();

const report = JSON.parse(analyze(source, "pricing.usage")); // diagnostics, tests, prices
const engine = new Engine(source, "pricing.usage");
const quote = JSON.parse(engine.call("estimate", JSON.stringify({ lines }), Date.now()));

crates/usage-ffi/include/usage.h

A small C ABI with JSON in and out: compile, validate an event, evaluate, run tests, and a store (usage_store_call) that takes every server method, quotas included. Python ctypes, Node-API, JVM Panama and .NET P/Invoke can embed it the same way.

The command line

cusage, the compiler's CLI. Check, test and inspect schemas, and generate clients.

cusage check pricing.usage [--json]        type-check and print diagnostics
cusage test  pricing.usage                 run the schema's test blocks
cusage info  pricing.usage                 print the compiled schema as JSON
cusage gen-client pricing.usage --lang go|python|ts --out <path> [--package <name>]
cusage scenarios pricing.usage [--scales 0.5,1,10]   every test on every plan, as JSON

Every release of livesession/cusage has cusage and usage-server for macOS, Linux and Windows. Or give your agent the SKILL.md: it installs them and knows the language.