The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore(realtime): add error handling information to protocol page (#46292)
Filipe Cabaçod1792a9de418
diff --git a/apps/docs/content/guides/realtime/protocol.mdx b/apps/docs/content/guides/realtime/protocol.mdxindex b823ffc50da..5170749dfc2 100644--- a/apps/docs/content/guides/realtime/protocol.mdx+++ b/apps/docs/content/guides/realtime/protocol.mdx@@ -478,7 +478,7 @@ Example on protocol version `2.0.0`:#### phx_error-This message is sent by the server when an unexpected error occurs in the channel. Payload will be an empty object+This message is sent by the server when the channel process terminates unexpectedly. Payload will be an empty object. See [Reconnection](#reconnection) for recovery guidance.```json["3", "3", "realtime:avatar-stack-demo", "phx_error", {}]@@ -500,7 +500,7 @@ The server sends these messages in response to client requests that require ackn- `status`: The status of the response, can be `ok` or `error`.- `response`: The response data, which can vary based on the event that was replied to-`phx_join` has a specific response structure outlined below.+`phx_join` has a specific response structure outlined below. When a join is rejected, `status` is `"error"` — see [Join errors](#join-errors) for the full list of error codes and recovery actions.Contains the status of the join request and any additional information requested in the `phx_join` payload.@@ -551,7 +551,7 @@ Example on protocol version `2.0.0`:#### system-The server sends system messages to inform clients about the status of their Realtime channel subscriptions.+The server sends system messages to inform clients about the status of their Realtime channel subscriptions. See [Channel-level system errors](#channel-level-system-errors) for the full list of messages and recovery actions.```ts{@@ -888,3 +888,100 @@ Example on protocol version `2.0.0`:}]```++## Error handling++Errors arrive on four channels:++- A WebSocket close frame before the channel joins.+- A `phx_reply` with `status: "error"` rejecting a `phx_join` or push.+- A `system` event on a live channel — channel-level system errors are always followed by `phx_close`, while `postgres_changes` system errors are informational and leave the channel open.+- A `phx_error` when the channel process terminates unexpectedly.++{/* supa-mdx-lint-disable-next-line Rule001HeadingCase */}++### Join errors++When a `phx_join` is rejected, the `phx_reply` payload carries `response.reason` as `"<ErrorCode>: <human message>"`. The server adds a backoff delay before replying, so avoid aggressive client-side retry loops on join errors.++```json+{+ "status": "error",+ "response": { "reason": "InvalidJWTExpiration: Token has expired 300 seconds ago" }+}+```++One exception: the `UnknownErrorOnChannel` code arrives as the bare human-readable string `"Unknown Error on Channel"` without the `<Code>: <message>` prefix. The JS client exposes the full `reason` string directly as the Error message without parsing it further.++| Category | Error codes | Action |+| -------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------- |+| Auth — expired token | `InvalidJWTExpiration` (message contains `"expired"`) | Refresh token, rejoin |+| Auth — invalid token | `MalformedJWT`, `JwtSignatureError`, `Unauthorized` | Do not retry; surface to caller |+| Rate limit | `ConnectionRateLimitReached`, `ClientJoinRateLimitReached`, `ChannelRateLimitReached` | Backoff, reduce join frequency |+| Database | `InitializingProjectConnection`, `IncreaseConnectionPool`, `DatabaseLackOfConnections`, `UnableToConnectToProject` | Retry with exponential backoff |+| Config | `TopicNameRequired`, `TenantNotFound`, `RealtimeDisabledForTenant`, `RealtimeDisabledForConfiguration` | Do not retry |+| Transient | `RealtimeRestarting` | Retry with backoff |++### Channel-level system errors++`extension: "system"`, `status: "error"`. Match on the `message` field content — there is no machine-readable code field. Every channel-level system error is immediately followed by `phx_close`; the channel is closed. Client libraries should expose a way for users to subscribe to `system` events since there is no automatic handling.++| Message contains | Cause | Recovery |+| ------------------------------------------------- | -------------------------- | ----------------------------- |+| `Too many messages per second` | Broadcast/event rate limit | Throttle sends before rejoin |+| `Too many presence messages per second` | Tenant presence rate limit | Reduce presence frequency |+| `Client presence rate limit exceeded` | Per-client presence window | Longer cooldown before rejoin |+| `Track message size exceeded` | Presence payload too large | Shrink payload |+| `Token has expired` | JWT expired mid-session | Refresh token, rejoin |+| `Fields \`role\` and \`exp\` are required in JWT` | Claims missing | Fix token issuance |+| `Server requested disconnect` | Operational disconnect | Reconnect after delay |++### Postgres Changes subscription errors++`extension: "postgres_changes"`. These do **not** close the channel — broadcast and presence continue. `status: "ok"` with `message: "Subscribed to PostgreSQL"` confirms the subscription is live.++| Scenario | Server retries? | Client action |+| ------------------------------------------------------ | ----------------- | -------------------------------------------------------------------------- |+| Invalid filter operator | No | Fix params and rejoin |+| Missing `schema`/`table` params | No | Fix params and rejoin |+| Subscription insert failed (table/publication missing) | Yes, every 5–10 s | Surface as degraded state; wait or check Realtime is enabled for the table |+| Database error during subscription | Yes, every 5–10 s | Surface as degraded state |+| `"Too many database timeouts"` | No | Reduce subscription load; retry later |++Supported filter operators: `eq`, `neq`, `lt`, `lte`, `gt`, `gte`, `in`.++The `ids` array on incoming `postgres_changes` payloads must match the subscription IDs returned in the `phx_join` reply. A mismatch means inconsistent server/client state — tear down and rejoin.++### Broadcast errors++Broadcast errors only affect **private channels**. When `config.broadcast.ack` is `false` (the default), all push failures — including size violations and RLS write denials — are silently dropped. RLS denials are always silent regardless of `ack`.++When `ack` is `true`, the server replies on error with `response.error` (an atom string), not `response.reason`:++```json+{ "status": "error", "response": { "error": "payload_size_exceeded" } }+```++Note that the JS client (`send()`) resolves to just the string `'error'` and does not expose the specific `error` atom to callers.++### Presence errors++Push replies surface payload-shape errors with `reason: "Presence track payload must be a map"`. Other push-level failures (RLS write denied, unknown event type, internal errors) return `status: "error"` with no reason field.++Presence rate-limit and size violations arrive as channel-level system errors (see above) and close the channel.++### Access token refresh++Refresh the JWT in-band on private channels without rejoining using the `access_token` event:++```json+["10", "1", "realtime:my-channel", "access_token", { "access_token": "<new-token>" }]+```++There is no reply on success. On failure, the server emits a `system` error and closes the channel. Tokens with the `sb_*` prefix are silently ignored by the server.++### Reconnection++`phx_error` (unexpected server-side channel process termination, empty payload) should trigger a rejoin with exponential backoff. The JS client uses `[1000, 2000, 5000, 10000]` ms (capped at 10 s) configurable via `reconnectAfterMs`.++`phx_close` following a rate-limit system error requires throttling before rejoin. Following a token system error, refresh the token first. A `phx_close` with no preceding system error is a clean close — only rejoin if it was unexpected. See [Limits](/docs/guides/realtime/limits) for the per-tenant thresholds that trigger rate-limit errors.