> ## Documentation Index
> Fetch the complete documentation index at: https://docs.slng.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# WebSocket integration guide

> Production patterns for SLNG WebSocket integrations. Reconnection, backpressure, audio buffering, error handling, and troubleshooting common issues.

This guide covers what you need to build a production-ready WebSocket integration. For message types and parameters, see the [WebSocket protocol reference](/websockets).

**Prerequisites:**

* Familiarity with the [SLNG WebSocket protocol](/websockets)
* A working WebSocket connection (see the [TTS](/examples/tts-websocket) or [STT](/examples/stt-websocket) quick starts)

***

## Best Practices

Items 1 and 2 are required for any production integration. Items 3-6 improve quality and resilience.

### 1. Connection Management

**Implement Reconnection Logic:**

```javascript theme={null}
class ResilientWebSocket {
  constructor(url) {
    this.url = url;
    this.backoff = 1000;
    this.maxBackoff = 30000;
    this.connect();
  }

  connect() {
    this.ws = new WebSocket(this.url);

    this.ws.onclose = () => {
      console.log(`Reconnecting in ${this.backoff}ms`);
      setTimeout(() => this.connect(), this.backoff);
      this.backoff = Math.min(this.backoff * 2, this.maxBackoff);
    };

    this.ws.onopen = () => {
      console.log("Connected");
      this.backoff = 1000; // Reset backoff on successful connection
    };
  }
}
```

### 2. Error Handling

Always handle errors gracefully:

```javascript theme={null}
ws.onerror = (error) => {
  console.error("WebSocket error:", error);
  // Notify user, attempt recovery
};

ws.onmessage = (event) => {
  if (typeof event.data === "string") {
    const message = JSON.parse(event.data);
    if (message.type === "error") {
      handleServerError(message.code, message.message);
    }
  }
};
```

### 3. Buffer Management (TTS)

Use flush strategically to control latency vs. quality:

```javascript theme={null}
// For low latency: flush after each sentence
ws.send(JSON.stringify({ type: "text", text: sentence }));
ws.send(JSON.stringify({ type: "flush" }));

// For better quality: batch multiple sentences
ws.send(JSON.stringify({ type: "text", text: paragraph }));
// ... send more text ...
ws.send(JSON.stringify({ type: "flush" })); // Flush at the end
```

### 4. Audio Format Consistency

Ensure your audio format matches configuration:

```javascript theme={null}
// Configuration
{
  encoding: 'linear16',    // 16-bit PCM
  sample_rate: 16000       // 16kHz
}

// Audio capture must match:
// - 16-bit samples
// - 16000 Hz sample rate
// - Single channel (mono)
```

### 5. Heartbeat/Keep-Alive

Send keep-alive messages to prevent idle disconnection. For STT sessions, use the built-in `keepalive` message type. For TTS, use a WebSocket ping frame:

```javascript theme={null}
// STT: use the protocol-level keepalive message
let keepaliveInterval = setInterval(() => {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: "keepalive" }));
  }
}, 10000); // Every 10 seconds

ws.onclose = () => {
  clearInterval(keepaliveInterval);
};
```

### 6. Interruption Handling (TTS)

<Note>[SLNG Voice Agents](/voice-agents) handle interruptions automatically via `enable_interruptions`. This only applies if you manage TTS WebSocket connections yourself.</Note>

When building your own voice agent, stop TTS output as soon as the user starts speaking:

* Send `{ "type": "close" }` to stop server-side generation and end the session
* Send `{ "type": "clear" }` to discard queued audio (keeps the session open)
* Clear your local audio buffer and stop playback

For complete patterns (immediate interrupt, clear-and-restart, fade-out, voice agent loop), see [TTS WebSocket examples](/examples/tts-websocket#interruption--cancellation-patterns).

***

## Troubleshooting

For WebSocket error codes and fixes for connection drops, choppy audio, delayed transcriptions, and authentication failures, see [Error Codes & Troubleshooting](/reference/errors).

***

## Next Steps

<CardGroup cols={2}>
  <Card title="WebSocket protocol" icon="plug" href="/websockets">
    Message types, parameters, and connection URLs
  </Card>

  <Card title="Protocol comparison" icon="arrow-left-right" href="/protocols">
    HTTP vs. WebSocket: when to use each
  </Card>

  <Card title="TTS examples" icon="bolt" href="/examples/tts-websocket">
    JavaScript and Python code for real-time TTS
  </Card>

  <Card title="STT examples" icon="waveform" href="/examples/stt-websocket">
    JavaScript and Python code for real-time STT
  </Card>
</CardGroup>
