# WebSocket streaming and realtime

> Use the /v1/graph/ws endpoint for turn-based agent streaming and /v1/graph/live for realtime audio, with bearer auth through the 10xgraph-bearer subprotocol.

Source: https://10xgraph.com/docs/server/websockets
Last updated: 2026-11-25

The API server offers two WebSocket endpoints, `/v1/graph/ws` for turn-based runs and `/v1/graph/live` for realtime audio. Both use the same token check and handshake rate limit as HTTP. WebSockets keep a persistent connection open so the server can stream responses token-by-token, the client can resume from checkpoints, and (for realtime agents) both sides can exchange audio in near-real-time.

WebSocket auth and connection limits are part of the [security model](/docs/production/security-model).

## When to use WebSocket

Use WebSocket when the client needs true bidirectional streaming or low-latency two-way communication. For simple invoke-and-wait workflows, REST's `/v1/graph/invoke` is simpler. For streaming where the client reads until done, REST's `/v1/graph/stream` (NDJSON) is also sufficient and works in more environments (proxies, browsers without WebSocket support).

Use WebSocket for:

- **Resume workflows**: the client detects a remote tool call in the stream, executes it, and resumes the same run without losing context.
- **Realtime audio** over `/v1/graph/live`.
- **Long-lived connections**: applications that keep one socket open for many sequential runs over hours.

## Authentication

Both endpoints use the same credential methods as REST APIs. The bearer token can come from one of two places:

1. **`Authorization` HTTP header** (standard): `Authorization: Bearer <token>`
2. **`10xgraph-bearer` Sec-WebSocket-Protocol** (recommended for browsers): browsers cannot set an `Authorization` header on a WebSocket, and this keeps the token out of the URL

A `?token=` query parameter is not accepted, because a token in the URL lands in access logs, proxy logs and trace spans.

At the WebSocket handshake, the server verifies the token. Before every graph run on `/v1/graph/ws` (the client can send several messages on one socket), the token is verified again: if it expires or is revoked between runs, the server sends an error chunk and closes the socket with code 1008.

On `/v1/graph/live` there is no run boundary, so the token is checked again after the init frame and then every 30 seconds for as long as the session lasts. The checks cover expiry and revocation, and they fail closed: if the cache store that holds revocations cannot answer, the token counts as revoked. When a check fails, the server sends a fatal `session_expired` error event and closes the socket with code 1008. Reconnect with a fresh token.

**Setting the subprotocol** (if using `10xgraph-bearer`): offer two subprotocols, the sentinel first and the raw token second.

```javascript
const socket = new WebSocket(
  "wss://api.10xgraph.com/v1/graph/ws",
  ["10xgraph-bearer", TOKEN]
);
```

The server accepts both `10xgraph-bearer` and the legacy `agentflow-bearer` (deprecated until 2.0), and echoes the sentinel back as the accepted subprotocol.

## Turn-based streaming: `/v1/graph/ws`

This endpoint streams graph execution as the agent runs step-by-step. The client sends one message, the server streams back chunks, and when done, the client can send another message or close the connection. It is suitable for turn-based agents (ReactAgent, PlanActReflect, etc.) where each user message is a complete turn.

### Protocol

**Fresh run (start a new thread or run on an existing one):**

```json
Client → Server:
{
  "invoke_type": "fresh",
  "messages": [
    {"role": "user", "content": [{"type": "text", "text": "What is 2 + 2?"}]}
  ],
  "config": {
    "thread_id": "existing-thread-id-or-omit-for-new-thread"
  }
}

Server → Client (StreamChunk JSON, the same format as POST /v1/graph/stream):
{"event": "updates", "data": {"status": "invoking_graph", ...}}
{"event": "message", "message": {...}}
...
{"event": "updates", "data": {"status": "done"}}
```

The final `{"event": "updates", "data": {"status": "done"}}` chunk is sent by the server after every run on the socket. The socket stays open for the next frame.

**Resume after remote tool call:**

When a run ends on a remote (client-executed) tool call, the client executes the tool (for example in the browser) and sends the result back. The server does not inspect chunks for tool calls; detecting them is the client library's job. The `resume` frame needs `tool_result` and `config.thread_id`. Each `tool_result` message must be a `tool` message of `tool_result` blocks that answers a pending remote tool call, or the server returns 422:

```json
Client → Server:
{
  "invoke_type": "resume",
  "tool_result": [
    {"role": "tool", "content": [{"type": "tool_result", "call_id": "call-abc123", "output": "result here"}]}
  ],
  "config": {
    "thread_id": "same-thread-from-checkpoint"
  }
}

Server → Client:
(same format: StreamChunk lines, ending with updates/status:done)
```

**Resume a human-in-the-loop pause:**

A `fresh` frame can also answer an `interrupt()` pause. Send `resume` (any JSON value, including `null` to cancel) with the thread's `config.thread_id`. No `messages` are needed. Add `interrupt_id` to bind the answer to the interrupt it belongs to:

```json
Client → Server:
{
  "invoke_type": "fresh",
  "resume": {"approved": true},
  "interrupt_id": "int_abc123...",
  "config": {"thread_id": "same-thread-from-checkpoint"}
}
```

Get the id from the `interrupt` object of the `interrupted` update chunk, or from the thread state at `execution_meta.interrupt_data.interrupt.id`. If the thread is not paused, or is paused at a different interrupt, the server sends an `error` chunk and runs nothing. A `resume` that fails the interrupt's `response_schema` also gets an `error` chunk. The socket stays open. See [Interrupts](/docs/concepts/interrupts#bind-a-resume-to-its-interrupt).

### Thread IDs

- Omit `thread_id` or send `"new"` to start a new thread. The server picks the id and puts it on each chunk as `thread_id`.
- Send an existing `thread_id` to resume that thread's conversation.
- A blank or missing `thread_id` also means "start a new thread".
- With the default `runs.thread_ids` of `"server"`, a `thread_id` that does not exist is refused like a thread you do not own. Do not invent ids. See [`runs.thread_ids`](/docs/reference/api-cli/configuration#thread_ids).
- `resume` runs require `config.thread_id`.
- When auth is enabled, the thread is read through the caller's scope before each run. A foreign or unknown thread gets an `error` chunk with code `THREAD_NOT_FOUND` and the socket stays open.

### One run per thread

The server runs one graph run at a time on a thread, and each run on the socket takes the thread's lock first. A run that finds the thread busy waits up to 30 seconds. After that the server sends an `error` chunk and the socket stays open:

```json
{"event": "error", "data": {"reason": "thread is busy"}}
```

To stop the running run and take its place, add `"on_busy": "cancel"` to the frame (the default is `"wait"`). New threads are locked as soon as their id exists. When a shared cache store is configured, the lock is shared across processes. `/v1/graph/live` holds the thread's lock for the whole session.

### Request limits and error text

A frame is limited to 500 messages (in `messages` or `tool_result`), 100 content blocks per message and 1,000,000 characters of text in total. An oversized frame gets 422 from the schema check, as does an `initial_state`, `config` or `resume` nested deeper than 64 levels by default (`MAX_NESTING_DEPTH`). In production (`MODE=production`), `error` chunks from a failing node or tool carry a generic message instead of the raw exception text. Development shows the details.

### Rate limiting and concurrency

Every WebSocket handshake and every graph run on the socket counts against the global rate limit: the same bucket as REST requests, when `rate_limit` is configured.

- A handshake over the limit is refused before `accept()` with close code 1013.
- A run over the limit gets an `error` chunk whose `data` has `reason` and `retry_after_seconds`. The run is skipped and the socket stays open; the check runs again on the next frame.

A run refused because the graph is closing gets an `error` frame whose `data` has `code: "SERVICE_UNAVAILABLE"`, a `reason` and `retry_after_seconds`, and no `done` frame. The server then closes the socket with code 1012 (service restart). Reconnect, which lands on another replica.

A frame that fails to parse or validate also counts against the rate limit. After 20 invalid frames in a row the server closes the socket with code 1008. A valid frame resets the count.

A socket that sits idle is not kept past its token's expiry. When the token expires, the server checks the credential again, and if it no longer verifies it sends an `error` chunk ("Session expired. Reconnect with a valid token.") and closes with code 1008. Reconnect with a fresh token.

Connection caps apply at the handshake only: `websocket.max_connections` and `websocket.max_connections_per_user`. Over either cap, the handshake is refused with close code 1013. Live sessions on `/v1/graph/live` count against `websocket.max_connections_per_user` like any other socket.

## Realtime audio: `/v1/graph/live`

This endpoint bridges a WebSocket to a **realtime agent** (a graph rooted at a live agent, driven through `CompiledGraph.arealtime()`), enabling true two-way audio conversation. The client and server exchange audio frames and control messages in real-time, with minimal latency.

Realtime is only for agents built for it: connecting to `/v1/graph/ws` with a realtime agent closes immediately with code 1008 (use `/v1/graph/live` instead). The reverse also holds: a turn-based graph on `/v1/graph/live` is closed with 1008.

### Protocol

**Init frame (JSON, the first frame sent):** a flat object. All keys are optional; the keys the server reads are `thread_id`, `model`, `voice`, `modalities`, `vad`, `system_prompt` and `tools_tags`.

```json
Client → Server:
{
  "model": "gemini-3.8-live",
  "voice": "Puck",
  "modalities": ["AUDIO"],
  "vad": {
    "enabled": true
  },
  "thread_id": "optional-thread-id"
}
```

`/v1/graph/live` follows `runs.thread_ids` like the other routes. With the default `"server"`, a `thread_id` the server never issued is refused with a `THREAD_NOT_FOUND` error event and close code `1008`. Omit `thread_id` (or send `"new"` or a blank value) and the server creates the thread. Every session starts with a `session_started` event that carries the id, so send that id back on reconnect to continue the thread. The TypeScript client does this for you and exposes the id as `session.threadId`.

The `model` override is honored only if it is listed in `websocket.realtime_models`; otherwise it is ignored and the agent's own model is used. A bad value (for example an invalid `modalities` entry) returns a fatal `error` event with code `invalid_config`.

**Downstream (Server → Client):**
- **Binary frames**: PCM16 audio deltas from the model
- **JSON text frames**: every other event (transcripts, turn complete, interrupted, tool calls, errors)

**Upstream (Client → Server):**
- **Binary frames**: PCM16 audio input from the user/environment
- **JSON text frames**: `{"type": "activity_start"}`, `{"type": "activity_end"}`, `{"type": "text", "text": "..."}`, `{"type": "close"}`

Refer to the [realtime audio guide](/docs/guides/use-realtime-audio) for details and examples.

## Configuration

Connection caps and realtime options are under `websocket` in `10xgraph.json`; see [Control WebSocket connections](/docs/server/configure#control-websocket-connections).

## Close codes

WebSocket close codes follow RFC 6455. The server sends these in specific situations:

| Code | Meaning | Retry? |
|---|---|---|
| 1000 | Normal closure (client initiated or clean shutdown) | No |
| 1003 | Unsupported data: the `/v1/graph/live` init frame is not a JSON object or could not be parsed | No |
| 1008 | Policy violation: wrong endpoint for the agent type, token expired/revoked between runs (or during a live session), or auth/authorization failure at the handshake | No |
| 1011 | Unexpected server error during run | May retry after brief delay |
| 1012 | Service restart: the server is shutting down | Yes, reconnect |
| 1013 | Try again later: rate limit or connection cap exceeded at the handshake | Yes, after a delay |

On `/v1/graph/ws`, an `error` chunk is sent before closing for the wrong-agent-type and expired-token cases. Handshake rejections (auth failure, rate limit, connection cap) close before the socket is accepted, so no chunk is sent.

## Proxy settings

If the API server is behind a reverse proxy (Nginx, HAProxy, CloudFlare, etc.), the proxy must be configured to preserve the WebSocket connection and pass through the upgrade headers.

### Proxy compatibility

- The proxy must support HTTP/1.1 upgrade requests (WebSocket handshake).
- Connection and Upgrade headers must be forwarded as-is.
- Most reverse proxies support this by default; confirm in their documentation.

**Nginx example** (snippet):

```nginx
location /v1/graph/ws {
  proxy_pass http://backend:8000;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_set_header Host $host;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto $scheme;
  proxy_read_timeout 86400s;  # Allow long-lived sockets
}
```

For client IPs behind a proxy, see [Behind a reverse proxy](/docs/server/rate-limiting#behind-a-reverse-proxy).

## Example: TypeScript client

Here's a minimal example using the 10xGraph TypeScript client:

```typescript
import { TenxGraphClient, Message } from "10xgraph-client";

const client = new TenxGraphClient({
  baseUrl: "http://localhost:8000",
  authToken: "your-jwt-token",
});

// wsStream() has the same signature as stream(), but runs over /v1/graph/ws.
// Omit thread_id to start a new thread. The server picks it and sends it on each chunk.
const stream = client.wsStream([Message.text_message("What is 2 + 2?")]);

let threadId: string | undefined;
for await (const chunk of stream) {
  if (chunk.thread_id) threadId = chunk.thread_id;
  if (chunk.event === "message") {
    console.log("Message:", chunk.message);
  }
}
```

`wsStream()` handles remote tool calls for you: it runs registered client-side tools and sends the `resume` frame on the same socket. Use `client.stream()` for the HTTP equivalent. See [Client streaming](/docs/client/stream-responses).

## Example: Raw WebSocket in JavaScript

If you prefer to manage the WebSocket directly:

```javascript
const token = "your-jwt-token";
const socket = new WebSocket("wss://api.10xgraph.com/v1/graph/ws", ["10xgraph-bearer", token]);

socket.onopen = () => {
  console.log("Connected");
  socket.send(JSON.stringify({
    invoke_type: "fresh",
    messages: [
      { role: "user", content: [{ type: "text", text: "Hello" }] }
    ]
  }));
};

socket.onmessage = (event) => {
  const chunk = JSON.parse(event.data);
  console.log("Chunk:", chunk.event, chunk.data);

  if (chunk.event === "updates" && chunk.data.status === "done") {
    // Run finished
    socket.close(1000);
  }
};

socket.onerror = (event) => {
  console.error("WebSocket error:", event);
};

socket.onclose = (event) => {
  console.log(`Closed: code=${event.code}, reason=${event.reason}`);
};
```

## Troubleshooting

**Connection refused or 403 forbidden**
- Check that your token is valid and not expired. Verify it is passed via the `Authorization` header or the `10xgraph-bearer` subprotocol (a `?token=` query is ignored). A rejected handshake closes with code 1008.
- Confirm authentication is enabled and configured in `10xgraph.json` (`"auth": "jwt"` or custom).

**Socket closes with code 1008**
- If the message is "This graph is a live agent...", you're using `/v1/graph/ws` on a realtime agent. Switch to `/v1/graph/live`.
- If the message is "Session expired...", your token has expired or was revoked. On `/v1/graph/live` this can happen mid-session, and the server sends a `session_expired` error event first. Reconnect with a fresh token.

**Socket closes with code 1013**
- Rate limit or connection cap exceeded at the handshake. Wait and reconnect.
- Check `websocket.max_connections` and `websocket.max_connections_per_user` in your config.

**Proxy forwarding issues**
- Confirm the proxy forwards the `Upgrade` and `Connection` headers. Most proxies do by default.
- Increase proxy timeouts: WebSocket connections can be long-lived, so set read/write timeouts to several minutes or higher.

**Audio glitches or delays on `/v1/graph/live`**
- Set `vad.enabled` to `false` and drive turns yourself if automatic detection cuts speech or reacts to background noise. The other `vad` keys (`start_sensitivity`, `end_sensitivity`, `prefix_padding_ms`, `silence_duration_ms`) are deprecated, have no effect and are removed in 2.0.
- Check network latency; realtime is sensitive to round-trip time.

## Related pages

- [Invoke and stream over REST](/docs/server/invoke-and-stream) covers HTTP POST endpoints for the same operations.
- [Realtime audio guide](/docs/guides/use-realtime-audio) provides complete examples and configuration for audio agents.
- [Client streaming](/docs/client/stream-responses) documents the TypeScript client's streaming API.
- [Authentication](/docs/server/auth) explains JWT setup and token validation.
