How to build a credit system for a Next.js AI app (Stripe + Supabase)
If you're building an AI app (image generation, transcription, an agent, anything that calls a model) you've probably realized a flat "$10/month" doesn't work. Every action costs you real money in GPU/API spend, so a single power user can torch your margins. The answer is usage credits : users buy a balance, each action spends some. Credits sound trivial. They are not. I've shipped about 10 small AI/SaaS apps, and the credit layer is where I got burned every single time. It took three patterns to fix it for good. Here they are, with copy-pasteable code for Next.js + Supabase + Stripe. Get these right and your billing won't oversell, double-charge, or strand a user's money. The three things everyone gets wrong Overdrawing. Two requests arrive at once, both read "balance = 1," both spend. Now the balance is negative and you gave away work for free. Double-granting. Stripe retries webhooks (it will ), and if you grant credits on every delivery, a $9 purchase becomes $18 of credits. Forgetting the refund. The AI job fails after you've already charged the credits. The user paid for nothing and emails you angry. Let's kill all three. Part 1. The atomic spend (overdraw becomes impossible) The mistake is doing the check in your app code: // DON'T: read-then-write has a race condition const { balance } = await getBalance ( userId ); if ( balance < cost ) throw new Error ( " insufficient " ); await setBalance ( userId , balance - cost ); // two concurrent requests both pass the check Do it in the database, in one statement, with the guard in the WHERE clause: -- balances: one row per user create table credit_balances ( user_id uuid primary key references auth . users ( id ) on delete cascade , balance integer not null default 0 check ( balance >= 0 ), updated_at timestamptz not null default now () ); -- append-only ledger = audit log + idempotency guard (see Part 2) create table credit_ledger ( id bigint generated always as identity primary key , user_id uuid not null referen