WebSocket Transport

WebSocket Relay (x402)

Consume paid x402 APIs over a shared WebSocket gateway while keeping the same payment semantics as HTTP.

RelAI supports both transports: HTTP relay and WebSocket relay. WebSocket is optimized for repeated requests in a session (agents, chats, iterative workflows), while HTTP remains a reliable fallback.

Shared Endpoint Model

Each API still has its own HTTP relay URL:

https://api.relai.fi/relay/{apiId}/...

WebSocket calls go to one shared gateway:

wss://api.relai.fi/api/ws/relay

Relay URL Mapping

Given this HTTP relay URL:

https://api.relai.fi/relay/1769629274857/v1/chat/completions?model=gpt-4o-mini

Map it to WS parameters:

  • apiId = 1769629274857
  • path = /v1/chat/completions?model=gpt-4o-mini

Request Envelope

Use method relay.call:

{
  "id": "req-42",
  "method": "relay.call",
  "params": {
    "apiId": "1769629274857",
    "path": "/v1/chat/completions?model=gpt-4o-mini",
    "requestMethod": "POST",
    "requestHeaders": {
      "Content-Type": "application/json",
      "Accept": "application/json"
    },
    "requestBody": {
      "messages": [{ "role": "user", "content": "Hello" }]
    }
  }
}

Payment Handshake

  1. Send the first request without top-level payment.
  2. If payment is required, the server responds with error.code = 402 and error.paymentRequired.
  3. Create a valid x402 payment payload.
  4. Retry the same request with top-level payment.
  5. Read result and optional paymentResponse.

Persistent Connections

  • Reuse one WS connection for many relay requests.
  • Correlate every response by id.
  • Keep per-request timeouts, not only connection-level timeout.
  • On transport errors, fall back to HTTP relay.

Frontend Integration

WebSocket transport is handled automatically by the app. End users do not need to configure any environment variables.

If WebSocket is unavailable, requests continue through HTTP fallback so payments can still complete.

For API Providers

If you are an API provider using RelAI server-side integration, you can keep your existing HTTP relay integration.

Buyers can still consume your paid endpoints over the shared WebSocket gateway, with the same x402 payment flow and automatic HTTP fallback.

Troubleshooting

No response for a request

Ensure every request has a unique id and your client matches responses by that id.

Unexpected 402 loop

Verify that the second request contains top-level payment and that payload matches one of the accepted requirements.

WS unavailable in some environments

Keep HTTP fallback enabled and set a shorter WS timeout so user flows are not blocked by long retries.