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
66Adapter-specific properties can be returned alongside the core options. TanStack DB ignores these extra properties. Development builds warn only about likely misspellings of a core option, such as `oninsert` for `onInsert`, when the correctly named option is absent. Missing or invalid required core options still throw.
67
68Keep adapter behavior in the adapter: returning `parse` or `serialize` does not make TanStack DB apply these conversions. Apply `parse` before calling `write` in your sync implementation, and apply `serialize` in mutation handlers. Put `rowUpdateMode` inside the returned `sync` object.
69
70### 2. Sync Implementation
71
72Each call to the sync function starts a **sync run**. The run owns the callbacks
73and resources installed by that call until its returned cleanup ends them. A
74sync run may make several backend requests or open a longer-lived provider
75session, so it is not itself a request or provider session.
76
77The sync function is the heart of your collection. It must return a cleanup
78function for proper garbage collection:
79
80```typescript
81const sync: SyncConfig<T>['sync'] = (params) => {
82 const { begin, write, commit, markReady, fail } = params
84 // 1. Initialize connection to your sync engine
85 const connection = initializeConnection(config)
86 const initialSyncAbort = new AbortController()
88 // 2. Set up real-time subscription FIRST (prevents race conditions)
89 const eventBuffer: Array<any> = []
90 let isInitialSyncComplete = false
92 connection.subscribe((event) => {
93 if (!isInitialSyncComplete) {
94 // Buffer events during initial sync to prevent race conditions
95 eventBuffer.push(event)
96 return
97 }
99 // Process real-time events
100 begin()
102 switch (event.type) {
103 case 'insert':
104 write({ type: 'insert', value: event.data })
105 break
106 case 'update':
107 write({ type: 'update', value: event.data })
108 break
109 case 'delete':
110 write({ type: 'delete', value: event.data })
111 break
112 }
114 commit()
115 })
117 // 3. Perform initial data fetch
118 async function initialSync() {
119 try {
120 const data = await fetchInitialData({ signal: initialSyncAbort.signal })
122 begin() // Start a transaction
124 for (const item of data) {
125 write({
126 type: 'insert',
127 value: item
128 })
129 }
131 commit() // Commit the transaction
133 // 4. Process buffered events
134 isInitialSyncComplete = true
135 if (eventBuffer.length > 0) {
136 begin()
137 for (const event of eventBuffer) {
138 // Deduplicate if necessary based on your sync engine
139 write({ type: event.type, value: event.data })
140 }
141 commit()
142 eventBuffer.splice(0)
143 }
144
145 // A complete initial snapshot is now available.
146 markReady()
147 } catch (error) {
148 if (initialSyncAbort.signal.aborted) return
149 console.error('Initial sync failed:', error)
150 // No usable initial snapshot exists in this run, and this example does
151 // not retry. After readiness, report failures with reportError() instead.
152 fail(error)
153 }
154 }
155
156 initialSync()
158 // 4. Return cleanup function
159 return () => {
160 initialSyncAbort.abort()
161 connection.close()
162 // Clean up any timers, intervals, or other resources
163 }
164}
165```
166
167### 3. Transaction Lifecycle
168
169Understanding the transaction lifecycle is important for correct implementation.
170
171The sync process follows this lifecycle:
172
1731. **begin()** - Start collecting changes
1742. **write()** - Add changes to the pending transaction (buffered until commit)
1753. **commit()** - Apply all changes atomically to the collection state
1764. **markReady()** - Signal that a usable initial snapshot exists
1775. **fail(error)** - Signal that you stopped trying. Before the Collection is ready, this fails the first load: the status becomes `error`, readiness waits reject with the cause, and `markReady()` afterward throws. After it, the node shows an `error`: the status and rows stay. Every later call in this sync run throws. Only `reload()` starts a new run
1786. **reportError(error)** - After the Collection is ready, report a sync problem while you keep trying. It sets the node's `failureReason` without changing its status or rows
1797. **reportHealthy()** - After the Collection is ready, report that sync works again. It clears the `failureReason`, and does nothing when nothing is wrong
180
181### Reporting failures
182
183Users see two separate signals: whether data can be shown, and whether it is
184still kept up to date. Follow these rules so both stay truthful:
185
1861. While you retry the initial sync, call nothing. The Collection stays
187 `loading`.
1882. Call `fail(error)` when you give up, before or after the first
189 `markReady()`. Do not call anything after it.
1903. After the first `markReady()`, call `reportError(error)` for a problem
191 while you keep trying, and `reportHealthy()` when sync works again. Never
192 discard rows because sync failed.
1934. Track the run's readiness in your `sync` function, as `ready` does below.
194 A reload calls `sync` again while `collection.status` still shows the
195 previous run, so status cannot tell you whether this run is ready. Write a
196 full snapshot on the run's first commit: a reload replaces every row then.
197
198```ts
199sync: ({ begin, write, commit, markReady, fail, reportError, reportHealthy }) => {
200 let ready = false
201 const stream = connect({
202 onData: (rows) => {
203 begin()
204 rows.forEach((row) => write({ type: "insert", value: row }))
205 commit()
206 if (!ready) {
207 markReady()
208 ready = true
209 } else {
210 reportHealthy()
211 }
212 },
213 onError: (error, { willRetry }) => {
214 if (!willRetry) fail(error)
215 else if (ready) reportError(error)
216 },
217 })
218 return () => stream.close()
219}
220```
221
222
223`commit()` accepts the transaction and returns `true`. An accepted transaction
224always applies, in commit order. While an optimistic transaction is persisting,
225the accepted transaction waits. It becomes visible when that optimistic
226transaction settles, in the same publication that drops its optimistic state.
227A mutation handler can therefore await its own write without waiting for
228itself. A wrapping sync, such as persistence, returns a promise that resolves
229after its durable step. A successful `loadSubset` must await or return every
230commit receipt that establishes its result.
231
232The collection keeps the object you pass to `write()` as the row's stored
233value. Pass a new object for each update. If your source changes a row object
234in place and writes it again, pass the row's previous value as
235`previousValue`. Without it, the change already overwrote the value the
236collection needs to publish the update, and live queries can keep the row in
237a result it left. In development, the collection throws
238`SyncRowReusedWithoutPreviousValueError` for that write when a top-level field
239changed. The check compares shallow copies, so it does not detect a change
240inside a nested object. Pass `previousValue` for those writes too.
241
242```ts
243// Changes a stored row in place, so it must name the previous value
244const previousValue = { ...row }
245row.status = `done`
246write({ type: `update`, value: row, previousValue })
247```
248
249For request-scoped writes, pass the request's abort signal to `commit(signal)`.
250If the signal has already aborted, the transaction is abandoned and the receipt
251rejects with `AbortError`. An accepted transaction ignores a later abort: its
252rows apply. To discard a stale page, check the signal before `commit()`. If the
253caller aborted after the page was accepted, the rows still apply, but reject the
254load with `AbortError` once its receipt resolves. Do not attach one request's
255signal to a shared stream transaction.
256
257An ordered request (one with `orderBy`) serves a prefix: every matching row
258from the start of the order through its boundary, the leading order value of
259the last row it returned, ties included. The ordered loader treats that whole prefix as loaded,
260so keep it whole when you refresh data the loader already holds. If your
261adapter refetches loaded subsets on its own, deliver every row that now sorts
262within a served prefix, even when it now falls between two served pages.
263Refetching each page alone can leave such a row in no result, and the loader
264receives no change that would request it. Either read each prefix again from
265the start of its order, or call `invalidateLoadedSubsets()` from the sync
266params once the refetched rows apply. Each ordered live query then repairs its
267window with a bounded read from the start of its order. Call it only when a
268refetch changed which rows a page holds, because every paging ordered live
269query on the Collection repairs. Do not call it for results that answer a
270`loadSubset` call.
271
272If an adapter supplies `unloadSubset`, release only the acquisition belonging to
273the supplied options. Release must be idempotent and non-throwing; the adapter
274owns any remote unsubscribe retry. A synchronous `loadSubset` throw must clean
275up resources acquired before it throws. Returning a promise transfers ownership
276even if that promise later rejects, so failed acquisitions must remain safe to
277release without affecting peers.
278
279**Race Condition Prevention:**
280Many 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:
281- Starting the listener BEFORE initial fetch and buffering events
282- Tracking timestamps, sequence numbers, or document versions
283- Using read timestamps or other ordering mechanisms
284
285### 4. Data Parsing and Type Conversion
286
287If your sync engine returns data with different types, provide conversion functions for specific fields:
288
289```typescript
290interface MyCollectionConfig<TItem, TRecord> {
291 // ... other config
293 // Only specify conversions for fields that need type conversion
294 parse: {
295 created_at: (ts: number) => new Date(ts * 1000), // timestamp -> Date
296 updated_at: (ts: number) => new Date(ts * 1000), // timestamp -> Date
297 metadata?: (str: string) => JSON.parse(str) // JSON string -> object
298 }
300 serialize: {
301 created_at: (date: Date) => Math.floor(date.valueOf() / 1000), // Date -> timestamp
302 updated_at: (date: Date) => Math.floor(date.valueOf() / 1000), // Date -> timestamp
303 metadata?: (obj: object) => JSON.stringify(obj) // object -> JSON string
304 }
305}
306```
307
308**Type Conversion Examples:**
309```typescript
310// Firebase Timestamp to Date
311parse: {
312 createdAt: (timestamp) => timestamp?.toDate?.() || new Date(timestamp),
313 updatedAt: (timestamp) => timestamp?.toDate?.() || new Date(timestamp),
314}
315
316// PostGIS geometry to GeoJSON
317parse: {
318 location: (wkb: string) => parseWKBToGeoJSON(wkb)
319}
320
321// JSON string to object with error handling
322parse: {
323 metadata: (str: string) => {
324 try {
325 return JSON.parse(str)
326 } catch {
327 return {}
328 }
329 }
330}
331```
332
333### 5. Schemas and Type Transformations
334
335When 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.
336
337#### Two Separate Concerns
338
339**Backend Format** - The types your storage layer uses (SQLite, Postgres, Firebase, etc.)
340- Examples: Unix timestamps, ISO strings, JSON strings, PostGIS geometries
341
342**Client Format** - The types users work with in their TanStack DB collections
343- Examples: Date objects, parsed JSON, GeoJSON
344
345Schemas in TanStack DB define the **client format** (TInput/TOutput for mutations). How you bridge between backend and client format depends on your integration design.
346
347#### Approach 1: Integration Provides Parse/Serialize Helpers
348
349For backends with specific storage formats, provide `parse`/`serialize` options that users configure:
350
351```typescript
352// TrailBase example: User specifies field conversions
353export function trailbaseCollectionOptions(config) {
354 return {
355 // ... getKey, schema, and sync options
356 // The sync implementation applies config.parse before calling write.
357
358 onInsert: async ({ transaction }) => {
359 const serialized = transaction.mutations.map(m =>
360 serializeFields(m.modified, config.serialize)
361 )
362 await config.recordApi.createBulk(serialized)
363 }
364 }
365}
366
367// User explicitly configures conversions
368const collection = createCollection(
369 trailbaseCollectionOptions({
370 schema: todoSchema,
371 parse: {
372 created_at: (ts: number) => new Date(ts * 1000) // Unix → Date
373 },
374 serialize: {
375 created_at: (date: Date) => Math.floor(date.valueOf() / 1000) // Date → Unix
376 }
377 })
378)
379```
380
381**Benefits:** Explicit control over type conversions. Integration handles applying them consistently.
382
383#### Approach 2: User Handles Everything in QueryFn/Handlers
384
385For simple APIs or when users want full control, they handle parsing/serialization themselves:
386
387```typescript
388// Query Collection: User handles all transformations
389const collection = createCollection(
390 queryCollectionOptions<{ id: string; created_at: Date }>({
391 schema: todoSchema,
392 queryKey: ['todos'],
393 queryClient,
394 getKey: (todo) => todo.id,
395 queryFn: async () => {
396 const response = await fetch('/api/todos')
397 const todos = await response.json()
398 // User manually parses to match their schema's TOutput
399 return todos.map(todo => ({
400 ...todo,
401 created_at: new Date(todo.created_at) // ISO string → Date
402 }))
403 },
404 onInsert: async ({ transaction, collection }) => {
405 // User manually serializes for their backend
406 await fetch('/api/todos', {
407 method: 'POST',
408 body: JSON.stringify({
409 ...transaction.mutations[0].modified,
410 created_at: transaction.mutations[0].modified.created_at.toISOString() // Date → ISO string
411 })
412 })
413 await collection.utils.refetch()
414 }
415 })
416)
417```
418
419**Benefits:** Maximum flexibility, no abstraction overhead. Users see exactly what's happening.
420
421#### Approach 3: Automatic Serialization in Handlers
422
423If your backend has well-defined types, you can automatically serialize in mutation handlers:
424
425```typescript
426export function myCollectionOptions(config) {
427 return {
428 onInsert: async ({ transaction }) => {
429 // Automatically serialize known types for your backend
430 const serialized = transaction.mutations.map(m => ({
431 ...m.modified,
432 // Date objects → Unix timestamps for your backend
433 created_at: m.modified.created_at instanceof Date
434 ? Math.floor(m.modified.created_at.valueOf() / 1000)
435 : m.modified.created_at
436 }))
437 await backend.insert(serialized)
438 }
439 }
440}
441```
442
443**Benefits:** Least configuration for users. Integration handles backend format automatically.
444
445#### Key Design Principles
446
4471. **Schemas validate client mutations only** - They don't affect how backend data is parsed during sync
4482. **TOutput is the application-facing type** - This is what users work with in their app
4493. **Choose your approach based on backend constraints** - Fixed types → automatic serialization; varying types → user configuration
4504. **Document your backend format clearly** - Explain what types your storage uses and how to handle them
451
452For more on schemas from a user perspective, see the [Schemas guide](./schemas.md).
453
454### 6. Mutation Handler Patterns
455
456There are two distinct patterns for handling mutations in collection options creators:
457
458#### Pattern A: User-Provided Handlers (Query, Standard)
459
460The user provides mutation handlers in the config. Your collection creator passes them through.
461
462Mutation handlers return `Promise<void>`. Trigger refetch or sync within the handler and await it before the handler completes.
463
464```typescript
465interface MyCollectionConfig<TItem extends object> {
466 // ... other config
467
468 // User provides these handlers
469 onInsert?: InsertMutationFn<TItem>
470 onUpdate?: UpdateMutationFn<TItem>
471 onDelete?: DeleteMutationFn<TItem>
472}
473
474export function myCollectionOptions<TItem extends object>(
475 config: MyCollectionConfig<TItem>
476) {
477 return {
478 // ... other options
479 sync: {
480 sync: syncFn,
481 rowUpdateMode: config.rowUpdateMode ?? 'partial'
482 },
483
484 // Pass through user-provided handlers
485 // Users handle sync coordination in their own handlers
486 onInsert: config.onInsert,
487 onUpdate: config.onUpdate,
488 onDelete: config.onDelete
489 }
490}
491```
492
493
494#### Pattern B: Built-in Handlers (Trailbase, WebSocket, Firebase)
495
496Your collection creator implements the handlers directly using the sync engine's APIs:
497
498```typescript
499interface MyCollectionConfig<TItem extends object>
500 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete'> {
501 // ... sync engine specific config
502 // Note: onInsert/onUpdate/onDelete are NOT in the config
503}
504
505export function myCollectionOptions<TItem extends object>(
506 config: MyCollectionConfig<TItem>
507) {
508 return {
509 // ... other options
510 sync: {
511 sync: syncFn,
512 rowUpdateMode: config.rowUpdateMode ?? 'partial'
513 },
514
515 // Implement handlers using sync engine APIs
516 onInsert: async ({ transaction }) => {
517 // Handle provider-specific batch limits (e.g., Firestore's 500 limit)
518 const chunks = chunkArray(transaction.mutations, PROVIDER_BATCH_LIMIT)
519
520 for (const chunk of chunks) {
521 const ids = await config.recordApi.createBulk(
522 chunk.map(m => serialize(m.modified))
523 )
524 // Wait for these IDs to sync back before completing
525 await awaitIds(ids)
526 }
527 // Handler completes after sync coordination
528 },
529
530 onUpdate: async ({ transaction }) => {
531 const chunks = chunkArray(transaction.mutations, PROVIDER_BATCH_LIMIT)
532
533 for (const chunk of chunks) {
534 await Promise.all(
535 chunk.map(m =>
536 config.recordApi.update(m.key, serialize(m.changes))
537 )
538 )
539 }
540
541 // Wait for mutations to sync back
542 await awaitIds(transaction.mutations.map(m => String(m.key)))
543 }
544 }
545}
546```
547
548Many providers have batch size limits (Firestore: 500, DynamoDB: 25, etc.) so chunk large transactions accordingly.
549
550**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.
551
552Choose Pattern A when users need to provide their own APIs, and Pattern B when your sync engine handles writes directly.
553
554## Row Update Modes
555
556Collections support two update modes:
557
558- **`partial`** (default) - Updates are merged with existing data
559- **`full`** - Updates replace the entire row
560
561Configure this in your sync config:
562
563```typescript
564sync: {
565 sync: syncFn,
566 rowUpdateMode: 'full' // or 'partial'
567}
568```
569
570## Production Examples
571
572For complete, production-ready examples, see the collection packages in the TanStack DB repository:
573
574- **[@tanstack/query-db-collection](https://github.com/TanStack/db/tree/main/packages/query-db-collection)** - Pattern A: User-provided handlers with full refetch strategy
575- **[@tanstack/trailbase-db-collection](https://github.com/TanStack/db/tree/main/packages/trailbase-db-collection)** - Pattern B: Built-in handlers with ID-based tracking
576- **[@tanstack/electric-db-collection](https://github.com/TanStack/db/tree/main/packages/electric-db-collection)** - Pattern A: Transaction ID tracking with complex sync protocols
577- **[@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
578
579### Key Lessons from Production Collections
580
581**From Query Collection:**
582- Simplest approach: Full refetch after mutations
583- Best for: APIs without real-time sync
584- Pattern: User provides `onInsert/onUpdate/onDelete` handlers
585
586**From Trailbase Collection:**
587- Shows ID-based optimistic state management
588- Handles provider batch limits (chunking large operations)
589- Pattern: Collection provides mutation handlers using record API
590
591**From Electric Collection:**
592- Complex transaction ID tracking for distributed sync
593- Demonstrates advanced deduplication techniques
594- Shows how to wrap user handlers with sync coordination
595
596**From RxDB Collection:**
597- Uses RxDB's built-in queries and change streams
598- Uses `RxCollection.$` to subscribe to inserts/updates/deletes and forward them to TanStack DB with begin-write-commit
599- Implements built-in mutation handlers (onInsert, onUpdate, onDelete) that call RxDB APIs (bulkUpsert, incrementalPatch, bulkRemove)
600
601## Complete Example: WebSocket Collection
602
603Here's a complete example of a WebSocket-based collection options creator that demonstrates the full round-trip flow:
604
6051. Client sends transaction with all mutations batched together
6062. Server processes the transaction and may modify the data (validation, timestamps, etc.)
6073. Server sends back acknowledgment and the actual processed data
6084. Client waits for this round-trip before dropping optimistic state
609
610```typescript
611import type {
612 CollectionConfig,
613 SyncConfig,
614 InsertMutationFnParams,
615 UpdateMutationFnParams,
616 DeleteMutationFnParams,
617 UtilsRecord
618} from '@tanstack/db'
619
620interface WebSocketMessage<T> {
621 type: 'insert' | 'update' | 'delete' | 'sync' | 'transaction' | 'ack'
622 data?: T | T[]
623 mutations?: Array<{
624 type: 'insert' | 'update' | 'delete'
625 data: T
626 id?: string
627 }>
628 transactionId?: string
629 id?: string
630}
631
632interface WebSocketCollectionConfig<TItem extends object>
633 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete' | 'sync'> {
634 url: string
635 reconnectInterval?: number
637 // Note: onInsert/onUpdate/onDelete are handled by the WebSocket connection
638 // Users don't provide these handlers
639}
640
641interface WebSocketUtils extends UtilsRecord {
642 reconnect: () => void
643 getConnectionState: () => 'connected' | 'disconnected' | 'connecting'
644}
645
646export function webSocketCollectionOptions<TItem extends object>(
647 config: WebSocketCollectionConfig<TItem>
648): CollectionConfig<TItem> & { utils: WebSocketUtils } {
649 let ws: WebSocket | null = null
650 let reconnectTimer: NodeJS.Timeout | null = null
651 let connectionState: 'connected' | 'disconnected' | 'connecting' = 'disconnected'
653 // Track pending transactions awaiting acknowledgment
654 const pendingTransactions = new Map<string, {
655 resolve: () => void
656 reject: (error: Error) => void
657 timeout: NodeJS.Timeout
658 }>()
660 const sync: SyncConfig<TItem>['sync'] = (params) => {
661 const { begin, write, commit, markReady } = params
663 function connect() {
664 connectionState = 'connecting'
665 ws = new WebSocket(config.url)
667 ws.onopen = () => {
668 connectionState = 'connected'
669 // Request initial sync
670 ws.send(JSON.stringify({ type: 'sync' }))
671 }
673 ws.onmessage = (event) => {
674 const message: WebSocketMessage<TItem> = JSON.parse(event.data)
676 switch (message.type) {
677 case 'sync':
678 // Initial sync with array of items
679 begin()
680 if (Array.isArray(message.data)) {
681 for (const item of message.data) {
682 write({ type: 'insert', value: item })
683 }
684 }
685 commit()
686 markReady()
687 break
689 case 'insert':
690 case 'update':
691 case 'delete':
692 // Real-time updates from other clients
693 begin()
694 write({
695 type: message.type,
696 value: message.data as TItem
697 })
698 commit()
699 break
701 case 'ack':
702 // Server acknowledged our transaction
703 if (message.transactionId) {
704 const pending = pendingTransactions.get(message.transactionId)
705 if (pending) {
706 clearTimeout(pending.timeout)
707 pendingTransactions.delete(message.transactionId)
708 pending.resolve()
709 }
710 }
711 break
713 case 'transaction':
714 // Server sending back the actual data after processing our transaction
715 if (message.mutations) {
716 begin()
717 for (const mutation of message.mutations) {
718 write({
719 type: mutation.type,
720 value: mutation.data
721 })
722 }
723 commit()
724 }
725 break
726 }
727 }
729 ws.onerror = (error) => {
730 console.error('WebSocket error:', error)
731 connectionState = 'disconnected'
732 }
734 ws.onclose = () => {
735 connectionState = 'disconnected'
736 // Auto-reconnect
737 if (!reconnectTimer) {
738 reconnectTimer = setTimeout(() => {
739 reconnectTimer = null
740 connect()
741 }, config.reconnectInterval || 5000)
742 }
743 }
744 }
746 // Start connection
747 connect()
749 // Return cleanup function
750 return () => {
751 if (reconnectTimer) {
752 clearTimeout(reconnectTimer)
753 reconnectTimer = null
754 }
755 if (ws) {
756 ws.close()
757 ws = null
758 }
759 }
760 }
762 // Helper function to send transaction and wait for server acknowledgment
763 const sendTransaction = async (
764 params: InsertMutationFnParams<TItem> | UpdateMutationFnParams<TItem> | DeleteMutationFnParams<TItem>
765 ): Promise<void> => {
766 if (ws?.readyState !== WebSocket.OPEN) {
767 throw new Error('WebSocket not connected')
768 }
770 const transactionId = crypto.randomUUID()
772 // Convert all mutations in the transaction to the wire format
773 const mutations = params.transaction.mutations.map(mutation => ({
774 type: mutation.type,
775 id: mutation.key,
776 data: mutation.type === 'delete' ? undefined :
777 mutation.type === 'update' ? mutation.changes :
778 mutation.modified
779 }))
781 // Send the entire transaction at once
782 ws.send(JSON.stringify({
783 type: 'transaction',
784 transactionId,
785 mutations
786 }))
788 // Wait for server acknowledgment
789 return new Promise<void>((resolve, reject) => {
790 const timeout = setTimeout(() => {
791 pendingTransactions.delete(transactionId)
792 reject(new Error(`Transaction ${transactionId} timed out`))
793 }, 10000) // 10 second timeout
795 pendingTransactions.set(transactionId, {
796 resolve,
797 reject,
798 timeout
799 })
800 })
801 }
803 // All mutation handlers use the same transaction sender
804 // Handlers wait for server acknowledgment before completing
805 const onInsert = async (params: InsertMutationFnParams<TItem>): Promise<void> => {
806 await sendTransaction(params)
807 // Handler completes after server confirms the transaction
808 }
809
810 const onUpdate = async (params: UpdateMutationFnParams<TItem>): Promise<void> => {
811 await sendTransaction(params)
812 }
813
814 const onDelete = async (params: DeleteMutationFnParams<TItem>): Promise<void> => {
815 await sendTransaction(params)
816 }
818 return {
819 id: config.id,
820 schema: config.schema,
821 getKey: config.getKey,
822 sync: { sync },
823 onInsert,
824 onUpdate,
825 onDelete,
826 utils: {
827 reconnect: () => {
828 if (ws) ws.close()
829 connect()
830 },
831 getConnectionState: () => connectionState
832 }
833 }
834}
835```
836
837## Usage Example
838
839```typescript
840import { DbClient, collectionOptions } from '@tanstack/react-db'
841import { webSocketCollectionOptions } from './websocket-collection'
842
843const db = new DbClient()
844
845const todosCollection = collectionOptions('todos', () =>
846 webSocketCollectionOptions({
847 id: 'todos',
848 url: 'ws://localhost:8080/todos',
849 getKey: (todo) => todo.id,
850 schema: todoSchema,
851 // Note: No onInsert/onUpdate/onDelete - handled by WebSocket automatically
852 })
853)
854
855const todos = db.collection(todosCollection)
856
857// Use the collection
858todos.insert({ id: '1', text: 'Buy milk', completed: false })
859
860// Access utilities
861todos.utils.getConnectionState() // 'connected'
862todos.utils.reconnect() // Force reconnect
863```
864
865## Advanced: Managing Optimistic State
866
867A critical challenge in sync-first apps is knowing when to drop optimistic state. When a user makes a change:
868
8691. The UI updates immediately (optimistic update)
8702. A mutation is sent to the backend
8713. The backend processes and persists the change
8724. The change syncs back to the client
8735. The optimistic state should be dropped in favor of the synced data
874
875The key question is: **How do you know when step 4 is complete?**
876
877### Strategy 1: Built-in Provider Methods (Recommended)
878
879Many providers offer built-in methods to wait for sync completion:
880
881```typescript
882// Firebase
883await waitForPendingWrites(firestore)
884
885// Custom WebSocket
886await websocket.waitForAck(transactionId)
887```
888
889### Strategy 2: Transaction ID Tracking (ElectricSQL)
890
891ElectricSQL returns transaction IDs that you can track:
892
893```typescript
894// Track seen transaction IDs
895const seenTxids = new Store<Set<number>>(new Set())
896
897// In sync, track txids from incoming messages
898if (message.headers.txids) {
899 message.headers.txids.forEach(txid => {
900 seenTxids.setState(prev => new Set([...prev, txid]))
901 })
902}
903
904// Electric-specific: expose awaitTxId through collection.utils so handlers
905// can coordinate txid-based sync before they complete
906const wrappedOnInsert = async (params) => {
907 // The user handler persists the mutation, then calls
908 // await params.collection.utils.awaitTxId(txid) internally.
909 await config.onInsert!(params)
910}
911
912// Utility function to wait for a txid
913const awaitTxId = (txId: number): Promise<boolean> => {
914 if (seenTxids.state.has(txId)) return Promise.resolve(true)
916 return new Promise((resolve) => {
917 const unsubscribe = seenTxids.subscribe(() => {
918 if (seenTxids.state.has(txId)) {
919 unsubscribe()
920 resolve(true)
921 }
922 })
923 })
924}
925```
926
927### Strategy 3: ID-Based Tracking (Trailbase)
928
929Trailbase tracks when specific record IDs have been synced:
930
931```typescript
932// Track synced IDs with timestamps
933const seenIds = new Store(new Map<string, number>())
934
935// In sync, mark IDs as seen
936write({ type: 'insert', value: item })
937seenIds.setState(prev => new Map(prev).set(item.id, Date.now()))
938
939// Wait for specific IDs after mutations
940const wrappedOnInsert = async (params) => {
941 const ids = await config.recordApi.createBulk(items)
942
943 // Wait for all IDs to be synced back before handler completes
944 await awaitIds(ids)
945}
946
947const awaitIds = (ids: string[]): Promise<void> => {
948 const allSynced = ids.every(id => seenIds.state.has(id))
949 if (allSynced) return Promise.resolve()
951 return new Promise((resolve) => {
952 const unsubscribe = seenIds.subscribe((state) => {
953 if (ids.every(id => state.has(id))) {
954 unsubscribe()
955 resolve()
956 }
957 })
958 })
959}
960```
961
962### Strategy 4: Version/Timestamp Tracking
963
964Track version numbers or timestamps to detect when data is fresh:
965
966```typescript
967// Track latest sync timestamp
968let lastSyncTime = 0
969
970// In mutations, record when the operation was sent
971const wrappedOnUpdate = async (params) => {
972 const mutationTime = Date.now()
973 await config.onUpdate(params)
974
975 // Wait for sync to catch up before handler completes
976 await waitForSync(mutationTime)
977}
978
979const waitForSync = (afterTime: number): Promise<void> => {
980 if (lastSyncTime > afterTime) return Promise.resolve()
982 return new Promise((resolve) => {
983 const check = setInterval(() => {
984 if (lastSyncTime > afterTime) {
985 clearInterval(check)
986 resolve()
987 }
988 }, 100)
989 })
990}
991```
992
993### Strategy 5: Refetch (Query Collection)
994
995The query collection pattern has users refetch after mutations:
996
997```typescript nocheck
998// Pattern A: User provides handlers and manages refetch
999export function queryCollectionOptions<TItem>(config) {
1000 return {
1001 // ... other options
1002
1003 // User provides handlers and they handle refetch themselves
1004 onInsert: config.onInsert, // User calls collection.utils.refetch() in their handler
1005 onUpdate: config.onUpdate,
1006 onDelete: config.onDelete,
1007
1008 utils: {
1009 refetch: () => {
1010 // Refetch implementation that syncs fresh data
1011 // automatically dropping optimistic state
1012 }
1013 }
1014 }
1015}
1016
1017// Usage: User refetches in their handler
1018const collection = createCollection(
1019 queryCollectionOptions({
1020 onInsert: async ({ transaction, collection }) => {
1021 await api.createTodos(transaction.mutations.map(m => m.modified))
1022 // User explicitly triggers refetch
1023 await collection.utils.refetch()
1024 }
1025 })
1026)
1027```
1028
1029### Choosing a Strategy
1030
1031- **Built-in Methods**: Best when your provider offers sync completion APIs
1032- **Transaction IDs**: Best when your backend provides reliable transaction tracking
1033- **ID-Based**: Good for systems where each mutation returns the affected IDs
1034- **Full Refetch**: Simplest but least efficient; good for small datasets
1035- **Version/Timestamp**: Works when your sync includes reliable ordering information
1036
1037### Implementation Tips
1038
10391. **Always wait for sync** in your mutation handlers to ensure optimistic state is properly managed
10402. **Handle timeouts** - Don't wait forever for sync confirmation
10413. **Clean up tracking data** - Remove old txids/IDs to prevent memory leaks
10424. **Provide utilities** - Export functions like `awaitTxId` or `awaitSync` for advanced use cases
1043
1044## Best Practices
1045
10461. **Report initial sync status** - Call `markReady()` after a usable snapshot, or `fail(error)` when you give up on the initial sync
10472. **Report health after readiness** - Use `reportError()` and `reportHealthy()` once the Collection is ready; recovery from an initial error is a restart, not a later `markReady()`
10483. **Clean up resources** - Return a cleanup function from sync to prevent memory leaks
10494. **Batch operations** - Use begin/commit to batch multiple changes for better performance
10505. **Race Conditions** - Start listeners before initial fetch and buffer events
10516. **Type safety** - Use TypeScript generics to maintain type safety throughout
10527. **Provide utilities** - Export sync-engine-specific utilities for advanced use cases
10538. **Coordinate sync in handlers** - Mutation handlers should await sync internally. For Electric collections, use `await collection.utils.awaitTxId(txid)`.
1054
1055## Testing Your Collection
1056
1057Test your collection options creator with:
1058
10591. **Unit tests** - Test sync logic, data transformations
10602. **Integration tests** - Test with real sync engine
10613. **Error scenarios** - Connection failures, invalid data
10624. **Performance** - Large datasets, frequent updates
1063
1064## Conclusion
1065
1066Creating 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.