Skip to content

Realtime

Last updated: 2026-11-26T03:21:52-03:00 (UTC-3)

Real-time voice conversations (the OpenAI and Azure Realtime API) go through the gateway like any other model: the key is checked before the connection, the provider credential stays on the server, and every response of the session is admitted, reserved, metered and settled on its own, like an HTTP request. Flag: realtime; the key needs the route:realtime scope.

models:
- id: voice
capabilities: [realtime]
targets: [{provider: azure, model: rt-mini}] # on Azure, the deployment name
realtime: # optional; these are the defaults
max_session: 30m # 1m to 24h
max_sessions_per_key: 100 # across every replica
key_session_limits: {} # per key ID, e.g. {key_voice_app: 500}
default_max_output_tokens: 4096

Each session captures the loaded realtime settings when it connects. An administrative refresh or an unrelated API/console edit preserves all four settings, including the per-key limits and the default output reservation. YAML baseline edits require a rollout. The optional runtime editor below creates a separate persisted override; it never replaces the settings of an already connected session.

client = AsyncOpenAI(base_url="https://gateway.example/v1", api_key=gateway_key)
async with client.realtime.connect(model="voice") as conn:
...

The gateway checks, in order, and refuses before the provider is called:

Check Refusal
Key, scope, RPM (the upgrade counts as one request) 401, 403, 429 rate_limit_exceeded
Alias, capability, OpenAI-compatible provider 403, 404, 422
A slot of the instance’s inference limit, held for the whole session 503 overloaded with Retry-After
Quota storage, when budget_limits or tpm_limits is on 503 quota_unavailable
A budget applies but the realtime model’s approved rate has no audio prices 422 quota_profile_unsupported
The key’s concurrent sessions, across replicas 429 realtime_session_limit with Retry-After
The session limit storage 503 realtime_session_limit_unavailable

A key under a budget or TPM policy gets a session: the limits are applied to each response inside it, below.

The gateway reads both directions as WebSocket messages and forwards each one whole and unchanged. That lets it see the events it accounts for, drop a client event, and add its own events between two others. Compression (permessage-deflate) is never negotiated: the client’s offer is not forwarded.

A response is admitted in the same order as an HTTP request: RPM (each response counts as one request), then the budget/TPM reservation, then the durable receipt.

  • Client response.create: admitted before it is forwarded. When it is refused, the event is dropped, the client gets an error event, and the session stays open.
  • Response the provider starts by itself (server VAD, or a request the gateway let through): admitted at response.created. When it is refused, the gateway sends response.cancel to the provider and an error event to the client. What the provider produced before the cancel is recorded in the usage, without a reservation.
  • One response at a time: while a response is in flight, a second response.create is forwarded without a second reservation; the provider answers it with its own error. If the provider starts it anyway, it is admitted at response.created, so no response runs unmetered.
  • Refused by the provider: when the provider answers a response.create with an error that names its event_id, the reservation is released. Set event_id on response.create for this; without it, the admission waits for the next response the provider starts.

The error event follows the provider’s format:

{"type": "error", "event_id": "evt_gw_…",
"error": {"type": "invalid_request_error", "code": "budget_exceeded",
"message": "Quota policy team-acme has no room for this response",
"param": null, "event_id": "<your event_id>", "retry_after": 3600}}
code Meaning
budget_exceeded, tpm_exceeded, tpd_exceeded A quota policy has no room; retry_after in seconds
rate_limit_exceeded A request rate policy is full; message names it (ID, limit, window and UTC reset), retry_after in seconds
quota_profile_unsupported The response cannot be reserved (input estimate above the profile limit, rate missing)
quota_unavailable, rate_limit_unavailable, durable_usage_unavailable Storage failed; nothing was sent (type: server_error)
session_closing The session is closing (ceiling or drain); no new response is admitted
invalid_event Under a limit, a client event that is not valid JSON is dropped
session_unmetered The session is being closed because it could no longer be metered (below)
Part Estimate
Input The last response’s input_tokens + output_tokens (the whole conversation is billed again on each response) + what was added since + 4096 for what the gateway does not see (default instructions, tools)
Audio added Decoded bytes of input_audio_buffer.append (and audio in conversation.item.create), converted by the session’s input format (pcm16 24 kHz: 48,000 bytes/s; G.711: 8,000 bytes/s; an unknown format counts as G.711) at 20 tokens per second, twice the provider’s documented one token per 100 ms
Text added One token per byte of conversation.item.create, session.update and response.create, the same upper bound as the HTTP estimate
Output The response’s max_output_tokens, else the session’s (max_output_tokens, or max_response_output_tokens in the beta API); "inf" or absent takes realtime.default_max_output_tokens (4096, the provider’s documented maximum)

A limit the client asks for in session.update applies at once only when it makes the estimate larger; a smaller one waits for the provider’s session.updated.

Price: the reservation charges every input token at the higher of the approved text and audio input prices, and every output token at the higher of the output prices, so it is never below any mix of the two. A budget on a realtime model needs an approved rate with audio prices:

quotas:
rates:
- provider_id: openai
model: gpt-realtime
connection: "<hash shown in the console>"
input_usd_per_million: "4"
output_usd_per_million: "16"
audio_input_usd_per_million: "32"
audio_output_usd_per_million: "64"
revision: rt-1

TPM alone needs no rate.

On response.done, also with status cancelled, failed or incomplete (they carry usage), the reservation is swapped for the reported usage: TPM takes the token totals; the budget prices input_token_details (text, audio) and output_token_details (text, audio) each at its own approved price. Cached input is charged at the full price: the gateway does not assume a discount it cannot price. A response.done with counters that do not add up, or with image input tokens, keeps the reservation held instead of charging it as text.

If the session ends while a response is running (client disconnect, provider close, ceiling, drain, emergency stop), the outcome of that response is unknown: its reservation stays held (not released, not zeroed), and its durable receipt becomes indeterminate, exactly like an HTTP request cut mid-answer.

A frame outside the supported profile (compression bits, wrong masking, unknown opcode), a message above 16 MiB, or a provider event that is not valid JSON:

  • with a limit in force (a budget, TPM or RPM policy applies to the key): the client gets an error event (session_unmetered) and the session closes with 1011, so it never runs unmetered; responses in flight are held;
  • with no limit: that direction is relayed byte for byte from then on, metering stops (realtime_metering_stopped in the log, at Warn) and the session goes on.
  • Per key: realtime.max_sessions_per_key (default 100) or realtime.key_session_limits per key ID. The count is shared by every replica through a lease in PostgreSQL, renewed every 10 s; a replica that dies stops renewing and its sessions stop counting after 30 s. Ephemeral tokens count against the key that issued them.
  • Duration: realtime.max_session (default 30 minutes). On the ceiling or a drain, the gateway stops admitting responses, waits up to 5 s for the response in flight to finish, then closes with 1001. On shutdown the gateway waits for its sessions to settle before closing the database.
  • Inference slot: a session holds one slot of the instance’s inference limit for its whole life.
  • Fallback: only the first target is used; a session cannot fall back after the upgrade.
  • One usage event per response, operation realtime, with the response’s tokens and cached input; its status is 200 (completed, incomplete), 499 (cancelled, or the client left), 502 (failed, or the provider closed), 504 (session ceiling), 503 (drain, stop), 429/503/422 (refused by the gateway).
  • One event for the session itself (status 101, no tokens), so nothing is counted twice.
  • All of them carry the upgrade’s request_id and trace_id: the request ID finds every response of a session. Logs add realtime_session_id (realtime_session_started, realtime_response, realtime_session_ended), with the reservation ID and the text/audio split of each response.
  • With durable_usage, each admitted response has its own durable receipt.

With realtime_client_secrets, the application’s backend exchanges the gateway key for a short-lived token and hands only the token to the browser:

Terminal window
curl https://gateway.example.com/v1/realtime/client_secrets \
-H "Authorization: Bearer $GATEWAY_KEY" -H 'Content-Type: application/json' \
-d '{"expires_after":{"anchor":"created_at","seconds":600},"session":{"type":"realtime","model":"voice"}}'
new WebSocket("wss://gateway.example.com/v1/realtime?model=voice",
["realtime", "openai-insecure-api-key." + token]);
  • Scope: the token (ek_gw1.…) is valid only for /v1/realtime, only for the model it was issued for, for 10 s to 2 h.
  • Revocation: revoking the key that issued it revokes the token, because each use resolves the key again.
  • Subprotocol: only ephemeral tokens are accepted there; a long-lived key is refused (401). The gateway responds by selecting realtime, without which the browser drops the connection.
  • Metering: unlike the OpenAI secret, which takes the browser straight to the provider, the session goes through the gateway, so per-response admission, quotas, session limits, logs and panic still apply.
  • Session configuration: instructions and voice are sent with session.update after connecting.
  • Input audio transcription (input_audio_transcription) is billed by the provider separately and is not reserved.
  • A response the provider starts by itself is reserved when it starts, not before: if it is refused, what it produced up to the cancel is recorded but not charged to the budget.
  • Out-of-band responses (conversation: "none") are estimated as if they used the whole conversation.
  • Gemini Live is not supported.

With boot_settings_view and authorized global configuration access, Settings & sources → Inspect session, vector and integration policies shows the four existing Realtime policies. The same bounded view is returned as infrastructure.realtime_settings by GET /api/v1/admin/config. It is read-only and remains separate from the operational realtime flag; inspecting a policy does not activate sessions.

YAML parameter Default Inspection
realtime.max_session 30m Maximum session duration; accepted range 1m–24h
realtime.max_sessions_per_key 100 Default concurrent-session ceiling per key, across replicas; up to 100,000
realtime.key_session_limits {} Only the number of overrides, up to 1,024; never key IDs or their individual limits
realtime.default_max_output_tokens 4096 Existing output reservation fallback; up to 100,000

Every row includes its default, decoded default/yaml origin and rollout requirement. Explicit default values and numeric zero (which selects the existing fallback) retain YAML provenance; an empty session duration selects the default. Unknown programmatic factories show unavailable value/source rather than inferred provenance. These are loaded boot policies, not live session counts, a provider capability claim, or an update to an already connected session. The per-key map is never exported through this summary.

The existing session duration, global session limit and output-token fallback share parameter definitions with validation and the safe console view. The per-key map remains its existing YAML policy: at most 1024 entries, key IDs of 1–256 UTF-8 bytes, and each limit 1–100000. Its readonly schema exposes these bounds with a null default for the nil/omitted map; an explicit empty map also has no overrides. The safe applied row reports only the configured entry count, whose default is zero. It does not list key IDs or create another count setting. An empty map uses the global policy. Global raw zero selects the existing defaults, while a map entry must have a positive limit. Boot changes require rollout and connected sessions retain their snapshots.

Manage policy without reconnecting existing sessions

Section titled “Manage policy without reconnecting existing sessions”

Enable features.realtime_management (default false) with realtime, ui and PostgreSQL. Settings & sources → Realtime policy and GET, PUT, DELETE /api/v1/admin/realtime-policy share the same global configuration version and audit. realtime:read belongs to global admin/viewer; realtime:manage belongs only to global admin. The flag grants no permission. The dedicated read response includes nonsecret per-key policy IDs; the general startup inspector continues to expose only their count.

PUT replaces all four fields, with no partial merge:

{"version":4,"realtime":{"max_session":"1h","max_sessions_per_key":100,"key_session_limits":{},"default_max_output_tokens":4096}}

Use the version just returned by GET. Empty max_session selects the compiled 30-minute default; zero sessions/output selects defaults 100/4096. These sentinels select defaults, not the previous YAML value. An empty map clears per-key overrides. Duration bounds are 1 minute–24 hours; sessions and reservation tokens are 1–100000. The map permits up to 1024 distinct nonempty IDs of at most 256 UTF-8 bytes, each with a positive session limit. API fields are required with exact canonical names; nulls, duplicates, unknown fields and invalid types are rejected. DELETE accepts only {"version":4} and restores YAML; deleting a missing override returns 404.

GET distinguishes the raw saved override from normalized effective values, with a source for each field, restart_required:false and applies_to:"new_sessions". A complete override has source console even when a sentinel chooses a compiled default. Runtime policy is separate from the immutable startup summary and does not depend on boot_settings_view.

Each new upgrade request captures its replica’s current snapshot before admission. Replicas converge asynchronously; a handshake already in progress can retain the old policy even if its upgrade completes after a save. Connected sessions keep their duration, output-reservation fallback and leases. Lowering a limit denies new leases until the live population falls below that limit; it does not disconnect existing sessions. default_max_output_tokens sizes quota reservations when a session/response supplies no numeric cap: it does not impose a generation limit on the provider or rewrite its session messages.

A 409 keeps the original console draft; reload, review and explicitly adopt the current version before saving. Denied access clears the draft and requires refreshed parent permissions before editing can return. A database/read-validation failure preserves each replica’s last valid snapshot. A post-commit refresh failure returns 503 configuration_sync_pending; reload before retrying because the write may have committed. Turning off management restores the local YAML/default baseline for new requests while preserving the dormant override for re-enable. Changing this management flag does not terminate existing sessions.

Migration98 adds only the runtime policy singleton. Back up and roll out all replicas before enabling management; old binaries refuse a newer schema at restart, and existing old replicas do not implement the editor. Schema downgrade is unsupported. Upgrade procedure.

m7gtwcontact@m7gtw.com