Price OpenAI calls per tenant with Postgres holds
Price each OpenAI call from a dated Postgres table, log usage per tenant in Node.js, and reserve budget so a burst of requests cannot blow the cap.
This article is published in English.
Sources: LLM Cost Tracking per Tenant in Node.js and Postgres
An OpenAI invoice shows up at about twice the figure you had in mind. Which tenant ran the spend, and which feature, is a question the app can't answer. Those calls were never written down.
A lot of cost advice stops once you multiply a token count by a rate. That is where the dollars go wrong. Cached prompt tokens carry a rate of their own. Models in the current generation also bill the write into cache. Reasoning tokens already sit inside the output total, so adding them a second time counts them twice. A stream stays quiet about usage until the request asks for it. A budget gate that reads the month-to-date sum and only then calls the API lets a pile of overlapping requests all observe that same sum and all proceed.
Close the gap in TypeScript. Keep a row for every call, and keep prices in Postgres with the moment each rate starts. Force every call through one wrapper. Hold budget so concurrent requests can't all slip under the same cap. Roll the rows up, then reconcile them with the provider. The figures below were measured on Postgres 16, using a local stand-in for OpenAI.
How the usage fields actually bill
Responses and Chat Completions label the same counters differently. The map is taken from the type definitions in openai-node at v7.32.0.
Responses API (usage.) Chat Completions (usage.)
input_tokens prompt_tokens
input_tokens_details.cached_tokens prompt_tokens_details.cached_tokens
input_tokens_details.cache_write_tokens prompt_tokens_details.cache_write_tokens
output_tokens completion_tokens
output_tokens_details.reasoning_tokens completion_tokens_details.reasoning_tokens
Two rules decide whether your total matches the invoice.
- Tokens read from cache, and tokens written into cache, already sit inside the input total. OpenAI's cache pricing notes price those slices on their own. Ordinary input is what remains after you subtract
cached_tokensand, separately, subtractcache_write_tokens. Each slice gets its own rate. From GPT-5.6 onward, a cache write costs 1.25 times the plain input rate. Models older than that don't bill the write. - Reasoning tokens already sit inside the output total. These reasoning notes call that charge "billed as output tokens". The worked example on that page already folds them into
output_tokens.
Collapse both payload shapes into one Tokens value. On Chat Completions the detail objects are optional, so a missing detail is zero.
Take a single call from the test. The input side was 1,726 tokens, and 1,536 of those were written into cache. The output side was 312 tokens, with 192 of them reasoning. Sample rates per million tokens: input at 2.00, a cache write at 2.50, output at 8.00. Price that call three ways and you get three different bills.
method cost (USD)
input * in + output * out 0.005948
+ cache writes priced correctly 0.006716
+ reasoning added again (wrong) 0.008252
Skip the cache-write premium and you land 11 percent under the real charge. Add the reasoning tokens again, on top of an output total that already contains them, and you land 23 percent over. One request, three charges.
Rates live in a dated table
Hardcoding a rate means a deploy every time the price moves. Computing the dollars when someone reads the row is worse, because yesterday's calls get repriced on today's card. Store the card in Postgres, and stamp each row with the timestamp it becomes active.
CREATE TABLE model_prices (
model text NOT NULL,
service_tier text NOT NULL DEFAULT 'default',
effective_from timestamptz NOT NULL,
input_per_1m numeric(12,6) NOT NULL,
cached_input_per_1m numeric(12,6) NOT NULL,
cache_write_per_1m numeric(12,6) NOT NULL,
output_per_1m numeric(12,6) NOT NULL,
PRIMARY KEY (model, service_tier, effective_from)
);
-- EXAMPLE prices, not real ones. Copy current numbers from the provider's pricing page.
INSERT INTO model_prices (model, service_tier, effective_from, input_per_1m, cached_input_per_1m, cache_write_per_1m, output_per_1m) VALUES
('example-small', 'default', '2026-01-01', 0.40, 0.04, 0.50, 1.60),
('example-small', 'default', '2027-01-01', 0.30, 0.03, 0.375, 1.20),
('example-large', 'default', '2026-01-01', 2.00, 0.20, 2.50, 8.00)
Names and dollar figures in that table are placeholders. Pull the live numbers from the OpenAI pricing page. service_tier belongs in the primary key. Flex and Batch do not share the default tier's price, and the response tells you which tier actually served the request.
Log every call that reached the provider
Write one row for each call that actually reached the provider.
CREATE TABLE llm_usage (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
created_at timestamptz NOT NULL DEFAULT now(),
tenant_id text NOT NULL,
user_id text,
feature text NOT NULL,
api text NOT NULL, -- 'responses' | 'chat'
requested_model text NOT NULL,
model text NOT NULL, -- what the API says it used
service_tier text NOT NULL,
request_id text, -- x-request-id header
response_id text,
status text NOT NULL, -- completed | incomplete | failed | aborted
input_tokens integer NOT NULL,
cached_tokens integer NOT NULL,
cache_write_tokens integer NOT NULL,
output_tokens integer NOT NULL, -- includes reasoning tokens
reasoning_tokens integer NOT NULL,
usage_missing boolean NOT NULL DEFAULT false,
cost_usd numeric(18,10) -- NULL = no price matched
);
CREATE INDEX llm_usage_tenant_time ON llm_usage (tenant_id, created_at);
CREATE UNIQUE INDEX llm_usage_request_id ON llm_usage (request_id) WHERE request_id IS NOT NULL;
Store money as numeric. On the first run, JavaScript produced 0.0033431999999999997 while Postgres kept 0.0033432000 for the same amount. Add a million binary floats and you'll spend the afternoon defending a gap that isn't real. An integer column of micro-dollars is a fair substitute: a rate quoted per million tokens is already the micro-dollar price of one token.
The model string on the response is a dated snapshot, not the alias you sent. Keep the snapshot, and keep requested_model beside it. Cost is calculated inside the INSERT. The lookup tries the snapshot name, then falls back to the alias.
INSERT INTO llm_usage (tenant_id, user_id, feature, api, requested_model, model, service_tier,
request_id, response_id, status, input_tokens, cached_tokens, cache_write_tokens,
output_tokens, reasoning_tokens, usage_missing, cost_usd)
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16,
CASE WHEN $16 THEN NULL ELSE
(($11::int - $12::int - $13::int) * p.input_per_1m
+ $12::int * p.cached_input_per_1m
+ $13::int * p.cache_write_per_1m
+ $14::int * p.output_per_1m) / 1000000 END
FROM (SELECT 1) one
LEFT JOIN LATERAL (
SELECT * FROM model_prices
WHERE model IN ($6, $5) AND service_tier = $7 AND effective_from <= now()
ORDER BY (model = $6) DESC, effective_from DESC LIMIT 1
) p ON true
RETURNING cost_usd
That lookup is a LEFT JOIN for a reason. When model_prices has no match, the usage row is still inserted and the cost stays NULL. Dropping the token counts because a rate is missing is the worse failure.
One wrapper, and a CI check that enforces it
createMeter is built from the OpenAI client and a pg pool. It is the only door you should leave open. Responses traffic uses respond, and respondStream when you want tokens as they arrive. Chat Completions uses chat, and chatStream for a stream.
You pass a context that names the tenant, the user, and the feature. The method estimates an upper bound, places a hold for that amount, performs the API call, and writes the result.
async respond(ctx: Ctx, params: ResponseCreateParamsNonStreaming): Promise<Response> {
const p = { ...params, max_output_tokens: params.max_output_tokens ?? DEFAULT_MAX_OUTPUT };
const res = await reserve(ctx, await estimate(String(p.model), p, p.max_output_tokens));
let out: { data: Response; request_id: string | null };
try {
out = await openai.responses.create(p).withResponse();
} catch (e) {
await release(res); // no usage came back; reconciliation catches billed timeouts
throw e;
}
const r = out.data;
await record({
ctx, api: "responses", requestedModel: String(p.model), model: r.model,
serviceTier: r.service_tier, requestId: out.request_id, responseId: r.id, status: r.status ?? "completed",
tokens: r.usage ? fromResponses(r.usage) : ZERO, usageMissing: !r.usage,
}, res);
return r;
},
.withResponse() is how you read the header x-request-id. Keep it when you open a ticket with OpenAI, and keep it as the key that identifies the attempt. Always set an output ceiling. The hold needs an upper bound even when the caller left the cap blank.
Until the build rejects a bypass, the wrapper is only a habit. Fail CI when any TypeScript file outside src/llm/ imports the OpenAI SDK on its own.
#!/usr/bin/env bash
# Fail if anything outside src/llm/ imports the OpenAI SDK directly.
leaks=$(grep -rlE --include='*.ts' "from ['\"]openai(/[^'\"]*)?['\"]" src | grep -v '^src/llm/')
if [ -n "$leaks" ]; then
echo "Direct OpenAI imports outside src/llm/ (use the metered client):"
echo "$leaks"
exit 1
fi
Streams report usage only if you ask
A Chat Completions stream omits usage unless stream_options carries include_usage set to true. Usage then arrives once, on an additional chunk after the content, and the choices array on that chunk is empty. In the test, a raw stream sent with the flag off produced no usage object at all. The wrapper turns the flag on and doesn't treat it as optional. These lines are the relevant slice.
const p = {
...params,
max_completion_tokens: params.max_completion_tokens ?? DEFAULT_MAX_OUTPUT,
stream_options: { ...params.stream_options, include_usage: true }, // not optional for us
};
// ... reserve and create, same as respond() ...
try {
for await (const chunk of call.data) {
last = chunk;
if (chunk.usage) usage = chunk.usage; // only on the final chunk, with choices: []
if (chunk.choices.length) yield chunk;
}
} finally {
await record({
ctx, api: "chat", requestedModel: p.model, model: last?.model ?? p.model,
serviceTier: last?.service_tier, requestId: call.request_id, responseId: last?.id ?? null,
status: usage ? "completed" : "aborted",
tokens: usage ? fromChat(usage) : ZERO, usageMissing: !usage,
}, res);
}
On the Responses API, response.completed includes the whole response object, and usage is on that object. response.incomplete includes it too. response.failed does as well. respondStream takes whichever of the three shows up.
A finally block still runs when the stream completes, when it throws, and when the caller stops reading. Typings shipped with the SDK call this out: a stream cut short may never hand you a usage object. In that case store the row with usage_missing set, and leave the entire hold on the budget. The test kept 0.008306 USD that way. You bill your own ledger on the high side, then correct the row once you know more.
Testing is what surfaced the next trap. A loop that breaks as soon as finish_reason is present on the first choice exits on the content chunk. The chunk that carries usage is the next one, so the loop never reads it, and every streamed call is stored with usage_missing. If the bytes are going to a browser, inspect Nginx buffering too. A buffer can sit on that trailing chunk.
Hold the budget before the call
The check people write first sums spend for the month and allows the API call when the sum is still under the cap. Fire several at once and each one samples that sum before a single write has landed. The test set the cap at 0.05 USD, fired 60 calls at roughly 0.0059 USD apiece, and gave the mock 40 ms of latency.
setup ran spent (USD)
naive, burst of 60 60 0.356400
naive, 8 workers 16 0.095040
reserve, burst of 60 4 0.023760
reserve, 8 workers 6 0.035640
The unlocked burst spent about seven times the cap. Fix it by reserving a worst-case amount in one UPDATE, and let the WHERE clause reject the write when the new total would pass the limit.
async function reserve(ctx: Ctx, amount: number): Promise<Reservation> {
const month = monthOf();
await pool.query(
`INSERT INTO tenant_spend (tenant_id, month) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
[ctx.tenantId, month]);
// Check and reserve in one statement. The row lock serializes concurrent callers.
const r = await pool.query(
`UPDATE tenant_spend s SET reserved_usd = s.reserved_usd + $3
FROM tenants t
WHERE t.id = s.tenant_id AND s.tenant_id = $1 AND s.month = $2
AND s.spent_usd + s.reserved_usd + $3 <= t.monthly_limit_usd`,
[ctx.tenantId, month, amount]);
if (r.rowCount === 0) throw new BudgetExceededError(`Tenant ${ctx.tenantId} is over budget`);
return { tenantId: ctx.tenantId, month, amount };
}
That UPDATE takes a lock on the spend row. Other sessions wait, and each one sees holds that are already in place. After the call returns, record replaces the hold with the measured cost. The replacement and the insert into llm_usage share a single transaction. When the API call throws, release puts the held amount back.
The estimate is deliberately fat. Take the character length of the JSON body and divide by 2. The mock treats 4 characters as one token, so the divisor of 2 is a twofold cushion. Price those tokens at the input rate or the cache-write rate, whichever is larger, then add the output ceiling at the output rate. You land near 0.0119 USD, close to twice what the call really costs. That spread is the compromise in the results. The reserved path never went over the cap, and it left somewhere between 17 percent and 52 percent of the budget sitting unused. Across reruns, the reserved worker row admitted anywhere from 4 calls up to 7. A real tokenizer, plus a tighter output ceiling, shrinks the unused slice.
Soft alerts use the same single-winner update. After the measured cost is stored, one UPDATE writes soft_alerted_at only on the row where that column is still null and spend has passed the line. Postgres hands the row to one session, so only that session sends the alert. Eight workers in the test all passed a line at 30 percent, and the handler ran a single time.
Daily and monthly totals per tenant
An index on (tenant_id, created_at) is enough for the rollup. The query is ordinary SQL, grouped by UTC day, tenant, and feature.
SELECT (created_at AT TIME ZONE 'UTC')::date::text AS day, tenant_id, feature,
count(*) AS calls, sum(input_tokens) AS input, sum(cached_tokens) AS cached,
sum(output_tokens) AS output, round(sum(cost_usd), 6) AS cost_usd,
count(*) FILTER (WHERE cost_usd IS NULL) AS unpriced
FROM llm_usage
WHERE created_at >= date_trunc('month', now() AT TIME ZONE 'UTC') AT TIME ZONE 'UTC'
GROUP BY 1, 2, 3 ORDER BY 1, 2, 3
Running it produced rows like these.
day tenant feature calls input cached output cost_usd unpriced
2026-10-10 acme support-bot 6 5204 1536 864 0.010984 2
2026-10-10 tiny load 4 6888 0 1248 0.023760 0
Bucket by UTC day so your groups line up with the provider. Casting the day to text is on purpose. node-postgres reads a date as midnight in the machine's local zone. On a host set to UTC+5, toISOString() moved 2026-10-10 back to 2026-10-09. Treat unpriced as the list of rows you still owe a price. In this sample, that is two streams that were cut short. For a monthly cut by person, group on user_id. Join tenants when you want each person's spend as a share of the tenant budget.
Match the ledger to the Usage API
Expect the two ledgers to diverge. A stream can abort. A call can go around the wrapper. A timeout on your side can still be a completed request on theirs, and they will bill it. OpenAI exposes the daily totals at /v1/organization/usage/completions, and that route wants an admin key. A notebook in the OpenAI cookbook walks through the call. Each bucket is one day. It carries num_model_requests. It carries input_tokens along with output_tokens. Cached input shows up as input_cached_tokens. You ask for grouping by model. A second route, /v1/organization/costs, returns dollars split by line_item and also by project_id.
Compare tokens, and leave dollars out of that check. Token totals ought to agree to the token. Dollar totals move with the rate card, and the rate card is what you are still trying to prove. Sum llm_usage for each UTC day and each model, drop rows where usage_missing is set, and raise a flag when the two sides differ by more than 1 percent. Against the mock, the comparison looked like this.
day|model ours req tok theirs req tok drift
2026-10-10|example-large-2026-01-15 88 179000 88 179000 0.0%
2026-10-10|example-small-2026-01-15 2 1992 5 7560 73.7% <-- check
The large snapshot for that day matched on requests and on tokens. The small snapshot did not. Three calls were absent locally: one went out through the raw client, and a pair of streams aborted. The Usage API is organized by project. It has no tenant field, so it cannot tell you who to bill. It can tell you how wide the hole is.
Where the ledger still breaks
- No rate on file. The wrapper will not send a model that has no price row, so an unfamiliar model name dies in staging. It won't show up later as a surprise on the invoice.
- A price change. Insert a new row and put
effective_fromin the future. Dollars you already stored stay put. A row dated 2027 was present in the test, and it was ignored, which is the behavior you want. - Retries. Out of the box, the SDK tries again two times. A try that actually reached the server can still appear on the invoice, while your wrapper only sees the try that came back.
- Long context and region. The pricing page keeps long-context rates in their own columns. Newer models also add 10 percent when processing is regional. Add columns when you pay either of those.
- Tools. Search on the web is charged per thousand calls. Search over files is charged the same way. Storing files is charged per GB each day. None of that is a per-token rate, so log those charges on separate rows.
- A busy tenant. Every hold for one tenant waits on a single row lock. That queue was never put through a load test. When one tenant's volume gets very high, take the holds in batches instead of once per request.
A single in-house tool doesn't need any of this. Filtering the dashboard your provider already offers, by project, is often enough. Build this when you invoice customers, or when you have to stop a tenant that has run past its cap.
What to ship first
Start with the usage table and the metering wrapper, well before budgets feel necessary. The rows are cheap to write, and you can't rebuild them after the calls are gone. Read rates from the table. Keep money in a numeric column. Always request usage on streams. Put the import guard into CI the day the wrapper lands. Reservations can wait until a tenant is able to spend money that matters. Run the comparison every night, and alert when drift passes 1 percent.
The runs used Node 22.22. TypeScript was 7.0, compiled with --strict. The openai package was 7.32.0 and pg was 8.23. Postgres itself was 16.15. Next to that, a small local server returned usage payloads in the shapes the SDK already expects. Ten groups of tests passed, then the same ten passed again across ten runs back to back.
When a user closes a stream halfway through, do you bill the estimate, or do you absorb the cost?