ai newsMi., 25. Nov.
EilmeldungCan Claude’s storage webhooks miss an hour-long outage?

Why a Simple `credits` Column Breaks in AI Apps (Two-Phase Holds, FIFO Lots & Stripe Refunds)

Every AI app that moves past flat subscriptions starts the same way: ALTER TABLE users ADD COLUMN credits INTEGER NOT NULL DEFAULT 50 ; You wire up a Stripe Checkout webhook that runs UPDATE users SET credits = credits + 500 , and on every /api/generate route you run: if ( user . credits 10 ) retur

dev.toMontag 00:01 · 23.11.5 Min. Lesezeit
Bild: dev.to

Every AI app that moves past flat subscriptions starts the same way:

ALTER TABLE users ADD COLUMN credits INTEGER NOT NULL DEFAULT 50; Enter fullscreen mode Exit fullscreen mode You wire up a Stripe Checkout webhook that runs UPDATE users SET credits = credits + 500, and on every /api/generate route you run:

if ( user. credits < 10 ) return Response. json ( { error: 'Out of credits' }, { status: 402 } ); await db. query ( 'UPDATE users SET credits = credits - 10 WHERE id = $1', [ user. id ] ); const result = await callOpenAI ( prompt ); Enter fullscreen mode Exit fullscreen mode It works cleanly in development. Then real users show up, and five failure modes hit back-to-back.

A user with 10 credits double-clicks "Generate" (or opens two tabs and hits both within 40ms). Both requests read credits = 10, both pass if (user.credits < 10), and both fire an expensive video/image generation call.

Now your user got two generations for the price of one—or their balance went negative ( -10 ).

The fix: Never read-then-write in application code. Lock the wallet row inside a single database transaction ( SELECT... FOR UPDATE ) or use an atomic conditional decrement before calling the upstream model.

AI providers fail constantly—rate limits, 502s, dropped streams, and 60-second timeouts.

The fix: Two-Phase Holds (Reserve → Settle / Refund)

Model every AI call like a hotel pre-authorization:

1. Reserve ──▶ Lock wallet row in Postgres, hold 10 credits (status = 'pending', TTL = 5m) 2. Execute ──▶ Call OpenAI / Anthropic / Replicate / Fal 3a.

Success ──▶ Settle hold (deduct exact usage, refund any unused reserved credits) 3b. Error ──▶ Refund hold (restore credits back to the exact original lots) 3c. Crash ──▶ Background TTL sweep releases expired holds automatically Enter fullscreen mode Exit fullscreen mode Reserve the maximum expected credits up front inside a transaction ( status = 'pending', with an expires_at TTL).

Run your AI call. Settle on success (even adjusting for actual token/second usage and refunding unused reserved credits), or Refund on error. If your Node process crashes mid-request and never calls settle or refund, a background TTL sweep releases expired holds automatically.

3. Mixed Expiration Rules Break a Single Integer Column Almost every mature AI product ends up mixing at least two of these in the same wallet:

If you store all of those in a single users.credits integer, you cannot know which credits should burn first. Worse, if you burn permanent paid credits before expiring free credits, users feel cheated the moment their free allowance expires.

Instead of one integer, store credit lots with remaining_amount and expires_at (NULL for permanent packs), and deduct soonest-expiring first:

SELECT id, remaining_amount FROM credit_lots WHERE wallet_id = $1 AND remaining_amount > 0 AND ( expires_at IS NULL OR expires_at > NOW ( ) ) ORDER BY expires_at ASC NULLS LAST, created_at ASC FOR UPDATE; Enter fullscreen mode Exit fullscreen mode When a hold is refunded after an upstream crash, you restore the exact amounts back to the exact lot_id s they came from—preserving every lot's original expiration date.

Suppose a customer buys a 1,000-credit pack for $20, spends 200 credits, and asks for a 50% refund ($10) in Stripe.

Without lot-level attribution (linking each credit_lots row to its stripe_payment_intent_id / stripe_charge_id ), your charge.refunded webhook has no clean way to claw back the exact proportional 500 credits —or freeze the wallet automatically on charge.dispute.created so a chargeback user can't keep burning your GPU bill.

Most AI apps charge one credit currency across multiple features ( chat = 1 cr, generate_image = 5 cr, generate_video = 25 cr ).

When you discount your largest credit pack (say $29 for 5,000 credits = 0.58¢ per credit), after Stripe's 2.9% + 30¢, a 25-credit video call only nets you ~13¢. If your video model costs 18¢ per run, your best customers lose you money on every single click.

Tracking your_api_cost_cents per action alongside your cheapest pack's effective net price per credit catches negative-margin actions before launch.

If you want to build this yourself, the core schema is 4 tables ( wallets, credit_lots, credit_holds, ledger_events ) plus a Stripe webhook handler with idempotency keys on event.id.

If you'd rather skip building and maintaining all of that yourself, I packaged this exact architecture into CreditKit —with a Postgres FIFO ledger, two-phase holds, per-action margin alerts, a drop-in paywall, and Stripe Direct Charges straight to your own Stripe account ($0/mo + 3% only when users buy).

In a Next.js App Router route, the entire reserve → execute → settle/refund loop collapses to one call:

// app/api/generate/route.ts import { credits } from '@/lib/creditkit'; import { getCurrentUser } from '@/lib/current-user'; export async function POST ( req: Request ) { const user = await getCurrentUser ( ); if (! user ) return Response. json ( { error: 'Sign in first' }, { status: 401 } ); const run = await credits. withCrashProofHold ( { req, userId: user. id, email: user. email, action: 'generate_image' }, async ( ) => { return await callYourAiModel ( ); // Throws? Credits auto-refund to exact lots. } ); if ( run. outcome === 'insufficient_credits' ) { return Response. json ( run, { status: 402 } ); // Opens the paywall automatically } if ( run. outcome!== 'ok' ) { return Response. json ( { error: 'Generation failed — credits refunded.' }, { status: 500 } ); } return Response. json ( run. data ); } Enter fullscreen mode Exit fullscreen mode If you want to try the full pattern locally in 2 minutes (including a "Simulate AI crash → auto-refund" button), I open-sourced a clean Next.js App Router starter here:

How are you handling failed LLM runs and credit expiration in your AI apps today? Happy to trade notes in the comments.

Expand Abdullah Naseer Abdullah Naseer Abdullah Naseer Follow Indie builder from Pakistan. First app: ShiftLog — free shift & profit tracker for gig workers. https://play.google.com/store/apps/details?id=com.shiftlog.app Joined Oct 26, 2026 • Nov 22 Dropdown menu Copy link Hide The FIFO lot ledger is the part I'd steal first — mixing daily free credits with never-expiring top-ups in a single integer is exactly the kind of thing that works until it quietly doesn't. One question on the two-phase hold: with a 5-minute TTL, what happens when the upstream model is slow but not dead — say a video render that takes 6 minutes? Do you extend the hold, or settle on a partial result? Curious how you picked the TTL when the costliest calls are also the slowest.

Quelle: dev.to (dev.to). Original öffnen