Skip to content
FluxMeter
中文

Writing

From AI gateway to usage ledger: what make demo verifies

One usage event from AI gateway to priced customer line, and what make demo verifies. 202 is custody. Not a billing suite; no zero-overspend guarantee.

2026-11-29 · Architecture · 12 min read

You are wiring an AI gateway or an SDK integration, and you have one practical question: after my code sends a usage event, what has to happen before it shows up as a priced line for the right customer, and which of those steps can I check on my own laptop?

(Two earlier posts cover the failure side of this path: what a gateway timeout does and does not tell you, and where attribution can break after it. This one is the map, not the incident.)

FluxMeter is open-source, self-hosted LLM token metering software: it attributes token usage to your customers, prices it from a catalog, and optionally checks or reserves budget before a request. It is not a billing suite, it does not replace Stripe, Lago, Orb or Metronome (it can export usage to them), and it does not guarantee zero overspend. Everything below is read from the fluxmeter repository and checked by running its local demo.

The path in one picture

Flowchart of one usage event from SDK and Gateway through HTTP Custody, Kafka, Flink, Redis, and the Usage API, with quarantine, DLQ, optional export, and a Gateway budget-check path to Redis.

Plain-text version: `SDK / Gateway → HTTP Custody (POST /ingest) → Kafka (token-events) → Flink (TokenUsageAggregator) → Redis → Usage API (GET /usage/customer/{id})`. Export to a billing system is a separate, optional step.

Hop by hop: who owns what

1. The event. One event is one LLM call: `customerId`, `modelId`, `inputTokens`, `outputTokens`, plus optional `cacheReadTokens`, `reasoningTokens`, `parentSpanId` (one agent run) and `sessionId` (one conversation or project). The field that matters most for an integrator is `eventId`. It is the retry identity. The Python SDK gives each event an ID and keeps it across its own delivery retries. The Gateway derives it from its reservation (`res:<reservationId>`). If you call `POST /ingest` yourself and omit it, the server creates one for that request, which means a retry of the same call cannot be recognized as the same event.

2. HTTP Custody. All public events enter here; Kafka has no public broker port in the base deployment, and the Gateway calls the same Custody module rather than writing to Kafka on its own. Custody claims the `eventId` for the tenant, wraps the event in a trusted envelope (customer and tenant come from the authenticated request, not from whatever the payload says), publishes to Kafka, and waits for the acknowledgement. Only then does it return 202. So 202 means custody: the event is durably in the pipeline. It does not mean the event has been priced, aggregated or billed. The other answers are just as useful:

- identical retry of a known `eventId` → 202 with `"idempotent": true`

- same `eventId`, different payload → 409 `event_id_conflict`

- Kafka unavailable or acknowledgement uncertain → retryable 503; custody at capacity → 429

- event timestamp too old or too far in the future (defaults: 24 hours back, 5 minutes ahead) → still 202, but with `"status": "quarantined"`, routed to `token-events-quarantine`, which the aggregator does not read

Retry identities are kept for 30 days by default.

3. Kafka. An internal transport between custody and aggregation (`token-events`, plus quarantine, DLQ, alert and watermark topics). Nothing to integrate against; it is why a 202 can be returned before any aggregation happens.

4. Flink. The `TokenUsageAggregator` job is where an event becomes a priced, attributed number. It drops malformed envelopes to the DLQ, de-duplicates by `eventId` inside a short crash-safety window (10 minutes by default; the long retry window lives at custody), routes events that arrive after their window has closed to the DLQ instead of silently dropping them, prices each event from the pricing catalog (`config/pricing.json`), and sums usage per customer and model in short tumbling event-time windows. Each window result is written to Redis in a single Lua script guarded by a set-if-absent key, so replaying a window does not count it twice; the same script deducts budget and settles any Gateway reservation. Flink here is the usage aggregation and pricing step. It is not an invoicing engine.

5. Redis. Holds the query state: lifetime, monthly and daily counters per customer, per-model counters, span and session rollups, and budgets.

6. Usage API. What your product or finance tooling reads. `GET /usage/customer/{id}` returns `customer_id`, `input_tokens`, `output_tokens`, `total_tokens`, `cache_read_tokens`, `reasoning_tokens`, `event_count` and `cost_usd`. `/usage/customer/{id}/period/{YYYY-MM}` and `/day/{YYYY-MM-DD}` return the same shape for a UTC bucket; `/usage/customer/{id}/model/{model}` splits by model. That row is the "usage ledger" in this post's title: a metered, priced record per customer. It is not an invoice. Turning it into one is the job of your billing system (export).

On the Gateway path there is one more branch, before the upstream call: estimate cost from the catalog, check budget, open a reservation (hold), call the provider, then send actual usage through Custody. That is a pre-request control. It lowers overspend risk and does not guarantee zero overspend (check and reserve).

What make demo actually verifies

`make demo` (Java 17, Docker Compose, Python 3.10+, no provider key) builds the Flink job, starts the stack (Kafka, Redis, Flink jobmanager and taskmanager, API, Gateway, webhook worker, Grafana), and then runs `demos/quickstart.py`. That script does three things:

1. Waits for `/ready`. Readiness is not a port check: the API pings Redis, checks Kafka, publishes a probe event, and returns ready only once Flink has consumed that probe.

2. Sends one event through `POST /ingest` with a fixed `eventId`: `gpt-4o-mini`, 1,200 input and 400 output tokens. It requires a 202 with `"status": "accepted"`.

3. Polls `GET /usage/customer/{id}` until the line is exactly right: one event, 1,200 / 400 / 1,600 tokens, and `cost_usd` of 0.00042 at the default catalog rates. Otherwise it fails.

Here is the end of our run on main:

202 custody accepted: evt-…; waiting for customer usage...
{
  "customer_id": "demo-9cfed8e91a144830920a95ed2d70ba3e",
  "total_tokens": 1600,
  "input_tokens": 1200,
  "output_tokens": 400,
  "cache_read_tokens": 0,
  "reasoning_tokens": 0,
  "event_count": 1,
  "cost_usd": 0.00042
}
PASS: 1 event, 1600 tokens, $0.00042; no provider key required.

So `make demo` proves the middle of the path end to end on one machine: HTTP Custody → Kafka → Flink → Redis → Usage API, with exact token counts, catalog pricing and customer attribution. `make demo-verify` repeats it with new IDs.

It is just as important to say what it does not touch. The quickstart script calls `/ingest` directly. It does not go through the SDK or the Gateway, it does not set a budget or open a reservation, and it does not export anything.

You can cover more of the path on the same running stack, still without a provider key:

- Retries and conflicts. Send the same `/ingest` body twice and you get `202 … "idempotent": true`, with `event_count` still 1. Change one field under the same `eventId` and you get `409 event_id_conflict`.

- Quarantine. Send an event stamped three days ago and you get `202 … "status": "quarantined"`, and no customer line appears. A 202 body is worth reading.

- The Gateway hop. The repo's runaway overlay (`docker-compose.runaway.yml`, used by `make demo-runaway`) points the Gateway at a local mock upstream. We set a $5.00 budget for a fresh customer and sent one chat completion through `localhost:8080` with `X-FluxMeter-Customer-Id`. The Gateway returned 200 with a reservation header. The event in Kafka carried `"source": "gateway"` and `"eventId": "res:<reservationId>"`. After the window closed, the customer line read 4,000 / 2,000 tokens and `cost_usd` 0.03, and the budget showed a 4.97 balance with nothing left on hold. Without a budget, the same request gets `402 no_budget`.

Home-grown reconciliation script vs. a custody → stream → Usage API pipeline

Many teams start with a script: export the provider's usage, join it with application logs by API key and time range, multiply by a price sheet, and write a table. That is reasonable early on. The useful comparison is not features but which responsibilities each design has to carry:

ResponsibilityTypical reconciliation scriptCustody → stream → Usage API
Which customer did this call belong to?Inferred later from logs, keys or time windowsSet on the event at request time; customer taken from the authenticated envelope
Was this retry the same call?Heuristic de-duplication`eventId` identity at custody: idempotent replay or 409 conflict
When is usage "in"?When the batch runs202 = custody; the priced line appears after aggregation
Late or odd eventsOften silently included or droppedQuarantine topic (time out of range), DLQ (late or malformed)
Replaying a batchMust be made idempotent by handPer-window set-if-absent guard in the Redis write
Price appliedWhatever sheet the script reads that dayVersioned catalog; unknown models fall back to a default (see below)
Query surfaceA table someone maintains`/usage/customer/{id}`, `/period`, `/day`, `/model`, span and session

Neither column removes the need to compare against the provider's invoice. Your customer lines and your upstream bill answer different questions (upstream invoice vs customer usage). The pipeline moves attribution and retry identity to the moment of the request, where a nightly script can only reconstruct them.

What the demo does not prove

- Production behavior. It is a single-machine stack with demo defaults: auth optional, budget fail policy open, one Kafka broker. It says nothing about throughput, latency or availability in your deployment.

- Upstream truth. FluxMeter meters the token counts the SDK, Gateway or caller reports. In the demo those come from a fixture or a local mock, not a real provider bill.

- Settlement and invoicing. No billing system is involved. Export to Stripe, Metronome or Orb exists as optional code paths and is not exercised by `make demo`.

- Zero overspend. In our one Gateway call the hold was quoted at about $0.020 and actual usage priced at $0.03. Flink settled the difference, but a pre-request estimate can be lower than the final cost. Checks and reservations reduce overspend risk; they do not remove it (a runaway-agent test).

- Unknown models. A model ID that is not in the catalog (and matches no prefix) is priced at the catalog default, $1 per million input and $3 per million output tokens in `config/pricing.json`. We sent 1,200 / 400 tokens for `my-finetune-xyz` and got `cost_usd` 0.0024, against 0.00042 for the same tokens on `gpt-4o-mini`. Nothing fails, so keep your catalog current.

- Quarantine handling. A quarantined event gets a 202 and then waits for an operator. The demo shows that it is kept out of the customer line, not how you resolve it.

- Cold storage. The optional ClickHouse copy (benchmark overlay, `make demo-proof`) is an audit store, not the source of the usage numbers, and it is not part of `make demo`.

- Identity mapping. Which `customerId` a request belongs to is still your decision, made at the gateway or SDK call site (customers, not API keys).

Where FluxMeter fits

If you are building the gateway or SDK layer, the parts FluxMeter takes off your hands are the boring, easy-to-get-wrong ones: retry identity at the edge, a durable hand-off, pricing and per-customer aggregation that can be replayed, and a query API for the result, plus optional pre-request checks and reservations that do not guarantee zero overspend. Invoicing, tax, payments and dunning stay in your billing system. The quickest way to see the middle of the path is the one in the repo: `git clone`, `make demo`, and read the line it prints. Then point one Gateway call at the runaway mock and watch the same line appear from the other entrance. More in the quickstart and on the architecture page.

If you are building the gateway or SDK layer, the parts FluxMeter takes off your hands are the boring, easy-to-get-wrong ones: retry identity at the edge, a durable hand-off, pricing and per-customer aggregation that can be replayed, and a query API for the result, plus optional pre-request checks and reservations that do not guarantee zero overspend.