---
name: rebase-realtime
description: Guide for the Rebase WebSocket realtime engine. Use this skill when the user needs real-time data synchronization, broadcast channels, presence tracking, channel message history and reconnect catch-up (collaborative/op-based editing), table change broadcasts, or live updates in their application.
---

# Rebase Realtime Engine

Rebase includes a built-in WebSocket-based realtime engine that broadcasts database changes, supports broadcast channels for arbitrary client-to-client messaging (optionally with replayable message history), and provides presence tracking for online status.

> **IMPORTANT FOR AGENTS:** The WebSocket protocol uses specific message types that differ from typical pub/sub patterns. Read the **Message Types** section carefully before generating any WebSocket code. Do NOT invent message type names — use only the types documented here.

## Architecture

```
┌──────────────┐      ┌────────────────────┐      ┌──────────────┐
│  PostgreSQL   │─────▶│  Rebase Server     │─────▶│  Client SDK  │
│  LISTEN/NOTIFY│      │  RealtimeService   │      │  WebSocket   │
└──────────────┘      └────────────────────┘      └──────────────┘
```

The realtime pipeline has three stages:

1. **Database mutation** — A record is created/updated/deleted (via REST API, SDK, or Studio).
2. **Server fan-out** — The `RealtimeService` detects the change and fans out to every active WebSocket subscription matching the affected table or entity.
3. **Client callback** — The client SDK fires the registered `onUpdate` callback with fresh data.

For multi-instance deployments, PostgreSQL `LISTEN/NOTIFY` broadcasts **row changes** across server instances: on the `rebase_cdc` channel when database-level change capture is active (the default wherever the database role can create triggers), otherwise via the `rebase_entity_changes` channel.

> **IMPORTANT FOR AGENTS:** That covers table/row subscriptions only. **Broadcast channels and presence are per-instance unless a channel bus is configured** — see [Multi-instance channels](#multi-instance-channels-and-presence). This is the single most likely cause of "collaboration works locally but not in production": behind a load balancer, two clients on different replicas see an empty room and nothing errors.

### Zero Configuration

Realtime is enabled out of the box. There is no flag to flip or service to start. If the Rebase server is running, the WebSocket endpoint is available on the same HTTP port — at the server's root (`/`) for an API at `/api`, which is where the SDK dials. See [The socket's path](#the-sockets-path).

## Client SDK Subscriptions (Recommended)

The `@rebasepro/client` SDK provides high-level methods with automatic authentication, reconnection, subscription deduplication, and typed responses.

### Subscribing to a Table — `listen()`

```typescript
import { createRebaseClient } from "@rebasepro/client";

const client = createRebaseClient({
    baseUrl: "http://localhost:3001",
    websocketUrl: "ws://localhost:3001",
    token: myAuthToken,
});

// Subscribe to all products
const unsubscribe = client.data.products.listen(
    undefined, // FindParams — pass undefined for all records
    (response) => {
        console.log("Products updated:", response.data);   // M[] — flat rows
        console.log("Total:", response.meta.total);
    },
    (error) => {
        console.error("Subscription error:", error);
    }
);

// Stop listening when done
unsubscribe();
```

### Subscribing with Filters

Pass `FindParams` as the first argument to filter the subscription:

```typescript
const unsubscribe = client.data.products.listen(
    {
        where: { status: ["==", "published"] },
        orderBy: ["createdAt", "desc"],
        limit: 50,
    },
    (response) => {
        console.log("Published products:", response.data);
    }
);
```

The server respects these filters — only matching records are included in updates. Filter, sort, limit, offset, and searchString are all supported.

`orderBy` takes a multi-column sort here as anywhere else —
`orderBy: [["category", "asc"], ["createdAt", "desc"]]`, or a second
`.orderBy()` call on the fluent builder, which adds a tie-breaker rather than
replacing the first key.

The server validates the *shape* of `orderBy` when the subscribe frame arrives
and answers a malformed one with an error frame (`INVALID_ORDER_BY`) instead of
subscribing. This matters more here than on the REST route: a
`collection_update` frame carries rows and page metadata but nothing about how
they were sorted, so a subscriber handed rows in no particular order has no way
to learn that its sort was dropped.

### `listen()` Signature

```typescript no-verify
listen(
    params: FindParams | undefined,
    onUpdate: (response: FindResult<M>) => void,
    onError?: (error: Error) => void
): () => void   // returns unsubscribe function
```

The `FindResult<M>` contains:

| Field | Type | Description |
|-------|------|-------------|
| `data` | `M[]` | Matching rows, flat — read `row.name`, there is no `.values` wrapper |
| `meta.total` | `number` | Matching rows in total |
| `meta.limit` | `number` | Requested limit |
| `meta.offset` | `number` | Requested offset |
| `meta.hasMore` | `boolean` | Whether more records exist beyond limit |

### Subscribing to a Single Entity — `listenById()`

```typescript
const unsubscribe = client.data.products.listenById(
    "product-123",
    (row) => {
        if (row) {
            console.log("Product changed:", row);   // the flat row — no `.values`
        } else {
            console.log("Product was deleted");
        }
    },
    (error) => {
        console.error("Subscription error:", error);
    }
);
```

### `listenById()` Signature

```typescript no-verify
listenById(
    id: string | number,
    onUpdate: (row: M | undefined) => void,
    onError?: (error: Error) => void,
    options?: { include?: IncludeSpec }   // relations to load into the row
): () => void   // returns unsubscribe function
```

The callback receives `undefined` when the row is deleted.

### Unsubscribing

Both `listen()` and `listenById()` return an unsubscribe function. Call it to stop receiving updates and clean up server-side resources:

```typescript
const unsubscribe = client.data.products.listen(undefined, (response) => {
    // handle updates
});

// Later:
unsubscribe();
```

In React, use `useEffect` cleanup:

```tsx
useEffect(() => {
    const unsubscribe = client.data.products.listen(
        { where: { active: ["==", true] } },
        (response) => setProducts(response.data)
    );
    return () => unsubscribe();
}, []);
```

> **WARNING FOR AGENTS:** Always call the unsubscribe function when a component unmounts or a page navigates away. Failing to do so causes memory leaks and unnecessary server-side work.

## Query Builder `.listen()`

The fluent query builder also supports realtime subscriptions. Chain your filters, then call `.listen()` instead of `.find()`:

```typescript
const unsubscribe = client.data.orders
    .where("status", "==", "pending")
    .orderBy("createdAt", "desc")
    .limit(20)
    .listen(
        (response) => {
            console.log("Pending orders:", response.data);
        },
        (error) => {
            console.error("Error:", error);
        }
    );
```

### `.listen()` Signature on QueryBuilder

```typescript no-verify
listen(
    onUpdate: (data: FindResult<M>) => void,
    onError?: (error: Error) => void
): () => void
```

> **IMPORTANT FOR AGENTS:** `.listen()` (on the query builder and on the table client) needs a socket. Realtime is on by default and `websocketUrl` defaults to one derived from `baseUrl`, so this only bites a client created with `realtime: false`, or one whose `baseUrl` is relative outside a browser. There, calling `.listen()` throws a `RebaseClientError` with code `REALTIME_DISABLED`: `"Listen is only available when RebaseClient is configured with a websocketUrl, and not when it was created with realtime: false."`

## Update Delivery: Instant Patch + Correctness Refetch

Every update a subscriber receives is a **debounced refetch under the subscriber's own scope**. When a row changes, the server waits out a 300ms debounce window (`REFETCH_DEBOUNCE_MS`), re-runs the subscription's query with its original filters and sort order *as that subscriber* (so RLS binds the reader, not the writer), and sends the result as `collection_update` (or `single_update` for a `listenById`). Multiple rapid mutations within the 300ms window are coalesced into a single database query. The window waits for 300ms without a further change, but never more than **1s** after the first one (`REALTIME_REFETCH_MAX_WAIT_MS` / `realtime.refetchMaxWaitMs`), so a collection written several times a second still sends a frame at least once a second.

There used to be an instant row patch (`collection_patch`) ahead of the refetch. Nothing sends it any more: it carried the row as the *writer* had read it, which a subscriber the row's RLS hides could see. The type is still declared; do not wait for the frame.

### What a write costs

A write costs **one read per distinct question asked by a distinct principal** on the table it touched, not one per socket: subscriptions with the same query held by the same user share a refetch, and different users never share one (that is what keeps a frame from carrying a row its reader may not see).

- **Filter each user's list on a column with `==` or `in`.** Such a list is asked to refetch only when the changed row matched its filter before the write or matches it after, so `listen({ where: { owner: ["==", me] } })` held by 5,000 users costs one read per write, not 5,000. It decides only *who* refetches; every list still reads under its own subscriber's scope.
- **A list narrowed only by RLS** (the same unfiltered `listen()` watched by a thousand signed-in users) is a thousand reads on every write to it. Put the owner filter in the query too.
- The pre-filter judges `==` / `in` on text, varchar, uuid, enum, integer and boolean columns. Anything it cannot judge asks every list, as before: other operators, `include`, a table with an `afterRead` hook or a field-level hook, a delete through the API, and an external `UPDATE` / `DELETE` read from the WAL on a table without `REPLICA IDENTITY FULL` (the trigger capture sends only the key, so it rules out only lists filtered on the key).

## Subscription Deduplication and Caching

The client SDK automatically deduplicates subscriptions:

- If multiple components subscribe to the same table with identical parameters (path, filter, orderBy, limit, etc.), only **one** WebSocket subscription is created on the server.
- Additional callbacks are registered locally and receive the same data.
- New subscribers immediately receive the cached latest data if available (`isInitialDataReceived`).
- The server subscription is only unsubscribed when the **last** callback for that key is removed.

Deduplication keys are computed deterministically:
- **Collection subscriptions:** JSON of every query field (`path`, `filter`, `logical`, `limit`, `offset`, `orderBy`, `searchString`, …) plus `collection.name`, with sorted keys.
- **Row subscriptions:** `"${path}|${id}"`, plus `|${JSON.stringify(include)}` when an `include` is given.

## WebSocket Protocol (Raw / Low-Level)

For environments where the SDK is not available, you can use the raw WebSocket protocol. Connect to the same host and port as the HTTP API, at the socket's path — `/` for an API at `/api` (`ws://localhost:3001`, not `ws://localhost:3001/api`). From 0.25 an upgrade to any other path is not answered by Rebase.

### Connection Lifecycle

1. Open a WebSocket connection to the server URL.
2. Send an `AUTHENTICATE` message with your JWT token.
3. Wait for `AUTH_SUCCESS` before sending subscription or other messages.
4. Send `subscribe_collection` or `subscribe_one` to start receiving data.
5. Receive `collection_update` and `single_update` messages.
6. Send `unsubscribe` to stop a subscription.

### Authentication Step (Required First)

```typescript
const ws = new WebSocket("ws://localhost:3001");

ws.onopen = () => {
    // Step 1: Authenticate FIRST
    ws.send(JSON.stringify({
        type: "AUTHENTICATE",
        requestId: "auth_1",
        payload: { token: "<jwt-token>" }
    }));
};
```

> **IMPORTANT FOR AGENTS:** Authentication is a SEPARATE step. Do NOT put the token inside subscribe messages. The `AUTHENTICATE` message must be sent and acknowledged before any other operations.

### Authentication Responses

| Response Type | Payload | Description |
|--------------|---------|-------------|
| `AUTH_SUCCESS` | `{ uid, roles }` | Token accepted, session authenticated |
| `AUTH_ERROR` | `{ error: { message, code } }` | Token rejected |

Auth error codes:

| Code | Meaning |
|------|---------|
| `INVALID_INPUT` | No token provided |
| `INVALID_TOKEN` | Token is invalid or expired |
| `SESSION_REVOKED` / `ACCOUNT_DISABLED` | Built-in auth: the session was signed out or revoked (or its account deleted), or the account is disabled |

### Subscribe to a Table (wire name `subscribe_collection`)

```typescript
ws.send(JSON.stringify({
    type: "subscribe_collection",
    payload: {
        subscriptionId: "sub_products_1",
        path: "products",
        filter: { status: ["==", "active"] },
        orderBy: "createdAt",
        order: "desc",
        limit: 50
    }
}));
```

### Subscribe to a Single Entity

```typescript
ws.send(JSON.stringify({
    type: "subscribe_one",
    payload: {
        subscriptionId: "sub_product_42",
        path: "products",
        id: "42"
    }
}));
```

### Unsubscribe

```typescript
ws.send(JSON.stringify({
    type: "unsubscribe",
    payload: { subscriptionId: "sub_products_1" }
}));
```

### Handling Server Messages

```typescript
ws.onmessage = (event) => {
    const message = JSON.parse(event.data);

    switch (message.type) {
        case "collection_update":
            // The subscription's query, re-run under this session's scope
            console.log("Collection:", message.subscriptionId);
            console.log("Rows:", message.rows);   // flat rows
            console.log("Meta:", message.meta);   // { total?, hasMore, … } when sent
            break;

        case "single_update":
            // A row subscription
            console.log("Row:", message.subscriptionId);
            console.log("Data:", message.row);    // flat row, or null when deleted
            break;

        case "ERROR":
            console.error("Error:", message.payload?.error?.message);
            console.error("Code:", message.payload?.error?.code);
            break;

        case "error":
            // A refused subscription or channel frame (INVALID_ORDER_BY,
            // TOO_MANY_SUBSCRIPTIONS, CHANNEL_FORBIDDEN, …), addressed by
            // `subscriptionId` or `channel`. `payload.error` is
            // `{ message, code }`, or a bare string when there is no code.
            console.error("Refused:", message.subscriptionId ?? message.channel, message.payload?.error);
            break;
    }
};
```

## Message Types Reference

### Client → Server

| Type | Payload | Description |
|------|---------|-------------|
| `AUTHENTICATE` | `{ token }` | Authenticate the WebSocket session with a JWT |
| `subscribe_collection` | `{ subscriptionId, path, filter?, logical?, orderBy?, order?, limit?, offset?, page?, startAfter?, searchString?, include?, fields? }` | Subscribe to collection changes |
| `subscribe_one` | `{ subscriptionId, path, id }` | Subscribe to a single row |
| `unsubscribe` | `{ subscriptionId }` | Unsubscribe from a subscription |
| `join_channel` | `{ channel }` | Join a broadcast channel |
| `leave_channel` | `{ channel }` | Leave a broadcast channel |
| `broadcast` | `{ channel, event, payload }` | Send a message to channel members |
| `presence_track` | `{ channel, state }` | Track presence with custom state (auto-joins channel) |
| `presence_untrack` | `{ channel }` | Stop tracking presence |
| `presence_state` | `{ channel }` | Request full presence entity |
| `channel_history` | `{ channel, sinceSeq?, limit? }` | Request retained messages after `sinceSeq` (retained channels only) |
| `FETCH_COLLECTION` | `{ path, filter?, orderBy?, limit?, offset?, … }` | One-shot collection fetch (request/response) |
| `FETCH_ONE` | `{ path, id, include? }` | One-shot row fetch |
| `SAVE` | `{ path, id?, values, status }` | Create or update a row |
| `DELETE` | `{ row: { id, path }, hard? }` | Delete a row |
| `COUNT` | `{ path, filter?, … }` | Count rows matching criteria |
| `CHECK_UNIQUE_FIELD` | `{ path, name, value, id? }` | Check field uniqueness |

> **IMPORTANT FOR AGENTS:** the one-shot operations are named `FETCH_ONE`,
> `SAVE`, `DELETE` and `COUNT` — **not** `FETCH_ENTITY`, `SAVE_ENTITY`,
> `DELETE_ENTITY` or `COUNT_ENTITIES`. The server's dispatch is a `switch` on the
> exact string, so a wrong name is answered with an `ERROR` frame coded
> `UNKNOWN_MESSAGE_TYPE`, never with the result you wanted.
> The admin/studio surface adds `EXECUTE_SQL`, `CANCEL_SQL`, `FETCH_DATABASES`,
> `FETCH_CURRENT_DATABASE`, `FETCH_TABLE_METADATA`, `FETCH_UNMAPPED_TABLES`,
> `FETCH_ROLES`, `FETCH_APPLICATION_ROLES`, `LIST_BRANCHES`, `CREATE_BRANCH` and
> `DELETE_BRANCH`.

### Server → Client

| Type | Key Fields | Description |
|------|-----------|-------------|
| `AUTH_SUCCESS` | `{ requestId, payload: { uid, roles } }` | Authentication successful |
| `AUTH_ERROR` | `{ requestId, payload: { error: { message, code } } }` | Authentication failed |
| `collection_update` | `{ subscriptionId, rows, pks?, meta? }` | The subscription's rows, re-read under the subscriber's scope. `pks` names the key columns; `meta` carries `total`/`hasMore` |
| `single_update` | `{ subscriptionId, row, etag? }` | A row subscription's row, or `null` if deleted. `etag` only when `subscribe_one` asked with `etag: true` |
| `collection_patch` | `{ subscriptionId, id, row, pks? }` | Declared in the types, **sent by nothing** — every delivery is a refetch |
| `error` | `{ subscriptionId?, channel?, payload: { error } }` | A refused subscription or channel frame (lowercase `type`). `error` is `{ message, code }`, or a bare string with no code |
| `broadcast` | `{ channel, event, payload, seq? }` | Broadcast from another channel member. `seq` is present only on retained channels |
| `broadcast_ack` | `{ channel, seq }` | Sent to the sender of a retained broadcast in place of its own message, only to a socket that opted into `channel_seq` |
| `hello` | `{ capabilities, heartbeatMs?, clientId? }` | First frame to a socket that opened with `?rebase_caps=…` (`heartbeat`, `channel_seq`, `cancel_sql`), listing the ones honoured |
| `heartbeat` | — | Every `heartbeatMs` (30s) to a socket that opted into `heartbeat` |
| `presence_state` | `{ channel, presences }` | Full presence entity |
| `presence_diff` | `{ channel, joins, leaves }` | Incremental presence update |
| `channel_history` | `{ channel, messages, retained, latestSeq? }` | Retained messages a client missed. `retained: false` means the channel keeps no history |
| `ERROR` | `{ requestId?, payload: { error: { message, code } } }` | General error |
| `FETCH_COLLECTION_SUCCESS` | `{ requestId, payload: { rows } }` | Response to FETCH_COLLECTION |
| `FETCH_ONE_SUCCESS` | `{ requestId, payload: { row } }` | Response to `FETCH_ONE` (`row` is `null` when not found) |

`rows` and `row` are the rows `GET /api/data/<table>` serves: dates as RFC 3339
strings, a `belongsTo` as its foreign key, a relation only when `include` names
it — never a `{ __type }` envelope.
| `SAVE_SUCCESS` | `{ requestId, payload: { row } }` | Response to `SAVE` |
| `DELETE_SUCCESS` | `{ requestId, payload: { success: true } }` | Response to `DELETE` |
| `COUNT_SUCCESS` | `{ requestId, payload: { count } }` | Response to `COUNT` |
| `CHECK_UNIQUE_FIELD_SUCCESS` | `{ requestId, payload: { isUnique } }` | Response to CHECK_UNIQUE_FIELD |

### Error Codes

| Code | Meaning |
|------|---------|
| `INVALID_INPUT` | Missing required field |
| `INVALID_TOKEN` | JWT invalid or expired |
| `UNAUTHORIZED` | Authentication required but session not authenticated |
| `SCOPE_MISSING` | The session lacks the scope the frame needs (`database:read` / `database:write` for the admin-plane types; `data:*` for an API key) |
| `UNKNOWN_MESSAGE_TYPE` | The `type` is not one the server handles |
| `RATE_LIMITED` | Too many requests (see Rate Limiting) |
| `INTERNAL_ERROR` | Unexpected server error |
| `NOT_SUPPORTED` | Operation not available for this driver |
| `SQL_ERROR` | SQL execution error (admin only) |

### Admin-Only Message Types

These message types run outside RLS and need a scope, refused with `SCOPE_MISSING` otherwise. The `admin` role holds both scopes; another role holds them only when the access model grants them:

| Type | Scope | Description |
|------|-------|-------------|
| `EXECUTE_SQL` | `database:write` | Execute raw SQL |
| `CANCEL_SQL` | `database:write` | Stop this socket's in-flight `EXECUTE_SQL` console run |
| `FETCH_DATABASES` | `database:read` | List available databases |
| `FETCH_ROLES` | `database:read` | List available roles |
| `FETCH_APPLICATION_ROLES` | `database:read` | List the roles held by application users |
| `FETCH_UNMAPPED_TABLES` | `database:read` | List tables not mapped to collections |
| `FETCH_TABLE_METADATA` | `database:read` | Get column/FK metadata for a table |
| `FETCH_CURRENT_DATABASE` | `database:read` | Get the current database name |
| `CREATE_BRANCH` | `database:write` | Create a database branch |
| `DELETE_BRANCH` | `database:write` | Delete a database branch |
| `LIST_BRANCHES` | `database:read` | List all database branches |

## Broadcast Channels

Broadcast channels let clients send arbitrary messages to each other in real time — useful for typing indicators, cursor positions, or custom notifications.

### Joining a Channel

```typescript
ws.send(JSON.stringify({
    type: "join_channel",
    payload: { channel: "room-42" }
}));
```

### Sending a Broadcast

```typescript
ws.send(JSON.stringify({
    type: "broadcast",
    payload: {
        channel: "room-42",
        event: "typing",
        payload: { userId: "user-1", isTyping: true }
    }
}));
```

### Receiving Broadcasts

The server relays broadcasts to **all other members** of the channel (the sender does NOT receive its own message):

```typescript
// Received by other clients in the channel
{
    type: "broadcast",
    channel: "room-42",
    event: "typing",
    payload: { userId: "user-1", isTyping: true }
}
```

### Leaving a Channel

```typescript
ws.send(JSON.stringify({
    type: "leave_channel",
    payload: { channel: "room-42" }
}));
```

When a client disconnects, they are automatically removed from all channels.

## Multi-instance channels and presence

Broadcast and presence fan out **only to clients on the instance that received them**, unless a channel bus is configured. Correct and free on one instance; silently broken on two.

```typescript
createPostgresAdapter({
    connection: db,
    schema: { tables, enums, relations },
    realtime: {
        bus: { type: "postgres" }   // "memory" (default) | "postgres"
    }
})
```

Or per deployment: `REALTIME_CHANNEL_BUS=postgres`.

| Bus | Use when |
|-----|----------|
| `memory` | Single instance. Default; zero overhead. |
| `postgres` | Two or more instances. Uses the database you already have — no extra service. |

> **No Redis ships in the box, and that is deliberate.** The Postgres bus measured ~10k cross-instance messages/second (flat out to 8 instances), about 8× what live-cursor collaboration generates, so a broker would add a stateful service to every deployment for no gain. Never suggest adding a broker dependency *to the framework*. If a user has genuinely outgrown it, point them at the extension point below.

### A transport can ship as its own package

`realtime.bus` accepts either a built-in name or **any `ChannelBus` instance**, so a Redis (or NATS, or anything) transport lives in its own package and plugs in without a framework change:

```typescript
import type { ChannelBus, ChannelBusFrame, ChannelBusHandler } from "@rebasepro/types";

class MyBus implements ChannelBus {
    constructor(private readonly url: string) {}
    readonly kind = "my-transport";
    readonly maxFrameBytes = Infinity;   // finite → large retained msgs go by pointer
    async start(handler: ChannelBusHandler) { /* reject if unusable */ }
    async publish(frame: ChannelBusFrame) { /* reach every other instance, or reject */ }
    async stop() { /* idempotent */ }
}

realtime: { bus: new MyBus(url) }
```

The contract is declared in `@rebasepro/types` (`types/channel_bus.ts`) — a transport package depends on that alone, never on `@rebasepro/server-postgres`. Must guarantee: `start()` rejects when unusable, `publish()` reaches all other instances or rejects, `stop()` is idempotent, malformed frames are dropped not thrown. Need **not** guarantee ordering, durability or exactly-once — retained frames dedupe by `seq`, presence diffs are idempotent.

`REALTIME_CHANNEL_BUS` only names built-ins; it never overrides a supplied instance (it warns if both are set).

**Diagnosing:** `realtimeService.getChannelBusKind()` returns the active transport. A misconfigured bus never blocks boot — it logs a warning and falls back to `"memory"`, so check the startup logs for `[ChannelBus]` when cross-instance delivery is missing.

### Coalescing (Postgres bus)

Outgoing frames are batched into one `pg_notify` per ~10ms window, leading-edge (the first frame of an idle stream goes immediately, so no added latency). Measured: **44× fewer database queries** on burst traffic, **12.5×** on paced ~500 msg/s traffic, 100% delivery in both. Tune with `bus: { type: "postgres", batchWindowMs: N }`; `0` disables it. The window is not sensitive — 5/10/20ms measured identically, since batches hit the 8KB ceiling or the traffic's natural gaps first.

> **IMPORTANT FOR AGENTS:** if a user reports missing channel messages *during a rolling deploy under load*, this is the likely cause: a batched payload is a different wire shape that an older instance drops. Single frames are always sent unwrapped, so idle/low-rate traffic is unaffected, and retained channels self-repair via history replay. Not a bug to "fix" by disabling batching — it resolves when the deploy completes.

### Two things agents get wrong here

1. **The Postgres bus needs a direct connection.** `LISTEN` is session state, so it must not go through pgBouncer or any transaction-mode pooler. Rebase uses `DATABASE_DIRECT_URL` when set.

2. **`pg_notify` caps payloads at 8000 bytes.** On a **retained** channel a large message travels as a `(channel, seq)` pointer and each instance reads the body back — no size limit. On an **ephemeral** channel it cannot: the message is delivered locally, the sender gets a `CHANNEL_BUS_PAYLOAD_TOO_LARGE` error, and a warning names the channel. The fix is always the same — add a retention rule for that channel.

With a bus active, presence rosters live in `rebase.channel_presence` (created automatically), so `presence_state` answers for the whole cluster. Rows whose instance stops heartbeating are reaped after the 30s presence timeout, which is also how a crashed pod's clients disappear from everyone's roster.

## Channel History and Catch-Up

By default a broadcast reaches currently-connected members and is then gone — correct for cursors and notifications, and it costs nothing. A channel can instead be configured to **retain** its messages, so a reconnecting client catches up on what it missed rather than resyncing. This is what makes channels usable for operation streams (collaborative editing).

> **IMPORTANT FOR AGENTS:** Retention is configured on the **server** and cannot be requested by a client. `{ history: true }` on the client only asks the SDK to *use* history for a channel the server already retains. If the user reports "history isn't working", check the server config first — the symptom of a missing rule is `retained: false`, not an error.

### Server config (required)

```typescript
createPostgresAdapter({
    connection: db,
    schema: { tables, enums, relations },
    realtime: {
        channels: [
            // Most specific first — first match wins.
            { match: "doc:*", limit: 500, ttl: "24h" }
        ]
    }
})
```

`match` is an exact channel name or a trailing-`*` prefix — **not** a general glob (`"doc:*:live"` matches nothing). A rule needs at least one of `limit` or `ttl`, or it is ignored and logged; unbounded retention is refused rather than honoured.

`ttl` accepts `"30s"`, `"15m"`, `"24h"`, `"7d"`, or a millisecond number. An unparseable value is ignored with a warning rather than guessed at.

### Client usage

```typescript
const channel = client.realtime.channel("doc:42", { history: true });

// Replayed messages arrive through the SAME handler, in order.
channel.onBroadcast("op", (payload) => applyOperation(payload));
await channel.join();
```

The SDK requests catch-up on `join()` and after every reconnect, resuming from the highest `seq` it has delivered. Explicit fetch:

```typescript
const { messages, retained, latestSeq } = await channel.history({ sinceSeq, limit });
console.log(channel.sequence); // highest seq delivered so far
```

### Behaviour worth knowing

- **`seq` is per-channel, dense and increasing.** It appears on `BroadcastEvent.seq` only for retained channels; ephemeral broadcasts have no `seq`.
- **`replayed: true`** marks a message delivered by catch-up rather than live. Handlers usually ignore it.
- **Replays overlap, and duplicates are dropped by the SDK.** Anything at or below the last delivered sequence is discarded, so handlers never see a message twice.
- **Your own messages are not filtered out of a replay.** A reconnect assigns a new client id, so filtering by sender would fail in exactly the case catch-up exists for. Operations must be idempotent.
- **A message that cannot be persisted is not delivered**, and the sender gets a `CHANNEL_HISTORY_WRITE_FAILED` error. Delivering it would leave a gap no replay could repair.
- **Live messages are held back during catch-up** so ordering holds, bounded by a 10s timeout.

### Storage

Two tables in the `rebase` schema, created on startup only when a rule exists: `rebase.channel_messages` (keyed `(channel, seq)`) and `rebase.channel_cursors`. Pruning removes messages only — cursors are kept forever, because restarting a sequence would change what a client's saved resume point means.

> **Security:** history has the same access model as the channel. Anyone who may join may replay what was said before they arrived. Enabling retention on a publicly-joinable channel makes its past readable to any visitor.

## Presence Tracking

Presence tracks which users are currently online in a channel, with custom state per user.

### Use the SDK, not the raw protocol

`client.realtime.channel(name)` wraps channels and presence, and handles the join roster and the heartbeat below for you. Reach for the raw messages only when you need something it doesn't expose.

```typescript
const channel = client.realtime.channel("document-42");

// Publish your own state — repeat calls update it (e.g. a moving cursor).
await channel.track({ name: "Alice", cursor: { line: 10, col: 5 } });

// Observe the roster. Fires with the full state, plus the diff that caused it.
const off = channel.onPresence((presences, diff) => {
    console.log(Object.keys(presences).length, "people here");
});

// Broadcasts — the sender never receives its own message.
await channel.broadcast("typing", { userId: "u1" });
channel.onBroadcast("typing", (payload) => { /* ... */ });

await channel.leave(); // releases the handlers and the heartbeat timer
```

Channels are per-name singletons: two components asking for `"document-42"` get the same object, so neither can cut the other off by leaving.

### Two behaviours that will bite you on the raw protocol

**1. A joining client is told only about its own join.** The `presence_diff` you receive after `presence_track` contains *just you* — the existing roster is not pushed. To learn who is already in the channel you must explicitly send `presence_state`. (The SDK's `join()` does this for you.)

**2. Presence expires after 30 seconds.** `presence_track` is not a durable registration. Unless you re-send it on a timer you silently disappear from everyone else's roster while still sitting in the document — no disconnect, no event, you just stop being listed. Beat well inside the window (the SDK uses 20s) so a single dropped frame isn't a disappearance. See [Presence Timeout](#presence-timeout).

A reconnect also drops server-side channel membership and presence, so both must be re-established; the SDK re-joins, re-requests the roster and re-tracks automatically.

### Tracking Presence

Sending `presence_track` **automatically joins the channel** — no separate `join_channel` needed:

```typescript
ws.send(JSON.stringify({
    type: "presence_track",
    payload: {
        channel: "document-42",
        state: { name: "Alice", cursor: { line: 10, col: 5 } }
    }
}));
```

### Receiving Presence Diffs

All channel members receive incremental `presence_diff` messages when users join or leave.

> The diff you receive on *your own* join contains only you. It is not the roster — request `presence_state` for that.

<!-- doc-examples: fragment -->
```typescript
{
    type: "presence_diff",
    channel: "document-42",
    joins: { "client_abc": { name: "Alice", cursor: { line: 10, col: 5 } } },
    leaves: {}
}
```

### Requesting Full Presence State

```typescript
ws.send(JSON.stringify({
    type: "presence_state",
    payload: { channel: "document-42" }
}));
```

Response:

<!-- doc-examples: fragment -->
```typescript
{
    type: "presence_state",
    channel: "document-42",
    presences: {
        "client_abc": { name: "Alice", cursor: { line: 10, col: 5 } },
        "client_def": { name: "Bob", cursor: { line: 22, col: 0 } }
    }
}
```

### Untracking Presence

```typescript
ws.send(JSON.stringify({
    type: "presence_untrack",
    payload: { channel: "document-42" }
}));
```

### Presence Timeout

Stale presences are automatically cleaned up after **30 seconds** of inactivity (`PRESENCE_TIMEOUT_MS = 30000`). The server checks for stale entries every 10 seconds. When a stale presence is removed, a `presence_diff` with a `leaves` entry is broadcast to the channel.

**This means `presence_track` must be re-sent on a timer.** A client that tracks once and then goes quiet is reaped at the 30s mark and vanishes from every other member's roster — while still connected and still sitting in the document. Re-send comfortably inside the window (20s is a good default: one lost beat still leaves time for the next). `client.realtime.channel().track()` starts this heartbeat for you and stops it on `untrack()` / `leave()`.

## Rate Limiting

The WebSocket server enforces per-client rate limiting:

| Setting | Value |
|---------|-------|
| Max messages per window | **2000** (`WS_RATE_LIMIT`) |
| Max channel frames per window (`join_channel`, `broadcast`, `presence_*`, `channel_history`, …), counted separately | **7200** (`WS_CHANNEL_RATE_LIMIT`) |
| Window duration | **60 seconds** (`WS_RATE_WINDOW_MS`) |

When the limit is exceeded, the server responds with:

```json
{
    "type": "ERROR",
    "payload": { "error": { "message": "Too many requests. Please slow down.", "code": "RATE_LIMITED" } }
}
```

The window is a fixed window — the counter resets after 60 seconds of the window start. A channel frame past its budget is answered `"Too many channel messages. Please slow down."`, also coded `RATE_LIMITED`. Separately, the one-shot data frames (`FETCH_COLLECTION`, `FETCH_ONE`, `COUNT`, `SAVE`, `DELETE`, `CHECK_UNIQUE_FIELD`) count against the caller's data rate limit, shared with their HTTP requests and other sockets; `subscribe_collection`, `subscribe_one` and `channel_history` count there too once the socket's own allowance (1,000, refilled over 15 minutes) is spent.

## Auto-Reconnect Behavior

The client SDK (`RebaseWebSocketClient`) automatically reconnects when the connection drops:

| Setting | Value |
|---------|-------|
| First step | **2 seconds** |
| Backoff formula | step = `min(1000 * 2^attempt, 30000)` ms, attempt counted from 1; the delay is drawn at random between 250 ms and the step (full jitter) |
| Maximum delay | **30 seconds** |
| Maximum attempts | **5** (`maxReconnectAttempts`) — only while nothing is registered. With a live subscription or joined channel the client keeps redialling at the 30s ceiling for as long as the outage lasts |
| Outage report | After **14 seconds** down, every live subscription's and channel's `onError` gets one `CONNECTION_LOST`; the registration is kept |

### Reconnection sequence:

1. Connection drops → `onclose` fires.
2. Client sets `isAuthenticated = false`. Requests already written to the dead socket are rejected with `CONNECTION_LOST` and **not** re-sent (the server may have run them). Requests made while down wait in a queue, for up to 30s from the call, then fail with `REQUEST_TIMEOUT`.
3. Reconnect after the backoff delay.
4. On successful reconnect:
   - Auto-authenticates if `getAuthToken` is configured.
   - Emits `"reconnect"` event.
   - Processes the queued message queue.
   - Calls `resubscribeAll()` — all active collection and entity subscriptions are re-registered with fresh subscription IDs.

### Connection Lifecycle Events

```typescript
// The RebaseWebSocketClient. `undefined` on a client built without realtime,
// so narrow it once rather than at every call.
const ws = client.ws;
if (ws) {
    ws.on("connect", () => console.log("Connected"));
    ws.on("disconnect", () => console.log("Disconnected"));
    ws.on("reconnect", () => console.log("Reconnected"));
    ws.on("error", (error) => console.error("Error:", error));
}
```

Each `on()` call returns an unsubscribe function:

```typescript
const unsub = ws.on("connect", () => { /* ... */ });
unsub(); // Stop listening
```

## Authentication & RLS

WebSocket subscriptions automatically respect Row-Level Security (RLS) policies:

1. The client sends an `AUTHENTICATE` message with a JWT token.
2. The server verifies the token (via `extractUserFromToken` or a custom `AuthAdapter`).
3. Every subscription refetch runs inside a PostgreSQL transaction with:
   - `set_config('app.uid', ...)` (and the legacy alias `app.user_id`)
   - `set_config('app.user_roles', ...)`
   - `set_config('app.is_anonymous', ...)`
   - `set_config('app.jwt', ...)`
4. RLS policies are enforced — each user only sees records they have permission to access.
5. If no auth context is present, the server defaults to `{ uid: "anonymous", roles: ["anon"] }`.

### Auto-Authentication

The client SDK handles authentication automatically:

- On connect, if `getAuthToken` is configured, the client authenticates immediately.
- On-demand authentication: if a non-auth message is sent before authentication, the client calls `ensureAuthenticated()` with up to 3 retries and backoff.
- The socket resolves its token exactly as HTTP does: `client.setAuthTokenGetter(getter)` first, then the token the client holds (its session, `client.setToken()`, or the `token` option). One `client.setAuthTokenGetter()` call — for a host signing users in with Clerk, Firebase Auth or its own session — authenticates HTTP **and** the socket (0.25+), and rebuilds an open socket as the new credential. `client.ws.setAuthTokenGetter()` is deprecated: it still works, replaces only the socket's getter and warns once. In 0.24 and earlier `client.setAuthTokenGetter()` reached HTTP only, and the socket needed `client.ws.setAuthTokenGetter()` as well.
- `reauthenticate()` forces re-authentication (call after token refresh).

### Auth Failure Recovery

When the server returns an `AUTH_ERROR` or `UNAUTHORIZED` error for any request or subscription:

1. The client calls `onUnauthorized()` (if configured) to attempt a token refresh — the handler set with `client.setOnUnauthorized()` answers socket auth errors as well as HTTP 401s (0.25+).
2. If the refresh succeeds, the failed request is retried automatically.
3. If the refresh fails, the error is propagated to the callback.

A session that was **refused**, not merely expired, is not refreshed and retried. The socket refuses a signed-out or revoked session with `SESSION_REVOKED` and a disabled account with `ACCOUNT_DISABLED` (0.25.1+, as the HTTP routes do; 0.25.0 and earlier say `INVALID_TOKEN`). The SDK warns once, does not ask again with the same token, and passes the error, with its `code`, straight to `listen()`'s `onError`. Handle those two codes as "sign the user out", not "try again".

## Client Configuration

### `RebaseWebSocketConfig`

This is the config of the low-level `RebaseWebSocketClient`, which
`createRebaseClient()` constructs for you. `websocketUrl` (derived from
`baseUrl` when omitted), `onUnauthorized`, `impersonate` and `debug` are also
`createRebaseClient()` options; `getAuthToken` is wired to the client's own
token resolution.

| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `websocketUrl` | `string` | Yes | WebSocket server URL (e.g., `"ws://localhost:3001"`) |
| `getAuthToken` | `() => Promise<string \| null>` | No | Async function that returns the current JWT token; a falsy answer leaves the socket anonymous |
| `WebSocket` | `typeof WebSocket` | No | Custom WebSocket constructor. **Only reachable when you construct `RebaseWebSocketClient` yourself** — `createRebaseClient()` does not forward it. |
| `onUnauthorized` | `() => Promise<boolean>` | No | Called on auth failure; return `true` if token was refreshed |
| `impersonate` | `string` | No | Sign in as this user id rather than the token's own; sent with every `AUTHENTICATE` |
| `debug` | `boolean` | No | Log the connection's progress with `console.debug` |

### Using in Node.js

The client resolves its constructor from `globalThis.WebSocket`. Node 22+ ships
one, so nothing is needed there. On older Node, set the global **before**
creating the client — `createRebaseClient()` takes no `WebSocket` option:

```typescript
import WS from "ws";
import { createRebaseClient } from "@rebasepro/client";

// Node < 22 only. Must run before createRebaseClient().
globalThis.WebSocket ??= WS as unknown as typeof globalThis.WebSocket;

const client = createRebaseClient({
    baseUrl: "http://localhost:3001",
    websocketUrl: "ws://localhost:3001",
});
```

> **IMPORTANT FOR AGENTS:** Do NOT pass `WebSocket` to `createRebaseClient()` —
> it is not an option and is silently ignored. If no constructor resolves, the
> client logs a warning and realtime subscriptions do NOT work. The warning is
> emitted on first *use*, not on construction, so a client that never subscribes
> stays silent.

### The socket connects lazily

Creating a client opens **no** WebSocket. The socket is dialled on the first operation that needs it — `collection().listen(...)`, or any channel operation (`join`, `track`, `broadcast`, `onPresence`, `onBroadcast`).

This matters for apps with meaningful signed-out traffic — marketing pages, docs, public read-only views, anonymous-first tools. Previously `realtime` was effectively all-or-nothing per client: enabling it to reach `channel()` dialled a socket on every page load, including the anonymous ones with no token to authenticate with. Realtime is a per-feature capability, so the socket is now per-use.

```typescript
const client = createRebaseClient({ baseUrl });   // no socket
const channel = client.realtime.channel("doc:1"); // still no socket
await channel.join();                             // socket opens here
```

Notes:

- `realtime: false` is unchanged — a hard opt-out. No socket ever, and `channel()` throws.
- Signing in does not open a socket. A socket opened later authenticates itself; one already open is re-authenticated on `SIGNED_IN` / `TOKEN_REFRESHED`.
- **Channel and presence frames do not require an account.** They are exempt from the client-side auth gate, so anonymous visitors can join public channels; the server still authorizes them.
- `client.close()` is final: nothing queued afterwards redials.
- Apps that subscribe on boot are unaffected — they connect at the same moment, just triggered by the subscribe rather than the constructor.

## Server Configuration

### The socket's path

The Postgres driver's socket shares the HTTP server and answers WebSocket
upgrades on **one path only** (0.25+): `/` by default, where the SDK dials — it
opens the socket at `baseUrl` while HTTP goes to `${baseUrl}/api`. The server
derives the path from the base path it is mounted under, minus a trailing
`/api`: `/api` → `/`, `/x/api` → `/x`.
Override it with `backend.attachRealtime(server, { path })` on a backend built
with `createRebaseBackend`, or the Postgres adapter's `realtime.path`; point the
client's `websocketUrl` at the same path.

An upgrade to any other path is left to the host's own `upgrade` listeners — so
your app can run its own WebSocket server on the same `http.Server` — or
answered `404` when there are none. Before 0.25 the socket took every upgrade on
the server, and a second WebSocket server on the same `http.Server` collided
with it ("handleUpgrade() was called more than once").

### Multiple data sources

With more than one Postgres database in a single instance (`database("warehouse")` beside the default), the single WebSocket server routes each subscription to the provider owning the subscribed collection — each database via its own `LISTEN/NOTIFY` — based on the collection's resolved data source. Broadcast channels and presence use a provider that implements them. Firestore (`direct` transport) realtime is handled entirely **client-side** by its SDK and never reaches the backend WebSocket. No extra configuration is needed beyond declaring the databases; single-database setups are unaffected. See the **rebase-tables** skill for the data-source model.

### Cross-Instance Broadcasting

For multi-instance deployments (behind a load balancer), Rebase uses PostgreSQL `LISTEN/NOTIFY` to synchronize changes.

With database-level change capture active, a write is heard whichever process or tool made it, and the path below is not used. `REALTIME_CDC=auto`, the default, reads changes from the write-ahead log where the database allows it (`wal_level=logical`, a role that may replicate, a free replication slot and a direct connection): a write then runs no trigger and sends no `NOTIFY`. Elsewhere it falls back to capture triggers, which publish on `rebase_cdc` that every instance listens on, and logs the fallback as info. Trigger capture's `NOTIFY` takes a server-wide commit lock, so under heavy concurrent writes WAL capture is the one to enable. A WAL instance keeps the capture triggers while any other realtime instance may still listen on them (a replica that fell back, an older version mid-rollout); realtime connections name their role in `application_name` (`rebase-realtime:<instance>:cdc` / `:wal` / `:entity`). `REALTIME_CDC=trigger` forces triggers. Without capture:

- A mutation on Instance A triggers `pg_notify('rebase_entity_changes', ...)`.
- Instance B receives the notification via its dedicated `LISTEN` connection.
- Instance B schedules a debounced refetch for its local subscribers of the affected path, under each subscriber's own scope.
- Each instance has a unique ID (`inst_<8 hex chars>`) to skip its own notifications.

This is **automatic**: the `LISTEN` client uses the adapter's direct connection (`directConnectionString`, else `connectionString`). The dedicated `LISTEN` connection auto-reconnects with a **3-second fixed delay** if it drops, then refetches every live subscription.

### `DATABASE_DIRECT_URL` Environment Variable

When using PgBouncer or a similar connection pooler, `LISTEN/NOTIFY` does not work through the pooler. Set `DATABASE_DIRECT_URL` to a direct PostgreSQL connection string that bypasses the pooler:

```bash
# Standard pooled connection
DATABASE_URL=postgres://user:pass@pgbouncer:6432/mydb

# Direct connection for LISTEN/NOTIFY (bypasses PgBouncer)
DATABASE_DIRECT_URL=postgres://user:pass@postgres:5432/mydb
```

The LISTEN client connects to the adapter's `directConnectionString` (new in
0.25), and falls back to `connectionString`. At boot, `DATABASE_DIRECT_URL`
fills `directConnectionString` when the config leaves it unset — so the variable
works as before, and the option is the same setting in code.

### Debounce Window

The server coalesces rapid entity mutations into a single database refetch using a configurable debounce:

| Constant | Value | Description |
|----------|-------|-------------|
| `REFETCH_DEBOUNCE_MS` | `300` ms | Debounce window for collection and entity refetches |

If 10 entities change within 300ms, only **one** database query is executed for each affected subscription.

### Presence Cleanup

| Constant | Value | Description |
|----------|-------|-------------|
| `PRESENCE_TIMEOUT_MS` | `30000` ms (30s) | Stale presence entries are removed after this timeout |
| Cleanup interval | `10000` ms (10s) | How often the server checks for stale presences |

## Nested Relation Updates

The realtime engine handles nested relation paths (e.g., `"posts/70/tags"`). When a record changes at a nested path:

1. The exact path is notified (`"posts/70/tags"`).
2. All parent paths are also notified (`"posts"`, `"posts/70"`).

This ensures that a subscription to `"posts"` receives updates even when a related `"tags"` entity changes.

## Error Handling

### SDK Error Types

The client throws `RebaseApiError` (exported from `@rebasepro/client`) for WebSocket errors — the same class HTTP failures use:

```typescript
class RebaseApiError extends Error {
    readonly status?: number;   // HTTP status; undefined for socket errors
    readonly code?: string;     // Error code (e.g., "UNAUTHORIZED", "RATE_LIMITED")
    readonly details?: unknown; // Structured payload from the server, when present
}
```

### Subscription Error Callbacks

```typescript
import { RebaseApiError } from "@rebasepro/client";

const unsubscribe = client.data.products.listen(
    undefined,
    (response) => { /* success */ },
    (error) => {
        // error is an Error or RebaseApiError instance
        if (error instanceof RebaseApiError) {
            console.error("Code:", error.code);
        }
        console.error("Message:", error.message);
    }
);
```

### Pending Request Timeout

To prevent client requests from hanging indefinitely, all pending WebSocket operations that expect a server response (such as `FETCH_COLLECTION`, `FETCH_ONE`, `SAVE`, `DELETE`, `COUNT`, and `CHECK_UNIQUE_FIELD`) have a default timeout of 30 seconds (`requestTimeoutMs = 30000`).

The deadline runs from the call, so a request that waited in the queue for a socket does not get a fresh 30s once it is written. If the server does not respond within this window, the client automatically deletes the pending request record and rejects the request's promise with a `RebaseApiError`:
- Code: `REQUEST_TIMEOUT`
- Message: `"The server did not answer the realtime request in time. It may or may not have been applied."` when it was written, or `"The realtime request timed out before it could be sent. It was not applied."` when it never reached a socket

One-way messages that do not expect a response (like `subscribe_collection`, `subscribe_one`, `unsubscribe`, `join_channel`, `leave_channel`, `broadcast`, `presence_track`, `presence_untrack`, and `presence_state`) resolve immediately upon transmission and do not trigger timeouts. A subscription whose first frame has not arrived 30 seconds after its subscribe was sent fails instead, with a `SUBSCRIPTION_TIMEOUT` error on its `onError`.

### Production Error Sanitization

In production (`NODE_ENV=production`):
- Debug logs are suppressed on both server and client.
- Unexpected errors (`INTERNAL_ERROR`) have their message sanitized to `"An unexpected error occurred"` to prevent PII/data leaks. Declared refusals — a validation error, a callback veto, `INVALID_LIMIT`, `NOT_FOUND`, … — keep their code and message.
- The `WebSocket` handler catches all unhandled errors and returns them as generic `ERROR` messages.

## When to Use Realtime

| Use Case | Method |
|----------|--------|
| Dashboard with live data | `listen()` with filters |
| Chat or notifications | `listen()` on messages collection |
| Detail page with live updates | `listenById()` |
| Admin panel monitoring | `listen()` with `orderBy` and `limit` |
| Collaborative editing cursors | Broadcast channels + presence |
| Typing indicators | Broadcast channels |
| Online user tracking | Presence tracking |
| A live list that must survive a dropped connection | `observe()` with `offline: true` |

### `listen()` vs `observe()`

`listen()` is the socket — it delivers what the server pushes and nothing at all when the socket is down.

`observe()` is the query. With `offline: true` on the client it emits from the local database first (before any request), subscribes to realtime itself, and re-emits on local writes, on queued writes reaching the server, and on rollbacks. Each result carries `fromCache` / `hasPendingWrites` / `partial`. Reach for it in a UI; reach for `listen()` when you specifically want the raw server stream. See the **rebase-sdk** skill.

## References

- **Backend Realtime Docs:** [rebase.pro/docs/backend/realtime](https://rebase.pro/docs/backend/realtime)
- **SDK Realtime Docs:** [rebase.pro/docs/sdk/realtime](https://rebase.pro/docs/sdk/realtime)
- **Offline & Live Queries:** [rebase.pro/docs/sdk/offline](https://rebase.pro/docs/sdk/offline)
- **GitHub:** [github.com/rebasepro/rebase](https://github.com/rebasepro/rebase)
