Prepaid credits and usage billing for AI products
Reserve a maximum cost before an AI job runs. Charge the actual usage when it finishes. Release the rest and give users an auditable receipt.
AI usage has a timing problem
You must decide whether a customer can start an AI request before the final cost exists. Tokens, seconds, images, and tool calls arrive after the provider finishes.
Resvary checks available credits and creates a reservation before provider work begins. It commits the final charge after execution and releases the unused amount.
- 01Concurrent jobs can spend the same apparent balance.
- 02A retried request can create a duplicate charge.
- 03Failed jobs can leave credits locked without an explicit release.
- 04Mutable prices make old charges hard to explain.
- 05A balance snapshot cannot show why the number changed.
One lifecycle from authorization to receipt
Fund the account
Grant product credits from your application or confirm an external funding payment.
Reserve the maximum cost
Rate the estimated usage against an immutable price version and hold that amount before expensive work begins.
Run the AI operation
Call a model, agent, generation pipeline, tool, or batch worker with your existing provider stack.
Commit actual usage
Rate the provider's final usage, charge it once, and release the unused part of the reservation in the same transaction.
Record the result
Store an immutable ledger entry, usage receipt, idempotency result, and outbox event for reconciliation.
The credit boundary around each AI call
Authorize spend before execution
Resvary checks available credits and creates an atomic reservation before your application starts provider work. Overlapping requests cannot reserve the same credits twice when the store supplies the required transaction isolation.
Charge once across retries
Every mutating command requires an idempotency key. Replaying the same key and payload returns the original result. Reusing the key with different input raises a conflict.
Explain each balance change
Immutable ledger entries and per-charge usage receipts record the price version, line items, amount charged, amount released, and balance after the operation.
Keep payment rails separate from usage
The credit lifecycle does not depend on checkout, wallets, or an AI provider. Your application can fund the same ledger through manual grants, Arc USDC payments, or another adapter without changing usage accounting.
Each commit records its own explanation
The usage receipt records the price version, line items, final charge, released credits, and resulting balance. Your team can trace each balance change without reconstructing it from logs.
Credit primitives that survive retries
- +Closed-loop USD product credit accounts
- +Six-decimal integer credit arithmetic
- +Multi-dimensional usage meters
- +Immutable price versions
- +Estimated-usage reservations
- +Actual-usage commit and release
- +Expiring open reservations
- +Persistent idempotency records
- +Append-only ledger entries
- +Per-charge usage receipts
- +Manual grants and explicit adjustments
- +Transactional outbox events
- +Signed credit webhook payloads
- +In-memory and SQLite stores
- +Arc Testnet USDC funding adapter
- +Next.js and Express starter generation
- +Stablecoin receipt and x402 compatibility modules
Price the usage your provider returns
A meter can rate one or more integer dimensions. Each immutable price version keeps old receipts tied to the rates used at the time of the charge.
The alpha supports linear multi-dimensional rates. Tiering, packages, subscriptions, monthly minimums, and allowances are outside the current scope.
- LLM chat
- input tokens · output tokens
- Image generation
- images · compute seconds
- AI agents
- tool calls · steps · runtime
- Speech and video
- seconds · minutes processed
- Batch jobs
- items · pages · completed jobs
- Developer APIs
- requests · domain-specific units
Wrap each provider call in a metered lifecycle
runMetered reserves estimated usage, runs your provider callback, commits the final charge, and returns the released amount with a receipt.
import { CreditLedger } from '@resvary/sdk/credits'; import { createSqliteCreditStore } from '@resvary/sqlite'; const credits = new CreditLedger({ projectId: 'my_ai_product', store: createSqliteCreditStore({ path: '.resvary/resvary.sqlite', }), }); const result = await credits.runMetered( { customerId: 'customer_123', priceId: 'price_llm_v1', estimatedUsage: { input_tokens: '2000', output_tokens: '1000', }, idempotencyKey: 'request_abc', }, async () => { const completion = await callModel(); return { value: completion, usageEventId: completion.id, actualUsage: { input_tokens: String(completion.usage.inputTokens), output_tokens: String(completion.usage.outputTokens), }, }; }, ); console.log(result.receipt.amount); console.log(result.receipt.releasedAmount);
If the provider throws, runMetered releases the full reservation. If provider execution succeeds but the commit fails, the reservation stays open so your application can retry the same commit without giving away completed usage.
The packages currently live in the Resvary monorepo. Use the setup guide until public package releases are available.
Run the credit lifecycle in one demo
The deterministic demo needs no AI key. Grant credits, run a request, replay it without a second charge, or trigger a provider failure and inspect the stored result.
Run the interactive demo →- Grant $5 in development credits
- Run a simulated AI operation
- Replay the same request
- Simulate provider failure
- Simulate an Arc Testnet funding confirmation
- Posted, reserved, and available balances
- Reservation status
- Actual charge and released amount
- Price line items
- Immutable ledger history
- Usage receipts
- Transactional outbox events
- Signed event headers
Add prepaid credits to variable-cost AI workloads
AI SaaS
Sell prepaid product credits while keeping subscriptions, checkout, and invoices in your existing billing stack.
AI APIs
Authorize requests before execution and reconcile each customer charge to provider usage.
Agent platforms
Reserve a budget for an agent run, then charge for its final steps, tools, tokens, or runtime.
Generation products
Rate images, audio, video, or batch jobs with units that match your provider costs.
Paid developer tools
Give teams auditable credit balances and retry-safe usage charges without building a ledger from scratch.
Balance changes stay inside one transaction
Each balance-changing command validates idempotency, checks the account and lifecycle state, writes ledger entries, updates the account snapshot, stores the domain record and outbox event, and saves the command result before commit.
The SQLite store uses BEGIN IMMEDIATE to serialize competing writers. It stores balances, reservations, receipts, idempotency results, and outbox events across restarts.
SQLite supports local, single-node, and design-partner deployments in the current alpha. Multi-process production deployments should use a custom CreditStore with equivalent transaction isolation or wait for the planned Postgres adapter.
Arc USDC is Resvary's reference and first-class external funding path. The adapter creates an invoice, validates its payment receipt, and grants credits once for each network + transaction hash pair. Usage accounting remains payment-rail agnostic.
The current Arc integration is Testnet-first development infrastructure.
A credit balance needs a transaction lifecycle
| Capability | Balance column | Resvary 0.3 alpha |
|---|---|---|
| Available balance snapshot | Yes | Yes |
| Atomic pre-request reservation | Custom work | Included |
| Actual-usage commit and release | Custom work | Included |
| Retry-safe mutating commands | Custom work | Included |
| Immutable price history | Custom work | Included |
| Per-charge usage receipts | Custom work | Included |
| Append-only ledger entries | Custom work | Included |
| Transactional outbox events | Custom work | Included |
| Funding rail independence | Depends on implementation | In the domain model |
Know the alpha boundary before you integrate
Resvary 0.3 includes the embedded credit domain, SQLite persistence, starter integration, and Arc Testnet funding. Hosted billing, Postgres, and multi-node deployment remain planned work.
- Credits belong to one merchant project
- Credits cannot move between users
- Users cannot redeem or cash out credits
- Resvary does not custody customer funds
- Usage receipts are operational records, not tax invoices
- Hosted dashboard or managed API
- Postgres adapter
- Multi-node deployment support
- Subscription management · checkout UI
- Tax calculation or tax invoices
- Transferable balances · cash redemption
- Marketplace wallets
- Enterprise SLA or compliance certification
- Postgres persistence
- Self-hosted HTTP service
- Hosted operations and delivery tooling
- Access control and operator workflows
- Analytics and reconciliation views
Roadmap items, not available features.
Keep the credit ledger inside your application
Run the Apache-2.0 TypeScript code inside your application. Inspect the balance rules, run the tests, use the store interface, and keep product usage in your infrastructure.
@resvary/sdk/credits
Accounts, grants, reservations, usage receipts, ledger, idempotency, outbox
@resvary/sdk/pricing
Meters, immutable price versions, integer usage rating
@resvary/sdk/funding/arc
Arc payment receipt to credit grant adapter
@resvary/sqlite
Persistent credit and payment receipt stores
@resvary/sdk/receipts
Stablecoin invoices, proofs, payment receipts, signed webhooks
@resvary/sdk/middleware
Compatible legacy x402 middleware for Express and Next.js
create-resvary
Starter generator for prepaid AI credit applications
Run the open-source alpha or request an integration review
Run Resvary in your application today. Design-partner reviews are available for a small number of AI teams. A managed service remains a roadmap item with no launch date or price.
- Full credit ledger and pricing engine
- SQLite store, embedded or as a service
- Arc funding adapter and signed webhooks
- No usage caps, no telemetry, no vendor account
- Community support through GitHub issues
- Everything in self-hosted
- Direct channel to the maintainers
- Integration review of your metering model
- Influence over the Postgres adapter and API surface
- Migration help when the schema changes
- Hosted ledger with managed backups
- Operator console and audit exports
- Reconciliation and analytics views
- Uptime commitments and support terms
- Same SDK, no application rewrite
Managed cloud is a roadmap item. No hosted plan, contract, or price exists today.
Questions engineers ask first
Is Resvary a payment processor?
No. Resvary manages closed-loop product credits and usage authorization. Keep checkout, subscriptions, tax, and fiat payment processing in the systems you already use.
Does Resvary replace Stripe Billing, Lago, or Orb?
Resvary handles the real-time credit boundary around an AI operation. A broader billing platform can continue to handle checkout, subscriptions, invoicing, or finance workflows.
Why reserve credits before the AI request?
The final provider cost arrives after execution. A reservation prevents concurrent requests from spending the same available balance while keeping the final charge tied to actual usage.
What happens when the provider fails?
runMetered releases the full reservation when the provider callback throws. The account keeps its posted credits.
What happens if commit fails after the AI request succeeds?
The reservation stays open. Retry the commit with the same idempotency key to record the completed usage without charging twice.
Can an actual charge exceed its reservation?
No. Your application must create another reservation before continuing work that needs a higher limit.
Can I use my existing AI provider?
Yes. The core ledger does not depend on a model vendor. Your application passes estimated and actual usage into the SDK.
Do I need crypto or Arc to use Resvary?
No. Manual grants can fund an account without a blockchain. Arc USDC is the reference external funding path and does not change the usage ledger.
Is SQLite production-ready?
The current SQLite adapter targets local, single-node, and design-partner deployments. Multi-process production deployments need a store with equivalent transaction isolation. A Postgres adapter is planned.
Are credits transferable or redeemable?
No. Resvary models non-transferable, non-redeemable product credits that customers use inside one merchant project.
Is a usage receipt a tax invoice?
No. A usage receipt explains an operational credit charge. Each merchant remains responsible for its customer terms, refund policy, privacy notice, invoices, and tax treatment.
Is Resvary free to use?
The current code is available under the Apache-2.0 license. No hosted paid plan exists yet.
How do I try the alpha?
Run the deterministic demo without an AI key, or open the repository and follow the getting-started guide.
Add a retry-safe credit ledger to your next AI request
Run the lifecycle in the demo, then evaluate the open-source SDK inside your application.