All projects

01 / ENGINEERING CASE STUDY · AI systems

Autonomous Billing Proxy

I built a FastAPI gateway that returns API responses without waiting for verification, evaluates their usefulness separately, and records approved charges in an atomic wallet ledger.

AT A GLANCE

The problem
An API response can be empty or unusable and still incur a charge. Agents need billing tied to useful results.
What I built
I built the FastAPI gateway, Gemini-backed verifier, and Postgres wallet and ledger flow.
The result
Responses return before verification finishes. Approved charges update the wallet and ledger in one transaction.
PythonFastAPINext.jsSupabaseGemini AI
April 2026 — Present

01 / CONTEXT

The problem

An HTTP request can return an empty response, a bot challenge, or irrelevant content and still count as billable traffic. I built this prototype to explore charging an AI agent only after the response is judged useful, while keeping verification off the agent’s response path.

02 / SYSTEM DESIGN

Architecture

Return the response; evaluate the charge separately

Agent · bearer token + target URL
FastAPI gateway · authenticate + proxy
Target API · response
Telemetry · verification
Verified outcome · wallet debit + ledger row
  • Gemini structured judgment + heuristic fallback
  • Failed verification: no charge
  • Next.js dashboard: tokens, balance, history
The gateway returns the upstream response to the agent. A separate asynchronous verification path decides whether to create a charge.

03 / TRADEOFFS

Engineering decisions

01

Keep verification off the response path

I moved verification into asynchronous tasks so the agent does not wait for model scoring and billing. The current client is fire-and-forget, so an unreachable verifier can mean dropped telemetry. I need a durable queue before relying on this flow for revenue.

Asynchronous verification client
02

Make a charge explainable

I use Gemini for structured judgments and local heuristics as a fallback when the model is unavailable. Status, body coherence, and failure signals inform the decision. Scores and proof metadata accompany ledger entries so I can trace why a request was charged.

Structured verification judge
03

Commit the debit and ledger entry together

I put the wallet debit and ledger insertion in one PL/pgSQL transaction, with a rollback if the balance is insufficient. The request-hash precheck helps identify repeated executions, but concurrent duplicates still need stronger guarantees. My next iteration needs concurrency-safe idempotency and tests that exercise retries.

Atomic billing function
04

Treat the gateway as an enforcement boundary

I store bearer tokens as SHA-256 hashes and use session checks, request fingerprints, per-developer rate limits, and bounded telemetry to constrain what reaches downstream services. Distributed rate limiting is still needed before running the gateway across multiple instances.

Gateway implementation
05

Connect usage to the developer wallet

I built a Next.js and TypeScript dashboard for bearer-token creation, balances, and transaction history. Stripe Checkout handles wallet top-ups; payment webhooks connect completed checkouts to account credits.

Stripe Checkout integration

04 / DEBUGGING

A high score could hide a failed request

What broke

The fallback evaluator combined several signals into a weighted score. Strong content scores could compensate for a failed HTTP status or an empty response, allowing an execution that should fail to qualify for billing.

The fix

I made HTTP success, a non-empty body, and the absence of a detected refusal mandatory gates before applying the score threshold. Scores and flags remain available to explain the verdict.

How I check it

Regression cases cover redirects, 4xx and 5xx responses with otherwise valid content, plus empty, whitespace-only, and trivial bodies. These protect the heuristic fallback; the Gemini judge still needs separate evaluation against labeled responses.

05 / VALIDATION

Evidence & measurement

The gateway, verifier, and atomic billing flow are implemented. Evaluator tests exercise billing decisions, and a local simulation script sends a request through the gateway and polls for its ledger entry.

End-to-end simulation

The script seeds test fixtures, makes one proxied request, and checks for a transaction. It is a functional walkthrough, not a load test or proof of retry safety.

View supporting reference

Atomic wallet + ledger writes

The database function combines wallet debit and ledger insertion in one transaction and rejects insufficient balances.

View supporting reference

Evaluator coverage

Pytest cases cover HTTP failures, empty bodies, refusal signals, and the composite decision pipeline.

View supporting reference

Benchmark notes

These reported figures do not have published benchmark or load-test results. Validating them requires measurements of the complete path, including successful writes and reconciliation between wallets and the ledger.

Reported figures and the context needed to reproduce them
FigureWhat I need to document
<50 ms proxy overheadA direct-versus-proxied baseline, payload sizes, concurrency, hardware, and latency percentiles. The gateway’s upstream timer alone does not measure proxy overhead.
100K+ micro-transactionsRun duration, transaction rate, environment, completed ledger writes, failures, and wallet-to-ledger reconciliation results.

06 / NEXT ITERATION

What I’d improve next

Durable verification and retry safety

My first priority is to put telemetry on a durable queue, add concurrency-safe idempotency, and verify that retries cannot create duplicate charges.

Calibrate the judge

I want to evaluate labeled agent responses and report false-positive and false-negative rates separately. A false positive can create an incorrect charge, so aggregate accuracy alone is insufficient.

Measure the full system

I want to exercise the complete path under load and injected failures, separating response overhead from verification time and checking that approved charges reconcile with wallet balances.

Code links point to revision 43cf21d of my billing gateway.

NEXT CASE STUDYDistributed Vector Database