Production AI budgets rarely blow up because of a single dramatic prompt. Across dozens of FinOps reviews with SaaS engineering leads, multi-tenant platforms, and AI product studios, unexpected outages and unexplained spend almost always trace back to two operational blind spots: first, a live service suddenly throwing HTTP 402 insufficient_quota during peak business hours because nobody wired an automated balance watcher to their prepaid wallet; second, a month-end finance review asking which customer cohort or background agent burned through last month's inference allocation while engineering scrambles through unstructured application logs trying to reconstruct costs from token estimates.
This TOP AI balance top-up and cost monitoring tutorial eliminates both failure modes permanently. If you already created your account and sent your first inference request through our TOP AI quickstart tutorial and wired your runtime using the TOP AI SDK integration tutorial for Python, Node.js, LangChain, and Vercel AI SDK, this guide is the exact FinOps engineering blueprint you should deploy before production traffic scales. Instead of treating billing as an afterthought, you will build a complete closed-loop financial control plane: funding prepaid TOP Points at 1 TP = Rp 1 (~$0.0000625 at Rp 16,000/USD) across QRIS, Virtual Account, Midtrans, and USDT rails; polling GET /v1/balance at zero cost; streaming inline topai.charged_gp and topai.balance_after telemetry into PostgreSQL and ClickHouse per-tenant ledgers; running a burn-rate aware Slack and Telegram alert worker that fires well ahead of 50,000 TP; modeling a realistic 1,000,000 TP (~$62.50 / Rp 1,000,000) monthly multi-workload budget; and enforcing strict client spend ceilings with scoped customer virtual keys.
FinOps Quick Reference: TOP AI uses a fixed
1 TP = Rp 1rate (~$0.0000625 USD at Rp 16,000/USD) with zero hidden platform surcharge and non-expiring prepaid balance. Top-ups at/dashboard/saldoaccept Rp 5,000 to Rp 10,000,000 per order (TOP-prefix) via QRIS, Virtual Account, Midtrans Snap, and USDT. Programmatic polling viaGET /v1/balancecosts 0 TP, and every inference response returns inline billing telemetry (topai.charged_gp,topai.balance_after,upstream,failover,latency_ms) plus thex-topai-chargeheader so your ledger reconciles to the exact integer TP.
Why Deterministic Prepaid Economics (1 TP = Rp 1) Changes AI FinOps Architecture
Engineering teams operating on postpaid credit-card billing across three or four direct LLM vendors inherit two structural headaches: unbudgeted runaway liability and delayed cost visibility. A single infinite retry loop inside an autonomous coding agent on a Saturday night can burn hundreds of dollars before a card issuer's fraud alert even fires. Even when traffic behaves normally, reconciling floating-point USD token invoices across multiple vendors, foreign exchange spreads, and delayed usage dashboards forces platform teams to maintain brittle client-side price tables that drift every time a provider tweaks a tier. We unpacked the broader economic trade-offs in our comparison of prepaid pay-as-you-go Top Points versus $200 monthly AI subscriptions.
TOP AI replaces that ambiguity with a deterministic, integer-denominated prepaid ledger where 1 TOP Point (TP) strictly equals Rp 1 (approximately $0.0000625 USD at Rp 16,000/USD). For FinOps and backend architects, four guarantees directly simplify production accounting:
- Integer precision with zero platform rake: When you fund Rp 500,000, your wallet receives exactly
500,000 TP. There is no hidden gateway surcharge, no currency conversion haircut on the platform side, and no floating-point rounding drift when summing millions of rows in SQL. International teams reporting in USD simply divide integer TP sums by their treasury's exact FX rate at reporting time while keeping every transaction row stored as an exactBIGINT. - Perpetual prepaid balance with zero monthly minimums: Unused TP never expires at month-end. Whether your startup runs heavy batch evaluations in Q1 and light inference in Q2, or holds a
250,000 TPsafety buffer solely for failover traffic, every remaining TP stays intact indefinitely with no activation fee or minimum monthly commitment. - Atomic non-negative balance locking: Inside the gateway database (documented in /en/docs and the platform billing specification), every debit executes inside an atomic row-locked transaction (
SELECT gp FROM Balance WHERE userId = ? FOR UPDATE). Two concurrent requests arriving in the same millisecond can never double-spend the same balance or push your account into overdraft. If an incoming call's estimated cost exceeds your available balance, the gateway rejects it cleanly withHTTP 402 insufficient_quotabefore touching any upstream provider. - Strict zero-charge boundaries for errors and utilities: Upstream failures (
502,503), pre-dispatch rejections (400,401,402,403,404,413,429), and utility calls—specificallyGET /v1/models,GET /v1/balance, andPOST /v1/messages/count_tokens—incur 0 TP. You only pay for successfully executed completions or image generations.

Notice the clean separation of concerns in the architecture above. The TOP AI gateway owns payment settlement, atomic balance enforcement, multi-provider failover, and authoritative per-request billing metadata. Your backend owns business attribution—mapping every integer charged_gp debit to a tenant_id, workspace_id, feature_tag, or job_id—and running proactive runway alerts so replenishment happens on your schedule rather than during an incident.
Step 1: Funding Your Prepaid Balance at /dashboard/saldo
If you have not provisioned an account yet, registering via /daftar credits a 5,000 TP signup bonus (bonus_daftar) immediately with no credit card required—plenty to test API keys, verify GET /v1/balance, and validate your ingestion pipeline locally. Once you are ready to load staging or production capital, navigate to /dashboard/saldo.
Transaction Limits, Quick Presets, and Payment Rails
TOP AI structures top-up boundaries to fit both solo indie hackers running $5 weekend experiments and funded SaaS teams funding recurring operational float:
- Minimum per order:
Rp 5,000(5,000 TP, ~$0.31 USD). - Maximum per order:
Rp 10,000,000(10,000,000 TP, ~$625 USD). Enterprise teams replenishing above Rp 10M simply submit sequential orders or split funding into weekly treasury tranches for cleaner cash-flow matching. - Quick presets: One-click buttons cover
Rp 10,000,Rp 25,000,Rp 50,000,Rp 100,000,Rp 250,000, andRp 500,000, alongside a custom integer input field covering the full Rp 5,000–Rp 10,000,000 range. - Zero hidden platform deduction: Funding
Rp 1,000,000credits exactly1,000,000 TPto your ledger under reasontopup.
Four production payment rails accommodate both Indonesian domestic finance workflows and international engineering teams:
| Payment Rail | Supported Channels | Typical Confirmation Time | Ideal Engineering & FinOps Use Case | Operational Reconciliation Notes |
|---|---|---|---|---|
| QRIS & QRIS Cross-Border | All Indonesian e-wallets and mobile banking apps (BCA, Mandiri, BNI, BRI, GoPay, OVO, Dana, ShopeePay) plus cross-border QR rails (Singapore PayNow/NETS, Malaysia DuitNow, Thailand PromptPay, Japan JPQR) | 2–15 seconds | Emergency on-call replenishment (Rp 50,000 – Rp 500,000) when Slack fires a low-runway alert | Fastest path from alert to restored headroom; triggers immediate settlement callback without interbank batching |
| Virtual Account (VA) | Major Indonesian corporate banks (BCA, BNI, BRI, Mandiri, Permata) routed through Midtrans | 10–60 seconds after transfer | Scheduled monthly or bi-weekly production funding (Rp 500,000 – Rp 10,000,000) from company treasury | Clean audit trail on corporate bank statements; each TOP- order issues a dedicated one-time VA number |
| Midtrans Snap (Cards & Wallets) | Domestic and international debit/credit cards plus Snap-connected digital wallets | Instant – 30 seconds | Global SaaS startups funding via corporate Visa/Mastercard for automated expense categorization | Order creation returns snapToken and mode: "midtrans" for hosted Snap checkout |
| USDT Stablecoin | On-chain transfers on TRC20, BEP20, and POLYGON networks | 1–5 minutes (network confirmations) | International remote teams, Web3 studios, and non-IDR treasury operations avoiding card FX fees | Order specifies exact USDT amount, destination wallet, network, and settlement expiry window |
Understanding the TOP- Order Lifecycle, Idempotent Callbacks, and Official Invoices
Every top-up request initiated in /dashboard/saldo creates an order record prefixed with TOP- (for example, TOP-LX2K1-AB12). Under the hood, the dashboard invokes the session-authenticated endpoint POST /api/topup (which intentionally requires your browser session cookie topai_sesi rather than an API key, keeping billing mutations isolated from /v1/* inference credentials):
# Example of the authenticated dashboard order-creation payload (session cookie only)
curl -X POST https://topai.id/api/topup \
-H "Content-Type: application/json" \
-H "Cookie: topai_sesi=<your-session-token>" \
-d '{ "amountRp": 1000000 }'The response returns the newly minted TOP- order identifier, payment mode, and Midtrans Snap token:
{
"topup": {
"id": "clx9k4p2q000108l4a8b7c9d1",
"orderId": "TOP-LX2K1-AB12",
"amountRp": 1000000,
"gp": 1000000,
"status": "pending"
},
"orderId": "TOP-LX2K1-AB12",
"snapToken": "66e4fa55-9c2a-4d1b-8e4f-7a1c02b49811",
"mode": "midtrans"
}Every TOP- order moves through a strict three-state finite state machine:
pending: The invoice exists and awaits payment settlement. No TP is added yet, and no official tax invoice is issued. If abandoned until expiration, the order cleanly fails with zero impact on your existing balance.paid: The payment gateway delivers acapture,settlement,paid, orsuccesswebhook toPOST /api/topup/callback. Callback handling is strictly idempotent—even if a payment rail retries the webhook multiple times due to transient network timeouts, TOP AI credits your TP balance exactly once and records a positivetopupledger entry.failed: The transfer was canceled, declined by the issuing bank, or expired past its settlement window. Simply create a new order in/dashboard/saldoto obtain a freshTOP-identifier.
Once an order reaches paid, open /dashboard/invoice/[orderId] (for instance, /dashboard/invoice/TOP-LX2K1-AB12). TOP AI locks a permanent invoice identifier formatted as INV-YYYYMM-XXXXXX and freezes your company name, legal address, billing email, and tax registration number (NPWP or corporate tax ID) as an immutable billing snapshot. Finance teams can archive the rendered invoice directly into Xero, QuickBooks, Jurnal, or NetSuite without manual spreadsheet re-entry.
Step 2: Zero-Cost Programmatic Balance Polling via GET /v1/balance
Manual dashboard checks break the moment your AI service moves from staging to 24/7 traffic. TOP AI exposes GET https://topai.id/v1/balance specifically for SDK preflight checks, CI/CD guards, reseller portals, and automated FinOps daemons.
Two design properties make /v1/balance uniquely reliable in production:
- Strictly 0 TP cost: You can poll it every 60 seconds from a Kubernetes CronJob, Cloudflare Worker, or GitHub Actions monitor without spending a single TP.
- Callable even when exhausted: Unlike inference endpoints that return
HTTP 402or quota errors once a key hits zero,/v1/balanceexplicitly permits exhausted keys to query their own state so your monitoring plane can still inspectbalance_tp,sisa_kuota_tp, andreset_periode_detikto compute exact recovery times.
Verify your key right now using cURL:
curl -sS https://topai.id/v1/balance \
-H "Authorization: Bearer $TOPAI_API_KEY" | jq .Here is the exact JSON payload returned by GET /v1/balance:
{
"object": "balance",
"balance_tp": 842550,
"saldo_tp": 842550,
"saldo_gp": 842550,
"kuota_tp": null,
"kuota_gp": null,
"sisa_kuota_tp": null,
"sisa_kuota_gp": null,
"terpakai_total_tp": 157450,
"terpakai_total_gp": 157450,
"terpakai_hari_ini_tp": 18420,
"terpakai_hari_ini_gp": 18420,
"terpakai_bulan_ini_tp": 157450,
"terpakai_bulan_ini_gp": 157450,
"request_hari_ini": 1940,
"request_bulan_ini": 16820,
"request_total": 16820,
"jenis_kunci": "user",
"periode": "sekali",
"batas_periode_gp": null,
"terpakai_periode_gp": 0,
"reset_periode_detik": null,
"model_diizinkan": "semua",
"bisa_dipakai": true
}Because TOP AI serves both international and Indonesian engineering teams, the response provides balance_tp alongside its Indonesian schema aliases (saldo_tp, saldo_gp, terpakai_*). The table below maps every operational field you should wire into your FinOps monitors and client dashboards:
| Response Field | Type | Semantic Meaning | How Engineering & FinOps Systems Should Use It | |
|---|---|---|---|---|
balance_tp | integer | Effective spendable balance in TP (min(owner_wallet, key_remaining_quota) for customer keys) | Primary input to low-balance alerting, circuit breakers, and reseller portal displays | |
kuota_tp / sisa_kuota_tp | `integer \ | null` | Total hard quota assigned to a scoped customer key and its remaining headroom (null if uncapped) | Renders client progress bars and triggers automated upsell/top-up emails for agency tenants |
terpakai_hari_ini_tp | integer | Cumulative TP debited by this specific API key since 00:00:00 local server midnight | Fast anomaly check: compare against trailing 7-day daily average to catch prompt loops early | |
terpakai_bulan_ini_tp | integer | Cumulative TP debited by this API key since the 1st of the current month | Direct reconciliation anchor against your internal PostgreSQL/ClickHouse monthly rollup | |
request_hari_ini / request_bulan_ini | integer | Total billable inference requests executed today and month-to-date | Compute blended cost per request (terpakai_hari_ini_tp / request_hari_ini) to spot model drift | |
jenis_kunci | `"user" \ | "customer"` | Indicates whether the credential is a master account key or a scoped customer virtual key | Prevents accidentally deploying a master user key inside an isolated customer microservice |
periode & batas_periode_gp | string, `integer \ | null` | Recurring quota window (sekali, harian, bulanan) and TP ceiling per window | Surfaces hard daily/monthly ceilings in tenant health-check endpoints |
terpakai_periode_gp & reset_periode_detik | integer, `integer \ | null` | TP consumed in the active window and exact seconds remaining until the window resets | Drives graceful UI countdown messages instead of cryptic 429/402 failures |
model_diizinkan | `string[] \ | "semua"` | Active model allowlist bound to this key ("semua" means unrestricted) | Validated at startup in CI/CD smoke tests so deployments fail fast on misconfigured allowlists |
bisa_dipakai | boolean | Composite readiness flag (!banned && balance_tp > 0 && quota_ok && period_ok) | Ideal single boolean for Kubernetes readiness probes or fallback router switches |
Step 3: Ingesting Inline topai.charged_gp Telemetry Into PostgreSQL and ClickHouse Ledgers
Polling /v1/balance gives you macro-level wallet visibility, but real FinOps governance requires request-level cost attribution: knowing that Workspace A spent 4,210 TP on support triage using deepseek-v4-1-flash while Workspace B burned 38,400 TP on long-context contract analysis using claude-sonnet-5-5.
Most gateways force you to approximate per-request spend by multiplying usage.prompt_tokens and usage.completion_tokens against a hardcoded pricing JSON file in your repo—an approach that breaks immediately when flat-rate promo models, minimum charges, or prompt-cache read multipliers (0.1x input) apply. You can read the exact math behind TOP AI's dual pricing model in our deep dive on Smart Router per-request flat pricing versus per-token metered billing and Anthropic prompt caching math explained.
TOP AI removes all guesswork by embedding authoritative billing telemetry directly inside every JSON response from /v1/chat/completions and /v1/messages—plus mirroring the debit in the HTTP response header x-topai-charge:
{
"id": "chatcmpl-9f8e7d6c5b4a",
"object": "chat.completion",
"model": "claude-sonnet-5-5",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Summary of Q4 variance across three regional cohorts..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 14820,
"completion_tokens": 1140,
"total_tokens": 15960
},
"topai": {
"charged_gp": 50,
"balance_after": 842500,
"upstream": "anthropic-primary",
"failover": false,
"latency_ms": 1340
}
}Look closely at the five fields inside topai:
charged_gp: The exact integer TP deducted atomically for this specific call (here50 TPbecauseclaude-sonnet-5-5runs in flat-per-request promo mode regardless of whether you sent 120 tokens or 40,000 tokens; on metered models likeclaude-sonnet-5-5-token, it reflectsmax(ceil(token_cost), min_charge)).balance_after: Your authoritative post-debit wallet balance in TP immediately after this transaction committed. Storingbalance_afteralongsidecharged_gplets you verify ledger continuity and trigger instant zero-polling alerts if a single burst pushes balance below your threshold.upstream: Which upstream provider route fulfilled the call.failover: Boolean indicating whether TOP AI's zero-downtime multi-provider failover architecture transparently rerouted the request around an upstream degradation.latency_ms: End-to-end gateway inference latency in milliseconds—invaluable for building combined cost-vs-p95-latency FinOps scorecards.
Ledger Storage Schema: PostgreSQL (ACID Chargeback) + ClickHouse (High-Volume Analytics)
Choose PostgreSQL when you are executing under ~5 million LLM requests per month and want transactional tenant billing tables alongside your SaaS application database. Add ClickHouse (or sink asynchronously via Kafka/BullMQ) once your telemetry volume crosses tens of millions of agentic calls per month and you want sub-second GROUP BY tenant_id, model, feature rollups across 12-month windows.
Below are production-ready DDL schemas for both engines:
-- ============================================================================
-- PostgreSQL 16+: Immutable FinOps Chargeback Ledger + Daily Materialized View
-- ============================================================================
CREATE TABLE ai_finops_ledger (
id BIGSERIAL PRIMARY KEY,
request_id TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
tenant_id TEXT NOT NULL,
workspace_id TEXT NOT NULL,
user_id TEXT,
feature_tag TEXT NOT NULL, -- e.g. 'rag_qa', 'code_review', 'json_extract'
api_key_alias TEXT NOT NULL, -- internal label, never store raw secret
model TEXT NOT NULL,
upstream TEXT NOT NULL,
failover BOOLEAN NOT NULL DEFAULT FALSE,
prompt_tokens INTEGER NOT NULL DEFAULT 0,
completion_tokens INTEGER NOT NULL DEFAULT 0,
cache_read_tokens INTEGER NOT NULL DEFAULT 0,
charged_tp INTEGER NOT NULL CHECK (charged_tp >= 0),
balance_after_tp BIGINT NOT NULL CHECK (balance_after_tp >= 0),
latency_ms INTEGER NOT NULL DEFAULT 0,
http_status SMALLINT NOT NULL DEFAULT 200
);
CREATE INDEX idx_finops_tenant_time ON ai_finops_ledger (tenant_id, created_at DESC);
CREATE INDEX idx_finops_feature_time ON ai_finops_ledger (feature_tag, created_at DESC);
CREATE INDEX idx_finops_model_time ON ai_finops_ledger (model, created_at DESC);
-- Hourly burn-rate and tenant chargeback query (runs in <5ms with index)
SELECT
tenant_id,
feature_tag,
model,
COUNT(*) AS total_requests,
SUM(charged_tp) AS total_tp,
ROUND(SUM(charged_tp)::NUMERIC / 16000.0, 4) AS approx_usd,
ROUND(AVG(charged_tp)::NUMERIC, 2) AS avg_tp_per_req,
PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY latency_ms) AS p95_latency_ms,
SUM(CASE WHEN failover THEN 1 ELSE 0 END) AS failover_hits
FROM ai_finops_ledger
WHERE created_at >= NOW() - INTERVAL '24 hours'
GROUP BY tenant_id, feature_tag, model
ORDER BY total_tp DESC;-- ============================================================================
-- ClickHouse: High-Throughput Telemetry Table + Real-Time Daily Rollup MV
-- ============================================================================
CREATE TABLE ai_finops_events (
event_time DateTime64(3, 'UTC'),
request_id String,
tenant_id LowCardinality(String),
workspace_id String,
feature_tag LowCardinality(String),
model LowCardinality(String),
upstream LowCardinality(String),
failover UInt8,
prompt_tokens UInt32,
completion_tokens UInt32,
cache_read_tokens UInt32,
charged_tp UInt32,
balance_after_tp UInt64,
latency_ms UInt32
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(event_time)
ORDER BY (tenant_id, feature_tag, model, event_time, request_id)
TTL event_time + INTERVAL 365 DAY;
CREATE TABLE ai_finops_daily_tenant_mv
(
day Date,
tenant_id LowCardinality(String),
model LowCardinality(String),
feature_tag LowCardinality(String),
request_count AggregateFunction(count, UInt64),
total_tp AggregateFunction(sum, UInt64),
total_prompt_tok AggregateFunction(sum, UInt64),
total_comp_tok AggregateFunction(sum, UInt64),
p95_latency_ms AggregateFunction(quantile(0.95), UInt32)
)
ENGINE = AggregatingMergeTree
PARTITION BY toYYYYMM(day)
ORDER BY (day, tenant_id, model, feature_tag);
CREATE MATERIALIZED VIEW mv_ai_finops_daily_tenant
TO ai_finops_daily_tenant_mv
AS SELECT
toDate(event_time) AS day,
tenant_id,
model,
feature_tag,
countState(toUInt64(1)) AS request_count,
sumState(toUInt64(charged_tp)) AS total_tp,
sumState(toUInt64(prompt_tokens)) AS total_prompt_tok,
sumState(toUInt64(completion_tokens)) AS total_comp_tok,
quantileState(0.95)(latency_ms) AS p95_latency_ms
FROM ai_finops_events
GROUP BY day, tenant_id, model, feature_tag;TypeScript Production Middleware: Zero-Overhead Telemetry Capture
Live TOP AI API Pricing for Models Mentioned
Frequently Asked Questions
Does TOP AI charge hidden platform fees or expire unused prepaid TOP Points?+
No. TOP AI operates on a strict 1 TP = Rp 1 exchange rate (~$0.0000625 USD at Rp 16,000/USD) with zero hidden platform surcharge, zero activation fees, and zero monthly minimum spend. Unused prepaid TOP Points remain in your wallet indefinitely and never expire.
What are the minimum and maximum top-up limits per transaction on /dashboard/saldo?+
Each top-up order supports a minimum of Rp 5,000 (5,000 TP) and a maximum of Rp 10,000,000 (10,000,000 TP). Quick preset buttons cover Rp 10,000, Rp 25,000, Rp 50,000, Rp 100,000, Rp 250,000, and Rp 500,000, and larger treasury replenishments can be split across sequential orders.
Does polling GET /v1/balance every minute from a monitoring worker consume TP?+
No. GET https://topai.id/v1/balance costs exactly 0 TP and remains callable even if a scoped virtual key has exhausted its total or periodic quota, allowing monitoring scripts to inspect remaining headroom and reset_periode_detik at all times.
How do I attribute exact AI inference spend per tenant or product feature without approximating token prices?+
Read the topai object included automatically in every /v1/chat/completions and /v1/messages response. topai.charged_gp gives the exact integer TP debited atomically for that call, topai.balance_after gives the post-debit wallet balance, and the x-topai-charge HTTP header mirrors the same debit figure.







