TL;DR: Usage-based billing (metered billing) charges customers based on API consumption — requests, storage, compute time, or users. Stripe's metered billing integration with TanStack Start makes this straightforward. This guide covers metering architecture, pricing models (per-request, tiered, overage), and developer portal design.
Introduction
Usage-based billing aligns your revenue with the value customers receive. Small users pay little; power users pay more. This model is standard for API products (Twilio, Stripe, OpenAI) and increasingly adopted by SaaS platforms.
Metering Architecture
// API usage metering middleware
export const meterApiUsage = defineMiddleware({
before: async ({ request, context }) => {
const apiKey = request.headers.get('x-api-key')
const user = await getUserByApiKey(apiKey)
// Record usage event
context.metering = {
userId: user.id,
endpoint: request.url,
timestamp: Date.now(),
}
},
after: async ({ context }) => {
// Increment usage counter in D1
await db.insertInto('api_usage').values({
user_id: context.metering.userId,
endpoint: context.metering.endpoint,
timestamp: context.metering.timestamp,
}).execute()
},
})
Pricing Models
| Model | Example | Best For |
|---|---|---|
| Per-request | $0.01/API call | Simple APIs |
| Tiered | First 10K free, then $0.005 | High-volume APIs |
| Overage | $29/mo includes 50K, $0.001/call beyond | SaaS + API |
| Per-unit | $10/GB stored | Storage products |
| Concurrent | $50/seat | Collaboration APIs |
Stripe Metered Billing
import Stripe from 'stripe'
// Report usage to Stripe
await stripe.subscriptionItems.createUsageRecord(
subscriptionItemId,
{
quantity: apiCalls,
timestamp: 'now',
action: 'increment',
}
)
Conclusion
Usage-based billing aligns pricing with value. The metering infrastructure — track usage, report to Stripe, display in a dashboard — is straightforward with TanStack Start server functions and Stripe's metered billing API. For a complete billing strategy, see our Stripe Billing guide and SaaS Pricing Tier Strategy.