# Realtime — Features

> WebSocket pub/sub, presence tracking, database change events, and AI token streaming — one connection per client handles all of it.

Aerostack Realtime is a WebSocket-based system for building live, collaborative features. One WebSocket connection per client handles everything: database change events, custom pub/sub, presence tracking, and AI token streaming.

## What you can build

- **Live dashboards** — react to database INSERT/UPDATE/DELETE automatically
- **Chat** — room-based messaging with history and persistence
- **Presence** — who's online, where they are, what they're doing
- **Collaborative tools** — sync state between users without a backend
- **AI streaming** — stream LLM tokens to 1000 users over a single channel

## How it works

Every client connects via a single WebSocket to `wss://api.aerostack.dev/api/realtime`. From there, they **subscribe to topics**. Messages flow through those topics.

There are two kinds of topics:

| Topic format | Example | How events arrive |
|---|---|---|
| `tableName` (no slash) | `orders` | Automatic — ChangeTracker polls the database every 200ms |
| `path/name` (with slash) | `chat/general` | Manual — your server calls `sdk.socket.emit()` |

## Quick start

```tsx

function LiveFeed() {
  const { realtime } = useAerostack()
  const [events, setEvents] = useState([])

  useEffect(() => {
    const channel = realtime.channel('orders')

    channel
      .on('INSERT', ({ data }) => setEvents(prev => [data, ...prev]))
      .on('UPDATE', ({ data }) => setEvents(prev =>
        prev.map(e => e.id === data.id ? data : e)
      ))
      .subscribe()

    return () => channel.unsubscribe()
  }, [realtime])

  return (
    <ul>
      {events.map(e => <li key={e.id}>{e.status}</li>)}
    </ul>
  )
}
```

```ts
// Server: emit events to a channel

// After any operation, notify subscribers:
await sdk.db.query('UPDATE orders SET status = ? WHERE id = ?', ['shipped', orderId])

// For custom events, emit manually:
sdk.socket.emit('order:updated', { id: orderId, status: 'shipped' }, 'orders')
```

## Connection management

The `RealtimeClient` handles reconnection automatically with exponential backoff. You can observe the connection status:

```ts
realtime.onStatusChange((status) => {
  // 'idle' | 'connecting' | 'connected' | 'reconnecting' | 'disconnected'
  console.log('Connection status:', status)
})
```

## Use Cases

### Live chat rooms

Build a Slack-style chat application with room-based messaging. Subscribe clients to `chat/{roomId}` topics, and every message sent by one user is instantly broadcast to all others in the room. Combine with message history for scroll-back.

```ts
const channel = realtime.channel('chat/engineering')
channel.on('message', ({ data }) => {
  addMessage(data)
})
channel.subscribe()

// Send a message from any client
sdk.socket.emit('message', { text, author, timestamp }, 'chat/engineering')
```

### Collaborative document editing

Sync cursor positions, text changes, and selection state between users editing the same document. Each document gets its own topic (`doc/{docId}`), and presence tracking shows who else is viewing or editing in real time.

### Presence tracking

Show "3 users viewing this page" or "Sarah is typing..." indicators. Presence is built into the Realtime system — clients announce their state on join, and the server broadcasts updates when users arrive, leave, or change their status.

### Live operations dashboard

Subscribe to your `orders` or `deployments` table and let the dashboard update automatically whenever a row is inserted or updated. No polling, no manual refresh — ChangeTracker pushes database mutations to connected clients within 200ms.

### Auction and bidding systems

Broadcast bid updates to all participants instantly. Each auction gets a topic (`auction/{id}`), and every new bid is emitted to all watchers. Combined with the database, you can validate bids server-side before broadcasting confirmed updates.

## Next steps

- [Database Subscriptions](/features/realtime/subscriptions) — react to database changes automatically
- [Pub/Sub](/features/realtime/pubsub) — broadcast custom events between clients
- [Presence](/features/realtime/presence) — track who is online
- [AI Streaming](/features/realtime/ai-streaming) — stream tokens to many clients
- [Message History](/features/realtime/history) — persist and retrieve messages
- [Examples: Realtime Chat](/examples/realtime-chat) — complete copy-paste example
