When you sell access to an AI coding IDE, two systems decide whether the business survives: the gateway that meters every token, and the billing that turns money into plans. Get metering wrong and you either give away inference or overcharge the users who trusted you. Get payments wrong in a market where cards aren't the default and you simply don't sell.

DeepCode Studio is the server side of an AI coding IDE: one OpenAI/Anthropic-compatible API in front of the model provider, per-plan model access, per-token credit metering, and, because its market pays with UPI, a checkout that ends in a QR code approved from the owner's phone. This post walks through the three subsystems with real executions. Nothing below is a README claim: I cloned the repo, installed it with pnpm 10, and ran everything shown.

What I ran first

$ pnpm typecheck # turbo, all packages, strict Tasks: 6 successful, 6 total $ pnpm --filter @deepcode/shared test Tests 10 passed (10) 

The monorepo (gateway, Next.js web, Drizzle db package, shared package) typechecks clean across all six turbo tasks. The integration suites boot Postgres and Redis through testcontainers, which needs Docker, and this sandbox has none, so those suites are quoted from code, not run. Everything in the sections below is a direct execution of the modules themselves.

Metering: a credit is a microdollar, and cache reads are 10x cheaper

All money in the system is integer credits, where 1 credit = $0.000001 (ADR-004). Model prices are integer credits per million tokens, and computeCredits is deliberately boring: normalize, multiply, sum, round up.

The interesting decisions are in the normalization. normalizeUsage clamps negatives and fractions to zero and caps cachedInput at input and reasoning at output, so a buggy or adversarial upstream usage record can never produce negative billing or bill more cache than was sent. The reasoning tokens are billed as output, and the doc comment says so, which is the kind of boring honesty that prevents support tickets.

The pricing weights are also thought through. The upstream provider (a pooled key service) gives each key a fixed monthly allowance, and a $1 of a $15-limit model consumes 4x the allowance of a $1 of a $60-limit model, so the credit price is the token price weighted by allowance share. Running the real numbers for kimi-k3 ($3/$15/$0.30 per MTok, $15 limit, so 4x weight):

weighted credits/MTok [input, output, cached]: [12000000, 60000000, 1200000] usage { input: 25100, cachedInput: 20000, output: 350 } -> 106200 credits = $0.1062 same usage without cache: 322200 credits; cache saved 216000 

A cache-heavy agentic coding session costs a third of the uncached price, and the pricing engine makes that automatic: cached input bills at a tenth of the input rate. Users who prompt-cache well literally pay less, which is the correct incentive for an IDE that sends enormous contexts.

Settlement is where metering usually dies under load, and the code carries the scar tissue as documentation. settleBatch settles many records in one transaction: a multi-row insert with ON CONFLICT DO NOTHING so replays are no-ops (the request ID and timestamp are the primary key), pre-aggregated daily rollups upserted only for rows that were actually new, and one atomic UPDATE ... RETURNING per subscription in ID order to avoid deadlocks. The comment explains why: per-request transactions serialized on the subscriber's row and starved the connection pool at 150 concurrent streams. Errors are classified by SQLSTATE prefix: data exceptions, integrity violations and undefined objects (22/23/42) are poison and go to a dead-letter stream; anything else is transient and retried. That distinction is the whole game in exactly-once-ish billing.

Streams: three API dialects, one truthful usage record

The gateway speaks OpenAI Chat, OpenAI Responses, Anthropic Messages and Google generateContent, and each protocol adapter normalizes usage into one shape. Anthropic reports uncached input, cache reads and cache writes separately; the adapter folds them (input = all three, cachedInput = reads). I drove the real stream parser with synthetic SSE events, a message_start carrying 100 fresh input tokens, 5,000 cache-write and 20,000 cache-read tokens, then a message_delta with 350 cumulative output tokens, then message_stop:

terminal on message_stop: { forward: true, terminal: true } usage(): { input: 25100, cachedInput: 20000, output: 350, reasoning: 0 } 

100 + 5,000 + 20,000 = 25,100, with the 20,000 reads correctly reported as the cached portion. Two details worth stealing: the parser only runs JSON.parse on events whose payload contains "usage" or "message_stop" (no parsing thousands of content deltas), and the terminal event is flagged terminal: true so the proxy can hold it until settlement finishes. The client never sees "done" before the money is counted. Also worth noting: raw fields are tracked separately per key because Anthropic's message_delta repeats only some usage fields, and resetting the others would silently lose the cache numbers.

Billing: the confirmation is a human, on purpose

Card rails are a poor fit for the market this serves, so payments are UPI QR codes with manual approval, and the doc comment states the decision date and the reasoning: "There is no automatic verification: the admin's confirmation IS the check."

The flow: pick a plan, get a payment row with a fixed amount and a short reference, and the page shows a QR any UPI app can scan. After paying, the user submits the bank UTR (transaction reference); the owner's phone app gets a push notification; the owner checks the money actually arrived in their own bank app and approves from the phone. Approval activates the plan through the same idempotent billing-event path as every other provider.

The helpers are small and sharp. References use an alphabet without 0/O/1/I so nobody misreads a QR reference over a phone call. UTRs are normalized (spaces and dashes stripped, uppercased) before validation. And the QR payload follows the NPCI URL spec with one deliberate deviation fixed: URLSearchParams encodes spaces as +, which some UPI apps render literally, so they're rewritten to %20. All executed live:

references: [ 'DCQHPMSV3N', 'DCCYJCHPXV', 'DCN77W6KLW' ] normalizeUtr(" ab12-cd34 5678 "): "AB12CD345678" upi://pay?pa=owner%40ybl&pn=DeepCode%20Studio&am=499.00&cu=INR&tn=DeepCode%20DC9K4TMX2P 

A user can have at most three open payments, stale ones expire lazily on read, and a UTR can never be claimed twice. Manual approval sounds like it doesn't scale, and it doesn't, which is fine: at this stage the failure mode that kills you is charging without delivering, not queue depth.

What I verified, and what I did not

Executed while writing this, on Node 22.23.5 with pnpm 10.33.2: the full monorepo typecheck (6/6 turbo tasks), the shared package suite (10/10), the credit math and clamping, the Anthropic stream normalization, and the UPI reference/UTR/QR helpers shown above. Not run: the gateway, db and web integration suites, which spin up Postgres and Redis via testcontainers (no Docker in this environment), the Playwright visual suite, and anything against the live provider or a real UPI account. The settlement batching and dead-letter behavior are quoted from source comments and code, not load-tested here. The hosted instance, pricing and model catalog are development-stage and may change.

The repo is github.com/ALSRKAL/deepcode-studio. If you take one thing: make your usage record truthful at the protocol boundary, make settlement idempotent at the database boundary, and let a human be the payment webhook when the market calls for it.