Open History to see the last commit
1---
2title: Creating a Collection Options Creator
3id: guide/collection-options-creator
4---
5A 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.
6
7## Overview
8
9Collection options creators follow a consistent pattern:
101. Accept configuration specific to the sync engine
112. Return an object that satisfies the `CollectionConfig` interface
123. Handle sync initialization, data parsing, and transaction management
134. Optionally provide utility functions specific to the sync engine
14
15## When to Create a Custom Collection
16
17You should create a custom collection when:
18- You have a dedicated sync engine (like ElectricSQL, Trailbase, Firebase, RxDB or a custom WebSocket solution)
19- You need specific sync behaviors that aren't covered by the query collection
20- You want to integrate with a backend that has its own sync protocol
21
22**Note**: If you're just hitting an API and returning data, use the query collection instead.
23
24## Core Requirements
25
26Every collection options creator must implement these key responsibilities:
27
28### 1. Configuration Interface
29
30Define a configuration interface that extends or includes standard collection properties:
31
32```typescript
33// Pattern A: User provides handlers (Query / ElectricSQL style)
34interface MyCollectionConfig<TItem extends object> {
35 // Your sync engine specific options
36 connectionUrl: string
37 apiKey?: string
39 // Standard collection properties
40 id?: string
41 schema?: StandardSchemaV1
42 getKey: (item: TItem) => string | number
43 sync?: SyncConfig<TItem>
45 rowUpdateMode?: 'partial' | 'full'
47 // User provides mutation handlers
48 onInsert?: InsertMutationFn<TItem>
49 onUpdate?: UpdateMutationFn<TItem>
50 onDelete?: DeleteMutationFn<TItem>
51}
52
53// Pattern B: Built-in handlers (Trailbase style)
54interface MyCollectionConfig<TItem extends object>
55 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete'> {
56 // Your sync engine specific options
57 recordApi: MyRecordApi<TItem>
58 connectionUrl: string
60 rowUpdateMode?: 'partial' | 'full'
62 // Note: onInsert/onUpdate/onDelete are implemented by your collection creator
63}
64```
65
66### 2. Sync Implementation
67
68Each call to the sync function starts a **sync run**. The run owns the callbacks
69and resources installed by that call until its returned cleanup ends them. A
70sync run may make several backend requests or open a longer-lived provider
71session, so it is not itself a request or provider session.
72
73The sync function is the heart of your collection. It must return a cleanup
74function for proper garbage collection:
75
76```typescript
77const sync: SyncConfig<T>['sync'] = (params) => {
78 const { begin, write, commit, markReady, markError, collection } = params
80 // 1. Initialize connection to your sync engine
81 const connection = initializeConnection(config)
82 const initialSyncAbort = new AbortController()
84 // 2. Set up real-time subscription FIRST (prevents race conditions)
85 const eventBuffer: Array<any> = []
86 let isInitialSyncComplete = false
88 connection.subscribe((event) => {
89 if (!isInitialSyncComplete) {
90 // Buffer events during initial sync to prevent race conditions
91 eventBuffer.push(event)
92 return
93 }
95 // Process real-time events
96 begin()
98 switch (event.type) {
99 case 'insert':
100 write({ type: 'insert', value: event.data })
101 break
102 case 'update':
103 write({ type: 'update', value: event.data })
104 break
105 case 'delete':
106 write({ type: 'delete', value: event.data })
107 break
108 }
110 commit()
111 })
113 // 3. Perform initial data fetch
114 async function initialSync() {
115 try {
116 const data = await fetchInitialData({ signal: initialSyncAbort.signal })
118 begin() // Start a transaction
120 for (const item of data) {
121 write({
122 type: 'insert',
123 value: item
124 })
125 }
127 commit() // Commit the transaction
129 // 4. Process buffered events
130 isInitialSyncComplete = true
131 if (eventBuffer.length > 0) {
132 begin()
133 for (const event of eventBuffer) {
134 // Deduplicate if necessary based on your sync engine
135 write({ type: event.type, value: event.data })
136 }
137 commit()
138 eventBuffer.splice(0)
139 }
140
141 // A complete initial snapshot is now available.
142 markReady()
143 } catch (error) {
144 if (initialSyncAbort.signal.aborted) return
145 console.error('Initial sync failed:', error)
146 // No usable initial snapshot exists.
147 // Only initial startup owns collection readiness. A later refetch
148 // failure must keep the last ready snapshot usable.
149 if (collection.status === 'loading') markError(error)
150 }
151 }
152
153 initialSync()
155 // 4. Return cleanup function
156 return () => {
157 initialSyncAbort.abort()
158 connection.close()
159 // Clean up any timers, intervals, or other resources
160 }
161}
162```
163
164### 3. Transaction Lifecycle
165
166Understanding the transaction lifecycle is important for correct implementation.
167
168The sync process follows this lifecycle:
169
1701. **begin()** - Start collecting changes
1712. **write()** - Add changes to the pending transaction (buffered until commit)
1723. **commit()** - Apply all changes atomically to the collection state
1734. **markReady()** - Signal that a usable initial or recovered snapshot exists
1745. **markError(error?)** - Signal that initial sync failed before producing a usable snapshot; pass the cause so readiness waits reject with it
175
176`commit()` returns `true` if its writes and events are already visible, or a
177promise that resolves when they become visible. A commit can wait behind a
178pending optimistic transaction; receiving a server response is not the same as
179applying its rows. A successful `loadSubset` must await or return every commit
180receipt that establishes its result. Do not use `begin({ immediate: true })` to
181bypass that ordering just to settle a load.
182
183For request-scoped writes, pass the request's abort signal to `commit(signal)`.
184Cancellation before application rejects the receipt with `AbortError`; aborting
185after application does not undo published rows. Do not attach one request's
186signal to a shared stream transaction.
187
188If an adapter supplies `unloadSubset`, release only the acquisition belonging to
189the supplied options. Release must be idempotent and non-throwing; the adapter
190owns any remote unsubscribe retry. A synchronous `loadSubset` throw must clean
191up resources acquired before it throws. Returning a promise transfers ownership
192even if that promise later rejects, so failed acquisitions must remain safe to
193release without affecting peers.
194
195**Race Condition Prevention:**
196Many 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:
197- Starting the listener BEFORE initial fetch and buffering events
198- Tracking timestamps, sequence numbers, or document versions
199- Using read timestamps or other ordering mechanisms
200
201### 4. Data Parsing and Type Conversion
202
203If your sync engine returns data with different types, provide conversion functions for specific fields:
204
205```typescript
206interface MyCollectionConfig<TItem, TRecord> {
207 // ... other config
209 // Only specify conversions for fields that need type conversion
210 parse: {
211 created_at: (ts: number) => new Date(ts * 1000), // timestamp -> Date
212 updated_at: (ts: number) => new Date(ts * 1000), // timestamp -> Date
213 metadata?: (str: string) => JSON.parse(str) // JSON string -> object
214 }
216 serialize: {
217 created_at: (date: Date) => Math.floor(date.valueOf() / 1000), // Date -> timestamp
218 updated_at: (date: Date) => Math.floor(date.valueOf() / 1000), // Date -> timestamp
219 metadata?: (obj: object) => JSON.stringify(obj) // object -> JSON string
220 }
221}
222```
223
224**Type Conversion Examples:**
225```typescript
226// Firebase Timestamp to Date
227parse: {
228 createdAt: (timestamp) => timestamp?.toDate?.() || new Date(timestamp),
229 updatedAt: (timestamp) => timestamp?.toDate?.() || new Date(timestamp),
230}
231
232// PostGIS geometry to GeoJSON
233parse: {
234 location: (wkb: string) => parseWKBToGeoJSON(wkb)
235}
236
237// JSON string to object with error handling
238parse: {
239 metadata: (str: string) => {
240 try {
241 return JSON.parse(str)
242 } catch {
243 return {}
244 }
245 }
246}
247```
248
249### 5. Schemas and Type Transformations
250
251When building a custom collection, you need to decide how to handle the relationship between your backend's storage format and the client-side types users work with in their collections.
252
253#### Two Separate Concerns
254
255**Backend Format** - The types your storage layer uses (SQLite, Postgres, Firebase, etc.)
256- Examples: Unix timestamps, ISO strings, JSON strings, PostGIS geometries
257
258**Client Format** - The types users work with in their TanStack DB collections
259- Examples: Date objects, parsed JSON, GeoJSON
260
261Schemas in TanStack DB define the **client format** (TInput/TOutput for mutations). How you bridge between backend and client format depends on your integration design.
262
263#### Approach 1: Integration Provides Parse/Serialize Helpers
264
265For backends with specific storage formats, provide `parse`/`serialize` options that users configure:
266
267```typescript
268// TrailBase example: User specifies field conversions
269export function trailbaseCollectionOptions(config) {
270 return {
271 parse: config.parse, // User provides field conversions
272 serialize: config.serialize,
273
274 onInsert: async ({ transaction }) => {
275 const serialized = transaction.mutations.map(m =>
276 serializeFields(m.modified, config.serialize)
277 )
278 await config.recordApi.createBulk(serialized)
279 }
280 }
281}
282
283// User explicitly configures conversions
284const collection = createCollection(
285 trailbaseCollectionOptions({
286 schema: todoSchema,
287 parse: {
288 created_at: (ts: number) => new Date(ts * 1000) // Unix → Date
289 },
290 serialize: {
291 created_at: (date: Date) => Math.floor(date.valueOf() / 1000) // Date → Unix
292 }
293 })
294)
295```
296
297**Benefits:** Explicit control over type conversions. Integration handles applying them consistently.
298
299#### Approach 2: User Handles Everything in QueryFn/Handlers
300
301For simple APIs or when users want full control, they handle parsing/serialization themselves:
302
303```typescript
304// Query Collection: User handles all transformations
305const collection = createCollection(
306 queryCollectionOptions({
307 schema: todoSchema,
308 queryFn: async () => {
309 const response = await fetch('/api/todos')
310 const todos = await response.json()
311 // User manually parses to match their schema's TOutput
312 return todos.map(todo => ({
313 ...todo,
314 created_at: new Date(todo.created_at) // ISO string → Date
315 }))
316 },
317 onInsert: async ({ transaction }) => {
318 // User manually serializes for their backend
319 await fetch('/api/todos', {
320 method: 'POST',
321 body: JSON.stringify({
322 ...transaction.mutations[0].modified,
323 created_at: transaction.mutations[0].modified.created_at.toISOString() // Date → ISO string
324 })
325 })
326 }
327 })
328)
329```
330
331**Benefits:** Maximum flexibility, no abstraction overhead. Users see exactly what's happening.
332
333#### Approach 3: Automatic Serialization in Handlers
334
335If your backend has well-defined types, you can automatically serialize in mutation handlers:
336
337```typescript
338export function myCollectionOptions(config) {
339 return {
340 onInsert: async ({ transaction }) => {
341 // Automatically serialize known types for your backend
342 const serialized = transaction.mutations.map(m => ({
343 ...m.modified,
344 // Date objects → Unix timestamps for your backend
345 created_at: m.modified.created_at instanceof Date
346 ? Math.floor(m.modified.created_at.valueOf() / 1000)
347 : m.modified.created_at
348 }))
349 await backend.insert(serialized)
350 }
351 }
352}
353```
354
355**Benefits:** Least configuration for users. Integration handles backend format automatically.
356
357#### Key Design Principles
358
3591. **Schemas validate client mutations only** - They don't affect how backend data is parsed during sync
3602. **TOutput is the application-facing type** - This is what users work with in their app
3613. **Choose your approach based on backend constraints** - Fixed types → automatic serialization; varying types → user configuration
3624. **Document your backend format clearly** - Explain what types your storage uses and how to handle them
363
364For more on schemas from a user perspective, see the [Schemas guide](./schemas.md).
365
366### 6. Mutation Handler Patterns
367
368There are two distinct patterns for handling mutations in collection options creators:
369
370#### Pattern A: User-Provided Handlers (Query, Standard)
371
372The user provides mutation handlers in the config. Your collection creator passes them through.
373
374**Note:** Handler return values are deprecated. Users should trigger refetch/sync within their handlers.
375
376```typescript
377interface MyCollectionConfig<TItem extends object> {
378 // ... other config
379
380 // User provides these handlers
381 onInsert?: InsertMutationFn<TItem>
382 onUpdate?: UpdateMutationFn<TItem>
383 onDelete?: DeleteMutationFn<TItem>
384}
385
386export function myCollectionOptions<TItem extends object>(
387 config: MyCollectionConfig<TItem>
388) {
389 return {
390 // ... other options
391 rowUpdateMode: config.rowUpdateMode || 'partial',
392
393 // Pass through user-provided handlers
394 // Users handle sync coordination in their own handlers
395 onInsert: config.onInsert,
396 onUpdate: config.onUpdate,
397 onDelete: config.onDelete
398 }
399}
400```
401
402
403#### Pattern B: Built-in Handlers (Trailbase, WebSocket, Firebase)
404
405Your collection creator implements the handlers directly using the sync engine's APIs:
406
407```typescript
408interface MyCollectionConfig<TItem extends object>
409 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete'> {
410 // ... sync engine specific config
411 // Note: onInsert/onUpdate/onDelete are NOT in the config
412}
413
414export function myCollectionOptions<TItem extends object>(
415 config: MyCollectionConfig<TItem>
416) {
417 return {
418 // ... other options
419 rowUpdateMode: config.rowUpdateMode || 'partial',
420
421 // Implement handlers using sync engine APIs
422 onInsert: async ({ transaction }) => {
423 // Handle provider-specific batch limits (e.g., Firestore's 500 limit)
424 const chunks = chunkArray(transaction.mutations, PROVIDER_BATCH_LIMIT)
425
426 for (const chunk of chunks) {
427 const ids = await config.recordApi.createBulk(
428 chunk.map(m => serialize(m.modified))
429 )
430 // Wait for these IDs to sync back before completing
431 await awaitIds(ids)
432 }
433 // Handler completes after sync coordination
434 },
435
436 onUpdate: async ({ transaction }) => {
437 const chunks = chunkArray(transaction.mutations, PROVIDER_BATCH_LIMIT)
438
439 for (const chunk of chunks) {
440 await Promise.all(
441 chunk.map(m =>
442 config.recordApi.update(m.key, serialize(m.changes))
443 )
444 )
445 }
446
447 // Wait for mutations to sync back
448 await awaitIds(transaction.mutations.map(m => String(m.key)))
449 }
450 }
451}
452```
453
454Many providers have batch size limits (Firestore: 500, DynamoDB: 25, etc.) so chunk large transactions accordingly.
455
456**Key Principle:** Built-in handlers should coordinate sync internally (using `awaitIds`, `awaitTxId`, or similar) and not rely on return values. The handler completes only after sync coordination is done.
457
458Choose Pattern A when users need to provide their own APIs, and Pattern B when your sync engine handles writes directly.
459
460## Row Update Modes
461
462Collections support two update modes:
463
464- **`partial`** (default) - Updates are merged with existing data
465- **`full`** - Updates replace the entire row
466
467Configure this in your sync config:
468
469```typescript
470sync: {
471 sync: syncFn,
472 rowUpdateMode: 'full' // or 'partial'
473}
474```
475
476## Production Examples
477
478For complete, production-ready examples, see the collection packages in the TanStack DB repository:
479
480- **[@tanstack/query-db-collection](https://github.com/TanStack/db/tree/main/packages/query-db-collection)** - Pattern A: User-provided handlers with full refetch strategy
481- **[@tanstack/trailbase-db-collection](https://github.com/TanStack/db/tree/main/packages/trailbase-db-collection)** - Pattern B: Built-in handlers with ID-based tracking
482- **[@tanstack/electric-db-collection](https://github.com/TanStack/db/tree/main/packages/electric-db-collection)** - Pattern A: Transaction ID tracking with complex sync protocols
483- **[@tanstack/rxdb-db-collection](https://github.com/TanStack/db/tree/main/packages/rxdb-db-collection)** - Pattern B: Built-in handlers that bridge [RxDB](https://rxdb.info) change streams into TanStack DB's sync lifecycle
484
485### Key Lessons from Production Collections
486
487**From Query Collection:**
488- Simplest approach: Full refetch after mutations
489- Best for: APIs without real-time sync
490- Pattern: User provides `onInsert/onUpdate/onDelete` handlers
491
492**From Trailbase Collection:**
493- Shows ID-based optimistic state management
494- Handles provider batch limits (chunking large operations)
495- Pattern: Collection provides mutation handlers using record API
496
497**From Electric Collection:**
498- Complex transaction ID tracking for distributed sync
499- Demonstrates advanced deduplication techniques
500- Shows how to wrap user handlers with sync coordination
501
502**From RxDB Collection:**
503- Uses RxDB's built-in queries and change streams
504- Uses `RxCollection.$` to subscribe to inserts/updates/deletes and forward them to TanStack DB with begin-write-commit
505- Implements built-in mutation handlers (onInsert, onUpdate, onDelete) that call RxDB APIs (bulkUpsert, incrementalPatch, bulkRemove)
506
507## Complete Example: WebSocket Collection
508
509Here's a complete example of a WebSocket-based collection options creator that demonstrates the full round-trip flow:
510
5111. Client sends transaction with all mutations batched together
5122. Server processes the transaction and may modify the data (validation, timestamps, etc.)
5133. Server sends back acknowledgment and the actual processed data
5144. Client waits for this round-trip before dropping optimistic state
515
516```typescript
517import type {
518 CollectionConfig,
519 SyncConfig,
520 InsertMutationFnParams,
521 UpdateMutationFnParams,
522 DeleteMutationFnParams,
523 UtilsRecord
524} from '@tanstack/db'
525
526interface WebSocketMessage<T> {
527 type: 'insert' | 'update' | 'delete' | 'sync' | 'transaction' | 'ack'
528 data?: T | T[]
529 mutations?: Array<{
530 type: 'insert' | 'update' | 'delete'
531 data: T
532 id?: string
533 }>
534 transactionId?: string
535 id?: string
536}
537
538interface WebSocketCollectionConfig<TItem extends object>
539 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete' | 'sync'> {
540 url: string
541 reconnectInterval?: number
543 // Note: onInsert/onUpdate/onDelete are handled by the WebSocket connection
544 // Users don't provide these handlers
545}
546
547interface WebSocketUtils extends UtilsRecord {
548 reconnect: () => void
549 getConnectionState: () => 'connected' | 'disconnected' | 'connecting'
550}
551
552export function webSocketCollectionOptions<TItem extends object>(
553 config: WebSocketCollectionConfig<TItem>
554): CollectionConfig<TItem> & { utils: WebSocketUtils } {
555 let ws: WebSocket | null = null
556 let reconnectTimer: NodeJS.Timeout | null = null
557 let connectionState: 'connected' | 'disconnected' | 'connecting' = 'disconnected'
559 // Track pending transactions awaiting acknowledgment
560 const pendingTransactions = new Map<string, {
561 resolve: () => void
562 reject: (error: Error) => void
563 timeout: NodeJS.Timeout
564 }>()
566 const sync: SyncConfig<TItem>['sync'] = (params) => {
567 const { begin, write, commit, markReady } = params
569 function connect() {
570 connectionState = 'connecting'
571 ws = new WebSocket(config.url)
573 ws.onopen = () => {
574 connectionState = 'connected'
575 // Request initial sync
576 ws.send(JSON.stringify({ type: 'sync' }))
577 }
579 ws.onmessage = (event) => {
580 const message: WebSocketMessage<TItem> = JSON.parse(event.data)
582 switch (message.type) {
583 case 'sync':
584 // Initial sync with array of items
585 begin()
586 if (Array.isArray(message.data)) {
587 for (const item of message.data) {
588 write({ type: 'insert', value: item })
589 }
590 }
591 commit()
592 markReady()
593 break
595 case 'insert':
596 case 'update':
597 case 'delete':
598 // Real-time updates from other clients
599 begin()
600 write({
601 type: message.type,
602 value: message.data as TItem
603 })
604 commit()
605 break
607 case 'ack':
608 // Server acknowledged our transaction
609 if (message.transactionId) {
610 const pending = pendingTransactions.get(message.transactionId)
611 if (pending) {
612 clearTimeout(pending.timeout)
613 pendingTransactions.delete(message.transactionId)
614 pending.resolve()
615 }
616 }
617 break
619 case 'transaction':
620 // Server sending back the actual data after processing our transaction
621 if (message.mutations) {
622 begin()
623 for (const mutation of message.mutations) {
624 write({
625 type: mutation.type,
626 value: mutation.data
627 })
628 }
629 commit()
630 }
631 break
632 }
633 }
635 ws.onerror = (error) => {
636 console.error('WebSocket error:', error)
637 connectionState = 'disconnected'
638 }
640 ws.onclose = () => {
641 connectionState = 'disconnected'
642 // Auto-reconnect
643 if (!reconnectTimer) {
644 reconnectTimer = setTimeout(() => {
645 reconnectTimer = null
646 connect()
647 }, config.reconnectInterval || 5000)
648 }
649 }
650 }
652 // Start connection
653 connect()
655 // Return cleanup function
656 return () => {
657 if (reconnectTimer) {
658 clearTimeout(reconnectTimer)
659 reconnectTimer = null
660 }
661 if (ws) {
662 ws.close()
663 ws = null
664 }
665 }
666 }
668 // Helper function to send transaction and wait for server acknowledgment
669 const sendTransaction = async (
670 params: InsertMutationFnParams<TItem> | UpdateMutationFnParams<TItem> | DeleteMutationFnParams<TItem>
671 ): Promise<void> => {
672 if (ws?.readyState !== WebSocket.OPEN) {
673 throw new Error('WebSocket not connected')
674 }
676 const transactionId = crypto.randomUUID()
678 // Convert all mutations in the transaction to the wire format
679 const mutations = params.transaction.mutations.map(mutation => ({
680 type: mutation.type,
681 id: mutation.key,
682 data: mutation.type === 'delete' ? undefined :
683 mutation.type === 'update' ? mutation.changes :
684 mutation.modified
685 }))
687 // Send the entire transaction at once
688 ws.send(JSON.stringify({
689 type: 'transaction',
690 transactionId,
691 mutations
692 }))
694 // Wait for server acknowledgment
695 return new Promise<void>((resolve, reject) => {
696 const timeout = setTimeout(() => {
697 pendingTransactions.delete(transactionId)
698 reject(new Error(`Transaction ${transactionId} timed out`))
699 }, 10000) // 10 second timeout
701 pendingTransactions.set(transactionId, {
702 resolve,
703 reject,
704 timeout
705 })
706 })
707 }
709 // All mutation handlers use the same transaction sender
710 // Handlers wait for server acknowledgment before completing
711 const onInsert = async (params: InsertMutationFnParams<TItem>): Promise<void> => {
712 await sendTransaction(params)
713 // Handler completes after server confirms the transaction
714 }
715
716 const onUpdate = async (params: UpdateMutationFnParams<TItem>): Promise<void> => {
717 await sendTransaction(params)
718 }
719
720 const onDelete = async (params: DeleteMutationFnParams<TItem>): Promise<void> => {
721 await sendTransaction(params)
722 }
724 return {
725 id: config.id,
726 schema: config.schema,
727 getKey: config.getKey,
728 sync: { sync },
729 onInsert,
730 onUpdate,
731 onDelete,
732 utils: {
733 reconnect: () => {
734 if (ws) ws.close()
735 connect()
736 },
737 getConnectionState: () => connectionState
738 }
739 }
740}
741```
742
743## Usage Example
744
745```typescript
746import { DbClient, collectionOptions } from '@tanstack/react-db'
747import { webSocketCollectionOptions } from './websocket-collection'
748
749const db = new DbClient()
750
751const todosCollection = collectionOptions('todos', () =>
752 webSocketCollectionOptions({
753 id: 'todos',
754 url: 'ws://localhost:8080/todos',
755 getKey: (todo) => todo.id,
756 schema: todoSchema,
757 // Note: No onInsert/onUpdate/onDelete - handled by WebSocket automatically
758 })
759)
760
761const todos = db.collection(todosCollection)
762
763// Use the collection
764todos.insert({ id: '1', text: 'Buy milk', completed: false })
765
766// Access utilities
767todos.utils.getConnectionState() // 'connected'
768todos.utils.reconnect() // Force reconnect
769```
770
771## Advanced: Managing Optimistic State
772
773A critical challenge in sync-first apps is knowing when to drop optimistic state. When a user makes a change:
774
7751. The UI updates immediately (optimistic update)
7762. A mutation is sent to the backend
7773. The backend processes and persists the change
7784. The change syncs back to the client
7795. The optimistic state should be dropped in favor of the synced data
780
781The key question is: **How do you know when step 4 is complete?**
782
783### Strategy 1: Built-in Provider Methods (Recommended)
784
785Many providers offer built-in methods to wait for sync completion:
786
787```typescript
788// Firebase
789await waitForPendingWrites(firestore)
790
791// Custom WebSocket
792await websocket.waitForAck(transactionId)
793```
794
795### Strategy 2: Transaction ID Tracking (ElectricSQL)
796
797ElectricSQL returns transaction IDs that you can track:
798
799```typescript
800// Track seen transaction IDs
801const seenTxids = new Store<Set<number>>(new Set())
802
803// In sync, track txids from incoming messages
804if (message.headers.txids) {
805 message.headers.txids.forEach(txid => {
806 seenTxids.setState(prev => new Set([...prev, txid]))
807 })
808}
809
810// Electric-specific: expose awaitTxId through collection.utils so handlers
811// can coordinate txid-based sync before they complete
812const wrappedOnInsert = async (params) => {
813 // The user handler persists the mutation, then calls
814 // await params.collection.utils.awaitTxId(txid) internally.
815 await config.onInsert!(params)
816}
817
818// Utility function to wait for a txid
819const awaitTxId = (txId: number): Promise<boolean> => {
820 if (seenTxids.state.has(txId)) return Promise.resolve(true)
822 return new Promise((resolve) => {
823 const unsubscribe = seenTxids.subscribe(() => {
824 if (seenTxids.state.has(txId)) {
825 unsubscribe()
826 resolve(true)
827 }
828 })
829 })
830}
831```
832
833### Strategy 3: ID-Based Tracking (Trailbase)
834
835Trailbase tracks when specific record IDs have been synced:
836
837```typescript
838// Track synced IDs with timestamps
839const seenIds = new Store(new Map<string, number>())
840
841// In sync, mark IDs as seen
842write({ type: 'insert', value: item })
843seenIds.setState(prev => new Map(prev).set(item.id, Date.now()))
844
845// Wait for specific IDs after mutations
846const wrappedOnInsert = async (params) => {
847 const ids = await config.recordApi.createBulk(items)
848
849 // Wait for all IDs to be synced back before handler completes
850 await awaitIds(ids)
851}
852
853const awaitIds = (ids: string[]): Promise<void> => {
854 const allSynced = ids.every(id => seenIds.state.has(id))
855 if (allSynced) return Promise.resolve()
857 return new Promise((resolve) => {
858 const unsubscribe = seenIds.subscribe((state) => {
859 if (ids.every(id => state.has(id))) {
860 unsubscribe()
861 resolve()
862 }
863 })
864 })
865}
866```
867
868### Strategy 4: Version/Timestamp Tracking
869
870Track version numbers or timestamps to detect when data is fresh:
871
872```typescript
873// Track latest sync timestamp
874let lastSyncTime = 0
875
876// In mutations, record when the operation was sent
877const wrappedOnUpdate = async (params) => {
878 const mutationTime = Date.now()
879 await config.onUpdate(params)
880
881 // Wait for sync to catch up before handler completes
882 await waitForSync(mutationTime)
883}
884
885const waitForSync = (afterTime: number): Promise<void> => {
886 if (lastSyncTime > afterTime) return Promise.resolve()
888 return new Promise((resolve) => {
889 const check = setInterval(() => {
890 if (lastSyncTime > afterTime) {
891 clearInterval(check)
892 resolve()
893 }
894 }, 100)
895 })
896}
897```
898
899### Strategy 5: Refetch (Query Collection)
900
901The query collection pattern has users refetch after mutations:
902
903```typescript
904// Pattern A: User provides handlers and manages refetch
905export function queryCollectionOptions<TItem>(config) {
906 return {
907 // ... other options
908
909 // User provides handlers and they handle refetch themselves
910 onInsert: config.onInsert, // User calls collection.utils.refetch() in their handler
911 onUpdate: config.onUpdate,
912 onDelete: config.onDelete,
913
914 utils: {
915 refetch: () => {
916 // Refetch implementation that syncs fresh data
917 // automatically dropping optimistic state
918 }
919 }
920 }
921}
922
923// Usage: User refetches in their handler
924const collection = createCollection(
925 queryCollectionOptions({
926 onInsert: async ({ transaction, collection }) => {
927 await api.createTodos(transaction.mutations.map(m => m.modified))
928 // User explicitly triggers refetch
929 await collection.utils.refetch()
930 // Prevent the pre-1.0 compatibility wrapper from refetching again.
931 return { refetch: false }
932 }
933 })
934)
935```
936
937### Choosing a Strategy
938
939- **Built-in Methods**: Best when your provider offers sync completion APIs
940- **Transaction IDs**: Best when your backend provides reliable transaction tracking
941- **ID-Based**: Good for systems where each mutation returns the affected IDs
942- **Full Refetch**: Simplest but least efficient; good for small datasets
943- **Version/Timestamp**: Works when your sync includes reliable ordering information
944
945### Implementation Tips
946
9471. **Always wait for sync** in your mutation handlers to ensure optimistic state is properly managed
9482. **Handle timeouts** - Don't wait forever for sync confirmation
9493. **Clean up tracking data** - Remove old txids/IDs to prevent memory leaks
9504. **Provide utilities** - Export functions like `awaitTxId` or `awaitSync` for advanced use cases
951
952## Best Practices
953
9541. **Report initial sync status** - Call `markReady()` after a usable snapshot, or `markError(error)` if initial sync fails
9552. **Recover explicitly** - After an error, call `markReady()` only when a later sync has produced a usable snapshot
9563. **Clean up resources** - Return a cleanup function from sync to prevent memory leaks
9574. **Batch operations** - Use begin/commit to batch multiple changes for better performance
9585. **Race Conditions** - Start listeners before initial fetch and buffer events
9596. **Type safety** - Use TypeScript generics to maintain type safety throughout
9607. **Provide utilities** - Export sync-engine-specific utilities for advanced use cases
9618. **Handler return values are deprecated** - Mutation handlers should coordinate sync internally (via `await`) rather than returning values. For Electric collections, use `await collection.utils.awaitTxId(txid)` instead of returning the txid
962
963## Testing Your Collection
964
965Test your collection options creator with:
966
9671. **Unit tests** - Test sync logic, data transformations
9682. **Integration tests** - Test with real sync engine
9693. **Error scenarios** - Connection failures, invalid data
9704. **Performance** - Large datasets, frequent updates
971
972## Conclusion
973
974Creating 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.