OpenAI Realtime API Usage Tracking: Meter Audio Tokens

Track OpenAI Realtime audio tokens from server-side response events, deduplicate each response, finalize sessions safely, and submit validated quantities to UsageBox.

12 min read

OpenAI Realtime API usage trackingaudio token meteringWebRTC sidebandresponse.doneAPI usage accounting
Quick answer: keep browser audio on WebRTC, but collect billable usage through a server-side sideband connection. Persist each response.done usage object once by response ID, mark missing final usage as unconfirmed, and send numeric meter quantities to UsageBox from a durable outbox. Call duration alone is not a reliable token-cost measure.

Choose the voice architecture before writing the UI

The Realtime API is a good fit when you want speech, reasoning, and tool use inside one live session. It gives an application a streaming conversation where a person can speak, interrupt, and hear a spoken response without building a transcription request, a text model request, and a separate text-to-speech request for every turn. OpenAI's voice-agent guide also describes chained voice pipelines, where speech recognition, an agent, and speech generation remain separate steps. Choose a chained design if you need to inspect or transform the transcript between stages, swap each provider independently, or retain a text-first policy layer. Choose Realtime when direct speech-to-speech interaction is the simpler product requirement.

This distinction affects your cost ledger as well as latency. A chained design can produce a transcription charge, a model charge, and a voice charge. Realtime usage is attached to the responses generated during a session, with separate treatment for optional input transcription. The design should decide which provider usage records are authoritative before you build dashboards or customer-facing summaries.

Step 1: keep credentials and session policy on the server

Never put a standard OpenAI API key into JavaScript shipped to a browser or mobile app. The browser is an untrusted client: a user can inspect its code, requests, and storage. Make a small authenticated route in your application server that creates a Realtime session or mints a temporary client secret. The server authenticates to OpenAI with the standard key; it returns only the limited credential or session material the client needs. OpenAI's current WebRTC documentation describes both a unified session route and ephemeral client secrets. For a browser, it recommends WebRTC rather than WebSockets for more consistent performance.

Use this route as a policy boundary. Check the signed-in user, the right to start a call, any product-specific concurrency limit, and the allowed session configuration before you ask the provider for a credential. Keep the model, voice, instructions, and enabled tools on a server-controlled allowlist. Do not accept an arbitrary model name, tool list, or prompt from a public request and forward it unchanged. Apply a per-user or per-account start limit, protect the route from cross-site requests, and avoid writing ephemeral credentials to logs. If you need an OpenAI safety identifier, set it on the server request that creates the client secret; the provider's guide says the identifier is bound to the resulting temporary token.

Step 2: connect the browser with WebRTC

The browser creates an RTCPeerConnection, requests microphone access only after the person takes an explicit action, adds the local audio track, and creates a data channel for session commands and transcript events. It then exchanges the session description with your server or with the Realtime endpoint using the short-lived credential. The remote audio arrives as a media track. The data channel is for control messages and events, not for manually forwarding each audio frame when the WebRTC media path is active.

In practical terms, separate the connection lifecycle into visible states: permission requested, connecting, connected, reconnecting, closing, and closed. Provide a clear stop control and a visible microphone indicator. Handle a denied permission request, browser autoplay restrictions, an expired temporary token, network changes, a provider error, and a user who closes the tab. Treat the browser's local clock and its own estimate of call length as UI aids; they are not your billing record.

For a first version, keep the screen small: a start button, connection state, mute control, transcript area if your product needs one, and a clear end-call action. Do not store a transcript merely because the API can provide one. Decide whether it is necessary, who can see it, how long you retain it, and how a user can request deletion. Voice data and transcripts can contain personal information even when the product is framed as a simple support assistant.

Step 3: make tools narrow and permission-aware

A voice model may request an application function such as checking an order or looking up an appointment. The request is not authorization. Your server must validate the function name and arguments, confirm that the authenticated person can access the referenced record, and enforce business rules before it performs a read or write. Return only the fields the agent needs. For actions with an external consequence, such as cancelling an order, changing a booking, or issuing a refund, add confirmation or a human review step appropriate to the action.

Design a tool response for failure as carefully as for success. A timeout should not be narrated as a completed transaction. Return a short, typed result that distinguishes found, not found, unavailable, and requires confirmation. Set a deadline for each tool and decide whether a safe retry exists. If the same call could create a duplicate side effect, use an idempotency key in your own business service. The model can say that it is checking; your server decides whether a transaction actually happened.

Test interruptions and overlapping speech. When a person interrupts an answer, stop or cancel work that no longer matters, avoid speaking the cancelled answer over the new request, and keep your tool state tied to the correct conversation turn. Add a maximum session duration and an explicit inactivity policy. Neither setting replaces usage metering, but both make the product behavior understandable and help contain accidental long-running sessions.

Step 4: collect the provider's usage, not just elapsed minutes

Realtime bills conversational responses by input and output tokens. Later turns can include earlier conversation items as input, and cached input is reported as a subset of input rather than a second quantity to add. The response.done server event carries a response ID, status, total input/output tokens, and modality details such as audio, text, and cached tokens when available. A cancelled or incomplete response can have a different status; retain the status and the usage object the provider actually returned.

A browser can observe its data-channel events, but it is a user-controlled client. For a trusted usage record, attach your backend to the same Realtime call with a server-side WebSocket, keep the standard API key there, and bind the provider call ID to the authenticated user's server-side session row. OpenAI documents this sideband path for WebRTC calls. Do not accept an arbitrary call ID from the browser and attach to it without checking that the session belongs to the current user.

import WebSocket from "ws";

export function attachUsageSideband({ session, authenticatedUserId, db, reportError }) {
  if (session.userId !== authenticatedUserId || !session.providerCallId) {
    throw new Error("No authorized provider session");
  }

  const url = "wss://api.openai.com/v1/realtime?call_id=" + encodeURIComponent(session.providerCallId);
  const socket = new WebSocket(url, {
    headers: { Authorization: "Bearer " + process.env.OPENAI_API_KEY },
  });

  socket.on("message", (raw) => {
    let event;
    try { event = JSON.parse(raw.toString()); } catch (error) { reportError(error); return; }
    if (event.type !== "response.done") return;

    const response = event.response;
    if (!response?.id || !response.usage) return;
    // Enforce a unique database key on (session.id, response.id).
    // Replayed events then cannot add the same response twice.
    db.insertResponseIfAbsent({
      sessionId: session.id,
      responseId: response.id,
      status: response.status,
      model: session.model,
      usage: response.usage,
    }).catch(reportError);
  });

  return socket;
}

The runnable Node.js sideband and UsageBox example stores each response once, separates input and output metering, checks the API result, and includes tests with a fake HTTP client. Production services should replace its single-process file ledger with a database unique constraint on the response ID and a transactional outbox.

When the user hangs up or the transport closes, mark the application session as closing and wait for the provider events already in flight. If the connection fails before final usage is persisted, label the response or session as usage unconfirmed; do not turn elapsed audio time into a made-up exact token count. Reconcile the gap against the provider's usage records before treating it as final.

For a session total, sum the actual response usage records and any separately billed transcription records. Then apply the exact model's current input, cached-input, and output rates in your own rating or finance code. Store the rate version and currency used for that calculation. OpenAI changes its catalog, and model identifiers can be confused with similar names; a rate lookup should be explicit and versioned rather than guessed from the word “Realtime.” A cost estimate made before a call is useful for product planning, but provider-reported usage after the call is the better reconciliation input.

Step 5: meter quantities without pretending a meter is a price

Keep two layers distinct. Your application or finance system can calculate a provider cost from the token usage and rate card. A usage meter records a chosen quantity, such as calls completed, input audio tokens, or output audio tokens. These are useful for analyzing volume and building a separate commercial model, but a token count is not itself a dollar charge. UsageBox aggregates submitted usage quantities; it does not apply the OpenAI price card, calculate your margin, or produce an invoice.

With UsageBox, create numeric meters for the quantities you want to roll up, then submit the stored response usage from your trusted server. Each record should name the subscription, product item, and meter ingest keys, and the plan needs a charge that covers that product item and meter. Keep the UsageBox API key in the server environment. These separate one-record batches make a skipped input metric independent from an accepted output metric:

const routing = {
  subscription: process.env.USAGEBOX_SUBSCRIPTION_INGEST_KEY,
  product_item: process.env.USAGEBOX_PRODUCT_ITEM_INGEST_KEY,
};
if (!routing.subscription || !routing.product_item) throw new Error("UsageBox routing keys are required");

const measurements = [
  { dimension: "input-audio", meter: process.env.USAGEBOX_INPUT_AUDIO_METER_KEY, value: usage.input_token_details?.audio_tokens },
  { dimension: "output-audio", meter: process.env.USAGEBOX_OUTPUT_AUDIO_METER_KEY, value: usage.output_token_details?.audio_tokens },
];
for (const item of measurements) {
  if (!Number.isFinite(item.value) || item.value <= 0) continue;
  if (!item.meter) throw new Error("Missing meter ingest key for " + item.dimension);
  const record = [{ ...routing, meter: item.meter, value: item.value }];
  const result = await fetch("https://api.usagebox.com/api/v1/usage", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": process.env.USAGEBOX_API_KEY,
      "Idempotency-Key": "openai-" + responseId + "-" + item.dimension,
    },
    body: JSON.stringify(record),
  });

  const body = await result.json();
  if (!result.ok || body.processed !== 1 || body.skipped !== 0) {
    throw new Error("UsageBox " + item.dimension + " was not fully processed: " + JSON.stringify(body));
  }
}

Use real ingest keys from the account that owns these resources; never copy an example key from documentation. The response ID plus dimension makes a retry for that single quantity use the same idempotency key. A successful HTTP status alone is not enough: read processed, skipped, and skipped details before marking that dimension complete. Back off and reuse the same key for a transient 429 or 503, and retry a reported commit_failed with the same key. For a configuration skip, pause that dimension, fix the key or plan charge, and resubmit only the unrecorded dimension under a new key; never re-send an already processed quantity with a new key.

The usage event schema is intentionally small: routing keys, one value, and an optional timestamp. It does not accept arbitrary model names, customer labels, session IDs, or dollar amounts as extra event dimensions. Keep the session-to-customer mapping and full token breakdown in your own application database, and choose the supported resource keys for the aggregates you actually need. That boundary prevents a common failure: sending a large JSON object, getting an accepted response, and assuming fields the meter does not ingest were retained.

Build a reconciliation loop before charging customers

For the first release, compare three views for a sample of calls: the response usage events, the session summary in your application database, and the aggregated meter quantities. The sums should agree for the dimensions you meter. If the token events do not add up, investigate missing final responses, duplicate delivery, transcription counted twice, or a retry that used a new idempotency key. Keep provider cost reconciliation separate from customer pricing so you can change a plan without rewriting the original usage record.

Sample across short and long calls, quiet pauses, interruptions, tool use, cache hits, rejected microphone access, and sessions that end unexpectedly. Compare cost estimates with final API usage. Include a test where the browser disconnects while the server still has a provider session, and define which system closes it. If no final usage arrives, label the record as pending or estimated rather than silently treating it as zero.

When the application is ready for commercial use, make the product rule explicit: which quantity is metered, which component determines a customer's price, when usage becomes billable, and how a user can dispute a record. UsageBox can provide quantity aggregation for those chosen meters. Your product's own billing layer remains responsible for converting the quantities into a price and communicating that price to the customer.

Launch checklist

  • Keep standard provider credentials on the backend and issue only limited session credentials to the client.
  • Allowlist models, voices, prompts, and tools; authenticate each session start.
  • Use WebRTC for browser media and a data channel for supported control and event messages.
  • Attach a server-side sideband and retain each provider response's ID, status, and reported usage.
  • Record token quantities and provider costs in separate fields and separate layers.
  • Send an idempotent final usage summary from a trusted server and read skipped-record details.
  • Do not send arbitrary metadata and assume UsageBox will retain it; the usage schema is deliberately limited.
  • Reconcile sample sessions against provider logs before using the data in customer-facing billing.

Realtime is the transport and model layer. Your server owns permissions, tool effects, and the durable session record. Your pricing system owns rates. A meter owns a quantity. Keeping those jobs separate makes both the voice experience and the resulting usage totals easier to audit.

For the official browser flow and server-side event capture, consult OpenAI's Realtime WebRTC guide, server-side controls guide, and response.done event reference. For the cost assumptions, see the voice-agent pricing comparison.

Related guides

Frequently asked questions

Does a five-minute OpenAI Realtime call have a fixed price?

No. Realtime response charges depend on the input and output token usage, the model, cached input, conversation history, and optional transcription. Use the provider usage events and current rate card to calculate the completed session cost.

Can I put my standard OpenAI API key in the browser?

No. Keep the standard key on your server and use a server-created Realtime session or short-lived client credential for the browser connection.

Does UsageBox turn Realtime tokens into dollars?

No. UsageBox aggregates submitted quantities. Your application or billing system must apply the provider rate card and customer pricing separately.

Key Topics

  • •OpenAI Realtime API usage tracking
  • •audio token metering
  • •WebRTC sideband
  • •response.done
  • •API usage accounting

Related Articles

Explore more articles on similar topics to deepen your understanding of usage-based billing.

Qwen API Pricing 2026: Qwen3.8 Max, Flash & Free Quota

Qwen API pricing, October 2026: Qwen3.8 Max at $2/$6 and Flash at $0.15/$0.47 per 1M tokens, the cheaper Global deployme...

10 min readRead more

Nano Banana Pro API Pricing 2026: Cost per Image, 1K to 4K

Nano Banana Pro API pricing, October 2026: $0.134 per 1K or 2K image and $0.24 at 4K, half in Batch, vs $0.0336 for Nano...

8 min readRead more

OpenCode Zen & Go Pricing 2026: Go Plus, Limits, Free Models

OpenCode Zen and Go pricing, October 2026: Go at $10 and Go Plus at $40 with per-model dollar limits, Zen pay-as-you-go ...

10 min readRead more

Explore More Articles

Discover our complete collection of usage-based billing guides and implementation patterns.

View all articles