●MCP — Rork now lets you add and manage your own MCP servers inside Plugins (11/21)●2.5 ROUTE — From 12/1, apps calling gemini-2.5-flash are routed to 3.5 Flash-Lite and billed at its rates (9 days left)●CHANNEL — Users report Android notification channel reads and writes failing in Expo Go●NEW — New: three clues to check before replying to a stuck-on-splash review●EXPORT — Export your projects before you downgrade or cancel a plan●SONNET 4.5 — Apps that call Sonnet 4.5 through the API should switch before it retires on 11/30●MCP — Rork now lets you add and manage your own MCP servers inside Plugins (11/21)●2.5 ROUTE — From 12/1, apps calling gemini-2.5-flash are routed to 3.5 Flash-Lite and billed at its rates (9 days left)●CHANNEL — Users report Android notification channel reads and writes failing in Expo Go●NEW — New: three clues to check before replying to a stuck-on-splash review●EXPORT — Export your projects before you downgrade or cancel a plan●SONNET 4.5 — Apps that call Sonnet 4.5 through the API should switch before it retires on 11/30
Usage-Based Billing for Rork AI Apps with Stripe Meter — Charge by API Calls and Tokens, Not Flat Rates
Implement usage-based billing in your Rork AI app with Stripe Meter — server-side reporting, identifier-based de-duplication, retry queues, aggregation with a self-built monthly cap, and metered vs prepaid credits, with what was verified and what wasn't.
There was a night I put two users side by side in a spreadsheet. One sends 50 messages a month to an AI chat feature; the other sends 200 a day. I assumed a cost of 3 yen per call — a placeholder — and the second user's cost came to more than 18,000 yen a month. Charging both the same flat fee stopped making sense right there, on paper.
A flat subscription is easy to explain, but for AI features it tends to make light users carry heavy ones. That is where Stripe's Meter Billing (usage-based billing) earns a look: you send usage as events, and Stripe handles the per-period aggregation and the invoice.
This guide walks through wiring Meter Billing into a Rork AI app, focusing on the server side. Along the way I'll point out a design flaw in my own first draft, and I've tried to separate what I actually ran from what I could not verify.
Why AI Apps Need Usage-Based Billing
Flat pricing has a structural skew. In AI apps, per-user usage routinely differs by 10× to 100× or more, so a 50-message user and a 200-a-day user paying the same amount means your cost grows with every heavy user you win.
Usage-based billing gives you three things:
Fairness — users pay in proportion to what they use, and you stop absorbing cost growth alone.
A low entry plan — "300 yen base plus usage" lowers the door for people who just want to try it.
A billing foundation that extends to API and B2B offerings.
Whether churn actually improves depends on your app and your prices; I have no evidence that adopting it guarantees retention. What I'd check first is the relationship between your unit cost and your unit price.
How Stripe Meter Billing Fits Together
A meter setup has three parts:
Meter — defines what you count, with a Sum, Count, or Last aggregation.
Meter Event — the usage report your server sends to Stripe.
Price with Meter — a price billed on the meter's aggregate for the period.
The flow:
Rork app → your backend (Cloudflare Workers): AI request
↓
Workers authenticates the user, calls the AI, decides the usage after success
↓
Workers → stripe.billing.meterEvents.create()
↓
Stripe aggregates per billing period and invoices
The one point to hold onto: the server that calls the AI counts the usage and reports it. My first draft had the app report "what it used". That means shipping a shared key inside the app, and any user could stop reporting — or send events against someone else's customer ID.
Count where you spend. The moment reporting is delegated to the client, the basis for the invoice rests on trust alone.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦Retry design with Cloudflare Queues and a Durable Object that reuses a pre-decided identifier (logic exercised against a mock)
✦Why Stripe has no hard usage cap per its docs, and how to enforce a monthly cap yourself
✦A prepaid-credits vs. metered-billing comparison with App Store review boundaries for choosing your model
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
You can use Billing → Meters in the dashboard, but I'll show the API so the setup is reproducible.
// One-time setup scriptconst meter = await stripe.billing.meters.create({ display_name: 'AI usage units', event_name: 'ai_usage', // key used when sending events default_aggregation: { formula: 'sum' }, // sum the `value` you send customer_mapping: { event_payload_key: 'stripe_customer_id', type: 'by_id' }, value_settings: { event_payload_key: 'value' }, // payload field holding the amount (default: value)});
The aggregation choice is something the old version of this article missed. Count counts events and ignores value. If you bill by tokens or weighted units, you need Sum. Leaving the dashboard on "count each event as 1" while sending a value means your token numbers never reach the invoice.
Fractions of a yen can't be expressed in unit_amount, so use unit_amount_decimal. I have not confirmed in test mode how a fractional yen rate is rounded on the invoice; please issue one small test invoice before launch.
Step 2: Call the AI and Report Usage from Workers
Accept only authenticated users, and look up the customer ID from your own mapping table. Never accept customerId from the client.
import Stripe from 'stripe';interface Env { STRIPE_SECRET_KEY: string; METER_RETRY: Queue<RetryPayload>;}interface RetryPayload { customerId: string; value: number; identifier: string;}function stripeClient(env: Env) { // On Workers, being explicit about the fetch-based HTTP client is the safe choice return new Stripe(env.STRIPE_SECRET_KEY, { httpClient: Stripe.createFetchHttpClient(), });}export async function sendMeterEvent(env: Env, p: RetryPayload): Promise<void> { await stripeClient(env).billing.meterEvents.create({ event_name: 'ai_usage', identifier: p.identifier, // a resend with the same identifier is treated as a duplicate payload: { stripe_customer_id: p.customerId, value: String(p.value), }, });}// Return the AI answer even if reporting fails; queue only failures a resend can fixexport async function recordUsage(env: Env, p: RetryPayload): Promise<void> { try { await sendMeterEvent(env, p); } catch (e) { if (e instanceof Stripe.errors.StripeInvalidRequestError) { console.error('meter event rejected (fix the request):', e.message); return; // malformed request; resending will not help } await env.METER_RETRY.send(p); // 5xx, rate limit, network failure }}
De-duplication relies on the Meter Event's identifier. According to the Meter Event API reference, Stripe enforces uniqueness within a rolling period of at least 24 hours. An HTTP Idempotency-Key also prevents double execution, but I prefer identifier because it works at the level of the event that justifies the invoice line.
The handler:
// Implement authenticate() for your auth stack (Supabase, etc.):// verify the JWT, get the userId, look up stripeCustomerId from your mapping.export async function handleChat(request: Request, env: Env, ctx: ExecutionContext) { const user = await authenticate(request, env); if (!user) return new Response('Unauthorized', { status: 401 }); const { message, requestId } = await request.json<{ message: string; requestId: string }>(); const answer = await callModel(message, env); // throws on failure → no charge ctx.waitUntil( recordUsage(env, { customerId: user.stripeCustomerId, value: 1, // one message = one unit identifier: `chat_${user.id}_${requestId}`, // identical on every resend }) ); return Response.json({ message: answer });}
requestId is a UUID the app generates once per send. If a double tap or a network retry delivers the same request twice, the identifier is identical and you are charged once.
Step 3: The Rork App Sends Only an Auth Token
The app holds no Stripe IDs and no shared key.
import * as Crypto from 'expo-crypto';export async function sendChatMessage(message: string, accessToken: string) { const res = await fetch('https://your-worker.example.workers.dev/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}`, // the signed-in user's token }, body: JSON.stringify({ message, requestId: Crypto.randomUUID() }), }); if (res.status === 429) throw new Error('monthly_cap_reached'); if (!res.ok) throw new Error(`chat failed: ${res.status}`); return (await res.json()) as { message: string };}
Anything in an EXPO_PUBLIC_ variable ends up in the app bundle; it is not a place for secrets. When you retry, reuse the same requestId.
Step 4: Base Fee Plus Metered Usage
Pure pay-per-use makes revenue hard to read, so I find a base fee plus metered usage easier to live with. Put a fixed price and the meter price on one subscription:
On API version 2025-03-31.basil and later, expanding latest_invoice.payment_intent no longer works and latest_invoice.confirmation_secret replaces it (that's my understanding, not verified in my environment). Adjust to the API version you pin.
Step 5: Free Allowance and Tiered Rates
The free allowance is just the first graduated tier set to 0 yen. No code changes; tiers restart each billing period.
Tier 1: 0–100 units → 0 yen (free allowance)
Tier 2: 101–500 units → 1 yen
Tier 3: 501+ units → 0.7 yen
For different allowances per plan, create one price per plan — for example 100 for Light and 500 for Standard.
Step 6: Stripe Won't Cap Spend for You
This is where my first draft was most wrong. It said you could set a spend cap in Billing Controls, and that billing_thresholds could act as a ceiling.
Reading the official docs again, I found no hard limit that stops usage:
Billing Alerts send a billing.alert.triggered webhook when usage crosses a threshold. They tell you; they don't stop anything.
billing_thresholdscreate an invoice early when a threshold is reached. They don't stop charging or usage.
So a "this month ends here" ceiling has to live in your own code. I show it together with the monthly counter in the aggregation section below. If you promise users a cap, verify first that your own code actually enforces it.
Step 7: Showing Usage in the App
Drive the number shown in the UI from your own counter rather than from Stripe. Stripe processes usage asynchronously, so aggregates may not yet include recent events (the docs give no specific delay).
To check Stripe's side, fetch daily summaries:
async function usageThisMonth(stripe: Stripe, meterId: string, customerId: string) { const now = new Date(); const start = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1) / 1000; const end = Math.floor(now.getTime() / 86400000 + 1) * 86400; // next 00:00 UTC const summaries = await stripe.billing.meters.listEventSummaries(meterId, { customer: customerId, start_time: start, end_time: end, value_grouping_window: 'day', // only 'day' or 'hour' are allowed; day aligns to 00:00 UTC }); return summaries.data.reduce((sum, s) => sum + s.aggregated_value, 0);}
The old version used value_grouping_window: 'month'; only day and hour are valid. Note too that this computes the UTC calendar month, which can differ from the billing period.
Pitfalls
Pitfall 1: Resends That Change the Idempotency Key
My first retry code built its key from a five-minute window number. If a resend crossed a window boundary, the key changed and the usage was counted twice. The fix: decide the identifier before the first send and carry it through every retry. That is why RetryPayload includes identifier.
Pitfall 2: Meter IDs Differ Between Environments
Test and live modes have different meter IDs. Keep them out of the code and in a Worker variable. process.env.NODE_ENV isn't reliable on Workers; switch via wrangler.toml vars or secrets.
Pitfall 3: Mapping App Users to Stripe Customers
Create the Stripe Customer at sign-up and store it against your app's user ID. Without that table you won't know which customer to report against.
Pitfall 4: An Accepted Event Isn't Necessarily on the Invoice
Accepting an event is not the same as it landing on an invoice. Timestamps must be within the past 35 days or up to 5 minutes in the future, and events that arrive after an invoice is finalized can show up in summaries without changing it. Invalid events are reported asynchronously (v1.billing.meter.error_report_triggered), so subscribe to that webhook.
Not Losing Failed Reports: A Retry Queue
Step 2 queued the failures a resend can fix. First wrangler.toml:
export default { async queue(batch: MessageBatch<RetryPayload>, env: Env): Promise<void> { for (const msg of batch.messages) { try { await sendMeterEvent(env, msg.body); // same identifier as the first attempt msg.ack(); } catch { msg.retry({ delaySeconds: 300 }); } } },};
Two points. Decide the identifier before the first send and reuse it on every retry. And decide up front that usage which falls into the DLQ after max_retries is not billed — I would rather under-collect a little than lose a user's trust. Since identifier uniqueness is only guaranteed for at least 24 hours, keep the total retry span inside that; this configuration is up to five attempts five minutes apart, roughly 25 minutes.
Fewer Calls: Aggregation and a Monthly Cap
Stripe's live-mode Meter Event endpoint is limited to 1,000 calls per second (the v2 event stream for high throughput is separate, at 10,000 events per second). It's worth knowing the aggregate-first design before you need it.
Give each user a Durable Object, buffer usage there, and flush it in an alarm. Keeping a monthly counter in the same place lets you do the Step 6 cap check here too.
const WINDOW_MS = 5 * 60 * 1000;export class MeterBuffer { constructor(private state: DurableObjectState, private env: Env) {} async fetch(request: Request): Promise<Response> { const store = this.state.storage; const monthKey = `month:${new Date().toISOString().slice(0, 7)}`; // UTC calendar month const monthTotal = (await store.get<number>(monthKey)) ?? 0; if (new URL(request.url).pathname === '/peek') { return Response.json({ monthTotal }); } const { customerId, value } = await request.json<{ customerId: string; value: number }>(); const pending = (await store.get<number>('pending')) ?? 0; await store.put({ [monthKey]: monthTotal + value, pending: pending + value, customerId }); if ((await store.getAlarm()) === null) { await store.setAlarm(Date.now() + WINDOW_MS); } return Response.json({ monthTotal: monthTotal + value }); } async alarm(): Promise<void> { const store = this.state.storage; const sending = (await store.get<number>('pending')) ?? 0; if (sending <= 0) return; const customerId = (await store.get<string>('customerId'))!; const seq = (await store.get<number>('seq')) ?? 0; // If this throws, the alarm is retried automatically with the same seq and identifier await sendMeterEvent(this.env, { customerId, value: sending, identifier: `flush_${customerId}_${seq}`, }); // Keep what arrived during the send; subtract only what was sent const rest = ((await store.get<number>('pending')) ?? 0) - sending; await store.put({ pending: Math.max(rest, 0), seq: seq + 1 }); if (rest > 0) await store.setAlarm(Date.now() + WINDOW_MS); }}
My first draft deleted the key after sending, which also deleted any usage added while the Stripe call was in flight. It also derived its window number from the clock, so an alarm retry could produce a different identifier. Advancing a sequence number only on a successful send closes both holes at once.
Aggregation has a cost: Stripe lags by up to a window. Read the number you show users from the Durable Object's monthTotal, and treat Stripe as the basis for the invoice. With aggregation in place the alarm owns retries, so the queue above drops out of the path.
What I ran: I exercised this Durable Object logic against a mock of storage, alarms, and Stripe, and confirmed that (1) a failed send is resent with the same identifier, (2) usage added mid-send is not lost, and (3) the sequence number advances only after success. Behavior on real Cloudflare and real latency are not verified.
Choosing the Unit
The unit is the most hands-on design decision here.
AI chat — one message, one unit, is easiest for users to grasp. Token billing is more accurate but needs thought in how you present it.
Image or video generation — weight by how heavy the operation is.
Transcription and summaries — use minutes of audio.
const OPERATION_WEIGHTS = { text: 1, image: 5, audio_minute: 2,} as const; // placeholder weights — derive real ones from your cost ratios// e.g. an image generation is 5 unitsawait buffer.fetch('https://do/add', { method: 'POST', body: JSON.stringify({ customerId, value: OPERATION_WEIGHTS.image }),});
When costs change, you only edit this constant; the meter and the price stay as they are.
Prepaid Credits as the Alternative
There is a second way to charge fairly: sell usage up front, like "500 yen for 100 messages". Which fits is mostly decided by how you distribute the app, so here is the comparison.
Aspect
Metered billing (Stripe Meter)
Prepaid credits (consumable IAP)
Revenue timing
Postpaid — billed at period end
Prepaid — locked in at purchase
User psychology
"What will this month cost me?" anxiety
Fixed spend, known up front
iOS-only apps
Limited applicability under Guideline 3.1.1
Rides the App Store's standard machinery
Engineering focus
Reliable reporting and aggregation
Balance ledger, restore flows, expiry policy
Unused allowance
Never exists
Needs an expiry and refund policy
B2B and web expansion
Extends to invoicing and API billing
Needs a separate web checkout path
My own split: digital features consumed entirely inside an iOS app get consumable IAP credits; once you have a web version or a B2B API, Stripe Meter earns its keep. Billing for digital services consumed inside an app generally has to go through In-App Purchase (App Store Review Guidelines 3.1.1). Treatment of external payments varies by region and has been changing, so please read the current text before you submit.
If you sell on both, unify the internal usage counter: the app draws down credit balance, web users pay by Meter afterward. Prepaid also makes revenue certain at purchase, which helps cash flow if you front the AI API costs.
Pre-Launch Checklist
The Step 2 Worker accepts no unauthenticated requests.
You have issued an invoice for a small amount of usage to confirm the free allowance and tiered rates.
Your own monthly cap behaves correctly just below and just above the limit.
You receive webhooks for billing.alert.triggered and v1.billing.meter.error_report_triggered.
Terms and onboarding state the model plainly — "first 100 free, then 1 yen each".
First, the cost-to-revenue ratio: compare your AI API bills with metered revenue. As a starting point, treat cost above about 40% of revenue as a warning line, then re-set it for your own margins.
function costRatio(aiApiCost: number, meteredRevenue: number) { const ratio = meteredRevenue > 0 ? aiApiCost / meteredRevenue : Infinity; return { ratio, status: ratio < 0.4 ? 'healthy' : ratio < 0.6 ? 'warning' : 'critical' } as const;}
Second, free-allowance consumption: telling people in-app at 80% means no bill-day surprises, and it doubles as a natural path to a higher plan.
Third, outliers: a user at 10× the average is either a devoted fan or automated abuse. Set Billing Alerts at a few times the average, and when the webhook arrives, look at when the usage happened.
Where to Start
Create one meter in Stripe test mode and send a few events by hand. Send the same identifier twice and watch the duplicate collapse into one — that alone explains half of this design. It's where I started when re-checking my own.
Share
Thank You for Reading
Rork Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.