Overview
Realtime features:- Server-Sent Events (SSE) - HTTP-based streaming (default)
- WebSocket - Bidirectional connection for lower latency
- Per-record subscriptions - Listen to changes on specific rows
- Bulk subscriptions - Listen to all changes in a table
- Filtered subscriptions - Only receive relevant updates
- Event types - Insert, Update, and Delete events
Event Types
TrailBase emits three types of events:Subscribing to Changes
Subscribe to a Single Record
- TypeScript
- React Hook
- Dart/Flutter
Subscribe to All Records
Receive updates for all rows in a table:Filtered Subscriptions
Subscribe only to records matching specific criteria:Filters use the same syntax as Record API queries. See the Record API reference for available operators.
Real-World Example: Live Todo List
Here’s a complete example from the collaborative clicker demo:src/App.tsx
WebSocket Subscriptions
For lower latency, use WebSocket instead of SSE:When to use WebSocket:
- Mobile apps (better battery life)
- High-frequency updates (lower overhead)
- Bidirectional communication needed
- Browser-only apps (simpler)
- Firewalls that block WebSocket
- Server-to-client updates only
WebSocket Authentication
WebSocket connections require authentication after connecting:The TrailBase client handles WebSocket authentication automatically when using
subscribeWs().Integration with TanStack DB
For automatic state synchronization, use @tanstack/trailbase-db-collection:Performance Considerations
Debouncing Updates
For high-frequency changes, debounce UI updates:Pagination with Subscriptions
For large datasets, combine pagination with subscriptions:Selective Subscriptions
Subscribe only to what the user is viewing:Error Handling
Connection Errors
Network State
Respond to network changes:Access Control
Subscriptions respect your Record API access rules:traildepot/config.textproto
Users only receive subscription events for records they have permission to read. Access rules are evaluated on every event.
Testing Subscriptions
Manual Testing with cURL
Automated Testing
Common Patterns
Optimistic Updates
Update UI immediately, then reconcile with server:Multi-Tab Sync
Subscriptions automatically sync across browser tabs:Presence Detection
Track active users (requires custom implementation):Next Steps
First App
Build a realtime todo app
Authentication
Secure your subscriptions
Database Setup
Design efficient schemas
WASM Runtime
Process events with WebAssembly
Examples
- Collaborative Clicker - Server-side rendered app with realtime updates
- TanStack Todo - Automatic synchronization with TanStack/db