Understanding Usage-Based Billing for AI Products
Usage-based billing charges customers according to actual consumption rather than fixed monthly fees. For AI SaaS applications this typically means metering tokens processed by LLMs, images generated, or API calls made. The model aligns costs with value delivered and reduces upfront commitment for users.
Stripe supports this through metered prices attached to subscriptions. Each price can define a usage type of licensed or metered. When set to metered, Stripe aggregates reported usage and generates invoices at the end of each billing period. You report usage via the subscriptionItems.createUsageRecord API endpoint.
Common pricing dimensions for AI products include separate rates for input tokens, output tokens, and fine-tuning hours. A single subscription item can report multiple dimensions using the quantity field combined with distinct price IDs, or you can report aggregated "compute units" that map to your internal cost model.
Trade-offs are clear. Customers appreciate paying only for what they use, which improves conversion for uncertain buyers. However, revenue becomes less predictable month-to-month. You must implement usage tracking, storage, and guardrails to prevent unexpected large bills. Stripe adds a small percentage fee on top of usage charges, and you are responsible for accurate metering to avoid disputes.
Next.js applications benefit from server actions and route handlers to report usage immediately after an AI call completes. This approach keeps the client bundle small and allows secure access to the Stripe secret key on the server.
Setting Up Metered Products in Stripe Dashboard
Begin in the Stripe dashboard by navigating to Products. Create a new product named "AI Platform Pro". Add a recurring price with billing scheme set to "per unit" and usage type "metered". Choose an aggregate usage type of "sum" so Stripe adds all reported quantities during the billing period.
For token-based pricing, create two prices: one for input tokens at $0.000001 per token (adjust according to your margins) and one for output tokens at a higher rate. Record the Price IDs — these are required for reporting usage against the correct meter. Use test mode first; the test Price IDs begin with price_1.
Configure billing period to monthly. Enable automatic tax calculation if you operate in multiple jurisdictions. Set invoice settings to include a custom PDF footer with your support contact. These settings are accessible later via the API but easier to configure in the dashboard initially.
After creation, note your webhook endpoint needs. Stripe will send invoice.created, invoice.paid, customer.subscription.updated and invoice.payment_failed events. You will handle these in a dedicated Next.js route handler.
Database Schema for Subscriptions and Usage Tracking
A robust database schema prevents double-reporting and enables usage dashboards. Using Drizzle ORM, define two tables: subscriptions and usage_records.
export const subscriptions = pgTable('subscriptions', {
id: text('id').primaryKey(),
userId: text('user_id').notNull(),
stripeSubscriptionId: text('stripe_subscription_id').notNull().unique(),
stripeCustomerId: text('stripe_customer_id').notNull(),
status: text('status', { enum: ['active', 'canceled', 'past_due'] }).notNull(),
currentPeriodStart: timestamp('current_period_start').notNull(),
currentPeriodEnd: timestamp('current_period_end').notNull(),
createdAt: timestamp('created_at').defaultNow(),
});
export const usageRecords = pgTable('usage_records', {
id: serial('id').primaryKey(),
subscriptionId: text('subscription_id').references(() => subscriptions.id),
eventId: text('event_id').notNull().unique(), // idempotency key
tokenType: text('token_type', { enum: ['input', 'output'] }).notNull(),
quantity: integer('quantity').notNull(),
recordedAt: timestamp('recorded_at').defaultNow(),
model: text('model'),
});
The eventId field stores a unique identifier from your application (for example a UUID generated before each AI call). This prevents accidental duplicate usage reports if your webhook or server action retries. Add indexes on userId and stripeSubscriptionId for fast lookups.
Store the mapping between your internal user and Stripe customer ID at signup time. When a user upgrades, create the Stripe subscription via the API and insert the record. This table lets you display current period usage without repeated calls to the Stripe API, which has rate limits.
Creating and Managing Subscriptions in Next.js Server Actions
Use server actions to create Stripe Checkout sessions or customer portal sessions. Install the Stripe library with npm install stripe@14.5.0 and initialize it once outside request handlers to reuse the instance.
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2024-06-20',
typescript: true,
});
export async function createCheckoutSession(userId: string, priceId: string) {
const customer = await getOrCreateStripeCustomer(userId);
const session = await stripe.checkout.sessions.create({
customer: customer.id,
mode: 'subscription',
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${process.env.NEXT_PUBLIC_URL}/dashboard?success=true`,
cancel_url: `${process.env.NEXT_PUBLIC_URL}/pricing`,
subscription_data: {
metadata: { userId },
},
});
return { url: session.url };
}
The getOrCreateStripeCustomer function checks your database first, then calls stripe.customers.create if needed. Pass the internal userId as metadata so webhook handlers can map events back to your users. After successful checkout, Stripe sends a checkout.session.completed event that you use to activate the subscription record.
For existing subscribers who want to upgrade or downgrade, use Stripe's Customer Portal instead of building custom forms. This reduces your compliance burden around PCI and billing UI.
Reporting Usage After AI Operations
The core of metered billing is accurate usage reporting. After every LLM call, immediately report the tokens consumed. Place this logic in a shared service function.
async function reportUsage(
subscriptionItemId: string,
inputTokens: number,
outputTokens: number,
model: string,
idempotencyKey: string
) {
if (inputTokens > 0) {
await stripe.subscriptionItems.createUsageRecord(
subscriptionItemId,
{
quantity: inputTokens,
timestamp: 'now',
action: 'increment',
},
{ idempotencyKey: `input-${idempotencyKey}` }
);
}
if (outputTokens > 0) {
await stripe.subscriptionItems.createUsageRecord(
subscriptionItemId,
{
quantity: outputTokens,
timestamp: 'now',
action: 'increment',
},
{ idempotencyKey: `output-${idempotencyKey}` }
);
}
// Also persist to your database for dashboard
await db.insert(usageRecords).values([
{ subscriptionId: '...', eventId: `input-${idempotencyKey}`, tokenType: 'input', quantity: inputTokens, model },
{ subscriptionId: '...', eventId: `output-${idempotencyKey}`, tokenType: 'output', quantity: outputTokens, model },
]);
}
Use separate idempotency keys for input and output to allow independent retries. The action: 'increment' tells Stripe to add to the existing total rather than set an absolute value. Call this function from both API routes and server actions after successful model inference. For batch jobs, aggregate usage before reporting to reduce API calls.
Trade-off: reporting after every request adds latency (typically 80-150ms). For high-throughput applications, queue reports using BullMQ or Inngest and process in batches every 30 seconds. This reduces Stripe API load but increases complexity around failure recovery.
Implementing Usage Limits and Guardrails
Prevent runaway usage with soft and hard limits. Query the user's current usage from your database before allowing an AI request. For a soft limit, show warnings when the user reaches 80% of their included usage. For a hard limit, reject requests and prompt upgrade.
Calculate current usage with a simple aggregation query:
const currentUsage = await db
.select({
totalInput: sql`sum(quantity)`,
})
.from(usageRecords)
.where(and(
eq(usageRecords.subscriptionId, sub.id),
gte(usageRecords.recordedAt, sub.currentPeriodStart)
));
Compare against limits stored in a plan_limits table. Different plans can have different monthly token allotments. For users on usage-based plans without included credits, you may still enforce absolute rate limits (for example 10 requests per minute) to protect infrastructure.
Store these limits in Redis for sub-10ms reads in hot paths. Invalidate the cache when usage records are written or when the billing period rolls over. This pattern avoids database load on every AI call while still providing accurate enforcement.
Processing Stripe Webhooks in Next.js Route Handlers
Webhooks are the source of truth for subscription state changes. Create an API route at app/api/stripe/webhook/route.ts that only accepts POST requests.
export async function POST(req: Request) {
const body = await req.text();
const signature = req.headers.get('stripe-signature')!;
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (err) {
return new Response(`Webhook signature verification failed.`, { status: 400 });
}
switch (event.type) {
case 'invoice.paid':
await handleSuccessfulPayment(event.data.object as Stripe.Invoice);
break;
case 'customer.subscription.updated':
await updateSubscriptionRecord(event.data.object as Stripe.Subscription);
break;
case 'invoice.payment_failed':
await handlePaymentFailure(event.data.object as Stripe.Invoice);
break;
}
return new Response('Success', { status: 200 });
}
The STRIPE_WEBHOOK_SECRET is unique per endpoint and must be kept server-only. Use the raw body (via req.text()) for signature verification; parsing to JSON first breaks the signature. Implement each handler to update your database, send emails, or revoke access. Idempotency is automatic because Stripe sends the same event with the same id on retries; check whether you already processed that event ID.
Test webhooks locally using the Stripe CLI command: stripe listen --forward-to localhost:3000/api/stripe/webhook. The CLI provides a temporary webhook secret you can swap into your .env.local file.
Building Usage Dashboard with Real-Time Updates
Users need visibility into their consumption. Create a dashboard page that displays tokens used this month, cost accrued, and projected end-of-month spend. Fetch data from your database rather than Stripe to reduce latency and API costs.
Use Server Components to load initial data, then TanStack Query on the client for live updates after each AI interaction. Show separate charts for input versus output tokens using Recharts. Add a breakdown by model so users understand which features drive cost.
For projected spend, apply the same per-token rates you configured in Stripe. Show this number with a note that it is an estimate and final invoice may differ due to taxes or rounding. Include a prominent "Upgrade plan" button that opens the Stripe Customer Portal.
Portal sessions are created via another server action:
export async function createPortalSession(customerId: string) {
const session = await stripe.billingPortal.sessions.create({
customer: customerId,
return_url: `${process.env.NEXT_PUBLIC_URL}/dashboard`,
});
return { url: session.url };
}
This gives users self-serve access to update payment methods, download invoices, and cancel subscriptions without you building those UI flows.
Securing API Keys and Multi-Tenancy Considerations
Never expose your Stripe secret key to the client. All usage reporting and subscription management must happen server-side. For teams and enterprise customers, implement per-project API keys that map to specific subscription items. When a user calls your AI API with a project key, resolve the underlying Stripe subscription item ID and report usage against it.
Use Stripe's customer.subscriptionItems list API sparingly. Cache subscription item IDs in your database after the initial webhook processing. Rotate your Stripe webhook secret quarterly and use separate secrets for production and staging.
Rate-limit your own usage reporting endpoint to 100 requests per second per user to protect against accidental loops in customer code. Log all reported usage with timestamps and model names for audit purposes. This data also helps you negotiate better rates with upstream LLM providers.
Production Deployment and Observability
Deploy the webhook handler to a region close to Stripe's servers (usually us-east-1) to minimize verification latency. Use Vercel Edge Config or Upstash Redis for caching subscription state. Monitor webhook processing latency with OpenTelemetry spans on the critical path.
Set up Stripe Radar rules to flag unusual usage spikes that might indicate token farming or abuse. Combine this with your own application-level anomaly detection that alerts on sudden increases in tokens per user.
Handle subscription pauses gracefully. When a customer pauses their subscription, Stripe stops metering until reactivation. Your usage dashboard should reflect the paused state and hide the current period usage graph. On reactivation, the next billing cycle begins with a fresh meter.
Finally, test the entire end-to-end flow in Stripe test mode with synthetic token counts. Simulate high-volume usage by running a script that reports 10,000 usage records in batches. Verify that invoices match your internal calculations. Once confident, flip to production keys and start with a small cohort of paying customers before opening to all users.
This implementation scales to thousands of concurrent users when usage reporting is queued and database writes are batched. The combination of Stripe's reliable metering, Next.js server actions for fast iteration, and your own usage database for instant dashboards provides a production-grade billing foundation for any AI SaaS product.
