/credit-metering
Usage credits on an append-only ledger with reserve, capture, release and refund.
Then type /credit-metering in Claude Code, or describe the task and let it pick the skill.
What you get back recorded run · 10 Oct 2026
- 10 same-ID requests → 1 charge
- 30 scans vs 5 credits → 5 run
- 25 tests pass
- Scan credits are built: Plus gets 50 scans per paid billing month, one scan costs one credit, people can buy a 100-scan top-up, and a double-click or retry is charged once. The OCR call is still a stub. All 25 tests pass against a local Postgres 16,
next buildsucceeds, and I ran an end-to-end check through the real routes. - 30 simultaneous scans against 5 credits: exactly 5 succeed.
- In the end-to-end run, 5 parallel requests with one scan ID produced one charge (one 409 "already running", four 200s), and a repeated webhook delivery returned
duplicate. - There's no auth in the app.
lib/auth.jsreturns the user from theDEV_USER_IDenv var, and only outside production.
Input → output from the run
const rows = [ ["Groups", "1", "Unlimited", "Unlimited", "Unlimited"], ["Members per group", "4", "20", "100", "Unlimited"], ["Receipt scanning", "—", "50 / month", "Unlimited", "Unlimited"], ["Multi-currency", "—", "✓", "✓", "✓"], ["Recurring bills", "—", "✓", "✓", "✓"], ["Export to CSV", "—", "—", "✓", "✓"], ["Priority support", "—", "—", "—", "✓"], ];
// Reserve one credit for a scan identified by the client's idempotency key.
// Returns { replay: true, request } for an already-succeeded key.
export async function reserveScan(userId, idempotencyKey) {
return tx(async (c) => {
const acct = await lockAccount(c, userId);
await expireAllowanceIfDue(c, acct);
await releaseStale(c, acct);
const existing = (
await c.query("select * from scan_requests where user_id = $1 and idempotency_key = $2", [userId, idempotencyKey])
).rows[0];
if (existing?.status === "succeeded") return { replay: true, request: existing };
if (existing?.status === "pending") throw new ScanInProgress("This scan is already running");When to use it
Use when an app meters consumable usage with credits.
Skip it for plain subscriptions with nothing consumable to meter; payments-with-dodo covers billing itself.
The thinking behind itCredits are money, so treat them like a ledger. Reserve, capture and refund cleanly, and usage stays fair even with retries and parallel requests.
Output contract from the skill's Output section
Report the denomination and policies, schema/migrations, ledger operations and invariants, protected usage paths, provider/product mapping, UI reconciliation, verification evidence, and remaining dashboard or production setup.
How it checks its own work from the instructions
- Reserve, capture, and release flows are tested
- Ledger and balance invariants hold under concurrent spend
- Payment replay and out-of-order events are tested
- Refunds, clawbacks, and promo races are tested
Requirements what it needs
- Works in
- Codex, Claude Code, Cursor
- Needs
- project files, terminal commands, network access
The instructions SKILL.md · 36 lines
Instructions & references
Back to overview ↑On this page 4 sections
Credit metering
Build credits as a financial state machine. Preserve existing denominations, billing semantics, and provider integrations.
Workflow
- Inspect backend/runtime, database/ORM, auth and tenant keys, current balance/ledger fields, payment provider, usage paths, retries, queues, and frontend state.
- Infer existing costs, grants, and packs from code. Ask only for unresolved commercial policy: denomination, per-action or measured cost, free/recurring grants, expiration/rollover, refund/clawback behavior, and overspend/debt policy. Never default to a new payment provider when one exists.
- Read database schemas, then implement only the matching database variant. Do not treat PostgreSQL, MySQL, Prisma providers, and MongoDB as interchangeable. PlanetScale runs both Vitess (MySQL) and Postgres: detect the engine before choosing. Write migrations that can run twice.
- Use an append-only ledger with a unique idempotency key/external event ID. Update cached balance and ledger in one database transaction, or derive balance from the ledger when scale permits. Enforce positive input amounts and the chosen non-negative/debt rule in the database.
- Implement explicit operations:
grantfor signup, subscription, promotion, or admin credit;reservebefore costly/concurrent work;captureafter measured success;releaseon cancellation/failure;refundorreverselinked to the original transaction;expire/rolloverwhen credits have lifecycle rules.
- Authenticate and authorize from server context. Never accept balance, price, pack value, or user identity from the browser. Map a server-owned product/price ID to the credit amount.
- Read payment providers only for the detected provider, or for provider choice on a new build. Its facts carry a check date; re-check any older than 90 days before relying on it. On Lemon Squeezy, check its status and flag the Stripe Managed Payments migration path; do not start a new build on it by default. If the provider offers native credits (Dodo credit entitlements, Stripe credit grants), name one balance source of truth and keep gating usage in the app. Verify raw-body signatures, durably deduplicate events, and retry transient failures. Acknowledge before processing only after a durable queue/inbox write.
- Make promotions atomic. Use a redemption table with a unique
(promo_id, user_id)constraint when one redemption per user is intended; update global usage and grant credit in the same transaction. - Treat the UI balance as a projection. Reconcile after responses, account switches, multi-tab updates, refunds, and webhook grants. Optimistic display must not authorize work.
Verification
Test signup/recurring grant, reserve-capture, reserve-release, insufficient balance, variable final cost, duplicate request, concurrent spend, payment replay, out-of-order event, refund/clawback, promo race, account switching, and reconciliation after network failure. Assert ledger/balance invariants and run database concurrency tests plus repository lint/type/test/build commands.
Output
Report the denomination and policies, the balance source of truth, schema/migrations and their re-run result, ledger operations and invariants, protected usage paths, provider/product mapping, UI reconciliation, verification evidence, and remaining dashboard or production setup.
Credit database variants
Read this reference after detecting the database. Implement one compatible variant and keep all balance/ledger mutations transactional.
PlanetScale is not a single engine. It offers Vitess (MySQL-compatible) and Postgres, with Neki for sharded Postgres (checked 2026-11-04: PlanetScale Postgres, Vitess foreign keys). Detect the engine from the connection string, driver, or ORM provider before choosing a variant. A PlanetScale Postgres project uses the PostgreSQL variant; a Vitess project uses the MySQL variant.
Contents
- Shared invariants
- PostgreSQL, Supabase, and PlanetScale Postgres
- Prisma
- MySQL and PlanetScale Vitess
- MongoDB
- Verification
Shared invariants
- Amounts are positive integers at the operation boundary; ledger deltas carry the sign.
- Every logical operation has a unique idempotency key.
- Ledger rows are append-only and link reversals/refunds to the original operation.
- Balance and ledger update in one transaction, or balance is derived from the ledger.
- Reservation status supports pending/captured/released where concurrent or variable-cost work exists.
- Database constraints enforce the chosen no-debt/debt policy.
PostgreSQL, Supabase, and PlanetScale Postgres
The migration is safe to re-run: every statement is guarded. ADD CONSTRAINT has no IF NOT EXISTS, so the check constraint is added inside a catalog lookup.
alter table public.users
add column if not exists credit_balance bigint not null default 0;
do $$
begin
if not exists (
select 1 from pg_constraint
where conname = 'users_credit_balance_nonnegative'
and conrelid = 'public.users'::regclass
) then
alter table public.users
add constraint users_credit_balance_nonnegative check (credit_balance >= 0);
end if;
end $$;
create table if not exists public.credit_transactions (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references public.users(id),
idempotency_key text not null unique,
kind text not null check (kind in (
'grant', 'reserve', 'capture', 'release', 'refund', 'reverse', 'expire', 'rollover'
)),
amount bigint not null check (amount <> 0),
balance_after bigint not null,
original_transaction_id uuid references public.credit_transactions(id),
external_reference text,
metadata jsonb not null default '{}'::jsonb,
created_at timestamptz not null default now()
);
create index if not exists credit_transactions_user_created_idx
on public.credit_transactions (user_id, created_at desc);
create unique index if not exists credit_transactions_external_reference_idx
on public.credit_transactions (external_reference)
where external_reference is not null;
Implement a database function or application transaction that locks/conditionally updates the balance and inserts the ledger row atomically. For spend/reserve, use a conditional update such as ... where credit_balance >= amount and confirm one affected row inside the transaction.
On sharded PlanetScale Postgres (Neki), confirm that the balance row and its ledger rows live on the same shard before relying on a single-transaction update.
Apply RLS/grants based on the real auth model. Users may read their own history; only trusted server paths should mutate financial rows.
Prisma
Model the same fields and unique constraints in the provider-compatible Prisma schema. Use an interactive transaction for conditional balance update plus ledger insert. Raw conditional SQL may be necessary for strict atomic spend; do not implement read-then-write in separate calls. JSON defaults and UUID generation differ by database provider, so avoid copying PostgreSQL annotations into MySQL.
MySQL and PlanetScale Vitess
Use MySQL-compatible types (char(36)/binary UUID choice, json, datetime) and migrations supported by the project. gen_random_uuid(), jsonb, partial indexes, and ADD COLUMN IF NOT EXISTS are PostgreSQL-specific. Foreign keys are supported on unsharded PlanetScale Vitess databases; verify the setting on the actual project and do not assume them on a sharded keyspace. Preserve idempotency with unique indexes and use a transaction or single conditional update supported by the database.
MongoDB
Store balance on the user/account document and ledger in a separate collection with unique indexes on idempotencyKey and optional externalReference. Use a replica-set transaction for balance+ledger atomicity, or a rigorously designed single-document ledger/balance model. A transaction schema alone is insufficient.
Verification
- Concurrent spends cannot cross the permitted balance boundary.
- Replaying an idempotency key returns the original result without another delta.
- Ledger and cached balances reconcile after grants, capture/release, and refund.
- Mutation attempts from ordinary client credentials are denied.
- Migration applies from a clean database, upgrades an existing fixture safely, and runs a second time without error.
Credit payment providers
Read this reference after detecting the existing provider and installed SDK version. Implement one provider path. Provider facts here were checked 2026-11-04 against the sources at the end; re-check a fact before relying on it if that date is more than 90 days old or the installed SDK differs. For raw API shapes, prefer the provider's official agent skill if installed, otherwise its docs.
Contents
Shared checkout contract
The browser submits only a server-owned pack key. The server maps that key to provider price/product ID, currency, and credit amount.
POST /api/billing/credit-checkout
authenticated body: { pack: "starter" }
server lookup: starter -> provider product/price -> 100 credits
Attach stable internal account/user ID and pack key as provider metadata. Never accept credits, amount_cents, price IDs outside an allow-list, or user identity as authoritative browser input.
Stripe
Use the installed Stripe SDK’s Checkout Session pattern and a server-owned price mapping. Fulfill on checkout.session.completed when payment_status is not unpaid, and on checkout.session.async_payment_succeeded for delayed payment methods. Verify the Stripe-Signature header over the raw body with the endpoint secret (constructEvent). Store both event ID and payment/session reference as unique identifiers where useful.
Stripe Billing has credit grants: monetary credits with priority, expiry, and price scoping, backed by an append-only ledger, emitting billing.credit_grant.* events. They apply only to metered subscription items at invoice finalization and cannot be used as stored value. They reduce an invoice; they do not gate usage in real time. Use them when the commercial model is "prepaid dollars against a metered bill". Keep the application ledger when the product spends unit credits per action and must refuse work at zero.
Stripe Managed Payments is Stripe's merchant-of-record product, generally available since 22 Apr 2026 in 39 countries, limited to eligible digital-product tax codes. For a new build that wants a merchant of record and has no provider yet, present it alongside Dodo Payments and check that the product's tax code is eligible. The credit ledger and webhook rules below do not change.
Lemon Squeezy
Check Lemon Squeezy's status before building anything new on it. Stripe acquired Lemon Squeezy in 2024. On 16 Apr 2026 Lemon Squeezy said its team is building Stripe Managed Payments and that its goal is an easy migration path for Lemon Squeezy users. @lemonsqueezy/lemonsqueezy.js was last published as 4.0.0 on 5 Nov 2024.
- Existing Lemon Squeezy integration: maintain it. Tell the user about the Stripe Managed Payments migration path and keep the credit ledger provider-neutral (internal pack keys, provider references only in
external_reference) so a move does not rewrite balances. - New build: do not default to Lemon Squeezy. Ask whether the user wants a merchant of record, and if so offer Stripe Managed Payments or Dodo Payments.
For an existing integration, use the server-owned variant mapping and pass the stable account/user ID plus pack key as custom data (checkout_data.custom via the API, checkout[custom][...] on a checkout link). It returns in webhooks as meta.custom_data, with values as strings. Verify the webhook signature exactly as the Lemon Squeezy docs specify and handle only the paid/order state that guarantees funds.
Dodo Payments
Use the official dodopayments SDK (2.61.1 when checked) and checkoutSessions.create with a server-owned product_cart (required, up to 20 items). Store account/user ID plus pack key in metadata. Prefer the SDK's webhooks.unwrap helper and Dodo's webhook events guide. Dodo also has native credit entitlements: grants, FIFO meter deductions, expiry, rollover, four overage modes, a per-customer ledger, and credit.* webhooks. Decide deliberately whether the application ledger or Dodo is the source of truth, and do not update both without reconciliation. Dodo does not block usage when a balance reaches zero, so the application must still gate requests on its own balance check either way. The payments-with-dodo skill covers the rest of the Dodo lifecycle.
Webhook processing
- Read the raw body and verify signature/timestamp with the provider-supported helper.
- Insert a webhook-inbox/event row with a unique provider event ID.
- If processing synchronously, grant credits and mark the event complete in a database transaction. Return non-2xx for transient failure so the provider retries.
- If acknowledging immediately, first durably enqueue/store the event, then return success and process with retry/dead-letter monitoring.
- Resolve pack value from the server-owned mapping, not mutable metadata credit amounts alone. Cross-check product/price, currency, amount, payment status, and environment.
- Grant with the payment/event reference as the ledger idempotency key.
- Handle refunds/disputes according to the explicit clawback/debt policy and link reversal entries to the purchase.
Do not “always return 200” after a database error in a synchronous handler; that permanently discards the provider’s retry opportunity.
Verification
- Unknown/tampered pack keys are rejected before checkout.
- Test and live product IDs cannot cross environments.
- Valid, invalid, duplicate, concurrent, and out-of-order events behave deterministically.
- A transient database failure is retried or remains in a durable queue.
- Refund/dispute behavior matches the documented balance policy.
- Ledger, cached balance, provider payment, and UI reconcile.
Sources checked 2026-11-04
- Stripe fulfillment events: https://docs.stripe.com/checkout/fulfillment
- Stripe credit grants: https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits , https://docs.stripe.com/api/billing/credit-grant/object
- Stripe Managed Payments GA (22 Apr 2026): https://docs.stripe.com/payments/managed-payments/changelog
- Lemon Squeezy status (16 Apr 2026): https://www.lemonsqueezy.com/blog/2026-update
- Lemon Squeezy custom data: https://docs.lemonsqueezy.com/help/checkout/passing-custom-data
- Lemon Squeezy SDK: npm
@lemonsqueezy/lemonsqueezy.js4.0.0, published 2024-11-05 - Dodo checkout sessions: https://docs.dodopayments.com/api-reference/checkout-sessions/create
- Dodo credit-based billing: https://docs.dodopayments.com/features/credit-based-billing
Claude app, ChatGPT and ZIP download
local coding agent required
This skill requires project files, terminal commands, and network access. Uploading it to a chat app does not provide equivalent execution.
ChatGPT Skills
This workflow needs a local coding environment or capabilities that a chat-only Skills upload does not provide.
Package details
- Package
- credit-metering/SKILL.md
- Author
- @tushaarmehtaa
- Added
- 6 Mar 2026
- Tags