7 things I learned charging for live AI video calls (tokens, billing, and a bundler bug)
I recently shipped a small web app where you can have a live video call with an AI character (emmaai.dev). The avatar, voice and speech recognition come from Anam; the app itself runs on Cloudflare Workers with a D1 data
I recently shipped a small web app where you can have a live video call with an AI character (emmaai.dev). The avatar, voice and speech recognition come from Anam; the app itself runs on Cloudflare Workers with a D1 database and sells prepaid credits.
The "talk to an avatar" part took an afternoon. Charging for it fairly and safely took most of a week. Here is what went wrong and what I ended up with, in case you are wiring a real-time AI API into a paid product.
1. Never let the browser hold anything that can start a session on its own
The Anam JS SDK runs in the browser, but it needs a session token, and that token is minted with your secret API key. So the browser asks your server, the server checks the user and their balance, then asks Anam for a token.
The mistake I almost made: by default, a session token can start more than one session for a while. If someone copies the token out of DevTools, they can keep starting calls that your billing never sees. So I made each token single-use and short-lived:
const res = await fetch('https://api.anam.ai/v1/auth/session-token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
personaConfig, // avatar, voice, LLM, system prompt, maxSessionLengthSeconds
maxSessions: 1, // one paid call = one session
expiresInSeconds: 120, // enough to connect, useless later
sessionOptions: {
dataRetention: { recording: false, transcripts: true },
},
}),
});
Two things follow from maxSessions: 1:
- Turn off the SDK's automatic retries on the client. A retry would need a second session, and the token won't allow it.
- If the connection fails, refund the reservation (see below) and let the user click again for a fresh token.
maxSessionLengthSeconds in the persona config is the other hard limit. Even if your own "end call" logic breaks, the provider cuts the call at that length, so a stuck tab can't keep a call running for an hour.
2. Reserve first, settle later
Live calls are billed by time, but you don't know the length up front. What worked for me:
-
Start: reserve the most a call can cost (my calls are capped at 5 minutes), or the user's whole balance if that is lower, together with a "call in progress" row. Then set the provider's hard
maxSessionLengthSecondsto exactly what was reserved, and only after that request the token. A user with 90 seconds of credit gets a call that the provider itself ends at 90 seconds. If the token request fails, the reservation goes straight back. - End: compute the billable time, charge it, and refund the rest of the reservation in a second atomic write.
On D1 there are no interactive transactions, so "atomic" here means one batch() with guard statements (for example "this call row is still processing") that make the whole batch fail if the condition doesn't hold. That guard also makes the end endpoint idempotent: if the browser calls it twice, the second call loses the race and does nothing.
I also block a second call while one is still processing for the same user. Otherwise one person could open two tabs and run two calls against a single reservation's worth of balance.
3. Don't trust the client's duration
The browser knows when the call actually connected and ended, so it reports a duration. But a modified client can report 0 seconds after a 5-minute call. The server knows when it minted the token, so it can compute a floor:
function billableSeconds(clientSeconds: number, serverElapsed: number) {
// Allow a few seconds for the WebRTC handshake before the call really starts.
const serverFloor = Math.max(0, serverElapsed - 6);
return Math.max(clientSeconds, serverFloor);
}
The client can make the call longer than the server thinks (that only costs them), but never shorter than wall-clock time minus a handshake allowance. There is one exception: if the client says "failed before connect" and the server sees that no more than 20 seconds passed, the whole reservation is refunded. Without that short window, "failed before connect" would be a free-call button.
Billing is in 10-second steps, rounded up, and never more than was reserved:
const used = Math.min(reserved, Math.max(1, Math.ceil(seconds / 10)));
const refund = reserved - used;
10-second steps felt like the right trade-off: per-minute rounding made a 61-second test call cost 2 minutes, which annoys people, while per-second billing makes the numbers in the user's history look noisy.
4. The bug that broke every call in production: buffer
Locally everything worked. In the production build, every call failed in the browser with:
Invalid session token format
The token was fine. The SDK decodes it with Buffer from the npm buffer package. My build (Vite with a server-side Workers target) treated buffer as the Node built-in node:buffer, and in the client bundle that became an empty module. So Buffer.from(...) was decoding nothing.
The fix was a small pre plugin that sends buffer to the real npm package in the client environment only, and leaves the server alone:
{
name: 'browser-buffer-package',
enforce: 'pre',
resolveId(id, importer, options) {
if (id !== 'buffer' && id !== 'node:buffer') return null;
const isClient = this.environment
? this.environment.name === 'client'
: !options?.ssr;
if (!isClient) return null;
// The trailing slash makes Node resolve the npm package, not the core module.
return require.resolve('buffer/', {
paths: [importer ? dirname(importer) : process.cwd()],
});
},
}
Lesson: if an SDK fails with a "format" error, check whether one of its dependencies was quietly replaced by a stub in your bundle before you blame the data.
5. Validate your IDs where you configure them
The second production failure: calls connected and then died immediately. The avatar and voice IDs I had used as defaults didn't exist in my account. The API happily minted a token, and the failure only appeared once the session started.
Now the admin "test connection" button doesn't just check that the API key works. It also looks up each configured avatar and voice ID and reports any that are missing. That kind of check is cheap, and it turns a confusing runtime failure into a clear message on the settings page.
6. "Busy" is not "broken"
Real-time providers limit how many sessions you can run at the same time, and small plans allow only a few. When the limit is hit, the token request fails. At first my app showed a generic "call failed, check settings" message, which made users think the site was broken.
Now the server detects this case (HTTP 429, or an error message that mentions concurrency or rate limits) and returns a distinct busy code. The UI tells the user the lines are busy and to try again shortly, and the reservation is returned, so nothing is charged.
7. Privacy defaults
Since people talk to these avatars face to face, I turned off audio/video recording completely and kept only the text transcript. That's the minimum I need to review a reported conversation, and it keeps the privacy policy short and honest.
Summary
- Mint provider tokens on the server, single-use and short-lived.
- Reserve the maximum cost before the call and refund the difference after it, in atomic writes with guards.
- Bill from server time with a handshake allowance; the client can only add time.
- If production fails and local works, look at what your bundler stubbed.
- Validate provider IDs when you save settings, not during the first paid call.
- Show "busy" as busy, not as an error.
If you've built usage-based billing for real-time AI (voice agents, avatars, streaming LLMs), I'd like to hear how you handled the "client reports the duration" problem. Did you end up with something better than a server-side floor?
This article was generated by an AI agent working from my own project's source code and incident notes. The code and the incidents are real, and the details were checked against the source before publishing.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.