Realtime API
An AISIX gateway relays the OpenAI Realtime API over WebSocket at GET /v1/realtime. Before accepting the connection, the gateway authenticates the client, resolves the model alias, and enforces access and rate-limit policy. It then relays events between the client and the provider in both directions.
In this guide, you will connect a Realtime client through the gateway and review the session behavior that matters for this endpoint.
Prerequisites
Before starting, prepare the following:
- A running AISIX gateway that can serve proxy requests.
- A caller API key that can access the model alias.
- A model alias backed by a provider that serves the OpenAI Realtime protocol.
Export the gateway connection and request values for the server-side example:
# AISIX_PROXY uses http or https and has no trailing slash or endpoint path.
# The local quickstarts use http://127.0.0.1:3000.
export AISIX_PROXY="YOUR_AISIX_GATEWAY_URL"
export AISIX_API_KEY="YOUR_CALLER_API_KEY"
export AISIX_MODEL="realtime-prod"
Provider support covers OpenAI-compatible providers (adapter openai, including custom api_base deployments) and Azure OpenAI (adapter azure-openai, /openai/realtime, or /openai/v1/realtime when the provider key's api_version is v1, with a resource API key or an Entra ID credential). A gateway before 1.11.0 accepts only a resource API key on Azure OpenAI realtime sessions. Gemini Live and Bedrock use different realtime event protocols and are not served by this endpoint.
Connect a Client
Select the model with the model query parameter. Server-side clients authenticate with the standard headers:
import WebSocket from "ws";
const realtimeUrl = new URL("/v1/realtime", process.env.AISIX_PROXY);
realtimeUrl.protocol = realtimeUrl.protocol === "https:" ? "wss:" : "ws:";
realtimeUrl.searchParams.set("model", process.env.AISIX_MODEL);
const ws = new WebSocket(realtimeUrl, {
headers: { Authorization: `Bearer ${process.env.AISIX_API_KEY}` },
});
Browser clients cannot set WebSocket headers. Pass the caller API key as a subprotocol item instead, matching the flow used by OpenAI browser examples. The gateway echoes the realtime subprotocol back:
// Use an absolute HTTP(S) gateway URL with no endpoint path, such as https://gateway.example.com
const aisixProxy = "YOUR_AISIX_GATEWAY_URL";
const aisixApiKey = "YOUR_CALLER_API_KEY";
const aisixModel = "realtime-prod";
const realtimeUrl = new URL("/v1/realtime", aisixProxy);
realtimeUrl.protocol = realtimeUrl.protocol === "https:" ? "wss:" : "ws:";
realtimeUrl.searchParams.set("model", aisixModel);
const ws = new WebSocket(realtimeUrl, [
"realtime",
`openai-insecure-api-key.${aisixApiKey}`,
]);
After the connection is established, send and receive Realtime events exactly as you would against the provider directly. AISIX relays events such as session.update, audio buffers, response.create, and server events without changing their shape.
The one value AISIX rewrites is the model name inside a session object. The session.created and session.updated events name the model alias the client connected with, not the provider's own model ID. A session.update that sends that alias back is translated to the provider's model ID on the way upstream, so a client can echo the session object it was given.
Authentication and Policy
Authentication, model access checks, client IP restrictions, and rate limits run before the WebSocket upgrade completes. Budget checks run at the same point. A request that fails any of these checks is rejected at the HTTP handshake (401, 403, or 429), which clients observe as a failed connection attempt.
During the session, configured guardrails scan text events in both directions. A blocked event produces an OpenAI-shaped error event followed by connection close.
Usage Tracking
The gateway harvests usage from the provider's response.done events (and transcription-completed events for transcription sessions) and records one aggregated usage event per session, including cached-token counts. Total session tokens count toward token-based rate limits.
Session Limits
AISIX applies an idle cap between events in either direction. It resolves the cap from the direct model's stream_timeout, then its timeout, and then the deployment-wide upstream.stream_timeout_ms or upstream.timeout_ms defaults. The default deployment cap is 6000 seconds. A silent session past the resolved deadline closes with code 1001 and reason idle timeout.
To opt a model out of the deployment backstop, set timeout: 0 and make sure the model does not set a nonzero stream_timeout. Deployment operators can instead set both upstream timeout defaults to 0. See How the Timeouts Relate for the complete precedence rules. A failed upstream connection closes the session with code 1011; see Upstream Connection Failures. Opening that upstream connection has its own budget: upstream.connect_timeout_ms (5 seconds by default) bounds the whole dial, the WebSocket upgrade handshake included, so an upstream that never answers fails there instead of holding the session open.
Upstream Connection Failures
AISIX accepts the client's WebSocket upgrade before it dials the upstream, so a failed dial reaches the client as a single error frame of type upstream_error, followed by a close with code 1011 and reason upstream connect failed. The rest depends on how the dial failed:
| How the dial failed | error.message in the frame | Recorded status | error_class | Cooldown setting |
|---|---|---|---|---|
The upstream refused the upgrade with a 4xx. | The upstream's text. The frame adds the upstream's code and param when it sent them. | That status | upstream_status | trigger_statuses |
The upstream refused the upgrade with a 5xx. | The upstream's text. | 502 | upstream_status | trigger_statuses |
The upstream answered with any other status, such as a 200 that is not an upgrade. | The upstream's text. | 502 | upstream_status | trigger_statuses |
| No HTTP response arrived, for example a DNS, connection, or TLS failure. | failed to connect to the upstream realtime endpoint | 502 | transport | trigger_on_transport |
The dial exceeded upstream.connect_timeout_ms, or the kernel reported a connection timeout. | failed to connect to the upstream realtime endpoint | 504 | timeout | trigger_on_timeout |
The recorded status is the one on the usage event, the access log, and the status and outcome request-metric labels. The recorded text still names what the upstream returned, such as upstream returned HTTP 500: <text>, and trigger_statuses and honor_retry_after read the upstream's own status and Retry-After, so a refusal with 400 does not cool the model down under the default list.
AISIX reads the upstream's text as an HTTP route does, capped at 1 KiB. When there is no text to quote, the frame uses the status instead, such as upstream returned 500 Internal Server Error or upstream returned 200 OK, without code or param. That covers an empty or compressed body, and a body that stalled or was cut off. AISIX reads the body within the model's stream budget, so a stalled body holds the frame for up to one budget past the dial. A model with no budget (timeout: 0 and no stream_timeout) holds it for as long as the upstream stalls and the client stays.
An azure-openai provider key's refusal is read as an OpenAI error, so a 4xx carries the upstream's own code untranslated: DeploymentNotFound, where chat completions answers model_not_found.
A gateway at 1.8.0 or earlier records every failed dial as 502 with error_class transport.
Upstream Refusals After the Upgrade
An upstream can complete the 101 upgrade and then refuse the session. OpenAI answers a wrong API key this way: it sends an error event, then closes with code 3000.
When the upstream's side ends having sent an error event and no other frame, the client receives only the upstream's frames and its close code and reason, with no gateway frame. A connection that drops without a Close frame still closes the client with 1011, also with no gateway frame.
AISIX records such a session as a failure, with error_class upstream_in_band and the text upstream reported an in-band error: <message>. No HTTP status comes with the event, so the recorded status is read from it:
| Error event | Recorded status |
|---|---|
code is invalid_api_key | 401 |
code is invalid_model or model_not_found | 404 |
code is rate_limit_exceeded or insufficient_quota | 429 |
type is invalid_request_error, with any other code | 400 |
code is a number in the 4xx range | That value |
| Anything else | 502 |
Cooldown follows the same status through trigger_statuses. An event that maps to no status takes trigger_on_transport.
A session is usable from its first frame that is not an error event. An error event after that frame is not a refusal: OpenAI sends one for a bad client event, and the session stays open. A gateway at 1.8.0 or earlier records a refused session as a 200.
Connection Close
AISIX completes the WebSocket close handshake in both directions:
- When the client closes the session, the client receives its own close code and reason back, and the upstream receives the same code and reason.
- When the upstream closes the session, the client receives the upstream's close code and reason. The reason is relayed as the upstream sent it, cut to 123 bytes.
- A close code that cannot be sent in a Close frame, such as a missing status code or
1006, reaches the other side as1011. So does a Close frame of exactly1002with the reasonProtocol violation, because AISIX cannot tell it apart from a frame its WebSocket library substituted for an invalid code. A1002with any other reason is relayed. - Any end other than a normal close (
1000) is preceded by a Realtimeerrorevent of typeserver_errorthat says what happened: the upstream's close code and reason, a close frame AISIX could not relay, a close without a status code, a connection that failed during the session, or a connection that ended without a close frame. The exception is a session the upstream refused after the upgrade, whose ownerrorevent already told the client. A failed dial sends theupstream_errorframe described in Upstream Connection Failures instead.
Usage that arrives while the close completes is still counted. The access-log status of the session does not depend on the close code.
When the gateway shuts down, it waits for open Realtime sessions to close before it exits, as it does for streamed responses, so their usage is recorded. Size the gateway's termination grace period for the longest session you expect.
Reach the Upstream Through a Proxy
AISIX opens the upstream connection of a wss:// provider through HTTPS_PROXY, and of a ws:// provider through HTTP_PROXY, falling back to ALL_PROXY, unless NO_PROXY covers the host. The proxy must be an HTTP proxy that supports CONNECT. A SOCKS proxy is not supported: the session fails with an error event and close code 1011, and the access log records 502.
Next Steps
You have now connected a Realtime client through the gateway. Next, review Speech and Audio for the non-Realtime audio endpoints.