Designing a user wallet for per-minute calls: holds, ticks, receipts and refunds
A per-minute wallet stays correct when four things are true: it is an append-only ledger in integer minor units, every write carries an idempotency key, each call is capped by what the wallet can pay, and the final charge is computed once from the provider’s server-side record of connected seconds rather than from a timer in the app.
With Titli, calls need no backend: an App Key in the app is enough. The wallet is the exception. The app should not be trusted to debit its own user’s wallet, so the ledger and the settlement below run on your server. That is production hardening for paid calls, not a requirement for making calls.
This article is vendor-neutral: the design works with any calling API that meters on its own servers. Where an example needs a concrete API, it uses ours and says so. It applies to any app where a user pays by the minute to talk to someone: expert consultations, astrology, tutoring, or a marketplace of advisers.
The ledger: entries, not balances
The first version of most wallets is a balance column that code adds to and subtracts from. It works until two requests arrive together, or until a user asks why the balance is ₹37 lower than expected and nobody can say. Replace it with a table of immutable entries, and derive every balance by summing them.
-- An append-only ledger. A balance is a SUM over entries, never a number you overwrite.
CREATE TABLE ledger_entries (
id BIGSERIAL PRIMARY KEY,
account TEXT NOT NULL, -- 'wallet:user_1001', 'hold:user_1001', 'earnings:host_42', 'revenue', 'promo'
amount_minor BIGINT NOT NULL, -- paise or cents. Positive = credit, negative = debit
kind TEXT NOT NULL, -- 'recharge' | 'hold' | 'release' | 'charge' | 'earning' | 'refund'
call_id TEXT, -- the provider's call id, when the entry belongs to a call
idem_key TEXT NOT NULL UNIQUE, -- 'recharge:pay_9f2', 'call:6a1f:hold', 'call:6a1f:charge', ...
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Every movement is a pair of rows that sums to zero. Example: hold ₹200 for a call.
INSERT INTO ledger_entries (account, amount_minor, kind, call_id, idem_key) VALUES
('wallet:user_1001', -20000, 'hold', '6a1f', 'call:6a1f:hold:out'),
('hold:user_1001', 20000, 'hold', '6a1f', 'call:6a1f:hold:in');
-- What the user can spend right now:
SELECT COALESCE(SUM(amount_minor), 0) FROM ledger_entries WHERE account = 'wallet:user_1001';Three rules make this ledger trustworthy:
- Integer minor units. Store paise or cents as integers. Floating-point rupees drift, and one drifting paisa is enough to fail an audit.
- Double entry. Money never appears or vanishes: it moves from one account to another, so every movement is two rows that sum to zero. The sum of all accounts is always zero, and that is the cheapest integrity check you will ever write.
- Append only. A mistake is corrected with a new, opposite entry that points to the old one, not with an update. The history then explains itself.
You need only a handful of accounts: the user’s wallet, a per-user hold account, the earner’s earnings, your revenue, and a promo account that funds free minutes and bonus credit.
Idempotency: the same request twice moves money once
Everything in a calling app is retried. Payment gateways resend callbacks, users double-tap, mobile networks replay requests, and call providers redeliver webhooks. An idempotency key turns all of that into a non-event: the second attempt hits a unique index and stops.
| Operation | A good key | Why |
|---|---|---|
| Wallet recharge | The payment gateway’s payment id | The gateway may call you back several times for one payment |
| Hold before a call | Call id plus hold | A retried “start call” request must not reserve twice |
| Charge after a call | Call id plus charge | Webhooks are delivered at least once, not exactly once |
| Refund | Your refund id | A support agent may press the button twice |
Build keys from ids that already exist. A random key generated per request protects nothing, because the retry generates a new one.
Reserve and settle, or pay-as-you-go ticks?
There are two ways to take money for a call that has no fixed length.
| Hold, then settle | Pay-as-you-go ticks | |
|---|---|---|
| How it works | Reserve what the wallet can pay, cap the call at that, charge once from the final record | Debit a small amount every few seconds or every minute while the call runs |
| Ledger writes per call | Three or four | One per tick, plus a correction at the end |
| Overdraft risk | None: the call cannot outlast the hold | Real: a tick can fail while the call keeps running |
| Rounding | Once | Every tick, so errors add up |
| Needs from the provider | A server-side time cap and a final record | A reliable heartbeat or your own timer per live call |
| Mid-call top-up | Needs a second hold and a longer cap | Natural |
Use holds for the ledger and ticks for the screen. The user watches a running total that the app computes locally; the database writes once, at the end. If you must support top-ups during a call, add a second hold and extend your own timer, keeping the provider’s cap as a safety net.
With Titli, the cap is max_duration_seconds on POST /v1/calls (10 to 86400), counted in connected seconds, and the server ends the call when it is reached. The worked version of this flow is in How to add per-minute paid video consultations to an astrology app.
The life of one call in the ledger
- RechargeCredit the walletThe payment gateway confirms a payment. One entry pair, keyed by the gateway’s payment id.
- QuoteFreeze the priceCopy the per-minute price onto the call row. Price changes after this point do not affect this call.
- HoldReserve and compute the capMove what the user can afford from wallet to hold. Cap in seconds = held amount × 60 ÷ price per minute.
- ConnectStart the visible timerThe provider reports that both people are connected. The app starts counting for display.
- TalkWrite nothingNo ledger entries while the call runs. The hold already guarantees the money is there.
- EndReceive the recordThe provider’s webhook delivers the ended call with its connected seconds, ideally signed.
- SettleCharge, release, creditIn one transaction: hold to revenue, the remainder back to the wallet, the earner’s share to earnings.
- ReconcileCheck every call againA scheduled job compares settled calls with the provider’s records and settles any that were missed.
Settle and reconcile against the signed receipt
Settlement reads the provider’s record, never the app’s. Subtract any free seconds, multiply by the frozen price, round once, and cap the charge at the hold.
// Settle ONE call from the provider's server-side record. Safe to run twice: the keys are unique.
export async function settle(callId, record) { // record = the signed receipt of the ended call
const c = await db.calls.find(callId); // holds pricePerMinuteMinor and heldMinor, written before the call
const seconds = Math.max(0, record.connected_seconds - record.free_seconds);
const owed = Math.ceil((seconds * c.pricePerMinuteMinor) / 60); // ONE rounding, at the end
const charge = Math.min(owed, c.heldMinor); // never more than was held
const release = c.heldMinor - charge;
await db.transaction(async (tx) => {
await tx.move({ from: `hold:${c.userId}`, to: 'revenue', amount: charge, kind: 'charge', key: `call:${callId}:charge` });
await tx.move({ from: `hold:${c.userId}`, to: `wallet:${c.userId}`, amount: release, kind: 'release', key: `call:${callId}:release` });
await tx.move({ from: 'revenue', to: `earnings:${c.hostId}`, amount: Math.floor((charge * c.hostSharePct) / 100), kind: 'earning', key: `call:${callId}:earning` });
await tx.calls.update(callId, { status: 'settled', seconds, record });
});
}A webhook is a notification, not a guarantee. With Titli, failed deliveries are retried after 10 seconds, 1 minute, 5 minutes and 30 minutes, and can arrive more than once or out of order. So add a job that does not depend on them:
// reconcile.js: a nightly job. Nothing here trusts a webhook having arrived.
for (const c of await db.calls.where({ status: ['created', 'active'], olderThanMinutes: 90 })) {
const r = await fetch(`${API}/v1/calls/${c.callId}/receipt`, { headers: { Authorization: AUTH } });
if (r.status === 409) continue; // call_not_ended: still running
const { receipt, signature } = await r.json();
if (!verifyReceipt(receipt, signature)) throw new Error(`bad receipt ${c.callId}`); // Ed25519, see below
await settle(c.callId, receipt); // idempotent, so a late webhook changes nothing
}The receipt is signed with Ed25519 over its canonical JSON (object keys sorted recursively, no whitespace), and the public key comes from GET /v1/receipts/public-key. Verifying it locally means a forged “call ended” request cannot move money, and a stored receipt can be shown to a user or an auditor months later. The verification code is in Webhooks and signed receipts; the events are in the webhooks reference.
Reconcile money as well as calls. Once a day, the sum of what you charged users for calls should match your own records call by call, and the sum of the provider’s amounts should match the provider’s usage report (with Titli, GET /v1/usage) for the same day.
Drops and reconnects
Mobile calls drop. The wallet must not punish the user for it, and must not give time away either.
- Do not end the hold on the first disconnect. Treat a call as over only when the provider says it is over. With Titli, when everyone leaves the call stays open for 30 seconds, and a rejoin inside that window continues the same call with the same id.
- Bill connected time, not wall-clock time. A provider that bills only while two people are connected gives you connected seconds directly. Charge your user on the same number, so a 20-second gap costs nobody anything.
- Pause the visible timer. Drive it from the SDK’s connection state so it stops while the app is reconnecting. The user should see the same number the receipt will show.
- Decide what a failed call is. If the second person never joined, connected seconds are zero: release the whole hold automatically, without a support ticket.
- Never leave a hold open. Give holds an expiry. If no record has arrived after your longest possible call plus a margin, the reconcile job fetches it or releases the hold.
Rounding rules
Rounding is a product decision with accounting consequences, so make it once and write it down. Take a call of 437 seconds (7 minutes 17 seconds) at an example price of ₹25 a minute.
| Rule | Calculation | The user pays |
|---|---|---|
| Per second, rounded up to the paisa | 437 × ₹25 ÷ 60 = ₹182.0833, rounded up | ₹182.09 |
| Per second, rounded down | The same, rounded down | ₹182.08 |
| Per started minute | 8 minutes × ₹25 | ₹200 |
| Per completed minute | 7 minutes × ₹25 | ₹175 |
The spread between the rules is ₹25.00 on one short call, which is why the rule must be visible before the call starts. Whatever you choose:
- Round once. Charging a rounded amount every 10 seconds on this call over-collects 14 paise compared with rounding once at the end. Small, but it is in every call, and always in the same direction.
- Round the split separately. Compute the earner’s share from the final charge and round it down; the remainder stays in revenue, so the two always add up to what the user paid.
- Know your provider’s unit. Your price is per call-minute to the user. Many providers, including us by default, bill per participant-minute: this call costs the app 2 × 437 ÷ 60 × ₹0.20 = ₹2.91 in call minutes. See Per-minute pricing explained.
Free seconds and promotions
A free first minute is a promotion, and promotions belong in the ledger like everything else. Charge the free seconds to a promo account instead of skipping the entry, and your reports will show what the offer costs.
- Subtract free seconds from the seconds you charge, never from the price. The price snapshot stays clean.
- Track eligibility on the server, per user, with its own idempotency key. “First call free” must survive a reinstall.
- If your provider has its own free allowance, read it from the record. Titli’s optional free seconds per end user (a first-time allowance and a daily one, set on your account) are reported as
free_secondson the receipt, andGET /v1/end-users/{end_user_id}shows what a user has left before the call. - Add free seconds to the cap. A user with a 60-second offer and money for 400 seconds can talk for 460.
Refunds
A refund is a new entry that reverses part or all of a charge and names the entry it reverses. Three kinds cover almost every case.
| Kind | When | Entries |
|---|---|---|
| Automatic release | The call never connected, or ended early | Hold back to wallet. Part of normal settlement, not really a refund |
| Goodwill credit | Poor quality, a late adviser, a complaint you accept | Promo or revenue to wallet, and decide whether the earner’s share is clawed back |
| Money back | The user wants the recharge returned | Wallet to gateway refund, limited to unspent, paid-in balance |
Keep bonus credit and paid-in credit distinguishable, because only paid-in money can go back to a bank account. And note what a refund does not change: the provider’s bill for minutes that really happened. Your provider relationship and your user relationship are separate ledgers.
What to show the user
- Before the call: the price per minute, the billing rule (“billed per second” or “per started minute”), the wallet balance and how many minutes it buys.
- During the call: elapsed time and running cost, and a warning with about a minute left that offers a recharge.
- After the call: duration to the second, free seconds, the price, the amount charged and the new balance. These are the numbers from the record, so they match what support will see.
- In the wallet history: one line per ledger entry in plain words: recharge, call with a named person, refund.
Frequently asked questions
Should I debit the wallet every minute or once at the end?
Hold the amount the user can afford before the call, then charge once at the end from the provider’s record and release the rest. Per-minute ticks are useful for what the user sees on screen, but as ledger writes they multiply rounding errors and failure cases.
What is the source of truth for call duration?
The provider’s server-side record of connected seconds, ideally one that is signed. A timer in the app can be paused, killed or tampered with, and two phones never agree to the second.
What happens to billing when a call drops and reconnects?
It depends on the provider, so test it. With Titli Video SDK a call stays open for 30 seconds after everyone leaves, a rejoin inside that window continues the same call, and nothing is billed while fewer than two people are connected.
How should I round per-minute charges?
Keep money in integer minor units such as paise, compute the charge from total seconds, and round once at settlement. Decide whether you bill per second or per started minute, and show that rule to the user before the call.
How do I stop a user being charged twice for one call?
Give every ledger entry an idempotency key built from the call id and the kind of entry, and enforce it with a unique index. A retried webhook then fails the insert instead of creating a second debit.
Do I need my own wallet if the video API already has a prepaid balance?
Yes. The provider’s prepaid balance is what your company owes the provider for minutes. Your user’s wallet is what the user has paid you. They have different owners, prices and refund rules.
Next steps
- See the whole flow with real requests: per-minute paid consultations in an astrology app.
- Read how connected time is metered in Billing and usage and how events are signed in Webhooks.
- Try it: the quickstart gets two people into a metered call, and the pricing page has the rates.
- Building for health? Telehealth video consultation app in India. Still choosing a vendor? The 12-point checklist.
