Open History to see the last commit
1---
2title: Creating a Collection Options Creator
3id: guide/collection-options-creator
4---
5# Creating a Collection Options Creator
6
7A collection options creator is a factory function that generates configuration options for TanStack DB collections. It provides a standardized way to integrate different sync engines and data sources with TanStack DB's reactive sync-first architecture.
8
9## Overview
10
11Collection options creators follow a consistent pattern:
121. Accept configuration specific to the sync engine
132. Return an object that satisfies the `CollectionConfig` interface
143. Handle sync initialization, data parsing, and transaction management
154. Optionally provide utility functions specific to the sync engine
16
17## When to Create a Custom Collection
18
19You should create a custom collection when:
20- You have a dedicated sync engine (like ElectricSQL, Trailbase, Firebase, RxDB or a custom WebSocket solution)
21- You need specific sync behaviors that aren't covered by the query collection
22- You want to integrate with a backend that has its own sync protocol
23
24**Note**: If you're just hitting an API and returning data, use the query collection instead.
25
26## Core Requirements
27
28Every collection options creator must implement these key responsibilities:
29
30### 1. Configuration Interface
31
32Define a configuration interface that extends or includes standard collection properties:
33
34```typescript
35// Pattern A: User provides handlers (Query / ElectricSQL style)
36interface MyCollectionConfig<TItem extends object> {
37 // Your sync engine specific options
38 connectionUrl: string
39 apiKey?: string
41 // Standard collection properties
42 id?: string
43 schema?: StandardSchemaV1
44 getKey: (item: TItem) => string | number
45 sync?: SyncConfig<TItem>
47 rowUpdateMode?: 'partial' | 'full'
49 // User provides mutation handlers
50 onInsert?: InsertMutationFn<TItem>
51 onUpdate?: UpdateMutationFn<TItem>
52 onDelete?: DeleteMutationFn<TItem>
53}
54
55// Pattern B: Built-in handlers (Trailbase style)
56interface MyCollectionConfig<TItem extends object>
57 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete'> {
58 // Your sync engine specific options
59 recordApi: MyRecordApi<TItem>
60 connectionUrl: string
62 rowUpdateMode?: 'partial' | 'full'
64 // Note: onInsert/onUpdate/onDelete are implemented by your collection creator
65}
66```
67
68### 2. Sync Implementation
69
70The sync function is the heart of your collection. It must:
71
72The sync function must return a cleanup function for proper garbage collection:
73
74```typescript
75const sync: SyncConfig<T>['sync'] = (params) => {
76 const { begin, write, commit, markReady, collection } = params
78 // 1. Initialize connection to your sync engine
79 const connection = initializeConnection(config)
81 // 2. Set up real-time subscription FIRST (prevents race conditions)
82 const eventBuffer: Array<any> = []
83 let isInitialSyncComplete = false
85 connection.subscribe((event) => {
86 if (!isInitialSyncComplete) {
87 // Buffer events during initial sync to prevent race conditions
88 eventBuffer.push(event)
89 return
90 }
92 // Process real-time events
93 begin()
95 switch (event.type) {
96 case 'insert':
97 write({ type: 'insert', value: event.data })
98 break
99 case 'update':
100 write({ type: 'update', value: event.data })
101 break
102 case 'delete':
103 write({ type: 'delete', value: event.data })
104 break
105 }
107 commit()
108 })
110 // 3. Perform initial data fetch
111 async function initialSync() {
112 try {
113 const data = await fetchInitialData()
115 begin() // Start a transaction
117 for (const item of data) {
118 write({
119 type: 'insert',
120 value: item
121 })
122 }
124 commit() // Commit the transaction
126 // 4. Process buffered events
127 isInitialSyncComplete = true
128 if (eventBuffer.length > 0) {
129 begin()
130 for (const event of eventBuffer) {
131 // Deduplicate if necessary based on your sync engine
132 write({ type: event.type, value: event.data })
133 }
134 commit()
135 eventBuffer.splice(0)
136 }
138 } catch (error) {
139 console.error('Initial sync failed:', error)
140 throw error
141 } finally {
142 // ALWAYS call markReady, even on error
143 markReady()
144 }
145 }
146
147 initialSync()
149 // 4. Return cleanup function
150 return () => {
151 connection.close()
152 // Clean up any timers, intervals, or other resources
153 }
154}
155```
156
157### 3. Transaction Lifecycle
158
159Understanding the transaction lifecycle is important for correct implementation.
160
161The sync process follows this lifecycle:
162
1631. **begin()** - Start collecting changes
1642. **write()** - Add changes to the pending transaction (buffered until commit)
1653. **commit()** - Apply all changes atomically to the collection state
1664. **markReady()** - Signal that initial sync is complete
167
168**Race Condition Prevention:**
169Many sync engines start real-time subscriptions before the initial sync completes. Your implementation MUST deduplicate events that arrive via subscription that represent the same data as the initial sync. Consider:
170- Starting the listener BEFORE initial fetch and buffering events
171- Tracking timestamps, sequence numbers, or document versions
172- Using read timestamps or other ordering mechanisms
173
174### 4. Data Parsing and Type Conversion
175
176If your sync engine returns data with different types, provide conversion functions for specific fields:
177
178```typescript
179interface MyCollectionConfig<TItem, TRecord> {
180 // ... other config
182 // Only specify conversions for fields that need type conversion
183 parse: {
184 created_at: (ts: number) => new Date(ts * 1000), // timestamp -> Date
185 updated_at: (ts: number) => new Date(ts * 1000), // timestamp -> Date
186 metadata?: (str: string) => JSON.parse(str) // JSON string -> object
187 }
189 serialize: {
190 created_at: (date: Date) => Math.floor(date.valueOf() / 1000), // Date -> timestamp
191 updated_at: (date: Date) => Math.floor(date.valueOf() / 1000), // Date -> timestamp
192 metadata?: (obj: object) => JSON.stringify(obj) // object -> JSON string
193 }
194}
195```
196
197**Type Conversion Examples:**
198```typescript
199// Firebase Timestamp to Date
200parse: {
201 createdAt: (timestamp) => timestamp?.toDate?.() || new Date(timestamp),
202 updatedAt: (timestamp) => timestamp?.toDate?.() || new Date(timestamp),
203}
204
205// PostGIS geometry to GeoJSON
206parse: {
207 location: (wkb: string) => parseWKBToGeoJSON(wkb)
208}
209
210// JSON string to object with error handling
211parse: {
212 metadata: (str: string) => {
213 try {
214 return JSON.parse(str)
215 } catch {
216 return {}
217 }
218 }
219}
220```
221
222### 5. Mutation Handler Patterns
223
224There are two distinct patterns for handling mutations in collection options creators:
225
226#### Pattern A: User-Provided Handlers (ElectricSQL, Query)
227
228The user provides mutation handlers in the config. Your collection creator passes them through:
229
230```typescript
231interface MyCollectionConfig<TItem extends object> {
232 // ... other config
234 // User provides these handlers
235 onInsert?: InsertMutationFn<TItem>
236 onUpdate?: UpdateMutationFn<TItem>
237 onDelete?: DeleteMutationFn<TItem>
238}
239
240export function myCollectionOptions<TItem extends object>(
241 config: MyCollectionConfig<TItem>
242) {
243 return {
244 // ... other options
245 rowUpdateMode: config.rowUpdateMode || 'partial',
247 // Pass through user-provided handlers (possibly with additional logic)
248 onInsert: config.onInsert ? async (params) => {
249 const result = await config.onInsert!(params)
250 // Additional sync coordination logic
251 return result
252 } : undefined
253 }
254}
255```
256
257#### Pattern B: Built-in Handlers (Trailbase, WebSocket, Firebase)
258
259Your collection creator implements the handlers directly using the sync engine's APIs:
260
261```typescript
262interface MyCollectionConfig<TItem extends object>
263 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete'> {
264 // ... sync engine specific config
265 // Note: onInsert/onUpdate/onDelete are NOT in the config
266}
267
268export function myCollectionOptions<TItem extends object>(
269 config: MyCollectionConfig<TItem>
270) {
271 return {
272 // ... other options
273 rowUpdateMode: config.rowUpdateMode || 'partial',
275 // Implement handlers using sync engine APIs
276 onInsert: async ({ transaction }) => {
277 // Handle provider-specific batch limits (e.g., Firestore's 500 limit)
278 const chunks = chunkArray(transaction.mutations, PROVIDER_BATCH_LIMIT)
280 for (const chunk of chunks) {
281 const ids = await config.recordApi.createBulk(
282 chunk.map(m => serialize(m.modified))
283 )
284 await awaitIds(ids)
285 }
287 return transaction.mutations.map(m => m.key)
288 },
290 onUpdate: async ({ transaction }) => {
291 const chunks = chunkArray(transaction.mutations, PROVIDER_BATCH_LIMIT)
293 for (const chunk of chunks) {
294 await Promise.all(
295 chunk.map(m =>
296 config.recordApi.update(m.key, serialize(m.changes))
297 )
298 )
299 }
301 await awaitIds(transaction.mutations.map(m => String(m.key)))
302 }
303 }
304}
305```
306
307Many providers have batch size limits (Firestore: 500, DynamoDB: 25, etc.) so chunk large transactions accordingly.
308
309Choose Pattern A when users need to provide their own APIs, and Pattern B when your sync engine handles writes directly.
310
311## Row Update Modes
312
313Collections support two update modes:
314
315- **`partial`** (default) - Updates are merged with existing data
316- **`full`** - Updates replace the entire row
317
318Configure this in your sync config:
319
320```typescript
321sync: {
322 sync: syncFn,
323 rowUpdateMode: 'full' // or 'partial'
324}
325```
326
327## Production Examples
328
329For complete, production-ready examples, see the collection packages in the TanStack DB repository:
330
331- **[@tanstack/query-collection](https://github.com/TanStack/db/tree/main/packages/query-collection)** - Pattern A: User-provided handlers with full refetch strategy
332- **[@tanstack/trailbase-collection](https://github.com/TanStack/db/tree/main/packages/trailbase-collection)** - Pattern B: Built-in handlers with ID-based tracking
333- **[@tanstack/electric-collection](https://github.com/TanStack/db/tree/main/packages/electric-collection)** - Pattern A: Transaction ID tracking with complex sync protocols
334- **[@tanstack/rxdb-collection](https://github.com/TanStack/db/tree/main/packages/rxdb-collection)** - Pattern B: Built-in handlers that bridge [RxDB](https://rxdb.info) change streams into TanStack DB's sync lifecycle
335
336### Key Lessons from Production Collections
337
338**From Query Collection:**
339- Simplest approach: Full refetch after mutations
340- Best for: APIs without real-time sync
341- Pattern: User provides `onInsert/onUpdate/onDelete` handlers
342
343**From Trailbase Collection:**
344- Shows ID-based optimistic state management
345- Handles provider batch limits (chunking large operations)
346- Pattern: Collection provides mutation handlers using record API
347
348**From Electric Collection:**
349- Complex transaction ID tracking for distributed sync
350- Demonstrates advanced deduplication techniques
351- Shows how to wrap user handlers with sync coordination
352
353**From RxDB Collection:**
354- Uses RxDB's built-in queries and change streams
355- Uses `RxCollection.$` to subscribe to inserts/updates/deletes and forward them to TanStack DB with begin-write-commit
356- Implements built-in mutation handlers (onInsert, onUpdate, onDelete) that call RxDB APIs (bulkUpsert, incrementalPatch, bulkRemove)
357
358## Complete Example: WebSocket Collection
359
360Here's a complete example of a WebSocket-based collection options creator that demonstrates the full round-trip flow:
361
3621. Client sends transaction with all mutations batched together
3632. Server processes the transaction and may modify the data (validation, timestamps, etc.)
3643. Server sends back acknowledgment and the actual processed data
3654. Client waits for this round-trip before dropping optimistic state
366
367```typescript
368import type {
369 CollectionConfig,
370 SyncConfig,
371 InsertMutationFnParams,
372 UpdateMutationFnParams,
373 DeleteMutationFnParams,
374 UtilsRecord
375} from '@tanstack/db'
376
377interface WebSocketMessage<T> {
378 type: 'insert' | 'update' | 'delete' | 'sync' | 'transaction' | 'ack'
379 data?: T | T[]
380 mutations?: Array<{
381 type: 'insert' | 'update' | 'delete'
382 data: T
383 id?: string
384 }>
385 transactionId?: string
386 id?: string
387}
388
389interface WebSocketCollectionConfig<TItem extends object>
390 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete' | 'sync'> {
391 url: string
392 reconnectInterval?: number
394 // Note: onInsert/onUpdate/onDelete are handled by the WebSocket connection
395 // Users don't provide these handlers
396}
397
398interface WebSocketUtils extends UtilsRecord {
399 reconnect: () => void
400 getConnectionState: () => 'connected' | 'disconnected' | 'connecting'
401}
402
403export function webSocketCollectionOptions<TItem extends object>(
404 config: WebSocketCollectionConfig<TItem>
405): CollectionConfig<TItem> & { utils: WebSocketUtils } {
406 let ws: WebSocket | null = null
407 let reconnectTimer: NodeJS.Timeout | null = null
408 let connectionState: 'connected' | 'disconnected' | 'connecting' = 'disconnected'
410 // Track pending transactions awaiting acknowledgment
411 const pendingTransactions = new Map<string, {
412 resolve: () => void
413 reject: (error: Error) => void
414 timeout: NodeJS.Timeout
415 }>()
417 const sync: SyncConfig<TItem>['sync'] = (params) => {
418 const { begin, write, commit, markReady } = params
420 function connect() {
421 connectionState = 'connecting'
422 ws = new WebSocket(config.url)
424 ws.onopen = () => {
425 connectionState = 'connected'
426 // Request initial sync
427 ws.send(JSON.stringify({ type: 'sync' }))
428 }
430 ws.onmessage = (event) => {
431 const message: WebSocketMessage<TItem> = JSON.parse(event.data)
433 switch (message.type) {
434 case 'sync':
435 // Initial sync with array of items
436 begin()
437 if (Array.isArray(message.data)) {
438 for (const item of message.data) {
439 write({ type: 'insert', value: item })
440 }
441 }
442 commit()
443 markReady()
444 break
446 case 'insert':
447 case 'update':
448 case 'delete':
449 // Real-time updates from other clients
450 begin()
451 write({
452 type: message.type,
453 value: message.data as TItem
454 })
455 commit()
456 break
458 case 'ack':
459 // Server acknowledged our transaction
460 if (message.transactionId) {
461 const pending = pendingTransactions.get(message.transactionId)
462 if (pending) {
463 clearTimeout(pending.timeout)
464 pendingTransactions.delete(message.transactionId)
465 pending.resolve()
466 }
467 }
468 break
470 case 'transaction':
471 // Server sending back the actual data after processing our transaction
472 if (message.mutations) {
473 begin()
474 for (const mutation of message.mutations) {
475 write({
476 type: mutation.type,
477 value: mutation.data
478 })
479 }
480 commit()
481 }
482 break
483 }
484 }
486 ws.onerror = (error) => {
487 console.error('WebSocket error:', error)
488 connectionState = 'disconnected'
489 }
491 ws.onclose = () => {
492 connectionState = 'disconnected'
493 // Auto-reconnect
494 if (!reconnectTimer) {
495 reconnectTimer = setTimeout(() => {
496 reconnectTimer = null
497 connect()
498 }, config.reconnectInterval || 5000)
499 }
500 }
501 }
503 // Start connection
504 connect()
506 // Return cleanup function
507 return () => {
508 if (reconnectTimer) {
509 clearTimeout(reconnectTimer)
510 reconnectTimer = null
511 }
512 if (ws) {
513 ws.close()
514 ws = null
515 }
516 }
517 }
519 // Helper function to send transaction and wait for server acknowledgment
520 const sendTransaction = async (
521 params: InsertMutationFnParams<TItem> | UpdateMutationFnParams<TItem> | DeleteMutationFnParams<TItem>
522 ): Promise<void> => {
523 if (ws?.readyState !== WebSocket.OPEN) {
524 throw new Error('WebSocket not connected')
525 }
527 const transactionId = crypto.randomUUID()
529 // Convert all mutations in the transaction to the wire format
530 const mutations = params.transaction.mutations.map(mutation => ({
531 type: mutation.type,
532 id: mutation.key,
533 data: mutation.type === 'delete' ? undefined :
534 mutation.type === 'update' ? mutation.changes :
535 mutation.modified
536 }))
538 // Send the entire transaction at once
539 ws.send(JSON.stringify({
540 type: 'transaction',
541 transactionId,
542 mutations
543 }))
545 // Wait for server acknowledgment
546 return new Promise<void>((resolve, reject) => {
547 const timeout = setTimeout(() => {
548 pendingTransactions.delete(transactionId)
549 reject(new Error(`Transaction ${transactionId} timed out`))
550 }, 10000) // 10 second timeout
552 pendingTransactions.set(transactionId, {
553 resolve,
554 reject,
555 timeout
556 })
557 })
558 }
560 // All mutation handlers use the same transaction sender
561 const onInsert = async (params: InsertMutationFnParams<TItem>) => {
562 await sendTransaction(params)
563 }
565 const onUpdate = async (params: UpdateMutationFnParams<TItem>) => {
566 await sendTransaction(params)
567 }
569 const onDelete = async (params: DeleteMutationFnParams<TItem>) => {
570 await sendTransaction(params)
571 }
573 return {
574 id: config.id,
575 schema: config.schema,
576 getKey: config.getKey,
577 sync: { sync },
578 onInsert,
579 onUpdate,
580 onDelete,
581 utils: {
582 reconnect: () => {
583 if (ws) ws.close()
584 connect()
585 },
586 getConnectionState: () => connectionState
587 }
588 }
589}
590```
591
592## Usage Example
593
594```typescript
595import { createCollection } from '@tanstack/react-db'
596import { webSocketCollectionOptions } from './websocket-collection'
597
598const todos = createCollection(
599 webSocketCollectionOptions({
600 url: 'ws://localhost:8080/todos',
601 getKey: (todo) => todo.id,
602 schema: todoSchema
603 // Note: No onInsert/onUpdate/onDelete - handled by WebSocket automatically
604 })
605)
606
607// Use the collection
608todos.insert({ id: '1', text: 'Buy milk', completed: false })
609
610// Access utilities
611todos.utils.getConnectionState() // 'connected'
612todos.utils.reconnect() // Force reconnect
613```
614
615## Advanced: Managing Optimistic State
616
617A critical challenge in sync-first apps is knowing when to drop optimistic state. When a user makes a change:
618
6191. The UI updates immediately (optimistic update)
6202. A mutation is sent to the backend
6213. The backend processes and persists the change
6224. The change syncs back to the client
6235. The optimistic state should be dropped in favor of the synced data
624
625The key question is: **How do you know when step 4 is complete?**
626
627### Strategy 1: Built-in Provider Methods (Recommended)
628
629Many providers offer built-in methods to wait for sync completion:
630
631```typescript
632// Firebase
633await waitForPendingWrites(firestore)
634
635// Custom WebSocket
636await websocket.waitForAck(transactionId)
637```
638
639### Strategy 2: Transaction ID Tracking (ElectricSQL)
640
641ElectricSQL returns transaction IDs that you can track:
642
643```typescript
644// Track seen transaction IDs
645const seenTxids = new Store<Set<number>>(new Set())
646
647// In sync, track txids from incoming messages
648if (message.headers.txids) {
649 message.headers.txids.forEach(txid => {
650 seenTxids.setState(prev => new Set([...prev, txid]))
651 })
652}
653
654// Mutation handlers return txids and wait for them
655const wrappedOnInsert = async (params) => {
656 const result = await config.onInsert!(params)
658 // Wait for the txid to appear in synced data
659 if (result.txid) {
660 await awaitTxId(result.txid)
661 }
663 return result
664}
665
666// Utility function to wait for a txid
667const awaitTxId = (txId: number): Promise<boolean> => {
668 if (seenTxids.state.has(txId)) return Promise.resolve(true)
670 return new Promise((resolve) => {
671 const unsubscribe = seenTxids.subscribe(() => {
672 if (seenTxids.state.has(txId)) {
673 unsubscribe()
674 resolve(true)
675 }
676 })
677 })
678}
679```
680
681### Strategy 3: ID-Based Tracking (Trailbase)
682
683Trailbase tracks when specific record IDs have been synced:
684
685```typescript
686// Track synced IDs with timestamps
687const seenIds = new Store(new Map<string, number>())
688
689// In sync, mark IDs as seen
690write({ type: 'insert', value: item })
691seenIds.setState(prev => new Map(prev).set(item.id, Date.now()))
692
693// Wait for specific IDs after mutations
694const wrappedOnInsert = async (params) => {
695 const ids = await config.recordApi.createBulk(items)
697 // Wait for all IDs to be synced back
698 await awaitIds(ids)
699}
700
701const awaitIds = (ids: string[]): Promise<void> => {
702 const allSynced = ids.every(id => seenIds.state.has(id))
703 if (allSynced) return Promise.resolve()
705 return new Promise((resolve) => {
706 const unsubscribe = seenIds.subscribe((state) => {
707 if (ids.every(id => state.has(id))) {
708 unsubscribe()
709 resolve()
710 }
711 })
712 })
713}
714```
715
716### Strategy 4: Version/Timestamp Tracking
717
718Track version numbers or timestamps to detect when data is fresh:
719
720```typescript
721// Track latest sync timestamp
722let lastSyncTime = 0
723
724// In mutations, record when the operation was sent
725const wrappedOnUpdate = async (params) => {
726 const mutationTime = Date.now()
727 await config.onUpdate(params)
729 // Wait for sync to catch up
730 await waitForSync(mutationTime)
731}
732
733const waitForSync = (afterTime: number): Promise<void> => {
734 if (lastSyncTime > afterTime) return Promise.resolve()
736 return new Promise((resolve) => {
737 const check = setInterval(() => {
738 if (lastSyncTime > afterTime) {
739 clearInterval(check)
740 resolve()
741 }
742 }, 100)
743 })
744}
745```
746
747### Strategy 5: Full Refetch (Query Collection)
748
749The query collection simply refetches all data after mutations:
750
751```typescript
752const wrappedOnInsert = async (params) => {
753 // Perform the mutation
754 await config.onInsert(params)
756 // Refetch the entire collection
757 await refetch()
759 // The refetch will trigger sync with fresh data,
760 // automatically dropping optimistic state
761}
762```
763
764### Choosing a Strategy
765
766- **Built-in Methods**: Best when your provider offers sync completion APIs
767- **Transaction IDs**: Best when your backend provides reliable transaction tracking
768- **ID-Based**: Good for systems where each mutation returns the affected IDs
769- **Full Refetch**: Simplest but least efficient; good for small datasets
770- **Version/Timestamp**: Works when your sync includes reliable ordering information
771
772### Implementation Tips
773
7741. **Always wait for sync** in your mutation handlers to ensure optimistic state is properly managed
7752. **Handle timeouts** - Don't wait forever for sync confirmation
7763. **Clean up tracking data** - Remove old txids/IDs to prevent memory leaks
7774. **Provide utilities** - Export functions like `awaitTxId` or `awaitSync` for advanced use cases
778
779## Best Practices
780
7811. **Always call markReady()** - This signals that the collection has initial data and is ready for use
7822. **Handle errors gracefully** - Call markReady() even on error to avoid blocking the app
7833. **Clean up resources** - Return a cleanup function from sync to prevent memory leaks
7844. **Batch operations** - Use begin/commit to batch multiple changes for better performance
7855. **Race Conditions** - Start listeners before initial fetch and buffer events
7866. **Type safety** - Use TypeScript generics to maintain type safety throughout
7877. **Provide utilities** - Export sync-engine-specific utilities for advanced use cases
788
789## Testing Your Collection
790
791Test your collection options creator with:
792
7931. **Unit tests** - Test sync logic, data transformations
7942. **Integration tests** - Test with real sync engine
7953. **Error scenarios** - Connection failures, invalid data
7964. **Performance** - Large datasets, frequent updates
797
798## Conclusion
799
800Creating a collection options creator allows you to integrate any sync engine with TanStack DB's powerful sync-first architecture. Follow the patterns shown here, and you'll have a robust, type-safe integration that provides excellent developer experience.