CIRCLE
AI and billing

Billing and consumption

From your backend, read a user's subscription, metered usage and invoices, and report consumption with idempotency keys.

The machine API calls auth-service as your application, with a client_credentials token minted from the application's own secret. It never acts as a user, and it can only read and write the data of your application. Concepts and endpoints are documented in auth-service: Consumption tracking and Stripe integration.

Prerequisites

  • A confidential application: createMachineApi throws CFG_001 without clientSecret.
  • The machine scopes billing:read, consumption:read and consumption:write. New confidential applications receive them by default; an application created before that needs a superadmin to set them. A missing scope makes the call throw TOK_004 with the scope in details.scope.
import { createAuthClient } from "@circle-rd/auth-ai";
import { createMachineApi } from "@circle-rd/auth-ai/server";

const auth = createAuthClient({
  issuer: "https://auth.example.com",
  clientId: "my-app",
  clientSecret: "<client-secret>",
  redirectUri: "https://app.example.com/auth/callback",
});

const machine = createMachineApi(auth);

Tokens are cached per scope until shortly before they expire, and simultaneous callers share one request to the token endpoint.

Read a user's billing

const subscription = await machine.billing.getSubscription("user-sub");
if (subscription?.isActive) {
  console.log(subscription.plan.name, subscription.currentPeriodEnd);
}

const usage = await machine.billing.getUsage("user-sub");
for (const feature of usage.features) {
  // usageLimit -1 is unlimited; remaining is null when unlimited
  console.log(feature.featureKey, feature.used, feature.remaining);
}

getSubscription returns null when the user holds no subscription. The userId is the user's sub.

Invoices are keyset-paginated, newest first (limit is 1 to 100):

import type { InvoiceView } from "@circle-rd/auth-ai/server";

async function allInvoices(userId: string): Promise<InvoiceView[]> {
  const invoices: InvoiceView[] = [];
  let cursor: string | undefined;
  do {
    const page = await machine.billing.listInvoices(userId, {
      limit: 50,
      ...(cursor === undefined ? {} : { cursor }),
    });
    invoices.push(...page.items);
    cursor = page.nextCursor ?? undefined;
  } while (cursor !== undefined);
  return invoices;
}

Report consumption

const result = await machine.consumption.report({
  userId: "user-sub",
  key: "exports",
  value: 1,
  idempotencyKey: "export-job-8c1f",
});
console.log(result.aggregate.total, result.metered);
  • key is 1 to 64 characters from a-zA-Z0-9.; value is a finite number (negative credits back). The SDK validates both before sending and throws CFG_001 otherwise.
  • aggregate.total is a decimal string: a running total is not bounded by a double.
  • Set idempotencyKey to a stable identifier of the business event (a job id, an order line). The same key reported twice counts once, which makes retries safe; without one, every call counts.

Counters and metered features

Plain counterMetered feature
WhenThe key is any other key.The key is the featureKey of a metered price on the plan of the user's active subscription.
metered in the resultfalsetrue
RulesAny finite value.value must be greater than zero; a report that would pass the plan's cap is refused.
Read back withmachine.consumption.list(userId) or .get(userId, key)machine.billing.getUsage(userId)

When the plan's cap is exceeded, auth-service answers with its own error, which the SDK raises as API_001: look at details.apiCode (BIL_003 for the cap, BIL_002 for a non-positive value) and details.status.

import { AuthAiError } from "@circle-rd/auth-ai";

async function recordExport(userId: string, jobId: string): Promise<"ok" | "quota"> {
  try {
    await machine.consumption.report({
      userId,
      key: "exports",
      value: 1,
      idempotencyKey: `export-${jobId}`,
    });
    return "ok";
  } catch (err) {
    if (err instanceof AuthAiError && err.details?.["apiCode"] === "BIL_003") return "quota";
    throw err;
  }
}

Reading a key that was never reported rejects: consumption.get throws API_001 with details.apiCode CONS_003.

Where to call it

Always from your backend: it needs the application secret. A typical flow is a signed-in request handler that knows request.authSession.userId, performs the work, then reports consumption. Keep the pre-check (getUsage, remaining) as a courtesy to the user and rely on the report's refusal as the authoritative cap.

Copyright © 2026