
Why a Pre-Request Balance Check Overspends Under Concurrent LLM Calls in Node.js
Most teams building multi-tenant LLM features start with the same check: read the tenant's remaining balance, decide whether the next call fits, then call the provider. That reads like a spending limit. It isn't one. This post shows why a pre-request balance check silently overspends under concurrent LLM calls in Node.js, and what has to replace it — atomic reservation, durable attempt records, and explicit handling of unknown outcomes.
On this page
A pre-request balance check is not a spending boundary
A pre-request balance read cannot enforce a shared limit
The claim here is narrow and testable: a "check availability, then await the provider, then debit" sequence cannot enforce a tenant budget, because the interval between checking and debiting is unbounded and other handlers run inside it. Any number of requests can observe the same available balance and all of them can proceed. This is an accounting race, not a tokenizer or pricing bug.
Enforcement has to happen at admission, and admission has to be a single atomic operation that turns available capacity into reserved capacity before any provider call is made. Reading a balance reports; reserving decides. Only one of those is a control.
Source boundary: headline context, not implementation
The supplied source is only a news discovery entry: a Startup Fortune headline, "How to Set Usage Limits Per Customer for LLM API Spend Before It Hurts", listed with a publication date of 2026-12-06, plus a one-line snippet. The supplied material contains no implementation, no measurements, and no described failure incident. I have not read the article body, and nothing below attributes a technique, a number, or a test result to it. The headline is used only as evidence that per-customer LLM spend controls are a live operational concern — which they are, if you run multi-tenant inference.
Everything concrete here comes from two places: PostgreSQL and Node.js semantics you can verify in the docs linked at the end, and arithmetic you can check by hand.
Scope: Node.js API, PostgreSQL budgets, and a deterministic provider
A Node.js HTTP API, a PostgreSQL database holding tenant budget periods, and a deterministic fake provider that charges a fixed number of accounting units per call. No claims are made about any particular model's tokenizer, pricing, or behaviour. Where a real provider's semantics matter, I name the specific documented mechanism and mark anything I have not verified as inference.
Reproduce the overspend with a controlled concurrent workload
The unsafe read-await-debit sequence
Here's the shape almost everyone writes first: one SELECT, one long await against the provider, one UPDATE.
// unsafe-admission.js
export async function handleGenerateUnsafe({ tenantId, prompt, db, provider }) {
const period = currentPeriod();
const read = await db.query(
"SELECT limit_units, committed_units FROM tenant_budget_periods " +
"WHERE tenant_id = $1 AND period_start = $2",
[tenantId, period]
);
if (read.rows.length === 0) {
return { status: 404, body: { error: "no_budget_period" } };
}
const { limit_units: limit, committed_units: committed } = read.rows[0];
const available = Number(limit) - Number(committed);
if (available < CHARGE_UNITS) {
return { status: 402, body: { error: "budget_exhausted" } };
}
// The liability has not been recorded yet, but the money is about to be spent.
const result = await provider.generate({ prompt, maxOutputTokens: 128 });
await db.query(
"UPDATE tenant_budget_periods SET committed_units = committed_units + $3 " +
"WHERE tenant_id = $1 AND period_start = $2",
[tenantId, period, result.usage.units]
);
return { status: 200, body: { text: result.text, charged: result.usage.units } };
}
The gap sits between available >= CHARGE_UNITS and the UPDATE. During that gap the tenant's liability is unchanged, so every other in-flight request sees the same available number. The await provider.generate(...) makes the gap long — hundreds of milliseconds to tens of seconds — which is exactly why this bug shows up in production and never in a one-request-at-a-time test.
A barrier that forces the collision
To make the failure deterministic instead of probabilistic, put a barrier between the read and the spend. Ten handlers all read, all park on the barrier, and only then does anyone proceed.
// repro-overspend.js
const TENANT = "tenant-a";
const CONCURRENCY = 10;
let arrivals = 0;
let release;
const barrier = new Promise((resolve) => { release = resolve; });
const db = createFakeDb({ tenantId: TENANT, limitUnits: 1000, committedUnits: 0 });
const provider = createFakeProvider({ chargeUnits: CHARGE_UNITS });
const baseQuery = db.query.bind(db);
db.query = async (sql, params) => {
const result = await baseQuery(sql, params);
if (sql.startsWith("SELECT limit_units")) {
arrivals += 1;
if (arrivals === CONCURRENCY) release();
await barrier; // every reader sees the pre-spend balance
}
return result;
};
const results = await Promise.all(
Array.from({ length: CONCURRENCY }, (_, i) =>
handleGenerateUnsafe({ tenantId: TENANT, prompt: "req-" + i, db, provider })
)
);
const snapshot = db.snapshot();
console.log(JSON.stringify({
admitted: results.filter((r) => r.status === 200).length,
rejected: results.filter((r) => r.status === 402).length,
limitUnits: snapshot.limitUnits,
committedUnits: snapshot.committedUnits,
overspendUnits: snapshot.committedUnits - snapshot.limitUnits
}, null, 2));
Expected output
node repro-overspend.js
{
"admitted": 10,
"rejected": 0,
"limitUnits": 1000,
"committedUnits": 2000,
"overspendUnits": 1000
}
These figures are the fixture's designed expectation, derived from the arithmetic below — not a measurement I collected from a run on this machine. The fixture has no randomness, no timers, and a fake provider that always charges exactly 200 units, so the output is fully determined: 10 handlers read available = 1000, each spends 200, the debit phase records 2000 against a 1000 limit.
The barrier is artificial, but it is not unrealistic. It compresses into one tick what happens naturally across a few hundred milliseconds of real traffic. Remove the barrier and the same code overspends under load — just with a distribution instead of a constant.
Why the event loop does not save you
JavaScript's single-threaded event loop serializes synchronous execution, not asynchronous request handlers. The loop runs one callback at a time, but every await is a suspension point where control returns to the loop and other pending work proceeds. A SELECT is I/O: the handler yields, the loop picks up the next request's handler, that handler issues its own SELECT, and so on until the first query result comes back.
So the ten handlers are not concurrent in the memory-corruption sense — there is no data race on a shared variable. They are concurrent in the state sense: each one's read and write are separated by suspension points, and the interleaving is chosen by I/O completion order, not by your code.
The usual first fix is a process-local mutex:
// Still wrong across processes.
let chain = Promise.resolve();
const withLock = (fn) => (chain = chain.then(fn, fn));
This works — inside a single process. It does nothing the moment you run node:cluster, PM2 cluster mode, two containers behind a load balancer, or a serverless platform that fans out to N instances. Each process has its own chain, so N processes each admit up to the full budget. A local mutex is a correctness placeholder, not a control.
Which leaves the database, the only component every replica shares.
Define the accounting invariant before writing middleware
The budget period model
Model each tenant budget period with four quantities:
| Field | Meaning |
|---|---|
limit_units | Total spend allowed in this period |
committed_units | Settled, final liability (money already spent) |
reserved_units | Held against in-flight attempts that may become liability |
available_units | limit - committed - reserved |
The invariant enforced at admission is:
committed_units + reserved_units + requested_reservation <= limit_units
Note what it is not: it is not committed_units <= limit_units. Committed spend can legitimately exceed the limit if a provider charges more than was reserved. A constraint that rejects the truthful settlement is worse than a recorded overspend, because it destroys the evidence of what you actually owe. Enforce the bound at admission; record reality at settlement.
Do not put CHECK (committed_units + reserved_units <= limit_units) on the budget table. It will fire on the one settlement path you most need to succeed — a charge above the reservation — and your ledger will either lose the liability or block the transaction that records it. Enforce the invariant in the conditional UPDATE and alert on violations instead.
Integer accounting units
Never use float/number for money. 0.1 + 0.2 !== 0.3 is the famous case, but the subtle failure is accumulation: millions of += operations on float cents drift, and the drift is invisible until reconciliation.
Pick a fixed accounting unit — a micro-dollar (1e-6 USD) is enough resolution for per-token pricing — and store integers:
limit_units numeric(20,0) NOT NULL
committed_units numeric(20,0) NOT NULL
reserved_units numeric(20,0) NOT NULL
In Node.js, do the arithmetic in BigInt. A BIGINT column read into a JS number is only safe below 2^53; micro-dollar balances go past that at roughly $9 billion, but the intermediate products in a cost calculation (tokens * micros_per_million) can exceed 2^53 at far more ordinary sizes. node-postgres returns int8 as a string by default, which is convenient — it means you are forced to notice. Confirm that behaviour against your driver version rather than assuming it; if your driver parses int8 to number, configure it not to.
Rate limits, concurrency limits, and budgets bound different resources
These three get conflated all the time, and conflating them is how you end up with a system that is technically rate-limited and financially unbounded.
| Control | Resource bounded | Fails to prevent |
|---|---|---|
| Request-rate limit (RPM) | Requests per unit time | 10 slow, expensive requests per minute |
| Concurrency limit | Simultaneous in-flight calls | Sequential long-context calls that drain the budget |
| Monetary budget | Money | Nothing about speed — but requires a cost bound per call |
A rate limit of 60 RPM still permits 60 maximum-length reasoning calls per minute. A concurrency limit of 4 still permits an unbounded spend over an hour. You need all three, and the budget is the only one that speaks in the unit the invoice uses.
Admission safety is not a bill guarantee
This distinction matters and is usually glossed over:
- Admission safety (achievable): no more than
limit_unitscan ever be reserved concurrently. This is a pure database property and holds exactly. - Hard spending containment (conditional): total provider charges never exceed
limit_units. This holds only if every admitted attempt has a defensible upper bound on its cost.
Admission safety is what the atomic reservation buys you. The bill guarantee additionally requires that the reservation is an actual upper bound — which is a modelling problem, addressed next.
Calculate a reservation that matches the provider request
The provider adapter contract for strict budgeting
A provider adapter that supports strict budgeting must return four things: a versioned price snapshot, the billable usage dimensions, the enforced output limit, and a reservation amount. Anything less and you are guessing.
const ceilDiv = (a, b) => (a + b - 1n) / b;
// Synthetic price sheet. Substitute the published prices for the model you call.
export const PRICE_SNAPSHOTS = {
"example-chat-2026-01": {
version: "example-chat-2026-01",
inputMicrosPerMillionTokens: 2_500_000n, // $2.50 per 1M input tokens
outputMicrosPerMillionTokens: 10_000_000n, // $10.00 per 1M output tokens
chatOverheadTokensPerMessage: 4n,
chatPrimingTokens: 3n,
maxOutputTokensCap: 8192n,
billableDimensions: ["input_tokens", "output_tokens"],
boundedSurcharges: []
}
};The boundedSurcharges array is the load-bearing field. It is empty above because this synthetic model has no per-call or per-session charges. A request that would activate a dimension you cannot bound should not be admitted under a strict budget at all.
Input and output liability, with explicit units
// quote.js
export function quoteUpperBound(snapshot, { messages, maxOutputTokens }) {
if (maxOutputTokens == null) {
return { ok: false, reason: "max_output_tokens_required" };
}
if (BigInt(maxOutputTokens) > snapshot.maxOutputTokensCap) {
return { ok: false, reason: "max_output_tokens_exceeds_cap" };
}
if (snapshot.boundedSurcharges.length > 0) {
return { ok: false, reason: "unbounded_surcharge_dimension" };
}
const promptText = messages.map((m) => m.content).join("\n");
// Character-based estimate, deliberately padded. Swap in the provider's
// tokenizer for the real thing; the padding is a hedge, not a guarantee.
const estimatedInputTokens =
BigInt(Math.ceil(promptText.length / 3)) +
BigInt(messages.length) * snapshot.chatOverheadTokensPerMessage +
snapshot.chatPrimingTokens;
const inputUnits = ceilDiv(
estimatedInputTokens * snapshot.inputMicrosPerMillionTokens,
1_000_000n
);
// Upper bound on output: the cap we enforced, at full price, no discounts.
const outputUnits = ceilDiv(
BigInt(maxOutputTokens) * snapshot.outputMicrosPerMillionTokens,
1_000_000n
);
return {
ok: true,
pricingVersion: snapshot.version,
reservationUnits: inputUnits + outputUnits,
breakdown: {
estimatedInputTokens: estimatedInputTokens.toString(),
inputUnits: inputUnits.toString(),
outputUnits: outputUnits.toString()
}
};
}
Two choices, both deliberate:
Round up everywhere. ceilDiv on each dimension independently, not on the total. Rounding down on input and down on output can each lose a fraction of a unit; rounding up can only over-reserve, and over-reserving is the safe direction.
Chat overhead is added, not ignored. Chat templates insert role markers, separators, and priming tokens that are not in your prompt string. The +4 per message + 3 in the fixture is a placeholder, not a spec — real overhead differs by provider and model, and the honest way to calibrate it is to compare your estimate against reported usage.input_tokens over a sample and take the maximum ratio. That is inference from measurement, not a documented constant.
Cached-token discounts are not applied to the reservation. If your provider charges less for cache hits, reserve at the undiscounted rate and settle at the real one. Reserving at the discounted rate means a cache miss silently blows through the bound.
What weakens a cost reservation bound
Every item here can make a reservation smaller than the actual charge. Each one is a reason to refuse strict budgeting, not to estimate harder.
| Cost source | Why it breaks the bound |
|---|---|
| Reasoning tokens | Billed as output, generated before and independent of the visible answer; the output text you receive does not reveal how many were produced |
| Tool / function calls | One logical request can become several billed round trips, each with its own prompt |
| Multimodal input | Image and audio token counts depend on provider-specific tiling and resolution rules |
| Provider-managed work | Web search, code execution, and file retrieval can carry per-invocation or per-session charges outside token math |
| Tiered / long-context pricing | Some price sheets change rate above a context threshold |
| Unlisted surcharges | Anything not on the price snapshot you vendored |
The correct response for an unbounded dimension is a 422, not a fudge factor. A 20% buffer over an unknown quantity is not a bound.
{ "error": "unsupported_cost_bound", "detail": "request enables a cost dimension this budget cannot bound" }
Estimated vs upper-bound reservations
Estimated reservation = expected_input_tokens * price + expected_output_tokens * price
Upper-bound reservation = padded_input_estimate * price + max_output_tokens * price
Estimated reservations feel efficient and are worthless as a control: they predict the mean, and the mean is not a bound. Upper-bound reservations are correct and cost utilization.
The trade is concrete. A tenant on a 50,000-unit budget, with a typical 400-token prompt and maxOutputTokens: 4096, holds output reservations around 41,000 units per call — so exactly one call in flight at a time fits, even though the median call consumes maybe 2,000 units. The tenant's effective budget is not 50,000; it is 50,000 minus the reservation slack they keep re-borrowing.
Three mitigations fit the bill, none of which preserve a hard bound:
- Tier the cap by request class. Short interactive calls get
maxOutputTokens: 512; long-form jobs get 4096 and their own concurrency lane. - Use the estimate for admission, the upper bound for the guarantee. Admit on the estimate when the tenant has slack; require the upper bound when they are near the limit. This is a policy decision about who eats the risk of a bound failure.
- Meter at a coarse granularity inside the period. E.g. per-hour sub-budgets, so a single oversized reservation blocks an hour, not a month.
Pick one deliberately. Do not discover the trade in production when a paying tenant is told they are out of budget with 92% of it unspent.
Design durable budget and attempt records
Budget and attempt schema
Four tables. Budget periods hold the counters; logical requests hold client identity; provider attempts hold billed work; reservations are a column on the attempt (a separate table only if a single attempt can hold multiple reservations, which it should not); settlement events are the immutable ledger.
CREATE TABLE tenant_budget_periods (
tenant_id text NOT NULL,
period_start date NOT NULL,
currency char(3) NOT NULL,
limit_units numeric(20,0) NOT NULL CHECK (limit_units >= 0),
committed_units numeric(20,0) NOT NULL DEFAULT 0 CHECK (committed_units >= 0),
reserved_units numeric(20,0) NOT NULL DEFAULT 0 CHECK (reserved_units >= 0),
PRIMARY KEY (tenant_id, period_start)
-- No CHECK on committed + reserved <= limit. See the note above.
);
CREATE TABLE logical_requests (
id uuid PRIMARY KEY,
tenant_id text NOT NULL,
idempotency_key text NOT NULL,
request_fingerprint bytea NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (tenant_id, idempotency_key)
);
CREATE TABLE provider_attempts (
id uuid PRIMARY KEY,
logical_request_id uuid NOT NULL REFERENCES logical_requests(id),
tenant_id text NOT NULL,
period_start date NOT NULL,
pricing_version text NOT NULL,
reserved_units numeric(20,0) NOT NULL CHECK (reserved_units >= 0),
state text NOT NULL,
dispatched_at timestamptz,
completed_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT provider_attempts_state_chk
CHECK (state IN ('held','dispatched','settled','released','unresolved')),
CONSTRAINT provider_attempts_budget_fk
FOREIGN KEY (tenant_id, period_start)
REFERENCES tenant_budget_periods (tenant_id, period_start)
);
CREATE TABLE settlement_events (
attempt_id uuid PRIMARY KEY REFERENCES provider_attempts(id),
actual_units numeric(20,0) NOT NULL CHECK (actual_units >= 0),
reserved_units numeric(20,0) NOT NULL,
source text NOT NULL,
settled_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX provider_attempts_open_idx
ON provider_attempts (tenant_id, created_at)
WHERE state IN ('held','dispatched','unresolved');
settlement_events.attempt_id as the primary key is the whole idempotency story for settlement: a duplicate completion handler attempts an insert that conflicts, ON CONFLICT DO NOTHING makes it a no-op, and the balance update is skipped.
Reservation states
held -> dispatched (about to send the HTTP request)
dispatched -> settled (authoritative usage received, liability recorded)
dispatched -> unresolved (authoritative usage absent; liability stays reserved)
held -> released (proven no billable work escaped: 4xx before generation,
connection refused, request rejected at the edge)
unresolved -> settled (late usage evidence arrives, or provider export reconciles)
released is deliberately narrow. It does not mean "the attempt got old," and it does not mean "the client disconnected." It means "we have evidence the provider did not bill." Everything else stays unresolved and stays reserved, because reservation is the only thing standing between an unknown charge and a clean-looking balance.
Bind attempts to period and price
Every attempt stores period_start and pricing_version, and settlement updates the period the attempt originally reserved against — not currentPeriod() at settlement time. A request that reserves at 23:59:58 on the last day of the month and settles at 00:00:03 must debit the old period.
Repricing past work is the second trap: if you recompute cost from today's price sheet when a settlement arrives a day late, a price increase retroactively inflates settled liabilities and a decrease retroactively creates headroom. Store the snapshot version on the attempt; recompute from the stored snapshot only.
Idempotency and tenant identity
The request fingerprint prevents key reuse with a different body: if the same idempotency_key arrives with a different fingerprint, return 409 rather than serving the cached response to a request the client did not make.
Tenant identity comes from authenticated server context — the session or API key resolved at the edge. It must never come from the JSON body. A tenantId field in the request payload is an authorization bug wearing a budget feature's clothes.
Reserve capacity atomically in PostgreSQL
The conditional UPDATE that reserves capacity
The entire control is this statement. It either converts available capacity into reserved capacity, or it changes nothing.
UPDATE tenant_budget_periods
SET reserved_units = reserved_units + $3
WHERE tenant_id = $1
AND period_start = $2
AND committed_units + reserved_units + $3 <= limit_units
RETURNING limit_units, committed_units, reserved_units,
limit_units - committed_units - reserved_units AS available_units;
Zero rows returned means the WHERE did not match — either no period row exists or the tenant is out of budget. Distinguish the two with a follow-up SELECT so the API can return 404 for a missing period and 402 for exhaustion.
Same transaction as the attempt
The balance update and the attempt insert must commit together. A reserved balance with no attempt row is a permanent leak; an attempt row with no reserved balance is a free call.
// reserve.js
export async function reserveAndCreateAttempt(db, { tenantId, periodStart, requestId,
pricingVersion, reservationUnits }) {
return db.withTransaction(async (tx) => {
const update = await tx.query(
"UPDATE tenant_budget_periods " +
"SET reserved_units = reserved_units + $3 " +
"WHERE tenant_id = $1 AND period_start = $2 " +
"AND committed_units + reserved_units + $3 <= limit_units " +
"RETURNING reserved_units",
[tenantId, periodStart, reservationUnits]
);
if (update.rowCount === 0) {
return { admitted: false, reason: "insufficient_capacity" };
}
const attempt = await tx.query(
"INSERT INTO provider_attempts " +
"(id, logical_request_id, tenant_id, period_start, pricing_version, " +
" reserved_units, state) " +
"VALUES (gen_random_uuid(), $1, $2, $3, $4, $5, 'held') " +
"RETURNING id",
[requestId, tenantId, periodStart, pricingVersion, reservationUnits]
);
return { admitted: true, attemptId: attempt.rows[0].id };
});
}
If the insert throws — a uniqueness violation, a foreign key failure, a connection drop — the transaction rolls back and the balance increment disappears with it. That's the point of putting both in one transaction.
Concurrent row-update behaviour
Under PostgreSQL's default READ COMMITTED, a second UPDATE targeting an already-locked row blocks until the first transaction commits or rolls back. When it unblocks, PostgreSQL re-evaluates the WHERE clause against the new row version. If committed + reserved + requested no longer fits, the row is skipped and the statement returns zero rows. You don't need SELECT ... FOR UPDATE; the conditional UPDATE is sufficient and holds the lock for less time.
Under REPEATABLE READ or SERIALIZABLE, the second transaction gets a serialization failure (40001) instead of a silent skip. That's also correct — but it means your application must retry. Retry on 40001 and 40P01 with jittered backoff, and cap attempts:
async function withRetry(fn, tries = 4) {
for (let i = 0; ; i += 1) {
try { return await fn(); }
catch (err) {
const code = err && err.code;
if (i >= tries - 1 || (code !== "40001" && code !== "40P01")) throw err;
await new Promise((r) => setTimeout(r, 10 * 2 ** i + Math.random() * 10));
}
}
}
Whatever isolation level you choose: commit before contacting the provider. Holding the budget row lock across a multi-second network call serializes every tenant-level admission and turns a provider latency spike into a database connection exhaustion event.
The corrected fixture under atomic reservation
Run the same ten-request harness against the conditional UPDATE, with the limit at 1000 and each reservation at 200.
node repro-reserve.js
{
"rounds": 1,
"requested": 10,
"admitted": 5,
"rejected": 5,
"limitUnits": 1000,
"reservedUnits": 1000,
"committedUnits": 0,
"availableUnits": 0
}
Again: designed expectation, not a collected measurement. Five is forced by the arithmetic — five reservations of 200 fit inside 1000 and the sixth cannot — and the rejection count follows from ten requests minus five admissions. The property that actually matters is not the count but the invariant, which holds regardless of arrival order: committed + reserved <= limit after every committed transaction.
Connect the reservation lifecycle to a Node.js request handler
Full Node.js request handler path
// handler.js
export async function handleGenerate({ auth, idempotencyKey, body, deps }) {
const { db, provider, clock } = deps;
// 1. Tenant identity from authenticated context only.
const tenantId = auth.tenantId;
if (!tenantId) return { status: 401, body: { error: "unauthenticated" } };
// 2. Cost bound. Refuse rather than guess.
const snapshot = PRICE_SNAPSHOTS[body.pricingVersion];
if (!snapshot) return { status: 422, body: { error: "unknown_pricing_version" } };
const quote = quoteUpperBound(snapshot, {
messages: body.messages,
maxOutputTokens: body.maxOutputTokens
});
if (!quote.ok) {
return { status: 422, body: { error: "unsupported_cost_bound", detail: quote.reason } };
}
// 3. Idempotent logical request.
const request = await deps.db.upsertLogicalRequest({
tenantId,
idempotencyKey,
fingerprint: deps.fingerprint(body),
periodStart: clock.currentPeriod(tenantId)
});
if (request.conflict) {
return { status: 409, body: { error: "idempotency_key_reused" } };
}
// 4. Atomic reservation, committed before any provider call.
let reserved;
try {
reserved = await reserveAndCreateAttempt(db, {
tenantId,
periodStart: request.periodStart,
requestId: request.id,
pricingVersion: quote.pricingVersion,
reservationUnits: quote.reservationUnits
});
} catch (err) {
if (err.code === "40001" || err.code === "40P01") {
return { status: 503, body: { error: "accounting_contention", retryAfter: 1 } };
}
throw err;
}
if (!reserved.admitted) {
return { status: 402, body: { error: "budget_exhausted" } };
}
// 5. Durable dispatch claim, then and only then the network call.
await db.markDispatched(reserved.attemptId);
let result;
try {
result = await provider.generate({
messages: body.messages,
maxOutputTokens: body.maxOutputTokens
});
} catch (err) {
if (err.kind === "definitely_not_billed") {
await db.releaseAttempt(reserved.attemptId, "provider_rejected_before_generation");
return { status: 502, body: { error: "provider_rejected" } };
}
// Unknown outcome: keep the reservation, mark unresolved.
await db.markUnresolved(reserved.attemptId, err.code || "unknown");
return { status: 504, body: { error: "provider_outcome_unknown", requestId: request.id } };
}
// 6. Settle with reported usage and the attempt's stored price snapshot.
await settleAttempt(db, {
attemptId: reserved.attemptId,
pricingVersion: quote.pricingVersion,
usage: result.usage
});
return { status: 200, body: { text: result.text, requestId: request.id } };
}
Transactions stay away from the provider
Step 4 commits. Steps 5 and 6 are separate statements. Nothing holds a database lock while the provider is generating.
An outbox or job lease does not fix this. A lease gives exactly one worker the right to try; it does not make the external call exactly-once. The provider will happily bill two HTTP requests that carry the same logical request id if your worker crashed after the first one's bytes left the socket. Exactly-once external effects require the provider to deduplicate, and most LLM APIs do not. Design for at-least-once dispatch with reservation as the cost ceiling.
Explicit API outcomes
| Condition | Status | Body | Retry |
|---|---|---|---|
| Budget exhausted | 402 | budget_exhausted | After period rollover or limit change |
| Accounting database unavailable | 503 | accounting_unavailable | Yes, jittered backoff |
| Serialization contention | 503 | accounting_contention | Yes, immediately |
| Unbounded cost dimension | 422 | unsupported_cost_bound | No — change the request |
| Idempotency key reused | 409 | idempotency_key_reused | No — new key |
| Provider outcome unknown | 504 | provider_outcome_unknown | Only with additional capacity |
The line that matters is accounting failure: if the accounting path is down, the request fails. Falling back to "let it through, we'll account for it later" re-creates the original bug with extra steps. Fail closed before dispatch.
Reconcile actual usage without double charging
Normalise usage through the adapter
Provider usage objects differ in field names and in what they count. Normalise to your own shape before touching the ledger:
// normalise.js
export function normaliseUsage(snapshot, rawUsage) {
const dims = {};
for (const name of snapshot.billableDimensions) {
const value = rawUsage && rawUsage[name];
if (!Number.isInteger(value) || value < 0) return { ok: false, reason: "usage_missing:" + name };
dims[name] = BigInt(value);
}
const inputUnits = ceilDiv(dims.input_tokens * snapshot.inputMicrosPerMillionTokens, 1_000_000n);
const outputUnits = ceilDiv(dims.output_tokens * snapshot.outputMicrosPerMillionTokens, 1_000_000n);
return { ok: true, actualUnits: inputUnits + outputUnits, dims };
}
Two things matter here. It refuses partial usage rather than filling in zeros — a missing output_tokens treated as zero silently understates liability. And it computes against the snapshot passed in, which the caller reads from provider_attempts.pricing_version, not from the current price sheet.
Atomic settlement
// settle.js
export async function settleAttempt(db, { attemptId, pricingVersion, usage }) {
return db.withTransaction(async (tx) => {
const attempt = await tx.query(
"SELECT tenant_id, period_start, reserved_units, state " +
"FROM provider_attempts WHERE id = $1 FOR UPDATE",
[attemptId]
);
if (attempt.rowCount === 0) return { settled: false, reason: "unknown_attempt" };
const row = attempt.rows[0];
if (row.state === "settled") return { settled: true, duplicate: true };
const norm = normaliseUsage(PRICE_SNAPSHOTS[pricingVersion], usage);
if (!norm.ok) {
await tx.query(
"UPDATE provider_attempts SET state = 'unresolved' WHERE id = $1",
[attemptId]
);
return { settled: false, reason: norm.reason };
}
const inserted = await tx.query(
"INSERT INTO settlement_events " +
"(attempt_id, actual_units, reserved_units, source) " +
"VALUES ($1, $2, $3, 'provider_usage') " +
"ON CONFLICT (attempt_id) DO NOTHING",
[attemptId, norm.actualUnits.toString(), row.reserved_units, "provider_usage"]
);
if (inserted.rowCount === 0) return { settled: true, duplicate: true };
await tx.query(
"UPDATE tenant_budget_periods p " +
"SET committed_units = p.committed_units + $2, " +
" reserved_units = p.reserved_units - $3 " +
"FROM provider_attempts a " +
"WHERE a.id = $1 AND p.tenant_id = a.tenant_id " +
"AND p.period_start = a.period_start",
[attemptId, norm.actualUnits.toString(), row.reserved_units]
);
await tx.query(
"UPDATE provider_attempts SET state = 'settled', completed_at = now() WHERE id = $1",
[attemptId]
);
return { settled: true, actualUnits: norm.actualUnits.toString() };
});
}
The FOR UPDATE on the attempt row serializes concurrent settlement attempts for the same attempt. The unique settlement_events.attempt_id is the second line of defence: a handler that arrives after the row lock is released sees state = 'settled' and returns early, and even if it did not, the insert conflicts and the balance update is skipped.
Three settlement cases
Starting state: limit = 1000, committed = 600, reserved = 400 (two attempts of 200 each). Attempt A settles.
| Case | actual_units | committed after | reserved after | available | Verdict |
|---|---|---|---|---|---|
| Exact | 200 | 800 | 200 | 0 | Bound held |
| Lower | 140 | 740 | 200 | 60 | Bound held, 60 released |
| Higher | 260 | 860 | 200 | -60 | Bound violated |
The negative available in the third row is the one that matters. It is not a bug in the SQL — it is the ledger telling the truth. Available capacity is below zero because the tenant's actual liability exceeded what was reserved. The next admission attempt fails the conditional UPDATE, which is exactly right. And crucially, the settlement row exists, so finance can see what was actually charged.
Bound failures are an alert, not a constraint violation
When actual_units > reserved_units:
- Record the settlement anyway. The liability is real. A rejected settlement loses the record.
- Block further admissions. The conditional
UPDATEdoes this automatically onceavailablegoes negative. - Alert. A bound failure means the price snapshot or the quote function is wrong for some request class. That is an engineering bug with a financial symptom, and it must be visible.
-- Bound violations in the last 24 hours.
SELECT a.id, a.tenant_id, a.pricing_version,
s.reserved_units, s.actual_units,
s.actual_units - s.reserved_units AS overrun_units
FROM settlement_events s
JOIN provider_attempts a ON a.id = s.attempt_id
WHERE s.settled_at > now() - interval '24 hours'
AND s.actual_units > s.reserved_units
ORDER BY overrun_units DESC;
Make streaming accounting survive missing final usage
Reserve, then open the stream
The reservation happens before the upstream request is opened, with the same quoteUpperBound path. Streaming does not change admission; it changes settlement, because usage evidence arrives at the end of the stream or not at all.
// stream.js
export async function streamGenerate(ctx, res) {
const reserved = await reserveAndCreateAttempt(ctx.db, ctx.reservation);
if (!reserved.admitted) {
res.writeHead(402, { "content-type": "application/json" });
res.end(JSON.stringify({ error: "budget_exhausted" }));
return;
}
await ctx.db.markDispatched(reserved.attemptId);
const controller = new AbortController();
let clientGone = false;
res.on("close", () => {
if (!res.d.writableEnded) {
clientGone = true;
controller.abort();
}
});
let finalUsage = null;
try {
const upstream = await ctx.provider.streamChat({
messages: ctx.messages,
maxOutputTokens: ctx.maxOutputTokens,
streamOptions: { include_usage: true },
signal: controller.signal
});
for await (const event of upstream) {
if (event.type === "usage") { finalUsage = event.usage; continue; }
if (event.type === "delta") {
if (!res.write(event.text)) {
await new Promise((r) => res.once("drain", r)); // backpressure
}
}
}
res.end();
} catch (err) {
if (!res.writableEnded) res.end();
}
if (finalUsage) {
await settleAttempt(ctx.db, {
attemptId: reserved.attemptId,
pricingVersion: ctx.pricingVersion,
usage: finalUsage
});
} else {
// No authoritative usage. Keep the liability reserved.
await ctx.db.markUnresolved(reserved.attemptId, clientGone ? "client_disconnect" : "usage_absent");
}
}
include_usage: true is the OpenAI-compatible Chat Completions mechanism for receiving a terminal usage chunk; Anthropic's Messages stream reports usage on message_start and cumulative output_tokens in message_delta. Check the exact event shape for whichever adapter you write — this is the part of streaming accounting that is genuinely provider-specific.
Disconnects are requests, not confirmations
AbortController propagates a cancellation to the upstream connection. It does not prove the provider stopped generating. Many providers continue a partially generated response server-side and bill for it; the abort just means you stopped listening. The authoritative statement about what was billed is the usage report, and if it never arrives, the outcome is unknown.
So: distinguish "we asked to cancel" from "billing stopped." Only the second one lets you release a reservation.
Missing usage keeps the reservation
When the stream ends without a usage event, the attempt moves to unresolved and the reserved units stay held. Do not substitute locally counted output text. Locally counted text omits at minimum the reasoning tokens a provider may have generated before the visible answer, the hidden tokens consumed by tool-call planning, and any server-side work billed per invocation. It also cannot see whether the provider continued after your abort. Counting what you received and charging for it is an estimate dressed as a measurement.
Streaming settlement test matrix
| Scenario | Upstream behaviour | Attempt state | Reserved | Committed |
|---|---|---|---|---|
| Normal completion | Usage chunk delivered | settled | 0 (released) | actual |
| Disconnect before first chunk | Request aborted before generation | unresolved | held | 0 |
| Disconnect during generation | Partial tokens delivered, no trailer | unresolved | held | 0 |
| Usage event missing, stream completed | All deltas, no usage | unresolved | held | 0 |
| Provider 4xx before generation | Explicit rejection | released | 0 | 0 |
Only the first and last rows release capacity, and the last one requires positive evidence — an explicit rejection status, not an absent response.
Account for retries and crash windows explicitly
Two kinds of identity: logical requests and provider attempts
A client idempotency_key identifies logical work: "the same generation the caller asked for twice." A provider_attempt_id identifies a billable call: "one request that will or will not appear on the invoice."
They are one-to-many. One logical request can legitimately produce two attempts — because the first timed out after dispatch and had to be retried. Both attempts carry reservations. Collapsing the two identities is how teams convince themselves a retry is free.
Timeout after dispatch is an unknown outcome
t=0 reserve 200, state=dispatched, send request
t=30s AbortSignal.timeout fires, socket closes
t=30s ??? the provider may have generated and billed the full response
This is not a failure you can refund. The reservation stays. A retry needs its own 200-unit reservation and must pass admission independently. If the tenant cannot afford a second reservation, the retry is denied — which is correct, because you may already owe for the first one.
const res = await provider.generate({ ..., signal: AbortSignal.timeout(30_000) });
// AbortError here means "we stopped waiting", not "the provider stopped billing".
Crash windows between reservation and settlement
| Crash point | Durable state | Recovery action | Risk |
|---|---|---|---|
| Before reserve commits | No attempt row | Nothing to do | None |
After reserve, before dispatched | held | Ambiguous: mark unresolved, keep reserved | Phantom hold; conservative |
After dispatched, before send | dispatched | Mark unresolved | Phantom hold |
| After send, before response | dispatched | Mark unresolved | Real charge, reserved |
| After response, before settlement | dispatched | Settle from persisted usage if stored; else unresolved | Real charge, reserved |
| During settlement transaction | Atomic — all or nothing | Retry settlement (idempotent) | None |
The third row decides your design. Writing dispatched before the HTTP call means a crash before the bytes leave the socket leaves a phantom hold — capacity that is reserved but never spent. Writing it after the call means a crash after the bytes leave leaves a free charge. The first errs toward holding tenant money; the second errs toward giving it away. Choose the first, and reconcile phantom holds against provider records rather than against a timer.
Why a TTL cannot release funds
A common shortcut: release reservations older than N minutes because "the request must be dead by now." It cannot be correct, because the provider's billing state is not a function of your wall clock. A long-running request, a provider-side queue, or a usage report delayed by an hour all break the assumption. A TTL converts an unknown liability into a silent write-off.
Use leases for worker ownership — who is allowed to finish this attempt — and keep funds reserved until you have evidence or an explicit, documented, bounded-risk policy. If you adopt such a policy, write down the maximum amount it can write off per period and alert when approaching it. "We release after 30 minutes" is a policy; "the request must be dead" is a wish.
Verify the accounting properties under contention and faults
Property test contract for concurrent admission
Following the shape used for evaluation reporting:
Task: 10 concurrent generation requests against one tenant budget period.
Inputs: limit = 1000 units, reservation = 200 units, fixed fake provider charge.
Criterion: every committed transaction leaves committed + reserved <= limit;
no attempt is settled twice; uncertain attempts stay reserved.
Runs: 100 rounds, fresh period per round.
Assertions per round:
admitted == 5,rejected == 5reserved_units <= 1000at the end of the admission phasecommitted_units + reserved_units <= 1000after every settlementunresolved == 0in the happy pathsettlement_eventsrow count equalssettledattempt count
Aggregate expectation over 100 rounds:
{
"rounds": 100,
"admitted": 500,
"rejected": 500,
"committedUnits": 100000,
"reservedUnits": 0,
"unresolved": 0,
"boundViolations": 0,
"duplicateSettlements": 0
}
This is a specification of what the suite should produce, not a measurement I have collected. The per-round numbers follow from the fixture arithmetic; the aggregate follows by multiplication. Anyone running the suite should expect these values and treat a deviation as a real finding — particularly duplicateSettlements > 0 or a mid-run committed + reserved > limit.
Integration tests that expose ledger bugs
Beyond the contention suite, these are the cases that have caught real bugs in ledgers I have seen:
- Duplicate admissions. Same
idempotency_keysent 5× concurrently. Expect one logical request, one attempt, four 409s or cached responses — never two reservations. - Duplicate settlements. Call
settleAttempt10× concurrently for the same attempt. Expect exactly onesettlement_eventsrow and one balance change. - Multiple Node.js processes. Run the fixture under
node:clusterwith 4 workers against one PostgreSQL instance and one tenant. This is the test that kills process-local mutexes. - Transaction retries. Force
40001by running the reservation atSERIALIZABLE. Expect retries to converge and the invariant to hold. - Period rollover. Reserve at 23:59:58, settle at 00:00:03. Expect the debit on the old period.
Fault-injection cases for unknown liability
| Fault | Expected outcome |
|---|---|
| Provider timeout after dispatch | Attempt unresolved, reservation held |
Worker SIGKILL after dispatched | Attempt unresolved on recovery, reservation held |
| Database connection drop mid-transaction | No partial reservation; retryable |
| Dropped stream trailer | Attempt unresolved, reservation held |
| Provider 4xx before generation | Attempt released, reservation returned |
The single property every row tests: uncertain liability never silently becomes available capacity. If a fault can turn an unknown charge into free budget, the ledger is not a control.
Operate the budget ledger as a financial control
Ledger metrics that reveal overspend risk
| Metric | Why | Alarm signal |
|---|---|---|
| Reservation age (p95, p99) | Stuck reservations mean stuck capacity | p99 over a few minutes |
| Unresolved liability (units) | Unknown charges you are holding for | Rising without settlement |
| Settlement lag | Time from dispatched to settled | Growing trend |
| Estimate-to-actual ratio | Quote quality | Median far below 1.0 wastes capacity; any value below 1.0 on a single attempt is a bound failure |
| Rejected admissions | Tenant hitting limits | Sudden spikes mean traffic change or a bad limit |
| Bound violations | Charges above reservation | Any non-zero count is a bug ticket |
The estimate-to-actual ratio deserves both tails. A ratio near 1.0 means the upper bound is tight and the tenant gets their money's worth. A median ratio of 0.1 means you are holding ten times what requests consume, and tenants will hit "budget exhausted" with most of their budget unspent. That is a product bug that looks like a finance bug.
Reconcile internal settlement against provider billing
Internal records are the control; provider billing is the check. Where the provider exposes a usage or billing export, reconcile periodically: sum settlement_events.actual_units per tenant per period against the provider's attribution for the same window.
Expect this to be imperfect. Reporting delays of hours are normal, and attribution by tenant is often only possible through your own request ids if the provider supports tagging or metadata passthrough. Where attribution is impossible, reconcile at the account level and accept that per-tenant attribution is internal-only. Write that limitation down; do not let a clean reconciliation report imply a precision it does not have.
The final guarantee, stated precisely
What atomic reservation guarantees: under any number of concurrent requests across any number of Node.js processes, the sum of committed_units + reserved_units never exceeds limit_units as the result of an admission decision. This is a database property, verifiable by the conditional UPDATE, and it holds regardless of event-loop interleaving, worker count, or replica count.
What it does not guarantee: that total provider charges stay under limit_units. That additionally requires every admitted attempt to have a valid upper cost bound, and every unknown outcome to be treated conservatively — reserved, not released, not written off on a timer, not assumed free because the client disconnected.
Those are two different claims, and only the first one is free. The second one is the actual work: a price snapshot you vendor, a quote function with no unbounded dimensions, an honest handling of unresolved, and a monitoring surface that makes bound failures loud. Skip any of those and you have a system that never exceeds its budget in the database and still overruns it on the invoice.
Further Reading
Source context
- Startup Fortune headline via Google News discovery — topic context only. The supplied material contains a headline and snippet; no implementation, measurement, or incident detail is attributed to it in this post.
PostgreSQL references
UPDATE—RETURNINGand conditional updates- Transaction isolation,
READ COMMITTEDre-evaluation, and serialization failures - Explicit locking and row-level lock behaviour
INSERT ... ON CONFLICTfor idempotent settlement events- Numeric types and
numeric(p,0)for integer accounting node-postgrestype parsing forint8
Node.js and provider references
AbortControllerandAbortSignalAbortSignal.timeout()- Stream backpressure and
drain - Cluster mode, for the multi-process contention test
- OpenAI Chat Completions create — usage object and
stream_options - OpenAI streaming responses guide
- OpenAI API pricing
- Anthropic Messages API — usage reporting and streaming events
- Anthropic API errors and rate limits
- Stripe idempotent requests — the general idempotency-key pattern
More posts

Rate Limiting, Circuit Breakers, and Queue Backpressure: Hardening Node.js Against DDoS
A practical Node.js security guide showing how rate limiting, circuit breakers, and queue backpressure can help harden services against DDoS-style traffic spikes.

Cost per Successful Agent Task with Qwen4-35B-A3B: Testing Quantization and CPU Offload Limits on 8GB GPUs
A reproducible cost-per-successful-task evaluation of Qwen4-35B-A3B on 8GB GPUs, measuring how quantization and CPU offload affect memory, latency, throughput, and agent reliability across context lengths.

Running a Stable-vs-RC TypeScript 7.1 CI Lane Before Upgrading
Set up a parallel CI lane that runs stable and TypeScript 7.1 RC builds to validate compiler API consumers, declaration output, editor integration, and toolchain compatibility before upgrading.
Loading comments…