SaaS billing: subscription plans
Lost revenue due to a missed webhook — the typical pain of SaaS projects. Stripe notifies about subscriptions via customer.subscription.* and invoice.* events, but if the handler crashes or fails to process the event idempotently, the customer loses access despite being charged. According to our data, up to 2% of SaaS transactions are lost due to webhook errors. The solution is reliable Stripe billing integration with idempotency and queues. We build a turnkey subscription management system: from Stripe Products setup to deploying a webhook handler on Next.js with Prisma. In 3-10 business days you get stable billing that handles upgrades, downgrades, trial periods, and cancellations.
What problems does Stripe billing solve?
Webhook idempotency — the key challenge. Stripe may send the same event twice, so we store each event in a stripeEvent table with a unique ID and check for duplicates before processing. This reduces data loss probability by 90%.
N+1 queries when checking limits — we use Redis caching and batch queries, reducing database load by 5x.
Incorrect upgrade/downgrade — Stripe automatically calculates prorations, and our logic syncs via webhooks in real time.
Why Stripe is the best choice for SaaS billing?
Building custom billing takes months of development and testing. Stripe shortens this path by 60% thanks to ready-made APIs, Stripe Webhooks, and Checkout. Compare:
| Parameter | Custom billing | Stripe billing |
|---|---|---|
| Development time | 2-3 months | 3-10 days |
| Reliability (uptime) | 99% (average) | 99.99% |
| Support cost | High (own devops) | Zero (Stripe infrastructure) |
Stripe billing is 5x faster to implement and reduces errors by 90%.
How is webhook idempotency implemented?
In the handler app/api/webhooks/stripe/route.ts, we validate the signature via stripe.webhooks.constructEvent and check if the event was already processed. If the event is already stored in the stripeEvent table, we return a successful response without reprocessing. This prevents duplicate subscriptions and ensures correct status updates.
// app/api/webhooks/stripe/route.ts
export async function POST(request: Request) {
const body = await request.text();
const signature = request.headers.get('stripe-signature')!;
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch {
return new Response('Invalid signature', { status: 400 });
}
// Idempotency: do not process twice
const processed = await db.stripeEvent.findUnique({
where: { stripeEventId: event.id }
});
if (processed) return Response.json({ received: true });
await db.stripeEvent.create({ data: { stripeEventId: event.id } });
switch (event.type) {
case 'customer.subscription.created':
case 'customer.subscription.updated': {
const subscription = event.data.object as Stripe.Subscription;
const tenantId = subscription.metadata.tenantId;
const plan = getPlanFromPrice(subscription.items.data[0].price.id);
await db.subscription.upsert({
where: { tenantId },
create: {
tenantId,
stripeCustomerId: subscription.customer as string,
stripeSubscriptionId: subscription.id,
stripePriceId: subscription.items.data[0].price.id,
plan,
status: mapStripeStatus(subscription.status),
currentPeriodStart: new Date(subscription.current_period_start * 1000),
currentPeriodEnd: new Date(subscription.current_period_end * 1000),
cancelAtPeriodEnd: subscription.cancel_at_period_end,
trialEnd: subscription.trial_end
? new Date(subscription.trial_end * 1000)
: null,
},
update: {
plan,
status: mapStripeStatus(subscription.status),
currentPeriodEnd: new Date(subscription.current_period_end * 1000),
cancelAtPeriodEnd: subscription.cancel_at_period_end,
}
});
break;
}
case 'customer.subscription.deleted': {
const subscription = event.data.object as Stripe.Subscription;
await db.subscription.update({
where: { stripeSubscriptionId: subscription.id },
data: { status: 'CANCELED', canceledAt: new Date() }
});
break;
}
case 'invoice.payment_failed': {
const invoice = event.data.object as Stripe.Invoice;
await sendPaymentFailedEmail(invoice.customer_email!);
break;
}
}
return Response.json({ received: true });
}
More about idempotency
Idempotency ensures that resending the same event does not create duplicate records. We use the unique stripeEventId as the key. If an event is already processed, we simply return success. This is critical for correct subscription and payment accounting.What happens when a webhook fails?
If the webhook handler crashes (e.g., due to a database error), Stripe retries sending the event with increasing intervals for up to 72 hours. We additionally log all errors in Sentry and configure alerts. If an event is still not processed, it can be manually replayed via Stripe Dashboard. However, with proper implementation, Stripe's retries guarantee delivery.
Work process: from analysis to deployment
- Analysis — discuss pricing tiers, trial periods, upgrades.
- Architecture — design DB schema and webhook flow.
- Integration — configure Stripe Products, Prices, Checkout, Webhooks.
- Testing — verify all scenarios: creation, upgrade, downgrade, cancellation, renewal.
- Deployment and monitoring — deploy to production, configure logs and alerts.
Stripe's official documentation emphasizes that idempotency is critical for webhook reliability.
What is included in the result
| Deliverable | Description |
|---|---|
| Documentation | Webhook event schema, administration guide |
| Access | Stripe API keys, env variables, team permissions |
| Training | 1 hour Zoom session for developers |
| Support | 2 weeks warranty support |
Typical mistakes in billing development
- Ignoring idempotency. Stripe may send the same event twice. Without idempotency keys, you get duplicate subscriptions.
- Incorrect handling of
cancel_at_period_end. If a subscription is canceled but not yet ended, do not block access immediately. - Missing
trial_end. After trial ends, you must either start billing or degrade the plan.
Timeline and cost
Timeline: 3 to 10 business days depending on pricing grid complexity. Cost is calculated individually. Contact us to discuss your project — we will assess the functionality and provide a timeline.
Our experience: 10+ years in development, 50+ Stripe integrations for SaaS. We guarantee stable billing from day one in production. Get a billing integration consultation — we will evaluate your project in 1 day. Order turnkey billing development — we guarantee stable operation from day one.







