Skip to main content

What is a Balance?

A balance represents prepaid credits that a customer can spend. As they use your product, credits are deducted from their balance.
ComponentDescriptionExample
CustomerWho owns the balancecust_123
NameIdentifier for the balanceAI Credits, api_credits
UnitWhat the credits representcredits, tokens, cents
Current BalanceAvailable amount5000
Minimum BalanceReserve amount0 or -100 (allow overdraft)
Balances are identified by the combination of customer_id + name. A customer can have multiple balances with different names (e.g., “AI Credits” and “Storage Credits”).

Balance vs Limits

FeatureBalancesLimits
DirectionDecrements (spend down)Increments (usage accumulates)
ResetsNever (until topped up)Periodically (hour/day/month)
Use casePrepaid creditsUsage caps
Use balances when customers pay upfront. Use limits for subscription-based caps.

Creating a Balance

from limitry import Limitry

client = Limitry()

# Create a balance for a customer
balance = client.balances.create(
    customer_id="cust_123",
    name="AI Credits",
    unit="credits",
    initial_balance=10000,
    minimum_balance=0  # Can't go negative
)

print(f"Created balance: {balance.id}")
print(f"Available: {balance.available_balance} {balance.unit}")

Credit (Add Funds)

Add credits when customers purchase or renew:
result = client.balances.credit(
    customer_id="cust_123",
    name="AI Credits",
    amount=5000,
    description="Monthly credit top-up",
    reference="stripe_pi_123"  # Optional: link to payment
)

print(f"New balance: {result.balance.current_balance}")

Debit (Spend Credits)

Deduct credits when customers use your product:
# Check and debit atomically
result = client.balances.debit(
    customer_id="cust_123",
    name="AI Credits",
    amount=100,
    description="GPT-4 completion",
    reference="evt_xyz789"  # Optional: link to event
)

if result.success:
    print(f"Remaining: {result.balance.current_balance}")
else:
    print(f"Failed: {result.error}")
Debits are atomic. If there aren’t enough credits, the operation fails entirely — no partial debits.

Check Balance Sufficiency

Check if a customer has sufficient credits before an operation:
result = client.balances.check_sufficiency(
    customer_id="cust_123",
    name="AI Credits",
    amount=500
)

print(f"Sufficient: {result.sufficient}")
print(f"Current: {result.current_balance}")
print(f"Available: {result.available_balance}")

if not result.sufficient:
    shortfall = result.requested_amount - result.available_balance
    print(f"Need {shortfall} more credits")

Transaction History

View all credits and debits for a balance:
transactions = client.balances.list_transactions(
    balance_id="bal_abc123",
    limit=50
)

for txn in transactions.data:
    sign = "+" if txn.type == "credit" else "-"
    print(f"{txn.created_at}: {sign}{txn.amount} - {txn.description}")
    print(f"  Balance after: {txn.balance_after}")

Minimum Balance (Reserves)

Set a minimum balance to reserve credits:
# Reserve 100 credits (can't spend below this)
balance = client.balances.create(
    customer_id="cust_123",
    name="Credits",
    unit="credits",
    initial_balance=1000,
    minimum_balance=100  # 100 credits always reserved
)

# available_balance = 900 (1000 - 100)

Allow Overdraft

Set a negative minimum to allow overdraft:
# Allow up to 500 credits of overdraft
balance = client.balances.create(
    customer_id="cust_123",
    name="Credits",
    unit="credits",
    initial_balance=1000,
    minimum_balance=-500  # Can go 500 into debt
)

# available_balance = 1500 (1000 - (-500))

Workflow: Credits + Events

A typical flow combines events for tracking and balances for payment:
customer_id = "cust_123"
balance_name = "AI Credits"

# 1. Check balance before the call
check = client.balances.check_sufficiency(
    customer_id=customer_id,
    name=balance_name,
    amount=100  # estimated tokens
)

if not check.sufficient:
    raise Exception("Insufficient credits")

# 2. Make the LLM call
response = openai.chat.completions.create(...)

# 3. Calculate actual cost
actual_tokens = response.usage.total_tokens
actual_cost = actual_tokens  # 1 credit per token

# 4. Debit the balance
client.balances.debit(
    customer_id=customer_id,
    name=balance_name,
    amount=actual_cost,
    description=f"GPT-4 completion ({actual_tokens} tokens)"
)

# 5. Record the event for analytics
client.events.record(
    customer_id=customer_id,
    event_type="llm.completion",
    values={"tokens": actual_tokens, "cost": actual_cost},
    dimensions={"model": "gpt-4"}
)

List Balances

# List all balances for a customer
balances = client.balances.list(customer_id="cust_123")

for bal in balances.data:
    print(f"{bal.name}: {bal.available_balance} {bal.unit}")

Delete a Balance

result = client.balances.delete("bal_abc123")
Deleting a balance is permanent. All transaction history will be lost.