Credit Points System
TanStack Ship loyalty points system for credit issuance, consumption, configurable credit plans, and idempotent transaction processing.
Overview
The credit points system in TanStack Ship provides a flexible loyalty currency that drives user engagement and retention. Users earn credits through various actions — invitations, promotions, purchases, and engagement milestones — and can spend them on subscriptions, features, or product upgrades.
As part of the platform, the credit system is designed with reliability as a core principle. It implements double-entry accounting with idempotent operations and full audit logging, ensuring that every credit movement is accurately recorded and never duplicated.
Credit Flow
The credit system follows a strict double-entry accounting model, where every issuance and consumption is recorded as an immutable transaction:
Design Philosophy
The credit system is built on three core principles of financial reliability:
- Double-Entry Accounting — Every credit movement is recorded as a transaction with both a debit and a credit entry. A user's balance is never stored as a single value, but derived as the sum of all transactions, ensuring mathematical integrity. Unlike LoyaltyLion or Yotpo — which operate as third-party SaaS platforms requiring API calls for balance queries and webhook integrations for event-based rewards — our credit engine is embedded directly in your database, with zero external latency for balance checks and full transactional integrity across all operations.
- Idempotent Operations — Every credit operation carries a unique idempotency key. If the same operation is retried (due to network issues, webhook redelivery, or client retries), the system detects the duplicate and returns the existing result rather than processing it again.
- Audit-First Design — All credit movements are logged with complete metadata: timestamp, amount, reason, reference entity, and performing user. This full audit trail satisfies compliance requirements and enables debugging, reconciliation, and customer support.
Core Capabilities
Configurable Credit Plans
Credit plans determine how credits are granted to users. Three plan types are supported:
- One-time Plans — A single credit grant with a fixed amount, suitable for welcome bonuses or one-off promotions
- Recurring Plans — Periodic credit grants (monthly, yearly) that renew automatically at the configured interval
- Permanent Plans — Indefinite recurring credits that never expire, ideal for lifetime loyalty programs
Each plan specifies the credit amount, interval (for recurring plans), and optional expiration rules. Plans can be activated or deactivated from the admin dashboard without losing historical data.
Example — Credit plan configuration:
{
"name": "Monthly Loyalty Bonus",
"type": "recurring",
"amount": 100,
"interval": "monthly",
"maxBalance": 5000,
"active": true
}
Issuance & Consumption Engine
Credit operations follow a strict double-entry accounting model:
- Issuance — Creates a positive transaction record, increasing the user's balance
- Consumption — Creates a negative transaction record, decreasing the user's balance
- Balance Calculation — The current balance is computed as the sum of all transactions
- Idempotency — Every operation carries a unique idempotency key, ensuring retries don't result in double-processing
The system validates all operations in real time, checking that the user has sufficient balance before processing any consumption request.
Reliability & Data Integrity
Enterprise-grade reliability features:
- Idempotency Keys — Prevents duplicate processing from webhook retries, network issues, or client retries
- Transaction Logging — Every operation is logged with timestamp, amount, reason, and reference entity
- Balance Validation — Real-time balance checks prevent overspending
- Audit Trail — Full history of all credit movements for debugging, compliance, and support
- Atomic Operations — Issuance and consumption are wrapped in transactions to prevent race conditions
Invitation Rewards Integration
The credit system integrates with the invitation module to power referral rewards:
- When a referred user subscribes, the inviter receives a credit reward (configurable amount per campaign)
- The new user receives a welcome credit bonus to incentivize first-time engagement
- Both transactions are logged with unique idempotency keys
- The system handles edge cases — duplicate referral attempts, self-referral prevention, and reward limits
Example — Reward payout transaction log:
| User | Type | Amount | Reason | Status |
|---|---|---|---|---|
| alice@example.com | Credit | +500 | Referral reward | Completed |
| bob@example.com | Credit | +200 | Welcome bonus | Completed |
| alice@example.com | Debit | -100 | Plan purchase | Completed |
Client-side credit balance component example:
import { useQuery } from '@tanstack/react-query'
export function CreditBalance() {
const { data } = useQuery({
queryKey: ['credit-account'],
queryFn: () =>
fetch('/api/credits/balance').then((r) => r.json()) as Promise<{
balance: number
transactions: Array<{ id: string; amount: number; reason: string }>
}>,
})
return (
<div className="rounded-lg border p-4">
<div className="mb-3">
<p className="text-sm text-muted-foreground">Credit Balance</p>
<p className="text-3xl font-bold">{data?.balance.toLocaleString() ?? '—'}</p>
</div>
<p className="mb-2 text-xs font-semibold uppercase text-muted-foreground">Recent</p>
{data?.transactions.slice(0, 3).map((tx) => (
<div key={tx.id} className="flex justify-between py-1 text-sm">
<span>{tx.reason}</span>
<span className={tx.amount > 0 ? 'text-green-600' : 'text-red-600'}>
{tx.amount > 0 ? '+' : ''}{tx.amount}
</span>
</div>
))}
</div>
)
}
Best Practices
Idempotency Key Management
Generate unique idempotency keys for each credit operation. Use a combination of entity type, entity ID, and operation type (e.g., invitation_reward_{id}) to ensure uniqueness.
Balance Verification
Display real-time balances to users but always verify sufficiency on the server before processing consumption. Client-side balance checks are for UX only.
Graceful Handling of Insufficient Balance
When a user lacks sufficient credits, provide clear feedback showing their current balance and the required amount. Offer alternative payment methods.
Regular Audit Reconciliation
Periodically run reconciliation reports that compare the transaction log against expected balances. The admin dashboard provides tools for this analysis.
Frequently Asked Questions
How do users earn credits? Through multiple channels: invitation referrals, promotional campaigns, monthly loyalty bonuses, manual admin adjustments, and credit grant offers.
Can credits expire? Yes, credit plans can optionally have expiration rules. Admins can configure credits to expire after a set period (e.g., 12 months after issuance).
How are credits used for purchases? During checkout, users can select "Pay with Credits" as an alternative to credit card. The system calculates the payment amount minus the credit value applied.
What happens if a subscription is refunded? If a subscription purchased with credits is refunded, the corresponding credits are restored to the user's account through a reversal transaction.
Can I manually adjust user credits? Yes. The admin dashboard provides a credit adjustment tool for granting or deducting credits manually. All adjustments are logged in the audit trail.
How does the system prevent fraud? Multiple fraud prevention measures: rate limiting, duplicate detection via idempotency keys, and suspicious activity logging.
Configuration
Manage credit plans and accounts from the admin dashboard:
- Credit Plans — Create and manage plans (one-time, recurring, permanent)
- Credit Accounts — View user balances and transaction history
- Transaction Log — Full transaction history with filtering and search
- Debug Panel — Troubleshooting tool for credit operations
No additional environment variables are required beyond the standard database configuration.
Integration Points
The credit system integrates with these platform modules:
- Billing — Credits can be used as an alternative payment method during Stripe Checkout
- Invitation System — Referral rewards are granted as credits with configurable amounts
- Campaign Offers — Credit grant offers award points to user balances
- UTM Campaigns — Traffic-source-specific promotions can include credit bonuses
- User Dashboard — Users view their credit balance, transaction history, and available plans
- Admin Dashboard — Comprehensive credit management interface with audit tools