AI API infrastructure
TokenBridge
Know if a user still has quota before every LLM call — not when reconciling at month end.
Li Ming · Backend lead
「We sell token packs but the gateway kept forwarding after balance hit zero. One user ran $2,000 of Opus on our dime — Stripe settled T+1, too late to block.」
Challenge
Prepaid token resale with multi-model pricing. Balance lived in a business DB, async from real token burn. Retries caused double-charge disputes.
How they integrate
- 1 Deploy Lite (make demo) — Redis + API, no Flink required.
- 2 On signup: POST /budget/{userId} with max_rpm. On recharge: POST /budget/{userId}/package.
- 3 Optional: POST /budget/{userId}/webhook for BUDGET_WARN at 70%/90% spent (v2.7 Lite).
- 4 Optional (v2.8): POST /admin/customers/{id}/apikeys/{key_id}/budget for per-key limits.
- 5 Hook 1 (sync): GET /budget/{userId}/check?estimated_cost_usd=… before forwarding to upstream.
- 6 If allowed: false → return HTTP 402. If true: call OpenAI / DeepSeek / Qwen, then Hook 2.
- 7 Hook 2 (async): POST /ingest with customerId, modelId, tokens, eventId=upstream id for idempotency.
- 8 Usage center: proxy GET /usage/customer/{id}/period|day|model/* — do not expose Admin Key to browsers.
Key APIs
- Pre-flight gate
GET /budget/{id}/check - Soft alerts
POST /budget/{id}/webhook - Per-key budget
POST /admin/customers/{id}/apikeys/{key_id}/budget - Token package
GET /budget/{id}/package - Post-call metering
POST /ingest - Developer dashboard
GET /usage/customer/{id}/period/{YYYY-MM}
ID mapping
customerId = user_{uuid} (1:1 with your user table). eventId = upstream request id (e.g. chatcmpl-xxx) for dedup.
# Hook 1 — before every upstream LLM call
curl "localhost:8000/budget/user_wang/check?estimated_cost_usd=0.03"
# → allowed: false → return HTTP 402 to developer
# Optional (v2.8): per-key API budget on customer keys
# POST /admin/customers/{id}/apikeys/{key_id}/budget
# Hook 2 — after upstream response (async OK)
curl -X POST localhost:8000/ingest \
-H 'Content-Type: application/json' \
-d '{"customerId":"user_wang","modelId":"gpt-4o","inputTokens":500,"outputTokens":150,"eventId":"chatcmpl-abc"}'
# Soft alerts (v2.7 Lite) — BUDGET_WARN at 70%/90% spent
curl -X POST localhost:8000/budget/user_wang/webhook \
-d '{"webhook_url":"https://api.example.com/hooks/fluxmeter"}'
# On recharge — token package
curl -X POST localhost:8000/budget/user_wang/package \
-d '{"tokens": 10000000}'Outcome
Zero platform overdraft losses. Soft alerts before hard cutoff. Developers self-serve day/month/model usage. Gateway adds two hooks — typically live in 3–4 weeks.