The software default is No subscriptions (
access_model = off, default_token_quota = 0 meaning unlimited). Fresh installs and existing self-hosts start there. No billing UI surfaces until an admin picks a Stripe posture.What you get
- Three access postures: no subscriptions, included + paid, or paid only
- Stripe-hosted Checkout — users upgrade without your code ever touching card data
- Customer Portal — users update payment methods, download invoices, cancel — all on Stripe’s UI
- Webhook-driven lifecycle — subscriptions provision and renew automatically; canceled paid users return to the included tier (or become unentitled in paid-only) at period end
- Quota enforcement — token usage recorded in an append-only ledger and summed per period; mid-stream cutoff with a structured upgrade prompt
- Admin pages for plan CRUD and subscription monitoring
Prerequisites
- Stripe account with Live mode activated. Singapore-incorporated companies must complete KYC (business UEN, director ID, bank account). Approval typically takes 1-3 days.
- Stripe Live API key of type Restricted (recommended over Standard
sk_live_***— easier to revoke, scoped permissions). - Webhook endpoint publicly reachable at
<your-domain>/api/webhooks/stripe. - Bank account for payouts. Multi-currency settlement (e.g. USD payout to a USD account) is recommended for non-USD-default Stripe accounts to avoid 1.5-2% FX leakage per transaction.
Setup
1. Stripe Dashboard
Create the Pro product
- Catalog → Products → + Add product
- Name:
Pro, description:5M tokens / month, priority support - Pricing: Recurring, monthly, $20.00 USD (adjust to your pricing strategy)
- Save → copy the resulting
price_***ID (you will UPDATE the localbilling_planstable with this value after activation)
Create a Restricted API key
- Developers → API keys → + Create restricted key
- Name:
fim-one production - Permissions (minimum):
- Customers: Write
- Subscriptions: Write
- Checkout Sessions: Write
- Customer portal: Write
- Prices: Read
- Products: Read
- Save → copy
rk_live_***
Register the webhook endpoint
- Developers → Webhooks → + Add endpoint
- URL:
https://<your-domain>/api/webhooks/stripe - Events to receive:
checkout.session.completedcustomer.subscription.createdcustomer.subscription.updatedcustomer.subscription.deletedinvoice.payment_succeededinvoice.payment_failed
- After save, click “Reveal signing secret” → copy
whsec_***
Configure multi-currency settlement (recommended)
If your Stripe account default currency differs from the price currency you charge in (common case: SGD account charging USD):- Settings → Bank accounts and currencies → Add a settlement currency
- Pick the price currency (e.g. USD)
- Attach the matching bank account (e.g. an Aspire USD virtual account)
- Save — Stripe routes USD charges directly to USD payouts, no FX conversion
2. Backend .env
Set these three keys in your production .env:
.env so the keys are picked up:
3. Activate in Admin
- Log in as an admin
- Admin → System Settings → Access and billing
- Pick one posture (the instance is always in exactly one):
- No subscriptions (software default) — Stripe unused. Token access is the default monthly quota (
0= unlimited). - Included + paid — Stripe required. New users land on the included tier; they can upgrade. Canceled paid users return to the included tier at period end.
- Paid only — Stripe required. No included tier. Users must subscribe before they can call models. Existing included-tier users keep their quota if you switch from Included + paid.
- No subscriptions (software default) — Stripe unused. Token access is the default monthly quota (
- The backend validates that both
STRIPE_SECRET_KEYandSTRIPE_WEBHOOK_SECRETare present when you pick a Stripe posture — if either is missing it returns 400 - On first activation of a Stripe posture the backend runs an idempotent setup:
- Included + paid: seeds the included plan (
slug=free) + a Pro template with an empty Price ID; setsdefault_plan_id; backfills users without a plan - Paid only: seeds the Pro template only; does not backfill
- Copies
default_token_quotaonto the included plan when that plan is seeded (0stays0, unlimited)
- Included + paid: seeds the included plan (
- Switching back to No subscriptions is a pure flag flip with no data side effects. The included default plan cannot be deleted while Included + paid is active.
4. Update the Pro plan with your live price
After activation, update the seeded Pro plan to point at your live Stripe price:- Admin → Billing → Plans → Pro → Edit
- Paste your
price_1***(from step 1) intoStripe Price ID - Save
5. Smoke test
- Open
/settings?tab=billingas a regular user - Click Switch to Pro
- Stripe Checkout opens; complete with a low-amount real card (refund afterwards)
- Webhook should fire — verify in Stripe Dashboard → Webhooks → recent events show 2xx responses
- Subscription row appears in
subscriptionstable;users.plan_idflips topro - UI now shows Pro plan + “Manage subscription” button
Disabling billing
Toggle the Enable Stripe Billing switch OFF in Admin → System Settings → Billing. When disabled:- All
/api/billing/*endpoints return 503 - The webhook endpoint returns 503 (Stripe will retry, then surface in Dashboard as failing — that’s fine, you can disable the webhook in Stripe Dashboard instead if billing is permanently off)
- The
Plan & Billinguser-facing tab disappears - The Admin → Billing nav group is hidden
- The quota chain skips the plan tier and falls back to
default_token_quotadirectly
subscriptions, billing_plans, and users.plan_id rows are untouched. Re-enabling resumes from the same state with no migration.
Calculation reference — quota & token math
This is the authoritative reference for every numeric rule that decides what a user is allowed to consume, when their counter resets, and how the resolution chain composes. Read this before changing pricing, adjusting quotas, building usage dashboards, or planning v2/v3 work. Future-but-not-yet-shipped rules are documented in their reserved slot so contributors know where new logic plugs in.Glossary
What counts as a token
Token consumption is metered in the model client, from the provider’susage object on every call, and written to the usage ledger (usage_ledger): an append-only table with one row per turn, run or request and model. A user’s “used” is the sum of their ledger rows since their window began. The quota check, the Usage card in Settings, Admin → Users and the user export all read that sum. The token figures of the platform statistics (Admin → Overview, Analytics, the metrics API) and of each user’s dashboard are read from the same ledger, by the time the usage was recorded; the evaluation center’s tokens consumed is the one figure still summed from the evaluation runs.
- Counted: prompt tokens + completion tokens of every model call made on the user’s account (the provider’s own
total_tokenswhen it reports one) - Counted: every model call of a chat turn, not only the answer: the agent’s tool rounds, routing in Auto mode, domain classification, step titles, context compaction, follow-up suggestions, the conversation title, and the calls of an agent the turn delegated to with
call_agent - Counted: a turn that was stopped or abandoned and a turn that failed, for what they consumed up to that point. When the provider sends no usage for a call (a stream cut short, or a provider that reports none), the call is estimated and its row is marked
estimated. The estimate counts the messages sent, the tool calls in their history, the tool definitions sent with the call, a fixed 1,100 tokens per image, and the text, reasoning and tool-call arguments that had come back, and is rounded up. Against OpenAI’so200k_basetokenizer it comes within about 10% on a tool-heavy agent call, and between 0.8 and 1.5 times the real count on English, Chinese, Japanese, Korean, Russian, Greek, Arabic, Hebrew, Thai and Hindi text, code, JSON, emoji, base64, hex, random identifiers and whitespace - Counted: a chat request sent without a
conversation_id - Counted: workflow runs, against whoever ran them; a run started by a trigger key or a schedule counts against the workflow’s author. Single-step tests count too
- Counted: the model-backed helper endpoints (AI-assisted agent and connector create and refine, connector action generation, database chat and schema annotation, knowledge-base chat), evaluation runs (the agent and the grader), and the vision model reading images and scanned pages while a document is added to a knowledge base
- Over quota or without a plan: adding a document to a knowledge base is not refused, but the document is read without the vision model (text only: no reading of images or scanned pages), the server logs it, and the document shows a warning with the reason; retrying the document once the quota allows reads it with the vision model
- Not counted: embedding, reranking and image generation requests
- Counted: a model call that had been sent but had returned nothing yet when its turn was stopped or abandoned (a call still waiting for its response, a stream before its first chunk, or a tool-call round whose arguments the model was still writing). The provider bills what it was sent, so the prompt is recorded, estimated, plus any tool-call arguments already received; the row is marked
estimated. The client cannot tell whether the request had reached the provider: a turn stopped while the call is still connecting is counted the same way, though the provider received nothing. During a provider outage, a user who presses Stop is therefore charged the prompt, and one who waits for the error is not - Not counted: requests that fail before reaching the provider (auth error, rate-limit pre-check, a call still waiting for the local rate limiter), and a call the provider refused or that broke on an error before its first chunk
- Cached input: counted at full price (no provider cache discount is applied). The ledger records cache-read and cache-creation tokens per row for later use.
source_type (conversation, workflow_run, eval_run or endpoint) with the id, entry (chat, dag, auto, background, a run mode such as trigger or schedule, ai_assist.*, kb_chat, db_chat, kb_ingest, eval), the model, and the organization of the agent, workflow, connector or knowledge base it ran through. conversations.total_tokens and workflow_runs.total_tokens are still kept as “what this conversation / this run reported” and can be lower than the ledger, which also holds interrupted turns, delegated agents and the streamed answer.
Rows are written when a turn, run or request ends, however it ends; a long one is also written as it goes, at most every 30 seconds. If the server process is killed, what its in-flight turns consumed in the last 30 seconds at most is not recorded. A write that fails is retried once and then logged at ERROR with the user and the numbers (Usage not recorded), and the turn is not failed for it.
Upgrading to the release that adds the ledger. The migration carries every conversation’s and run’s total_tokens into the ledger, so each user’s “used” is the same before and after. It then compares the result per user with the source tables once. If an instance of the previous release is still serving and changed a total while the migration ran, each user that differs is carried over again and compared in a single transaction (one snapshot on PostgreSQL), so a writer that keeps running does not stop the migration from finishing. The migration fails only if a user’s carry-over does not match the sources it read, which points to a fault, not to a running writer; it resumes where it was when run again. What an old instance writes after that has no ledger row: for a user who was carried over again, what was committed after their carry-over began; for everyone else, what was committed after the comparison, and everything written once the migration has finished. Once the last old instance has stopped, run the top-up command described in the next paragraph.
After rolling back and upgrading again. A release older than the ledger keeps adding to conversations.total_tokens and workflow_runs.total_tokens without writing ledger rows. If you roll back to one and later upgrade again, run python -m fim_one.core.usage.topup (with the application’s DATABASE_URL) to see what the ledger is missing, and again with --apply to record it: one adjustment row per conversation or run whose ledger rows add up to less than its total. It only adds rows, and a second run finds nothing left. The added usage counts in the window in which the command is run. Run it with the application stopped: against a live one it can count a turn twice whose conversation total was saved a moment before its ledger rows. It compares sums per conversation or run, so where the ledger already holds usage the total never reported (an interrupted turn, a delegated agent), that much of a gap is not recovered: a conversation reporting 180 whose rows add up to 170, 20 of them a delegated agent’s, is missing 30 and gets 10.
Three-state override semantics
users.token_quota is the per-user administrative override. It carries three meanings in one column:
The override always wins over plan and default. It exists so admins can pin individual users above or below their plan tier without touching Stripe.
Quota resolution chain — v1 (current)
For any authenticated request, the cap is computed top-down — first match wins:default_token_quota is 0.
Period reset
- “Used” is not a counter that is reset: it is the sum of the user’s ledger rows from the start of their current window. A new window starts with nothing in it.
- For paid users the window is the subscription period: it starts on the monthly anniversary of the subscription and ends at
Subscription.current_period_end(mirrored onusers.quota_reset_at), which theinvoice.payment_succeededwebhook advances on each renewal. - For users without a Stripe subscription the window is the calendar month (UTC).
- Plan changes mid-period do not start a new window, only renewals do. This prevents quota-cycling exploits (“subscribe → use Pro quota → cancel → subscribe again”).
Mid-stream enforcement
- Pre-flight check at chat-call entry: cheapest path, blocks requests the user can’t afford to start.
- While an answer streams, the turn compares what the user had used when it started, plus what the turn itself has consumed so far (the calls that have finished, and an estimate of the answer being written), with the cap, about every 200 characters. No database query is made for this. Crossing the cap closes the stream with a structured terminator frame, not a network error. Usage from the same user’s other tabs during the turn is seen by the next turn’s pre-flight check.
- The frontend interprets the terminator and surfaces
<QuotaExceededDialog>with a deep link to/settings?tab=billing. - An evaluation run and a workflow batch are admitted once, and checked again the same way before each case or item starts: what the user had used when the run or batch started plus what it has consumed since (for an evaluation, its own meter; for a batch, the totals of the items that have finished). Once the cap is reached no further case or item starts; those under way finish. The evaluation run ends
failedwithtoken_quota_exceededand the number of cases not run in its error; each batch item not started isfailedwithtoken_quota_exceeded. A single workflow run is checked only when it starts (and when it continues after waiting for a decision). - A request made when the quota is already used up is refused before any stream starts: HTTP
429witherror_codetoken_quota_exceeded. Under Paid only, a user with no plan gets HTTP402witherror_codesubscription_required. - The same pre-flight check guards the other endpoints that call a model: AI-assisted agent and connector create and refine, connector action generation, database chat and schema annotation, knowledge-base chat, starting an eval run, and every way of starting a workflow. What they consume counts against the quota like a chat turn does.
Billing-disabled fallback
Whensystem_settings.billing_enabled = FALSE:
- Step 2 of the chain is skipped — the chain collapses to
override → default → unlimited. /api/billing/*and/api/webhooks/stripereturn503.Plan & Billinguser tab and Admin → Billing nav group are hidden.- All billing data (subscriptions, plans,
users.plan_id) is preserved — re-enabling resumes from the same state with no migration.
Reserved: quota chain v2 — Team seats
Not yet shipped. Documented here so v2 work has a known landing spot.
Subscription.quantitycarries seat count (Stripe-native).- A user’s effective plan resolves through Team membership before falling back to their personal plan:
- Quota is per seat (each Team member gets a full
monthly_token_quota), not a pooled bucket. Pooled buckets create first-come-first-served exhaustion and are anti-customer. - Override semantics are unchanged — Team admins can still hard-cap individual members via
users.token_quota = N, which sits above the team plan in the chain.
Reserved: quota chain v3 — native Org allocation (no Stripe)
Not yet shipped. Reserved for on-prem / enterprise deployments that allocate quota internally without paying Stripe per user.
- New table
org_quota_allocations(user_id, monthly_token_quota, org_id)distributes a parent budget across members. - Allocations are per user, not a shared pool — every member has a clear individual SLA.
- Updated chain:
max(), notsum(). A paid Pro user never gets less than they paid for, even if their Org admin sets a low allocation. Stripe-paid quota is sacrosanct.
Reserved: pay-per-use credit balance (v3 separate dimension)
Not yet shipped. A separate axis from the chain above — credits are a one-time top-up, not a subscription tier.
- New table
user_credits(user_id, balance_cents, currency)— funded via Stripe Checkoutmode='payment'. - Consumption order: subscription quota first, then credit balance (only after subscription is exhausted does the credit decrement begin).
- Credit balance is non-refundable (industry standard for prepaid).
- UI exposes both bars:
Subscription quota: 4.2M / 5M used+Credits: $7.40 remaining.
Default values
Ship-time defaults — all tunable post-install except where noted.Pricing model
V1 is a flat subscription. Free + Pro, monthly billing, USD-only. Out of scope for v1 (intentional, deferred to roadmap):- Team plan (Stripe seats /
subscription.quantity) - Annual billing
- Multi-currency presentment
- Coupons / promo codes
- Tax handling (Stripe Tax integration — needs separate compliance review)
- Usage-based metering / overage charges
- Pay-per-use credit balance (one-time top-up)
Troubleshooting
Toggle won't activate — 400 error
Toggle won't activate — 400 error
The activation endpoint requires both
STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET to be set. Confirm they’re present in .env and that the backend was restarted after editing.Webhook returns 503
Webhook returns 503
Either billing is disabled (toggle is OFF), or the request signature failed verification (mismatched
STRIPE_WEBHOOK_SECRET). Check Stripe Dashboard → Webhooks → recent events for the actual error body.User subscribed but still sees Free plan
User subscribed but still sees Free plan
The
checkout.session.completed webhook didn’t reach your backend. Verify the endpoint URL in Stripe Dashboard matches <your-domain>/api/webhooks/stripe exactly, including the trailing path. Check Webhook recent deliveries for failures.Pro user sees the test-mode price ID
Pro user sees the test-mode price ID
The seed migration writes a test-mode price ID. After activating production billing, update the Pro plan to use your live
price_1*** via Admin → Billing → Plans → Pro → Edit, or via direct SQL UPDATE.Receipts are branded with Stripe defaults
Receipts are branded with Stripe defaults
Configure your business branding in Stripe Dashboard → Settings → Branding. Add your logo, business name (e.g. “FIM Labs Pte. Ltd.”), and address. Stripe applies these to all auto-generated receipts and invoices.
FX losses on payouts
FX losses on payouts
If your Stripe account default currency differs from your charge currency, Stripe converts at every payout (1.5-2% spread). Add a matching settlement currency under Settings → Bank accounts and currencies, attach a same-currency bank account, and Stripe will route same-currency payments without conversion.