Billing

A fleet request is charged exactly once, even if the process dies at any line

A same-transaction settlement outbox, 26 database round trips cut to 12, and a per-user ledger queue for one hot row, with the run or test behind each number.

On this page

A request that is killed between "we held the money" and "we settled the bill" can leave a hold that nothing reconciles, and a settle that runs twice can charge the customer twice. For fleet requests we closed both with an outbox written in the same database transaction, and the proof is a test that kills the process at every step. The design then cost 26 database round trips per request, which we cut to 12. Separately, on the personal pay-as-you-go path, one account's heavy traffic hit a single row lock: in one rig run at 120 requests per minute for 300 s, one user row served 269 of 600 requests, and the per-user ledger queue we built for it served all 600. The queue's option is still on in production, but since 2026-11-17 personal pay-as-you-go ledger writes go to a single database function first, so the queue now carries only the writes the function cannot route. Its effect was measured on a rig, never in production.

The short version

  • Reserve, attempt, settle once. A fleet request holds money in a reservation, records an attempt before it sends anything upstream, and ends in exactly one terminal state. Every transition is a single conditional write, so two replicas racing to finish one request produce one winner.
  • Write the side effects in the same transaction. The log, counter and cache updates that follow a settlement are rows written with the settlement itself; the request applies them right after the commit, idempotently, and an outbox worker applies any it could not. A process that dies after the commit loses nothing.
  • Count round trips. On local PostgreSQL, one fleet request went from 26 to 12 statements and its outbox from 27 (31 with cold caches) to 8. A personal reservation on the other billing path went from 8 to 6, and later to one function call.
  • Queue per user, not per token. We built a per-user ledger queue for one user's reservations, settlements and refunds, so a hot user row is locked once per batch instead of once per request. In one rig run it served all 600 requests where the old path served 269; in production, a later single-function path now runs ahead of it.

The problem: a process can die at any line

Our money path was a sequence of independent writes: debit the wallet, call the upstream, adjust by the actual cost afterwards. The risk we wrote down for it (#3323) was that a kill after the upstream send leaves a wallet hold with nothing to reconcile it, and that a duplicate settle can charge twice. The existing text path wrote no reservation row and no settlement identity.

We built a new path for fleet requests beside it (#3323), as a small state machine. It covers personal-token pay-as-you-go chat completions only and ships behind a flag that is off by default; this post does not claim it is on in production:

reserved -> dispatching -> settled
   |            |
   v            v
refunded    outcome_unknown   (held, never re-sent, resolved by reconciliation)

Three rules do the work:

  1. Reserve and the wallet debit are one transaction. There is never a hold without a row that names it, or a row without a hold.
  2. Every transition is one conditional UPDATE on the request's identity, its expected state and an authority epoch. A stale replica is fenced out instead of overwriting a newer one.
  3. The attempt is recorded before the send. If the process dies after that point, we cannot know whether the upstream was called. The request is moved to outcome_unknown, the full hold stays in every ledger, and it is never re-sent. The request path never settles or refunds a row it recorded as unknown; only an approved reconciliation moves it. Unknown is not treated as zero.

How we proved it

We did not trust the PR prose. The proof is the test file, which discards all in-memory state at each step and reads only the database:

  • killed before the reserve commits: nothing exists, ledgers unchanged;
  • killed after the reserve commits, before the attempt: restart recovery refunds the hold, and a slow live request that wakes up later is fenced and cannot send;
  • the reserve's acknowledgement lost: a retry with the same identity finds the row and debits once;
  • killed after the attempt is recorded: recovery moves the row to outcome_unknown and never refunds it;
  • a stream cut mid-way: the hold stands until an approved reconciliation resolves it;
  • the settlement's acknowledgement lost: a second settle changes nothing, and a refund after a settlement is refused.

An invariant is checked after every case, in both the wallet and the token. Wallet plus outstanding holds equals the start minus what was settled, and used equals the monthly counter equals settled plus holds. Four concurrency tests each run with 2 and with 4 replicas; two of them are the races that matter here. In one, a settle and a refund race for one request and exactly one terminal transition applies. In the other, replicas race to begin an attempt and exactly one may send.

Two deliberately broken versions each turned named tests red: one where the request path accepted any unknown row, and one where a zero-row update was read back as a win. The second matters. Attempt ids are deterministic, so a loser that read the row back would believe it had won and send a second upstream request.

The cost: 26 round trips

A correct path was a slow one. With the database about 75 ms away, each statement is a round trip, and a fleet request issued 26 of them. We counted them at the connection pool in a test on local PostgreSQL (#6107): reserve 11, begin attempt 3, settle 12, in a current monthly window. The test comment records 28 for the first request of a month, when the monthly window resets.

What we did:

  • Reserve uses guarded single-statement updates, users first and then tokens, with the balance and monthly-limit checks in the WHERE clause, then the settlement row with INSERT ... ON CONFLICT DO NOTHING. No FOR UPDATE read. Any miss, such as a stale window, an org-pool token, a duplicate identity or a refusal, falls back to the old locking flow, which still owns every refusal and message.
  • Settle gets its row back from the fence update with RETURNING, and the ledger delta is two guarded updates instead of a savepoint and six statements. If the token refuses, the user half is undone in the same transaction, so a refused delta never moves one ledger without the other.
  • The outbox reads the settlement row once and shares it across its effects, applies the counters as one statement built from data-modifying CTEs gated on the claim (a replay counts nothing), and skips default transaction wrappers on lone statements.

Result at #6107, steady state, asserted by tests: a fleet request is 5 + 1 + 6 = 12 statements, and its outbox is at most 8, against 27 before (31 with cold per-process caches). Later changes took the outbox to 6 (#8097) and, behind an option, the fleet reserve and settle to one statement each (#8026). A refund-only outbox is 3. The counts are statements, not time, and they are for the fleet settlement path.

The amounts did not change. We checked that against the locking primitives for five wallet shapes and four actual costs, with exact ledgers, and ran 50 concurrent fleet requests end to end through the outbox with exact quota, counters and logs.

The personal reservation on the other billing path had the same problem in a smaller form (#6089). It sent its two monthly counters as separate updates, which made 8 statements. Folding each counter into the debit of its own row made it 6, with the same amounts and the same refusals. In production the /v1/messages reservation step had a p50 of 450 ms, which the pull request attributes to 8 serial round trips of about 75 ms each. That pull request stopped at 6 on purpose. Reaching 4 needed a PostgreSQL-only CTE with one joined FOR UPDATE, which would make lock order depend on the planner, need a second read to name a refusal, and need a second path for SQLite and MySQL. The pull request estimated about 340 ms for 6; that was a projection, and this article does not give a measured value. A later change (#7485) moved the personal reservation to one PostgreSQL function call behind an option, on in production since 2026-11-17 (#8836).

A separate ceiling: one row

On the personal pay-as-you-go (PAYG) path, a different ceiling showed up first: one row (#4949, 2026-10-15, ten days before the round-trip work above). Every personal PAYG request locked its user's row, in a transaction of its own, for each reservation, each settlement and each returned hold. Our existing group commit coalesced settlements per token, but the lock that serializes is the user row, so twenty tokens could still queue up to twenty transactions on one row. Refunds were never coalesced at all.

On a local rig at 75 ms database latency, 2,500 requests per minute all billed to one user gave a time to first token (p95) of about 11 s and a settlement lag (p50) of about 15 s, in two runs. The same load spread over 20 users gave 1.9 s and 2.5 s, in one run (#4949, from #3934). Some of our traffic bills every request to one user row.

The fix (#4986) is a per-user ledger queue behind an option, UserLedgerGroupCommitEnabled, default off and read on every call. One user's reservations, settlement deltas of either sign and returned holds enter a queue, and at most one batch transaction per user per process is in flight. A waiting item holds no database connection. A batch locks the user row, then its tokens in one ordered statement, and writes with a fixed number of statements however large the batch is. It judges items in queue order with the old guards, so it accepts exactly what the old calls would accept one at a time; twin-user tests compare every error text and the final ledgers against serial calls. A COMMIT whose outcome is unknown is never re-applied: every caller in that batch gets the error. A failed batch, or an item whose token changed owner, takes the old individual call. With the option off, every entry point is the old function.

What did not work, and what nearly misled us

  • Coalescing per token did not remove the lock, as above.
  • A scary number that was our rig. In a preliminary local run, the option-off arm at 300 requests per minute showed 1,321,061 quota points (1 USD is 1,000,000 points) charged more than logged. Reading the run showed that the gap was 287 holds of exactly 4,603 points each, still in flight on the server when the rig took its snapshot: the rig waited only for the clients' successes, not for the server to go quiet. It was a measurement artifact, not an overcharge, and we changed the rig to wait for quiet before it compares ledgers (#5039). Until it was explained, we treated that number as a finding about the old path.

The result: one run, both arms at once

We ran the option off and on side by side on two cloud VMs, with the same binary and the same shape, once, on 2026-10-16, with one heavy user on 6 tokens (#4949 comment 6209786567). This is one run. The reservation path, 300 s per step:

Offered (req/min) Off: served Off: TTFT p95 On: served On: TTFT p95
120 269 / 600 98.6 s 600 / 600 1.29 s
300 213 / 1451 126.1 s 1451 / 1451 1.28 s
600 0 / 2993 none 2993 / 2993 1.28 s
1200 0 / 6042 none 6042 / 6042 1.26 s

With the option off, almost every database connection was waiting on the user's row at every step. With it on, the median was 0 and the maximum 1 at the first three steps and 0 at 1200. Settlement lag with the option on stayed under 1 s (p95 0.82 s at 600). Every on step read exact in the ledger. On the control path with no monthly limit, both arms served every request with the same TTFT, and the option cut settlement lag (p95) from about 6.5 s to under 0.8 s. Reserving still costs time to first token with the option on: a TTFT p50 of 1.05 s against 0.29 s without a reservation, at 75 ms round trips. That remains separate work.

Is it on in production?

The option is, but the queue now carries only the writes the function cannot route. We read the production database, read-only, on 2026-11-24: UserLedgerGroupCommitEnabled is true, and so is PaygPersonalLedgerFunctionEnabled. That second option was turned on on 2026-11-17 (#8836). It sends every personal PAYG reservation, settlement and returned hold to one PostgreSQL function call ahead of the queue, and the function hands a write to the queue only when it cannot route it. The queue serves that traffic again only if the function's option is turned off.

Before that, the queue did carry it. It shipped off on 2026-10-16 and was switched on later the same day under written rollback triggers: any ledger mismatch, a sustained rise in settlement lag, a new negative balance, or a panic in the queue. During the observation window, which ended on 2026-10-23, the rollback was never used. The last read-only read, on 2026-10-22, covering all personal PAYG users since the switch-on, found 2,582 settled rows in 224 batches with settlement lag p50 0.5 s, p95 1.4 s and max 2.0 s, and none of the queue's error log patterns; earlier reads had gaps in which we had no log coverage.

What we did not measure: the heavy account's own time to first token, or its lock waits, in production. The plan's observation was recorded as unknown for lack of evidence, because no read isolated that account. What we measured in production is exposure and lag for all personal PAYG users during that window. The queue's effect on one hot row was measured on the rig above, never in production.

What we would do differently

  • Write the production measurement into the switch-on, not after it. We specified the heavy account's TTFT and lock waits as the success measure and never took them. A measurement that depends on a later session remembering is not a plan. A month later another path went ahead of the queue, and the chance to measure it on that traffic was gone.
  • Make the rig prove it is quiet before it reads ledgers. Our first off-arm reading looked like an overcharge and was not.
  • Count statements in a test from the start. Now tests fail if a fleet request grows past 12 statements or its outbox past 6 (it was 8 at #6107).

Still open

  • No production time-to-first-token number exists for the account this was built for.
  • One API key's remaining quota rose by 400,000 quota points (US$0.40) on 2026-10-17 with no usage, which our reconciliation counts as a token mismatch. The numbers match the key's spend limit being raised from US$0.40 to US$0.80, which moves no wallet money, but we found no record of that edit (#4949, comments 6230436956 and 6284876062). It did not grow during the window, and the reads after 2026-10-22 do not exist.
  • As of #4986, the queue is routed at the personal PAYG reservation, settlement and refund call sites; since 2026-11-17 the function runs ahead of it at the same sites. The fleet settlement path's round-trip savings above are a separate result from the queue's, and we do not claim the queue's numbers for it.
  • The about 0.75 s that a reservation added to time to first token on the rig has not been re-measured since the personal reservation became one function call (#7485, on in production since 2026-11-17, #8836).

How each number was measured

  • 26 to 12, 27 (31) to 8, and 3 for a refund: countRoundTrips statement counts at the connection pool in tests on local PostgreSQL, steady state, personal token (#6107). Statements, not milliseconds. The outbox bound is 6 since #8097.
  • 8 to 6: the same kind of count for a personal reservation (#6089); the 450 ms p50 is production /v1/messages pre-consume time quoted in that pull request.
  • Kill points and the 2- and 4-replica races: the tests of #3323, run on PostgreSQL and SQLite.
  • 11 s / 15 s against 1.9 s / 2.5 s: local rig at 75 ms, 2,500 requests per minute, one user (two runs) against 20 (one run) (#4949, from #3934).
  • The table above: one run on two cloud VMs on 2026-10-16, 300 s per step on the reservation path, off and on side by side (#4949).
  • Production state: read-only reads of the options on 2026-11-22 (the queue's) and 2026-11-24 (both); the function option's switch-on on 2026-11-17 (#8836); the 2,582-row read on 2026-10-22 (#4949).