Most AI backend tutorials end in the same place: a POST /chat handler that proxies a stream and returns text. That is the easy 10%. The other 90% is the part that decides whether you can actually charge for it:
- Who is calling, and what are they allowed to do?
- How many credits do they have left, and can you explain the number when they ask?
- What happens when Stripe delivers the same webhook twice?
- How do you bill a stream whose cost is only known after the last token?
- What if the client closes the tab halfway through?
This post walks through one working answer to those questions in FastAPI: an append-only credit ledger, a reserve-then-reconcile streaming model, and Stripe webhooks that are idempotent at two layers. All the code below is from a service I run and test, not pseudocode.
A counter is a lie you tell yourself
The usual first implementation is a column: users.credits -= cost. It works in a demo and breaks in three predictable ways.
1. The double grant. Stripe retries webhooks. It retries on timeouts, on non-2xx responses, and sometimes just because. If checkout.session.completed is processed twice, a credits += 50000 runs twice, and you have given away a plan you were paid for once.
2. The lost update. Two requests arrive at the same time, both read credits = 10, both write 10 - 8 = 2. You charged once for two completions. Under load this is not rare, it is routine.
3. The unexplainable balance. A customer writes "I had 4,000 credits yesterday, now I have 3,120, what happened?" With a single integer you can only say "trust me". There is no history, so support becomes archaeology.
All three come from the same mistake: storing state where you should store facts. Balances are derived; charges are facts.
An append-only ledger, in one table
The fix is small enough to fit in a model:
class CreditLedger(Base): __tablename__ = "credit_ledger" __table_args__ = ( UniqueConstraint("idempotency_key", name="uq_credit_ledger_idempotency"), ) id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) user_id: Mapped[str] = mapped_column( String(40), ForeignKey("users.id", ondelete="CASCADE"), index=True ) delta: Mapped[int] = mapped_column(Integer) balance_after: Mapped[int] = mapped_column(Integer) reason: Mapped[str] = mapped_column(String(64)) reference: Mapped[str | None] = mapped_column(String(120)) idempotency_key: Mapped[str | None] = mapped_column(String(160)) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), default=utcnow, index=True ) Three rules make this work:
- Rows are only inserted. No updates, no deletes. A correction is another row.
- The balance is the latest
balance_afterfor the user, read with one indexed query. - Every row explains itself.
delta,reason,referenceand the resulting balance are on the row, soGET /v1/creditscan return something a human can read:
{ "balance": 49958, "plan": "pro", "monthly_credits": 50000, "entries": [ { "id": 41, "delta": -14, "balance_after": 49958, "reason": "chat_stream", "reference": "req_9f3a" }, { "id": 40, "delta": 2, "balance_after": 49972, "reason": "usage_refund", "reference": "req_9f3a" }, { "id": 39, "delta": -30, "balance_after": 49970, "reason": "chat_stream", "reference": "req_9e11" }, { "id": 38, "delta": 50000, "balance_after": 50000, "reason": "plan:pro", "reference": "cs_test_a1" } ] } balance_after is denormalised on purpose. Strictly it is derivable by summing deltas, but summing is O(n) and grows forever; the stored value makes reads O(1) and also pins the row to the balance at that moment, which is exactly what an audit needs.
One function writes, and it can't go negative
If every credit change goes through one function, you only have to get that function right once.
def apply( db: Session, user_id: str, delta: int, reason: str, *, reference: str | None = None, idempotency_key: str | None = None, ) -> tuple[CreditLedger, bool]: if delta == 0: raise ValueError("delta must be non-zero") # Fast path: this key was already applied. if idempotency_key: existing = _find_by_idempotency(db, idempotency_key) if existing is not None: return existing, False # Serialise concurrent writers for this user. db.execute(select(User.id).where(User.id == user_id).with_for_update()) balance = get_balance(db, user_id) new_balance = balance + delta if new_balance < 0: raise InsufficientCredits(balance=balance, required=-delta) entry = CreditLedger( user_id=user_id, delta=delta, balance_after=new_balance, reason=reason, reference=reference, idempotency_key=idempotency_key, created_at=utcnow(), ) try: with db.begin_nested(): db.add(entry) db.flush() except IntegrityError: # Lost a race on the key: return the winner's row. existing = _find_by_idempotency(db, idempotency_key or "") if existing is None: raise return existing, False return entry, True Three guards, doing three different jobs:
- The lookup is an optimisation: it turns a retry into one cheap SELECT instead of an exception.
- The row lock (
SELECT … FOR UPDATE) makes two invoices for the same user queue up instead of reading the same balance. On SQLite this is a no-op, which is fine for the demo; on Postgres it is the thing that stops the lost update. - The unique constraint is the actual guarantee. Two requests can both pass the lookup, both compute a balance, and both try to insert; only one wins, and the loser catches
IntegrityErrorand returns the winner's row. The database, not application logic, decides who was first.
Note that InsufficientCredits is raised before the insert, so the balance can never go below zero. A charge that can't afford itself fails loudly as a 402 rather than silently as a negative number.
Pricing: one function, no tokenizer dependency
INPUT_TOKENS_PER_CREDIT = 100 OUTPUT_TOKENS_PER_CREDIT = 50 # output costs 2x def credits_for_usage(input_tokens: int, output_tokens: int) -> int: input_credits = math.ceil(max(input_tokens, 0) / INPUT_TOKENS_PER_CREDIT) output_credits = math.ceil(max(output_tokens, 0) / OUTPUT_TOKENS_PER_CREDIT) return max(1, input_credits + output_credits) Two decisions worth copying:
Round up per request, minimum 1. Otherwise a one-word completion costs zero credits and becomes a free API. The floor is not about revenue; it is about not letting a holder of N API keys make unbounded free calls.
Estimate tokens instead of counting them exactly. estimate_tokens splits on word-ish chunks and punctuation, and counts CJK by character:
words = re.findall(r"[\w']+|[^\w\s]", text) cjk = len(re.findall(r"[\u3400-\u9fff\uac00-\ud7af]", text)) return max(1, len(words) + cjk // 2) A provider-exact tokeniser is a dependency, differs per provider, and changes under you. Metering needs a number that (a) moves with text size and (b) errs on the side of the house. If you later want exactness, swap this function for tiktoken; every ledger call stays the same, because the ledger only ever sees credits.
Streaming: reserve the maximum, then reconcile
Here is the real problem with SSE billing. You must check the balance before you call the model, or a user with 0 credits gets a free completion. But you don't know the cost until the last token arrives, and by then the response has already started and you can no longer return a 402.
The pattern that works: charge the maximum up front, stream, then charge the actual and refund the difference.
messages, input_tokens, max_tokens, estimate = _prepare(body, settings) # estimate = credits_for_usage(input_tokens, max_tokens) credit_service.charge( db, user_id, estimate, reason="chat_stream", reference=request_id, idempotency_key=f"charge:{user_id}:{request_id}", ) db.commit() Because this runs before the provider is called, a poor balance gets a real 402 insufficient_credits, not a stream that dies on the first chunk. The request id namespaces the key, and it is namespaced again by user id, so one client reusing an X-Request-ID cannot collide with another account.
Then the stream itself. Four event types, each with a job:
event: meta data: {"id":"chat_9f3a","model":"gpt-4o-mini","provider":"openai", "credits_charged_estimate":8,"request_id":"req_9f3a"} event: delta data: {"text":"A credit ledger "} event: usage data: {"input_tokens":57,"output_tokens":214,"credits_charged":6,"balance":48210} event: done data: {"id":"chat_9f3a"} -
metatells the client what was reserved, so the UI can show a pending charge. -
deltais the text. -
usagecloses the loop with the true cost and the new balance, so the client does not need a second request to find out what it was charged. -
doneis a terminal marker. Without it, a dropped connection and a finished answer look identical to the client.
The generator is straightforward; the interesting part is what happens when it ends early:
async def event_stream(): collected: list[str] = [] finalised = False def finalise(status_code: int, *, note: str | None = None) -> int: nonlocal finalised output_tokens = estimate_tokens("".join(collected)) actual = credits_for_usage(input_tokens, output_tokens) refund = estimate - actual with database.session() as session: # a NEW session if refund > 0: credit_service.grant( session, user_id, refund, reason="usage_refund", reference=request_id, idempotency_key=f"refund:{user_id}:{request_id}", ) usage_service.record(session, ...) balance_now = credit_service.get_balance(session, user_id) finalised = True return balance_now try: yield _sse("meta", {...}) async for delta in provider.stream(messages, body.model, max_tokens): collected.append(delta) yield _sse("delta", {"text": delta}) balance_now = finalise(200) yield _sse("usage", {...}) yield _sse("done", {"id": chat_id}) except asyncio.CancelledError: if not finalised: finalise(499, note="disconnected") raise Three details that took me a debugging session each:
Finalise in a new session. By the time the generator body runs, response headers are already sent. The request-scoped Session from the dependency is not the right lifetime for work that happens after the response has begun, and long-lived sessions held open for a stream will exhaust your pool. Opening a short session inside finalise keeps the transaction milliseconds long.
asyncio.CancelledError is a billing event. When the client disconnects, Starlette cancels the task and the loop raises. Without the handler, you have already charged the full estimate and never refund it: the customer pays for 500 tokens and receives 40. With it, collected holds exactly what was sent, and the refund covers the rest. The recorded status is 499, which is non-standard but universally understood as "client closed request".
Refunds are keyed, so double-finalising is harmless. The happy path and the cancel path both want to refund. refund:{user_id}:{request_id} means the second one returns the first row and changes nothing. That is what lets you call finalise defensively from several branches without a flag dance.
A provider error gets the same treatment in the other direction: refund the whole estimate and return a 502 with a retryable flag.
Stripe webhooks: idempotent at two layers
Webhooks are where money enters the system, and Stripe deliberately retries them. You need to be safe when an event arrives twice, and you need to not lose one when your process dies mid-handler.
Layer 0: verify the signature over raw bytes.
def verify_signature(payload: bytes, header: str | None, secret: str, tolerance_seconds: int = 300) -> None: parts: dict[str, list[str]] = {} for item in header.split(","): key, _, value = item.strip().partition("=") if key and value: parts.setdefault(key, []).append(value) timestamps, signatures = parts.get("t", []), parts.get("v1", []) if not timestamps or not signatures: raise WebhookSignatureError("Malformed Stripe-Signature header") timestamp = int(timestamps[0]) if tolerance_seconds > 0 and abs(int(time.time()) - timestamp) > tolerance_seconds: raise WebhookSignatureError("Signature timestamp outside tolerance") signed = f"{timestamp}.".encode() + payload expected = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest() if not any(hmac.compare_digest(expected, candidate) for candidate in signatures): raise WebhookSignatureError("Signature mismatch") What matters here:
- The signed string is
"{t}.{raw_body}", not the JSON. Any middleware that parses and re-serialises the body changes the bytes and breaks the HMAC, which is why the route doespayload = await request.body()before anything else. -
v1can appear multiple times during secret rotation. Accept if any candidate matches. - Compare with
hmac.compare_digest, not==. - The 300-second window bounds replay of a captured payload. Signature verification alone proves authenticity, not freshness.
Layer 1: the event id. A webhook_events table with a unique stripe_event_id column:
record = db.scalar( select(WebhookEvent).where(WebhookEvent.stripe_event_id == event["id"]) ) if record is not None and record.status == "processed": return {"received": True, "event_id": event["id"], "status": "duplicate"} The row is inserted with status processing before the handler runs. If two deliveries race, the insert loses on the unique index, and the loser returns duplicate without touching anything. On success the status becomes processed; on failure it becomes failed with the error, so Stripe's retry can run it again. That distinction matters: a blanket "ignore if id exists" would permanently swallow an event your code failed to handle.
Layer 2: a per-object grant key. Every credit grant carries its own key:
credits.grant( db, user.id, PLANS[plan].monthly_credits, reason=f"checkout:{plan}", reference=str(obj.get("id")), idempotency_key=f"checkout:{obj.get('id')}", ) Why both layers? The event id protects against the same event twice. The object key protects against different events describing the same payment: a checkout.session.completed and an invoice.paid for the same session, the demo flow and the real webhook, or a manual replay by an operator. If either layer is bypassed, the other still holds. That redundancy is deliberate; idempotency is not a place to be clever.
The handlers themselves are boring, which is the goal: checkout.session.completed sets the plan and grants monthly credits, customer.subscription.updated/deleted maps status to plan (anything not active/trialing/past_due drops to free), invoice.paid grants the monthly allowance, invoice.payment_failed marks past_due without revoking access immediately.
Proving it without a Stripe account
You cannot test this by clicking around the Stripe dashboard, and you should not need to.
sign_payload produces a valid Stripe-Signature header from any secret, so tests and a CLI replay script send genuinely signed events:
python scripts/replay_webhook.py invoice --user-id usr_1234 --plan pro # 200 {"received":true,"event_id":"evt_replay_...","status":"invoice_paid:pro"} # run it again with the same event id # 200 {"received":true,"event_id":"evt_replay_...","status":"duplicate"} And demo mode goes further: with DEMO_MODE=true, POST /v1/billing/checkout returns a local page with a "Complete demo payment" button, and that button builds a checkout.session.completed event and runs the same process_event a real webhook runs. No mock of the interesting part. The local AI provider implements the same stream interface as OpenAI, so the SSE path is exercised too.
That is what makes the whole thing testable in CI with no keys and no network.
The checklist
If you take five things from this:
- Never
UPDATEa balance. Insert a row with the resulting balance. Derive, don't mutate. - Reserve before you generate. A 402 before the first token beats a stream that dies at chunk three.
- Finalise in a fresh transaction. Response headers are gone; the request session is not yours anymore.
- Treat client disconnect as a billable event. Charge what was produced, refund the rest, and key the refund.
- Two idempotency layers on webhooks. Event id and per-object key. Overkill until the day it saves you.
None of this is exotic. It is the ordinary care that separates a demo from something you can put a price on, and it is a few hundred lines of code once you stop reinventing it.
I packaged that implementation as a starter kit: FastAPI + Stripe AI Backend Kit — JWT + API keys, the ledger above, usage metering, Stripe Checkout and Portal, signature-verified idempotent webhooks, OpenAI/Anthropic-compatible SSE streaming, rate limits, Docker, Alembic, 58 tests, and a demo that runs with no Stripe account and no API key.
- Product: FastAPI + Stripe AI Backend Kit — $25, one-time, commercial licence for one team, 30-day refund.
- Launch code:
LAUNCH30for 30% off ($17.50) at checkout. - More kits: the rest of the store.
If you only copy one thing from this post, copy the ledger. Everything else is easier once the money has a history.

