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
Never block your end user's HTTP response waiting for an analytics database write. The TypeScript wrapper below calls https://topai.id/v1/chat/completions, extracts the topai object and x-topai-charge header, pushes an immutable ledger record into PostgreSQL via a non-blocking flush queue (or direct pooled write), and immediately surfaces an out-of-band callback if balance_after drops below your emergency floor—giving you sub-second visibility even between scheduled cron polls.
// language: TypeScript, file: src/lib/topai-finops-client.ts, runtime: Node 20+
import { Pool } from "pg";
export interface TopAiTelemetry {
charged_gp: number;
balance_after: number;
upstream: string;
failover: boolean;
latency_ms: number;
}
export interface AttributionContext {
tenantId: string;
workspaceId: string;
userId?: string;
featureTag: string;
apiKeyAlias: string;
}
export interface ChatCompletionWithTelemetry {
id: string;
model: string;
choices: Array<{
index: number;
message: { role: string; content: string };
finish_reason: string;
}>;
usage?: {
prompt_tokens?: number;
completion_tokens?: number;
prompt_tokens_details?: { cached_tokens?: number };
};
topai?: TopAiTelemetry;
}
const pgPool = new Pool({ connectionString: process.env.DATABASE_URL });
const EMERGENCY_FLOOR_TP = Number(process.env.TOPAI_EMERGENCY_FLOOR_TP ?? 50_000);
export async function callTopAiWithLedger(
payload: Record<string, unknown>,
ctx: AttributionContext,
options?: { apiKey?: string; onLowBalance?: (balanceAfter: number) => Promise<void> },
): Promise<ChatCompletionWithTelemetry> {
const apiKey = options?.apiKey ?? process.env.TOPAI_API_KEY;
if (!apiKey) throw new Error("Missing TOPAI_API_KEY");
const startedAt = Date.now();
const res = await fetch("https://topai.id/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
if (res.status === 402) {
const errBody = await res.text();
throw new Error(`TOP AI HTTP 402 insufficient_quota for tenant=${ctx.tenantId}: ${errBody}`);
}
if (!res.ok) {
throw new Error(`TOP AI request failed (${res.status}): ${await res.text()}`);
}
const headerCharge = Number(res.headers.get("x-topai-charge") ?? 0);
const data = (await res.json()) as ChatCompletionWithTelemetry;
const chargedTp = data.topai?.charged_gp ?? headerCharge;
const balanceAfterTp = data.topai?.balance_after ?? 0;
const latencyMs = data.topai?.latency_ms ?? Date.now() - startedAt;
// Fire-and-forget durable ledger insert so user latency stays untouched
void pgPool
.query(
`INSERT INTO ai_finops_ledger (
request_id, tenant_id, workspace_id, user_id, feature_tag,
api_key_alias, model, upstream, failover,
prompt_tokens, completion_tokens, cache_read_tokens,
charged_tp, balance_after_tp, latency_ms, http_status
) VALUES (
$1, $2, $3, $4, $5,
$6, $7, $8, $9,
$10, $11, $12,
$13, $14, $15, 200
) ON CONFLICT (request_id) DO NOTHING`,
[
data.id || `req-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
ctx.tenantId,
ctx.workspaceId,
ctx.userId ?? null,
ctx.featureTag,
ctx.apiKeyAlias,
data.model ?? String(payload.model ?? "unknown"),
data.topai?.upstream ?? "unknown",
Boolean(data.topai?.failover),
data.usage?.prompt_tokens ?? 0,
data.usage?.completion_tokens ?? 0,
data.usage?.prompt_tokens_details?.cached_tokens ?? 0,
chargedTp,
balanceAfterTp,
latencyMs,
],
)
.catch((err) => {
console.error("[FinOpsLedger] Failed to persist billing row:", err);
});
if (data.topai && balanceAfterTp <= EMERGENCY_FLOOR_TP && options?.onLowBalance) {
void options.onLowBalance(balanceAfterTp).catch((err) => {
console.error("[FinOpsLedger] Low-balance hook error:", err);
});
}
return data;
}Python Async Worker Instrumentation for Batch Pipelines and AI Agents
Data engineering teams running document extraction, RAG indexing, or autonomous agent workers in Python can mirror the exact same contract using httpx and clickhouse-connect (or asyncpg), pairing pre-flight token estimation via [preflight token counting with /v1/messages/count_tokens](/en/blog/preflight-token-counting-with-messages-count-tokens) with post-call topai.charged_gp recording:
# language: Python, file: workers/topai_ledger.py, runtime: Python 3.11+
from __future__ import annotations
import os
from datetime import datetime, timezone
from typing import Any
import httpx
class TopAiMeteredClient:
def __init__(self, api_key: str | None = None, base_url: str = "https://topai.id/v1") -> None:
self.api_key = api_key or os.environ["TOPAI_API_KEY"]
self.base_url = base_url.rstrip("/")
self._client = httpx.AsyncClient(
base_url=self.base_url,
headers={"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"},
timeout=60.0,
)
async def get_balance(self) -> dict[str, Any]:
"""Zero-cost (0 TP) programmatic balance and quota inspection."""
resp = await self._client.get("/balance")
resp.raise_for_status()
return resp.json()
async def complete_and_record(
self,
*,
model: str,
messages: list[dict[str, str]],
tenant_id: str,
workspace_id: str,
feature_tag: str,
max_tokens: int = 1024,
) -> tuple[dict[str, Any], dict[str, Any]]:
resp = await self._client.post(
"/chat/completions",
json={"model": model, "messages": messages, "max_tokens": max_tokens},
)
if resp.status_code == 402:
raise RuntimeError(f"TOP AI HTTP 402 insufficient_quota: {resp.text}")
resp.raise_for_status()
body = resp.json()
topai_meta = body.get("topai") or {}
usage = body.get("usage") or {}
header_charge = int(resp.headers.get("x-topai-charge", "0") or 0)
ledger_row = {
"event_time": datetime.now(timezone.utc).isoformat(),
"request_id": body.get("id", ""),
"tenant_id": tenant_id,
"workspace_id": workspace_id,
"feature_tag": feature_tag,
"model": body.get("model", model),
"upstream": topai_meta.get("upstream", "unknown"),
"failover": int(bool(topai_meta.get("failover", False))),
"prompt_tokens": int(usage.get("prompt_tokens", 0)),
"completion_tokens": int(usage.get("completion_tokens", 0)),
"cache_read_tokens": int((usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0)),
"charged_tp": int(topai_meta.get("charged_gp", header_charge)),
"balance_after_tp": int(topai_meta.get("balance_after", 0)),
"latency_ms": int(topai_meta.get("latency_ms", 0)),
}
return body, ledger_row
async def aclose(self) -> None:
await self._client.aclose()Note one important edge case when working with streaming (stream: true): SSE chunks deliver deltas incrementally, so inspect the x-topai-charge response header or the final usage/telemetry chunk at stream completion—or reconcile streaming workloads hourly against terpakai_hari_ini_tp from GET /v1/balance.
Step 4: Automated Slack & Telegram Low-Balance Alert Worker (Preventing HTTP 402 Forever)
An HTTP 402 insufficient_quota error in production is 100% avoidable. Because GET /v1/balance costs 0 TP, you can run a lightweight cron worker every 5 minutes that evaluates both static TP floors and dynamic burn-rate runway.
Static thresholds alone are dangerous: 50,000 TP lasts ten days for an internal documentation bot spending 5,000 TP/day, yet disappears in 45 minutes during a Friday product launch burning 65,000 TP/hour. Combining a hard threshold (< 50,000 TP) with a projected runway floor (< 12 hours at current rolling burn rate) guarantees your finance or on-call engineer always gets actionable lead time.
Designing a Noise-Free Multi-Tier Alert Escalation Ladder
Alert fatigue kills FinOps programs. If a script fires every 5 minutes all afternoon once balance dips to 49,500 TP, engineers mute the channel and miss the actual outage. Implement tiered severity bands with stateful cooldowns (persisted in Redis, PostgreSQL, or a tiny state table) that only re-notify when severity escalates or the cooldown window expires:
| Severity Tier | Balance Trigger (TP) | Dynamic Runway Trigger | Target Channel | Cooldown Window | Required Action & Top-Up Rail |
|---|---|---|---|---|---|
| Tier 1: Advisory | < 150,000 TP (~$9.38) | < 48 hours runway | Slack #finops-ai-alerts | 6 hours | Schedule normal corporate Virtual Account top-up (Rp 500k–Rp 2M) during business hours |
| Tier 2: Warning | < 50,000 TP (~$3.13) | < 12 hours runway | Slack #finops-ai-alerts + Telegram On-Call Bot | 60 minutes | Immediate finance or engineering lead replenishment via QRIS or Midtrans Snap (Rp 250k+) |
| Tier 3: Critical | < 15,000 TP (~$0.94) | < 2 hours runway | Slack @here + Telegram Pager Group | 15 minutes | Instant QRIS top-up (2–15s settlement) + optional soft-throttle of non-critical batch jobs |
| Tier 4: Recovery | >= 200,000 TP after alert | >= 72 hours runway | Slack + Telegram | One-shot reset | Confirm TOP- order settled as paid, archive /dashboard/invoice/[orderId], clear incident state |
Production TypeScript Worker: Slack Block Kit + Telegram Bot API
Deploy this single-file worker on a 5-minute cron via GitHub Actions, Railway, Fly.io, Kubernetes CronJob, or a plain systemd timer. It calls GET /v1/balance, reads the last 3 hours of real burn from PostgreSQL (falling back cleanly to terpakai_hari_ini_tp if no DB is attached), calculates exact remaining runway hours, applies deduplication cooldowns, and posts formatted alerts to both Slack and Telegram.
// language: TypeScript, file: workers/topai-balance-watchdog.ts, runtime: Node 20+
import { Pool } from "pg";
interface BalanceResponse {
balance_tp: number;
terpakai_hari_ini_tp: number;
terpakai_bulan_ini_tp: number;
request_hari_ini: number;
jenis_kunci: string;
bisa_dipakai: boolean;
sisa_kuota_tp: number | null;
reset_periode_detik: number | null;
}
type AlertLevel = "OK" | "ADVISORY" | "WARNING" | "CRITICAL";
const CONFIG = {
apiKey: process.env.TOPAI_API_KEY ?? "",
slackWebhook: process.env.SLACK_WEBHOOK_URL ?? "",
tgBotToken: process.env.TELEGRAM_BOT_TOKEN ?? "",
tgChatId: process.env.TELEGRAM_CHAT_ID ?? "",
dbUrl: process.env.DATABASE_URL ?? "",
fxIdrPerUsd: Number(process.env.FX_IDR_PER_USD ?? 16_000),
advisoryTp: 150_000,
warningTp: 50_000,
criticalTp: 15_000,
warningRunwayHours: 12,
criticalRunwayHours: 2,
};
async function fetchTopAiBalance(): Promise<BalanceResponse> {
const res = await fetch("https://topai.id/v1/balance", {
headers: { Authorization: `Bearer ${CONFIG.apiKey}` },
});
if (!res.ok) throw new Error(`GET /v1/balance failed: HTTP ${res.status}`);
return (await res.json()) as BalanceResponse;
}
async function computeHourlyBurnRate(balance: BalanceResponse): Promise<number> {
if (CONFIG.dbUrl) {
const pool = new Pool({ connectionString: CONFIG.dbUrl });
try {
const { rows } = await pool.query<{ burn_3h: string }>(
`SELECT COALESCE(SUM(charged_tp), 0)::TEXT AS burn_3h
FROM ai_finops_ledger
WHERE created_at >= NOW() - INTERVAL '3 hours'`,
);
const burn3h = Number(rows[0]?.burn_3h ?? 0);
if (burn3h > 0) return Math.ceil(burn3h / 3);
} finally {
await pool.end();
}
}
const now = new Date();
const hoursElapsedToday = Math.max(1, now.getHours() + now.getMinutes() / 60);
return Math.ceil(balance.terpakai_hari_ini_tp / hoursElapsedToday);
}
function classifySeverity(balanceTp: number, runwayHours: number): AlertLevel {
if (balanceTp <= CONFIG.criticalTp || runwayHours <= CONFIG.criticalRunwayHours) return "CRITICAL";
if (balanceTp <= CONFIG.warningTp || runwayHours <= CONFIG.warningRunwayHours) return "WARNING";
if (balanceTp <= CONFIG.advisoryTp) return "ADVISORY";
return "OK";
}
async function notifySlack(level: AlertLevel, balance: BalanceResponse, burnPerHour: number, runwayHours: number) {
if (!CONFIG.slackWebhook) return;
const usdApprox = (balance.balance_tp / CONFIG.fxIdrPerUsd).toFixed(2);
const runwayText = Number.isFinite(runwayHours) ? `${runwayHours.toFixed(1)} hours` : "N/A (idle)";
const payload = {
text: `[${level}] TOP AI Balance Alert: ${balance.balance_tp.toLocaleString("en-US")} TP (~$${usdApprox})`,
blocks: [
{
type: "header",
text: { type: "plain_text", text: `TOP AI FinOps Watchdog — ${level}` },
},
{
type: "section",
fields: [
{ type: "mrkdwn", text: `*Remaining Balance:*\n${balance.balance_tp.toLocaleString("en-US")} TP (~$${usdApprox})` },
{ type: "mrkdwn", text: `*Est. Runway:*\n${runwayText}` },
{ type: "mrkdwn", text: `*Rolling Burn Rate:*\n${burnPerHour.toLocaleString("en-US")} TP / hr` },
{ type: "mrkdwn", text: `*Today's Spend:*\n${balance.terpakai_hari_ini_tp.toLocaleString("en-US")} TP (${balance.request_hari_ini} reqs)` },
],
},
{
type: "context",
elements: [
{
type: "mrkdwn",
text: "Top up instantly via QRIS, VA, Midtrans, or USDT at <https://topai.id/dashboard/saldo|topai.id/dashboard/saldo> (1 TP = Rp 1, zero expiry).",
},
],
},
],
};
const res = await fetch(CONFIG.slackWebhook, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) throw new Error(`Slack webhook failed: HTTP ${res.status}`);
}
async function notifyTelegram(level: AlertLevel, balance: BalanceResponse, burnPerHour: number, runwayHours: number) {
if (!CONFIG.tgBotToken || !CONFIG.tgChatId) return;
const usdApprox = (balance.balance_tp / CONFIG.fxIdrPerUsd).toFixed(2);
const runwayText = Number.isFinite(runwayHours) ? `${runwayHours.toFixed(1)}h` : "idle";
const text = [
`<b>[TOP AI FinOps — ${level}]</b>`,
`Balance: <code>${balance.balance_tp.toLocaleString("en-US")} TP</code> (~$${usdApprox})`,
`Burn Rate: <code>${burnPerHour.toLocaleString("en-US")} TP/hr</code> | Runway: <b>${runwayText}</b>`,
`Today: ${balance.terpakai_hari_ini_tp.toLocaleString("en-US")} TP (${balance.request_hari_ini} requests)`,
`Usable: <code>${String(balance.bisa_dipakai)}</code>`,
`Action: https://topai.id/dashboard/saldo`,
].join("\n");
const res = await fetch(`https://api.telegram.org/bot${CONFIG.tgBotToken}/sendMessage`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
chat_id: CONFIG.tgChatId,
text,
parse_mode: "HTML",
disable_web_page_preview: true,
}),
});
if (!res.ok) throw new Error(`Telegram sendMessage failed: HTTP ${res.status}`);
}
async function main() {
if (!CONFIG.apiKey) throw new Error("TOPAI_API_KEY is required");
const balance = await fetchTopAiBalance();
const burnPerHour = await computeHourlyBurnRate(balance);
const runwayHours = burnPerHour > 0 ? balance.balance_tp / burnPerHour : Number.POSITIVE_INFINITY;
const level = classifySeverity(balance.balance_tp, runwayHours);
console.log(
JSON.stringify({
event: "topai_balance_check",
level,
balance_tp: balance.balance_tp,
burn_per_hour_tp: burnPerHour,
runway_hours: Number.isFinite(runwayHours) ? Number(runwayHours.toFixed(2)) : null,
bisa_dipakai: balance.bisa_dipakai,
}),
);
if (level !== "OK") {
await Promise.all([
notifySlack(level, balance, burnPerHour, runwayHours),
level === "WARNING" || level === "CRITICAL"
? notifyTelegram(level, balance, burnPerHour, runwayHours)
: Promise.resolve(),
]);
}
}
main().catch((err) => {
console.error("[Watchdog Fatal]", err);
process.exit(1);
});Graceful Application-Side Degradation Below the Safety Floor
For mission-critical SaaS platforms, pair your Slack/Telegram alerts with a soft circuit breaker inside your job queue. Whenever the cached /v1/balance snapshot falls below 15,000 TP, pause low-priority background jobs (nightly document re-indexing, marketing copy variants, historical analytics summarization) while preserving 100% of the remaining TP for live customer-facing checkout or support chats until on-call finishes a 10-second QRIS top-up.
Step 5: Realistic 1,000,000 TP (~$62.50 / Rp 1,000,000) Monthly Multi-Workload Budget Breakdown
Engineering managers frequently ask how far a single 1,000,000 TP (Rp 1,000,000 / ~$62.50 USD at Rp 16,000/USD) monthly allocation actually stretches in a real multi-feature SaaS product. When teams naively send every classification, JSON extraction, and support reply to a frontier reasoning model, $62.50 evaporates in 48 hours. When you pair TOP AI's flat-rate promo tiers and fast specialized models—following the routing architecture detailed in our guide to cutting agentic coding token bills by 72%—a single 1,000,000 TP budget easily powers a full mid-stage B2B SaaS platform with tens of thousands of production requests per month.

The reference allocation below models a real-world SaaS product running six concurrent AI workloads across deepseek-v4-1-flash, claude-sonnet-5-5, glm-5-3, and image generation, while reserving a strict 10% (100,000 TP) buffer against traffic spikes. Always cross-check live model rates on /en/pricing before finalizing unit economics, since promo flat tiers and metered token prices evolve as new frontier checkpoints ship.
| Production Workload | Primary Model & Billing Mode | Monthly Request Volume | Avg. Cost / Req (TP) | Monthly Allocation (TP) | Approx. USD (@ Rp 16k) | % of 1M TP Budget | Key Optimization Lever |
|---|---|---|---|---|---|---|---|
| 1. Real-Time JSON Extraction & Triage | deepseek-v4-1-flash (metered / ultra-low latency) | 45,000 reqs | 4 TP | 180,000 TP | $11.25 | 18.0% | Strict max_tokens ceiling + compact JSON schema prompts |
| 2. Deep Code Review & Complex Reasoning | claude-sonnet-5-5 (flat 50 TP promo / request) | 5,600 reqs | 50 TP | 280,000 TP | $17.50 | 28.0% | Pack full PR diff & context into one flat-rate call rather than 5 micro-calls |
| 3. Bilingual Customer Support & Docs Q&A | glm-5-3 (balanced bilingual SEA/Global tier) | 18,000 reqs | 10 TP | 180,000 TP | $11.25 | 18.0% | Semantic RAG chunk top-k capped at 4 passages + cache warm system prompt |
| 4. Long-Context Compliance & Contract Audit | claude-sonnet-5-5 (flat 50 TP) + metered fallback | 2,400 reqs | 50 TP | 120,000 TP | $7.50 | 12.0% | Preflight POST /v1/messages/count_tokens (0 TP) to reject oversized uploads |
| 5. Automated Product & Marketing Visuals | gemini-3-pro-image (flat 100 TP / image) | 900 images | 100 TP | 90,000 TP | $5.63 | 9.0% | Deduplicate prompt hashes in Redis before triggering generation |
| 6. Staging, Evals & CI Regression Suite | deepseek-v4-1-flash + glm-5-3 | 10,000 reqs | 5 TP | 50,000 TP | $3.13 | 5.0% | Isolated CI virtual key capped at 2,000 TP/day via batasPeriode |
| 7. Operational Safety Reserve | Unallocated master wallet buffer | — | — | 100,000 TP | $6.25 | 10.0% | Absorbs launch surges; Slack alert triggers at 150,000 TP / 50,000 TP |
| Total Monthly Budget | Multi-Model Routed Portfolio | 81,900 billable calls | 11.0 TP blended | 1,000,000 TP | $62.50 | 100.0% | Blended cost ~$0.00069 per production AI interaction |
Three High-Leverage Tactics That Protect This 1,000,000 TP Budget
- Exploit the crossover math between flat and metered tiers: On a flat promo model such as
claude-sonnet-5-5(50 TP / request), a 40,000-token architectural document review costs the exact same50 TPas a 200-token greeting. Conversely, sending a 200-token intent classifier to a flat50 TPmodel wastes 90% of your spend compared to routing it todeepseek-v4-1-flash(see our DeepSeek V4.1 Flash latency and JSON extraction audit) orglm-5-3(benchmarked in our Kimi K3 and GLM-5.3 bilingual review). Route short, high-volume tasks to fast metered models and consolidate heavy context analysis into flat-rate calls. - Count tokens for free before dispatching oversized user uploads: Whenever users upload PDFs or transcripts, call
POST /v1/messages/count_tokens(0 TP) to measure exact prompt size before execution. If an attachment exceeds your tier's policy threshold, chunk or reject it before a single TP is spent. - Cache deterministic visuals and static system prompts: For visual pipelines built with our production image pipeline guide for Flux 2 Pro and Gemini Image API, hash
(model, prompt, aspect_ratio, seed)in object storage so repeated dashboard previews never pay100 TPtwice. For metered text models supporting prompt caching, keep static system instructions and tool definitions at the prefix so cache reads bill at0.1xinput cost.
Step 6: Agency, SaaS, and Reseller Quota Isolation with Scoped Customer Virtual Keys
Once you operate an AI agency, a white-label SaaS platform, or an internal platform team serving multiple engineering squads, sharing a single master API key (jenis_kunci: "user") across all consumers becomes an unacceptable blast radius. One compromised key or misbehaving client cron job can drain your entire 1,000,000 TP treasury overnight.
TOP AI natively solves multi-tenant governance through Scoped Customer Virtual Keys at /dashboard/customer-keys (expanded further in our enterprise AI API key governance guide covering caps, allowlists, and audit logs).

Production Controls Enforced at the Gateway Layer
Every account can maintain up to 50 active customer virtual keys simultaneously, backed by one unified master TP wallet. The gateway enforces five strict guardrails before forwarding any request:
- Uncommitted balance protection (
quota_exceeds_balance): When you allocate a hard total quota (quotaGp) to a new virtual key, TOP AI verifies thatquotaGp <= master_balance - sum(unspent_quotas_of_active_keys). This prevents accidental over-promising across 50 clients when your master wallet does not yet hold the backing TP. SettingquotaGp: 0creates an uncapped total key that still obeys periodic limits or draws directly against the master wallet. - Periodic spend windows (
periode&batasPeriode): Assign a rolling ceiling scoped tosekali(one-time lifetime cap),harian(daily auto-resetting cap), orbulanan(monthly auto-resetting cap). Even if a client buys a300,000 TPmonthly package, adding a25,000 TPdaily cap ensures a weekend bug cannot wipe out their entire month in two hours. - Model allowlists (
allowlist): Restrict each virtual key to a curated subset of active model IDs (for example,["deepseek-v4.1-flash", "glm-5.3"]for a Starter tier client, while reservingclaude-sonnet-5-5for Enterprise keys). Any attempt to invoke an unlisted model is rejected withHTTP 403at 0 TP cost. - Instant pause (
dijeda) and revocation (revoked): Suspend a delinquent client or a leaked staging credential with a single click—without rotating keys for any other tenant. - Tenant-scoped
/v1/balancevisibility: When an agency client or reseller sub-app callsGET /v1/balanceusing its own virtual key, TOP AI automatically computesbalance_tp = min(owner_wallet, remaining_key_quota)and never exposes your master wallet balance or other clients' usage.
Multi-Tenant Governance Blueprint & Agency Reseller Margin Model
The matrix below illustrates how an AI solutions agency or B2B SaaS operator can partition one 1,000,000 TP master wallet across four distinct client and internal profiles while maintaining healthy SaaS gross margins:
| Key Profile / Segment | quotaGp (Total Cap) | periode & batasPeriode | Model Allowlist (allowlist) | Wholesale Cost (1M TP Base) | Typical Client Retainer / Margin | Operational Blast-Radius Guard |
|---|---|---|---|---|---|---|
| Client A — Enterprise RAG Portal | 350,000 TP | bulanan / 350,000 TP | ["claude-sonnet-5-5", "deepseek-v4.1-flash"] | Rp 350,000 (~$21.88) | $249/mo managed AI tier (~91% gross margin) | Hard monthly ceiling + Slack alert at 80% (280k TP) triggers upsell conversation |
| Client B — E-Commerce Support Bot | 250,000 TP | harian / 12,000 TP | ["glm-5.3", "deepseek-v4.1-flash"] | Rp 250,000 (~$15.63) | $149/mo support automation (~89% gross margin) | Daily 12,000 TP throttle prevents DDoS/spam chats from burning monthly budget |
| Client C — Creative Studio Asset Gen | 150,000 TP | sekali / 150,000 TP | ["gemini-3-pro-image", "deepseek-v4.1-flash"] | Rp 150,000 (~$9.38) | $99 prepaid campaign pack (~90% gross margin) | One-time sekali cap stops cleanly when campaign deliverables conclude |
| Internal Prod — Core SaaS Microservices | 200,000 TP | harian / 15,000 TP | "semua" (all active models) | Rp 200,000 (~$12.50) | Internal COGS allocation | Separated from client keys so internal deploys never skew customer chargebacks |
| CI/CD & QA Staging Pipeline | 50,000 TP | harian / 2,000 TP | ["deepseek-v4.1-flash"] | Rp 50,000 (~$3.13) | Internal R&D overhead | Locked to low-cost flash model; runaway test suites halt cleanly at 2,000 TP/day |
Automated Client Quota Health Monitor (TypeScript)
If you manage 10 to 50 scoped customer keys for agency clients, run a nightly reconciliation script that polls GET /v1/balance for each stored client key (0 TP total cost across all 50 keys), flags tenants above 80% quota utilization, and notifies your account manager before the client hits their ceiling:
// language: TypeScript, file: workers/agency-client-quota-audit.ts, runtime: Node 20+
interface ManagedClientKey {
clientName: string;
accountManagerSlackId: string;
apiKey: string;
}
interface ScopedBalance {
balance_tp: number;
kuota_tp: number | null;
sisa_kuota_tp: number | null;
terpakai_bulan_ini_tp: number;
terpakai_periode_gp: number;
batas_periode_gp: number | null;
periode: string;
reset_periode_detik: number | null;
bisa_dipakai: boolean;
}
async function auditClientKeys(clients: ManagedClientKey[]) {
const report = [];
for (const client of clients) {
const res = await fetch("https://topai.id/v1/balance", {
headers: { Authorization: `Bearer ${client.apiKey}` },
});
if (!res.ok) {
report.push({ client: client.clientName, status: "ERROR", httpStatus: res.status });
continue;
}
const data = (await res.json()) as ScopedBalance;
const totalUtilizationPct =
data.kuota_tp && data.kuota_tp > 0 && data.sisa_kuota_tp !== null
? Number((((data.kuota_tp - data.sisa_kuota_tp) / data.kuota_tp) * 100).toFixed(1))
: 0;
const periodUtilizationPct =
data.batas_periode_gp && data.batas_periode_gp > 0
? Number(((data.terpakai_periode_gp / data.batas_periode_gp) * 100).toFixed(1))
: 0;
report.push({
client: client.clientName,
usable: data.bisa_dipakai,
effectiveBalanceTp: data.balance_tp,
monthSpendTp: data.terpakai_bulan_ini_tp,
totalUtilizationPct,
periodUtilizationPct,
periode: data.periode,
resetInMinutes: data.reset_periode_detik ? Math.ceil(data.reset_periode_detik / 60) : null,
needsUpsellAlert: totalUtilizationPct >= 80 || periodUtilizationPct >= 85 || !data.bisa_dipakai,
});
}
console.table(report);
return report;
}
// Example invocation loading client keys from your encrypted secrets vault
void auditClientKeys([
{
clientName: "Acme Corp Enterprise RAG",
accountManagerSlackId: "U04FINOPS01",
apiKey: process.env.CLIENT_ACME_TOPAI_KEY ?? "",
},
]);You can also export all customer key usage statistics directly as CSV from /dashboard/customer-keys (backed by /api/customer-keys/ekspor) and per-request usage history from /dashboard/pemakaian for quarterly external audits.
Month-End Reconciliation, Anomaly Triage, and Zero-Leakage Operations
Even the cleanest ingestion pipeline needs a monthly close procedure that proves your internal application ledger matches TOP AI's authoritative balance ledger down to the last TP. Because TOP AI writes every credit (bonus_daftar, bonus_referral, topup) and debit (usage, playground, gambar) into an immutable server-side ledger, reconciling your PostgreSQL ai_finops_ledger against /dashboard/saldo and /dashboard/pemakaian takes less than two minutes using the following SQL integrity check:
-- ============================================================================
-- Month-End FinOps Reconciliation Query (PostgreSQL)
-- Verifies internal ledger continuity against authoritative topai.balance_after
-- ============================================================================
WITH ordered_events AS (
SELECT
created_at,
request_id,
tenant_id,
model,
charged_tp,
balance_after_tp,
LAG(balance_after_tp) OVER (ORDER BY created_at ASC, id ASC) AS prev_balance_tp
FROM ai_finops_ledger
WHERE created_at >= date_trunc('month', NOW())
)
SELECT
COUNT(*) AS recorded_requests,
SUM(charged_tp) AS ledger_sum_tp,
MIN(balance_after_tp) AS lowest_balance_tp,
MAX(balance_after_tp) AS highest_balance_tp,
COUNT(*) FILTER (
WHERE prev_balance_tp IS NOT NULL
AND (prev_balance_tp - charged_tp) <> balance_after_tp
AND balance_after_tp < prev_balance_tp
) AS potential_untracked_debits,
COUNT(*) FILTER (
WHERE prev_balance_tp IS NOT NULL
AND balance_after_tp > prev_balance_tp
) AS topup_events_detected
FROM ordered_events;How to read those two diagnostic counters:
topup_events_detected: Counts every moment wherebalance_after_tpjumped upward between consecutive API calls—confirming yourTOP-replenishments landed cleanly mid-month. Cross-check that exact count against yourpaidinvoices at/dashboard/invoice/[orderId].potential_untracked_debits: Flags any downward gap whereprev_balance_tp - charged_tp != balance_after_tp. Common legitimate causes include concurrent requests committing out of timestamp order, manual tests run inside/dashboard/playground(logged underplaygroundreason), or image generation calls logged in a separate pipeline (gambar). If the gap comes from an uninstrumented service using your master API key, this query exposes it immediately.
Production Anomaly Playbook: Diagnosing Unexpected Spend Spikes
When your Slack or Telegram alert fires earlier than expected, work through this triage matrix before blindly topping up more capital:
| Observed Anomaly | Most Likely Root Cause | Fast Verification Query / Check | Immediate Remediation |
|---|---|---|---|
Sudden 5x spike in terpakai_hari_ini_tp with normal request count | Client switched from a flat/flash model to a metered long-context model, or system prompt bloated | Group ai_finops_ledger by model and AVG(prompt_tokens) over the last 2 hours | Enforce allowlist on the service's virtual key and add POST /v1/messages/count_tokens preflight caps |
Sudden 10x spike in request_hari_ini at constant avg TP | Unbounded agent retry loop or webhook storm re-triggering the same job ID | Check duplicate (tenant_id, feature_tag) bursts per minute in PostgreSQL/ClickHouse | Add idempotency keys per job + enforce batasPeriode (harian) on the worker's virtual key |
Unexpected HTTP 402 insufficient_quota despite master balance > 0 | Service is using a scoped customer virtual key whose sisa_kuota_tp or batas_periode_gp hit zero | Call GET /v1/balance with the failing key; inspect sisa_kuota_tp, terpakai_periode_gp, and bisa_dipakai | Raise quotaGp or batasPeriode in /dashboard/customer-keys, or wait for reset_periode_detik |
Ledger sum is lower than terpakai_bulan_ini_tp from /v1/balance | Streaming calls omitted telemetry persistence, or async DB writes dropped during a pod restart | Compare request_bulan_ini from /v1/balance against COUNT(*) in ai_finops_ledger | Capture x-topai-charge header on every response and buffer ledger writes through a durable queue (Redis/SQS) |
Order stuck in pending at /dashboard/saldo | Bank transfer or USDT confirmation still in flight, or user closed checkout before completing payment | Check order status (TOP-...) in /dashboard/saldo; confirm tx hash or bank receipt | Wait 1–5 min for USDT confirmations; if expired (failed), create a fresh TOP- order without double-paying |
Production Go-Live Checklist for Engineering & FinOps Teams
Before flipping real customer traffic onto your TOP AI integration, verify all eight operational controls below:
- Create and fund your account cleanly: Register at /daftar (starts with
5,000 TPbonus_daftar), complete your company billing profile (legal name, address, tax ID) before your first top-up, and fund your initial production runway at/dashboard/saldo(1 TP = Rp 1, zero expiry). - Archive your first official invoice: Confirm your
TOP-order transitions topaidand verify your finance team can download the permanentINV-YYYYMM-XXXXXXrecord at/dashboard/invoice/[orderId]. - Never ship a master
userkey into tenant-facing workloads: Mint dedicated scoped virtual keys in/dashboard/customer-keysfor production services, staging/CI runners, and individual agency clients—each with explicitquotaGp,periode,batasPeriode, andallowlistpolicies. - Instrument
topai.charged_gpandtopai.balance_afteron every call: Persist every billable request asynchronously into PostgreSQL or ClickHouse withtenant_id,workspace_id,feature_tag,model,upstream,failover, andlatency_ms. - Deploy the zero-cost
GET /v1/balancewatchdog: Schedule the Slack and Telegram burn-rate alert worker every 5 minutes with tiered thresholds (150,000 TPadvisory,50,000 TPwarning,15,000 TPcritical) and runway-hours math soHTTP 402never reaches production users. - Wire
POST /v1/messages/count_tokenson untrusted long inputs: Reject or chunk oversized uploads at0 TPbefore dispatching metered completions. - Benchmark model routing quarterly against /en/pricing: Keep short high-volume extraction on fast metered models (
deepseek-v4-1-flash), bilingual SEA/global support onglm-5-3, and complex long-context synthesis on flat-rate promo tiers (claude-sonnet-5-5). - Run the month-end SQL continuity check: Reconcile
SUM(charged_tp)againstGET /v1/balance,/dashboard/pemakaianCSV exports, and your archivedINV-YYYYMM-XXXXXXinvoices so engineering and finance close every month with zero unexplained variance.
For full endpoint references, error codes, and SDK examples, explore /en/docs, review current model rates on /en/pricing, or jump straight into your workspace via /daftar.
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.
What happens if an incoming API request costs more than my remaining TP balance?+
The TOP AI gateway validates balance headroom atomically before forwarding the request upstream. If your balance is below the estimated cost, the gateway immediately returns HTTP 402 insufficient_quota with zero TP deducted, and balances can never go negative.
How can software agencies or SaaS resellers cap individual client spend from one master wallet?+
Use /dashboard/customer-keys to mint up to 50 active scoped virtual keys per account. Each key supports an independent total quota (quotaGp), a periodic cap (sekali, harian, or bulanan via batasPeriode), a model allowlist, and one-click pause or revocation.
Where do finance teams download official invoices for accounting and tax reconciliation?+
Every TOP- prefixed order that reaches paid status generates a permanent invoice page at /dashboard/invoice/[orderId] carrying a sequential INV-YYYYMM-XXXXXX number and the billing entity details saved in your account profile.



