Under a convention where posted balance is settled spendable value and reservations are positive holds, the core invariant is available balance = posted balance − active reservations for the same wallet, currency or credit unit, and accounting scope. Every successful reservation, capture, release, expiry, refund, top-up, or adjustment must preserve that relationship, remain traceable to an auditable transaction record, and be safe under concurrent requests and retries.
The Short Answer: Define the Signs, Then Enforce the Balance Equation
A prepaid API wallet needs more than three mutable balance fields. It needs authoritative transaction and reservation records from which those balances can be derived, checked, and reconstructed. Before writing an equation, define the wallet identity, unit, accounting scope, and sign convention.
Posted balance, reserved balance, and available balance
For a common credit-positive convention:
- Posted balance (
P) is the settled value currently held by the wallet. Completed top-ups, captures, refunds, and adjustments affect this balance once they are posted. - Reserved balance (
R) is the sum of funds held for authorized but unsettled usage. Reservations reduce spending capacity but are not themselves settled charges. - Available balance (
A) is the capacity that may be committed to new usage under the wallet's current policy.
An API usage estimate may be used to size a reservation, but it is not a settled charge. Final usage can differ from the estimate, so the wallet must distinguish authorization from capture and support release of any unused hold.
Core convention: available equals posted minus active reservations
If posted funds and reservations are both represented as non-negative credit amounts, the relationship is:
A(wallet, unit, scope) = P(wallet, unit, scope) - R(wallet, unit, scope)
R(wallet, unit, scope) = Σ remaining_amount of active reservations
The equality is meaningful only when every term refers to the same:
- Wallet or balance account
- Currency, token-credit unit, or other denomination
- Ledger boundary and accounting scope
- Point in the committed transaction history
A cached balance read can temporarily lag after a write, but it should not silently redefine the invariant. Caches and reporting projections are derived views; the authoritative records must remain capable of reconstructing the committed balance.
How debit-positive, credit-positive, and liability conventions change the formula
The formula is not universal without a declared sign convention. If settled debits are stored as positive amounts, the posted value may instead be derived as credits minus debits. If the wallet is represented as a liability account, an increase in customer funds may be recorded with the opposite ledger sign from an operational “spendable credit” display.
A robust implementation therefore separates:
- Ledger signs, which follow the chosen bookkeeping model.
- Operational quantities, such as positive remaining reservation amounts.
- Displayed balances, which may translate ledger values into user-facing spendable capacity.
For example, an implementation could define operational posted value as:
P_operational = posted_credits - posted_debits
A = P_operational - R
Another ledger may use the inverse sign internally. That is acceptable if the transformation is explicit, deterministic, and consistently applied. Tests should verify the declared equation rather than assuming that all credit entries are positive in storage.
Accounting invariants versus configurable wallet policies
An invariant describes a relationship that must remain true under the selected model. A policy determines which states and transitions the business permits.
The following choices are policies, not universal accounting truths:
- Whether available balance may become negative
- Whether overdrafts or credit limits are allowed
- How long a reservation remains active
- Whether partial captures are permitted
- Whether a capture may exceed its reservation
- Whether multiple captures may consume one reservation
- How cancellation differs from release or expiry
- Which adjustment types require approval
If overdrafts are prohibited, the implementation should enforce A ≥ 0, and a new reservation must not exceed available capacity. If controlled overdrafts are permitted, the lower bound should be explicit and enforced consistently. The equation still applies; the permitted range changes.
Invariant Table for Wallet Writes, Monitoring, and Tests
The following table turns the balance model into checks that can be applied during design, code review, testing, reconciliation, and production monitoring.
| Invariant | Rationale | Violation Example | Monitoring or Test Approach |
|---|---|---|---|
A = P − R under the declared convention | Keeps settled funds, holds, and spendable capacity consistent | Posted is 100 and reserved is 30, but available is reported as 80 | Recompute available from authoritative records after every committed transition and during scheduled reconciliation |
Aggregate R equals the sum of active reservation remainders | Prevents the wallet total from drifting away from reservation detail | Aggregate reserved is 25 while active records sum to 30 | Compare the aggregate with a grouped sum by wallet, unit, and scope; alert on any non-zero difference |
| Every term uses one currency or credit unit | Prevents invalid arithmetic across denominations | USD funds are combined directly with token credits | Validate unit identity on writes and reconciliation; require an explicit conversion transaction for unit changes |
| Successful transitions preserve conservation | Ensures value does not appear or disappear through state changes | A release removes a hold but fails to restore available capacity | Use state-transition tests that compare pre- and post-transaction values |
| A reservation has a valid remaining amount | Prevents negative holds and excess capture | A reservation for 20 records total captures of 24 without an overage policy | Enforce state and amount constraints atomically; alert when captured value exceeds authorized value |
| Terminal reservation actions cannot be applied repeatedly | Prevents duplicate capture, release, cancellation, or expiry | A retry captures the same reservation twice | Persist idempotency outcomes and test repeated, delayed, and reordered requests |
| Authorization is atomic at the wallet scope | Prevents concurrent requests from spending the same capacity | Two simultaneous reservations each approve against the same available funds | Run concurrency tests with barriers; use locking, serialization, or conditional writes appropriate to the data store |
| Every balance change has an auditable cause | Makes totals reconstructable and explainable | An administrator edits the posted total without an adjustment record | Reject unexplained mutations; reconcile aggregates to immutable or otherwise auditable transaction records |
| Derived views reconcile to authoritative records | Detects stale caches and projection failures | The API cache reports more available credit than the committed records support | Rebuild projections periodically, track drift, and invalidate or repair stale views |
| External funding events reconcile where applicable | Connects wallet funding to completed payment outcomes | A top-up is posted twice after duplicate payment notifications | Match stable external references to internal transactions and alert on missing, duplicate, or mismatched records |
Balance equality and reservation aggregation
The reserved total should be a projection of active reservation records, not an independently editable number. A useful reservation record normally identifies the wallet, unit, original amount, captured amount, released amount, status, timestamps, and idempotency references.
Its remaining hold can be expressed as:
reservation_remaining = authorized - captured - released
R = Σ reservation_remaining for active reservations
Expiry and cancellation generally release the uncaptured remainder. Whether the implementation records that outcome as a release transaction, a distinct expiry transaction, or another auditable event is a schema choice. The resulting active reservation remainder must nevertheless become zero exactly once.
A reservation state machine should reject impossible transitions. Examples include capturing an expired hold, releasing more than the remaining amount, or returning a completed reservation to an active state without an explicit compensating operation.
Conservation across wallet state transitions
Using the credit-positive convention, each operation has a predictable effect:
- Create reservation: Increase
R; decreaseAby the same amount; leavePunchanged. - Partial capture: Decrease
PandRby the captured amount; leaveAunchanged because the capacity was already withheld. - Full capture: Decrease
Pby the remaining captured amount and reduce that reservation's remainder to zero. - Release, cancellation, or expiry: Decrease
Rby the unused amount; increaseAby the same amount; leavePunchanged. - Top-up: Increase
PandA; do not change existing reservations. - Refund: Increase
PandAwhen the refund is posted, subject to the wallet's refund model. - Adjustment: Apply a signed, classified transaction to
P; changeAby the same amount unless another linked operation also changes reservations.
These effects apply after successful commit. A failed operation should leave no partial combination of ledger, reservation, and aggregate writes.
One wallet example across the complete lifecycle
Consider a wallet that starts with a posted balance of 100 credits, no reservations, and 100 credits available.
- Reserve 30:
P=100,R=30,A=70. The authorization changes capacity but is not a settled charge. - Partially capture 18:
P=82,R=12,A=70. Posted funds and the hold both decline by 18. - Release the unused 12:
P=82,R=0,A=82. - Reserve and fully capture 20: Reservation creation temporarily produces
P=82,R=20,A=62; full capture producesP=62,R=0,A=62. - Reserve 15 and let it expire: The active state is
P=62,R=15,A=47; expiry returns the wallet toP=62,R=0,A=62. - Reserve 10 and cancel it: Cancellation removes the hold, returning the wallet to
P=62,R=0,A=62. - Post an 18-credit refund:
P=80,R=0,A=80. - Post a 20-credit top-up:
P=100,R=0,A=100. - Post a negative adjustment of 2:
P=98,R=0,A=98, with an adjustment record explaining the change.
The example illustrates why an authorization estimate must not be posted immediately as final API usage. Partial capture settles only the measured charge, while the unused reservation is released separately.
Configured bounds, non-negativity, and unit consistency
Each balance should remain within declared numeric and business bounds. These include storage precision, maximum representable value, accepted decimal scale, and any wallet-level credit or overdraft limit.
If negative availability is prohibited, reservation creation must test and consume capacity in one atomic operation. Reading A, approving a request in application code, and writing R later leaves a race window in which simultaneous requests can both pass the same balance check.
Units require equally strict treatment. A wallet must not add monetary funds, token credits, model-specific quotas, or promotional credits unless they share a defined denomination. Conversion should be represented as an explicit event that records the source amount, destination amount, and applicable conversion rule. Historical values should remain explainable even if the conversion policy changes later.
Atomicity, concurrency, and retry safety
Reservation authorization is a contention point because multiple API requests may target one wallet at the same time. The balance check and reservation write should be atomic at the scope where capacity is shared. Depending on the data architecture, that can be implemented with serialized transactions, row or account locking, versioned conditional updates, or another mechanism that prevents lost updates.
Idempotency addresses a different problem: retries. Reservation, capture, release, top-up, refund, cancellation, and adjustment operations should accept or derive stable operation identifiers. Reusing an identifier with the same request should return the recorded outcome rather than apply the financial effect again. Reusing it with conflicting parameters should be rejected or routed to explicit review logic.
Idempotency does not by itself create exactly-once execution. The implementation still needs atomic persistence of the business result and the idempotency outcome. Tests should include retries before a response, after a commit, during a timeout, and after a worker restart.
Capture also needs amount-level protection. Unless an explicit overage policy exists, the total captured amount must not exceed the remaining reservation. If overage is allowed, the additional amount should pass a separate capacity rule and remain visibly attributable rather than silently forcing the wallet negative.
Traceability and reconciliation
Aggregate balance fields are useful for fast reads, but an unexplained mutable total is not an adequate source of truth. Every change should point to an auditable event such as a reservation, capture, release, top-up, refund, expiry, cancellation, conversion, or adjustment.
A practical reconciliation process compares four layers:
- Transaction records: Reconstruct posted value from settled wallet events.
- Reservation records: Reconstruct the aggregate remaining hold.
- Balance projections and caches: Verify that derived posted, reserved, and available values match the authoritative result.
- External payment records: Where top-ups or refunds use an external payment system, match stable references, amounts, units, and completion states.
Reconciliation differences should not be hidden by overwriting the aggregate with a newly calculated total. Record the discrepancy, identify its cause, and use a classified repair or compensating transaction where correction is necessary. This preserves an understandable history.
Implementation tests and operational alerts
A useful test suite should exercise both equations and state transitions:
- Property-based tests that generate valid operation sequences and verify
A = P − Rafter every commit - Concurrency tests in which competing reservations attempt to consume the same remaining capacity
- Retry tests for every balance-changing operation, including delayed and reordered messages
- Partial-capture tests followed by release, cancellation, and expiry of the remainder
- Boundary tests at zero availability, configured overdraft limits, numeric precision limits, and maximum values
- Unit-mismatch tests that attempt arithmetic across currencies or credit types
- Projection-rebuild tests that reconstruct balances exclusively from authoritative records
- Failure-injection tests between transaction steps to confirm that partial writes do not survive
Operational monitoring should detect:
- Non-zero differences between stored and reconstructed balances
- Aggregate reserved value that differs from active reservation records
- Orphaned reservations with missing wallets or authorization events
- Stale holds beyond their expected expiry or processing window
- Duplicate or conflicting captures and releases
- Negative availability when policy prohibits it
- Capture totals above the permitted reservation amount
- Cached projections that remain inconsistent after the expected refresh interval
- Missing, duplicate, or unit-mismatched external funding records
Alerts should include the wallet, unit, operation identifiers, relevant record versions, and reconciliation difference. Avoid placing sensitive request content into alert payloads when identifiers and structured transaction metadata are sufficient for diagnosis.
Applying These Principles to Managed API Access
Prepaid-wallet invariants are general billing architecture guidance rather than a description of Token Forge Cloud functionality. They are relevant whenever a team chooses to build prepaid controls around metered API consumption, particularly when authorization estimates and final usage charges can differ.
Token Forge Cloud offers Managed Model APIs as an API-first route to model access. For organizations moving beyond managed access, Token Forge Cloud Private LLM Inference supports private deployment and serving-layer optimization through capabilities including caching, routing, batching, quantization, and GPU scheduling. Wallet and ledger design should remain a separately defined system concern, with its own units, transaction model, reconciliation process, and operational policies.
Contact Token Forge Cloud to discuss API access, private deployment, and LLM inference cost control.