{"slug": "why-a-simple-credits-column-breaks-in-ai-apps-two-phase-holds-fifo-lots-stripe", "title": "Why a Simple `credits` Column Breaks in AI Apps (Two-Phase Holds, FIFO Lots & Stripe Refunds)", "summary": "A developer outlined a four-table schema (wallets, credit_lots, credit_holds, ledger_events) for handling AI app billing, arguing that a single integer credits column fails under concurrency, provider failures, expiring credits, Stripe refunds and per-action margins. The approach uses two-phase holds (reserve, then settle or refund with a TTL sweep), a FIFO credit-lot ledger that spends soonest-expiring credits first and restores refunds to their original lots, and per-action cost tracking to catch negative-margin generations.", "body_md": "Every AI app that moves past flat subscriptions starts the same way:\n\n```\nALTER TABLE users ADD COLUMN credits INTEGER NOT NULL DEFAULT 50;\n```\n\nYou wire up a Stripe Checkout webhook that runs `UPDATE users SET credits = credits + 500`, and on every `/api/generate` route you run:\n\n```\nif (user.credits < 10) return Response.json({ error: 'Out of credits' }, { status: 402 });\nawait db.query('UPDATE users SET credits = credits - 10 WHERE id = $1', [user.id]);\nconst result = await callOpenAI(prompt);\n```\n\nIt works cleanly in development. Then real users show up, and **five failure modes** hit back-to-back.\n\nA 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.\n\nNow your user got two generations for the price of one—or their balance went negative (`-10`).\n\n**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.\n\nAI providers fail constantly—rate limits, 502s, dropped streams, and 60-second timeouts.\n\n**The fix: Two-Phase Holds (Reserve → Settle / Refund)**\n\nModel every AI call like a hotel pre-authorization:\n\n```\n1. Reserve  ──▶ Lock wallet row in Postgres, hold 10 credits (status = 'pending', TTL = 5m)\n2. Execute  ──▶ Call OpenAI / Anthropic / Replicate / Fal\n3a. Success ──▶ Settle hold (deduct exact usage, refund any unused reserved credits)\n3b. Error   ──▶ Refund hold (restore credits back to the exact original lots)\n3c. Crash   ──▶ Background TTL sweep releases expired holds automatically\n```\n\n`status = 'pending'`, with an `expires_at` TTL).\nAlmost every mature AI product ends up mixing at least two of these in the same wallet:\n\nIf 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.\n\n**The fix: A FIFO Credit Lot Ledger**\n\nInstead of one integer, store **credit lots** with `remaining_amount` and `expires_at` (NULL for permanent packs), and deduct **soonest-expiring first**:\n\n```\nSELECT id, remaining_amount\nFROM credit_lots\nWHERE wallet_id = $1\n  AND remaining_amount > 0\n  AND (expires_at IS NULL OR expires_at > NOW())\nORDER BY\n  expires_at ASC NULLS LAST,\n  created_at ASC\nFOR UPDATE;\n```\n\nWhen 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.\n\nSuppose a customer buys a 1,000-credit pack for $20, spends 200 credits, and asks for a 50% refund ($10) in Stripe.\n\nWithout 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.\n\nMost AI apps charge one credit currency across multiple features (`chat = 1 cr`, `generate_image = 5 cr`, `generate_video = 25 cr`).\n\nWhen 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**.\n\nTracking `your_api_cost_cents` per action alongside your cheapest pack's effective net price per credit catches negative-margin actions before launch.\n\nIf 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`.\n\nIf you'd rather skip building and maintaining all of that yourself, I packaged this exact architecture into **[CreditKit](https://creditkit.dev)**—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).\n\nIn a Next.js App Router route, the entire reserve → execute → settle/refund loop collapses to one call:\n\n``` js\n// app/api/generate/route.ts\nimport { credits } from '@/lib/creditkit';\nimport { getCurrentUser } from '@/lib/current-user';\n\nexport async function POST(req: Request) {\n  const user = await getCurrentUser();\n  if (!user) return Response.json({ error: 'Sign in first' }, { status: 401 });\n\n  const run = await credits.withCrashProofHold(\n    { req, userId: user.id, email: user.email, action: 'generate_image' },\n    async () => {\n      return await callYourAiModel(); // Throws? Credits auto-refund to exact lots.\n    }\n  );\n\n  if (run.outcome === 'insufficient_credits') {\n    return Response.json(run, { status: 402 }); // Opens the paywall automatically\n  }\n  if (run.outcome !== 'ok') {\n    return Response.json({ error: 'Generation failed — credits refunded.' }, { status: 500 });\n  }\n  return Response.json(run.data);\n}\n```\n\nIf 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:\n\nHow are you handling failed LLM runs and credit expiration in your AI apps today? Happy to trade notes in the comments.", "url": "https://wpnews.pro/news/why-a-simple-credits-column-breaks-in-ai-apps-two-phase-holds-fifo-lots-stripe", "canonical_source": "https://dev.to/dchin/why-a-simple-credits-column-breaks-in-ai-apps-two-phase-holds-fifo-lots-stripe-refunds-23d6", "published_at": "2026-11-22 23:01:22+00:00", "updated_at": "2026-11-22 23:11:41.558453+00:00", "lang": "en", "topics": ["ai-products", "ai-tools", "developer-tools", "ai-infrastructure"], "entities": ["Stripe", "OpenAI", "Anthropic", "Replicate", "Fal", "Postgres"], "also_reported_by": [], "takeaway": "Model AI credits as a FIFO lot ledger with two-phase holds (reserve, settle or refund, TTL sweep) instead of a single integer column, so concurrent requests can't double-spend and refunds restore exact lots and expirations.", "recommendation": {"advice": "Replace read-then-write credit decrements with a locked, atomic reserve/settle/refund hold, and track per-action API cost against your cheapest pack's net price to catch negative-margin generations.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/why-a-simple-credits-column-breaks-in-ai-apps-two-phase-holds-fifo-lots-stripe", "markdown": "https://wpnews.pro/news/why-a-simple-credits-column-breaks-in-ai-apps-two-phase-holds-fifo-lots-stripe.md", "text": "https://wpnews.pro/news/why-a-simple-credits-column-breaks-in-ai-apps-two-phase-holds-fifo-lots-stripe.txt", "jsonld": "https://wpnews.pro/news/why-a-simple-credits-column-breaks-in-ai-apps-two-phase-holds-fifo-lots-stripe.jsonld"}}