Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

electric-collection.md

485 lines15.4 KB

1---
2title: Electric Collection
3---
4​
5Electric collections provide seamless integration between TanStack DB and ElectricSQL, enabling real-time data synchronization with your Postgres database through Electric's sync engine.
6​
7## Overview
8​
9The `@tanstack/electric-db-collection` package allows you to create collections that:
10- Automatically sync data from Postgres via Electric shapes
11- Support optimistic updates with transaction matching and automatic rollback on errors
12- Handle persistence through customizable mutation handlers
13​
14## Installation
15​
16```bash
17npm install @tanstack/electric-db-collection @tanstack/react-db
18```
19​
20## Basic Usage
21​
22```typescript
23import { createCollection } from '@tanstack/react-db'
24import { electricCollectionOptions } from '@tanstack/electric-db-collection'
25​
26const todosCollection = createCollection(
27 electricCollectionOptions({
28 shapeOptions: {
29 url: '/api/todos',
30 },
31 getKey: (item) => item.id,
32 })
34```
35​
36## Configuration Options
37​
38The `electricCollectionOptions` function accepts the following options:
39​
40### Required Options
41​
42- `shapeOptions`: Configuration for the ElectricSQL ShapeStream
43 - `url`: The URL of your proxy to Electric
44​
45- `getKey`: Function to extract the unique key from an item
46​
47### Optional
48​
49- `id`: Unique identifier for the collection
50- `schema`: Schema for validating items. Any Standard Schema compatible schema
51- `sync`: Custom sync configuration
52​
53### Persistence Handlers
54​
55Handlers are called before mutations to persist changes to your backend:
56​
57- `onInsert`: Handler called before insert operations
58- `onUpdate`: Handler called before update operations
59- `onDelete`: Handler called before delete operations
60​
61Each handler should call `await collection.utils.awaitTxId(txid)` to wait for synchronization. For cases where your API cannot return txids, use the `awaitMatch` utility function.
62​
63## Persistence Handlers & Synchronization
64​
65Handlers persist mutations to the backend and wait for Electric to sync the changes back. This prevents UI glitches where optimistic updates would be removed and then re-added. TanStack DB blocks sync data until the mutation is confirmed, ensuring smooth user experience.
66​
67### 1. Using Txid (Recommended)
68​
69The recommended approach uses PostgreSQL transaction IDs (txids) for precise matching. The backend returns a txid, and the client waits for that specific txid to appear in the Electric stream.
70​
71```typescript
72const todosCollection = createCollection(
73 electricCollectionOptions({
74 id: 'todos',
75 schema: todoSchema,
76 getKey: (item) => item.id,
77 shapeOptions: {
78 url: '/api/todos',
79 params: { table: 'todos' },
80 },
81​
82 onInsert: async ({ transaction, collection }) => {
83 const newItem = transaction.mutations[0].modified
84 const response = await api.todos.create(newItem)
85​
86 // Wait for txid to sync
87 await collection.utils.awaitTxId(response.txid)
88 },
89​
90 onUpdate: async ({ transaction, collection }) => {
91 const { original, changes } = transaction.mutations[0]
92 const response = await api.todos.update({
93 where: { id: original.id },
94 data: changes
95 })
96​
97 // Wait for txid to sync
98 await collection.utils.awaitTxId(response.txid)
99 }
100 })
102```
103​
104### 2. Using Custom Match Functions
105​
106For cases where txids aren't available, use the `awaitMatch` utility function to wait for synchronization with custom matching logic:
107​
108```typescript
109import { isChangeMessage } from '@tanstack/electric-db-collection'
110​
111const todosCollection = createCollection(
112 electricCollectionOptions({
113 id: 'todos',
114 getKey: (item) => item.id,
115 shapeOptions: {
116 url: '/api/todos',
117 params: { table: 'todos' },
118 },
119​
120 onInsert: async ({ transaction, collection }) => {
121 const newItem = transaction.mutations[0].modified
122 await api.todos.create(newItem)
123​
124 // Use awaitMatch utility for custom matching
125 await collection.utils.awaitMatch(
126 (message) => {
127 return isChangeMessage(message) &&
128 message.headers.operation === 'insert' &&
129 message.value.text === newItem.text
130 },
131 5000 // timeout in ms (optional, defaults to 15000)
132 )
133 }
134 })
136```
137​
138### 3. Using Simple Timeout
139​
140For quick prototyping or when you're confident about timing, you can use a simple timeout. This is crude but works as almost always the data will be synced back in under 2 seconds:
141​
142```typescript
143const todosCollection = createCollection(
144 electricCollectionOptions({
145 id: 'todos',
146 getKey: (item) => item.id,
147 shapeOptions: {
148 url: '/api/todos',
149 params: { table: 'todos' },
150 },
151​
152 onInsert: async ({ transaction }) => {
153 const newItem = transaction.mutations[0].modified
154 await api.todos.create(newItem)
155​
156 // Simple timeout approach
157 await new Promise(resolve => setTimeout(resolve, 2000))
158 }
159 })
161```
162​
163On the backend, you can extract the `txid` for a transaction by querying Postgres directly.
164​
165```ts
166async function generateTxId(tx) {
167 // The ::xid cast strips off the epoch, giving you the raw 32-bit value
168 // that matches what PostgreSQL sends in logical replication streams
169 // (and then exposed through Electric which we'll match against
170 // in the client).
171 const result = await tx.execute(
172 sql`SELECT pg_current_xact_id()::xid::text as txid`
173 )
174 const txid = result.rows[0]?.txid
175​
176 if (txid === undefined) {
177 throw new Error(`Failed to get transaction ID`)
178 }
179​
180 return parseInt(txid as string, 10)
182```
183​
184### Electric Proxy Example
185​
186Electric is typically deployed behind a proxy server that handles shape configuration, authentication and authorization. This provides better security and allows you to control what data users can access without exposing Electric to the client.
187​
188​
189Here is an example proxy implementation using TanStack Start:
190​
191```typescript
192import { createServerFileRoute } from "@tanstack/react-start/server"
193import { ELECTRIC_PROTOCOL_QUERY_PARAMS } from "@electric-sql/client"
194​
195// Electric URL
196const baseUrl = 'http://.../v1/shape'
197​
198const serve = async ({ request }: { request: Request }) => {
199 // ...check user authorization
200 const url = new URL(request.url)
201 const originUrl = new URL(baseUrl)
202​
203 // passthrough parameters from electric client
204 url.searchParams.forEach((value, key) => {
205 if (ELECTRIC_PROTOCOL_QUERY_PARAMS.includes(key)) {
206 originUrl.searchParams.set(key, value)
207 }
208 })
209​
210 // set shape parameters
211 // full spec: https://github.com/electric-sql/electric/blob/main/website/electric-api.yaml
212 originUrl.searchParams.set("table", "todos")
213 // Where clause to filter rows in the table (optional).
214 // originUrl.searchParams.set("where", "completed = true")
216 // Select the columns to sync (optional)
217 // originUrl.searchParams.set("columns", "id,text,completed")
218​
219 const response = await fetch(originUrl)
220 const headers = new Headers(response.headers)
221 headers.delete("content-encoding")
222 headers.delete("content-length")
223​
224 return new Response(response.body, {
225 status: response.status,
226 statusText: response.statusText,
227 headers,
228 })
230​
231export const ServerRoute = createServerFileRoute("/api/todos").methods({
232 GET: serve,
233})
234```
235​
236## Optimistic Updates with Explicit Transactions
237​
238For more advanced use cases, you can create custom actions that can do multiple mutations across collections transactionally. You can use the utility methods to wait for synchronization with different strategies:
239​
240### Using Txid Strategy
241​
242```typescript
243const addTodoAction = createOptimisticAction({
244 onMutate: ({ text }) => {
245 // optimistically insert with a temporary ID
246 const tempId = crypto.randomUUID()
247 todosCollection.insert({
248 id: tempId,
249 text,
250 completed: false,
251 created_at: new Date(),
252 })
254 // ... mutate other collections
255 },
257 mutationFn: async ({ text }) => {
258 const response = await api.todos.create({
259 data: { text, completed: false }
260 })
262 // Wait for the specific txid
263 await todosCollection.utils.awaitTxId(response.txid)
264 }
265})
266```
267​
268### Using Custom Match Function
269​
270```typescript
271import { isChangeMessage } from '@tanstack/electric-db-collection'
272​
273const addTodoAction = createOptimisticAction({
274 onMutate: ({ text }) => {
275 const tempId = crypto.randomUUID()
276 todosCollection.insert({
277 id: tempId,
278 text,
279 completed: false,
280 created_at: new Date(),
281 })
282 },
284 mutationFn: async ({ text }) => {
285 await api.todos.create({
286 data: { text, completed: false }
287 })
289 // Wait for matching message
290 await todosCollection.utils.awaitMatch(
291 (message) => {
292 return isChangeMessage(message) &&
293 message.headers.operation === 'insert' &&
294 message.value.text === text
295 }
296 )
297 }
298})
299```
300​
301## Utility Methods
302​
303The collection provides these utility methods via `collection.utils`:
304​
305### `awaitTxId(txid, timeout?)`
306​
307Wait for a specific transaction ID to be synchronized:
308​
309```typescript
310// Wait for specific txid
311await todosCollection.utils.awaitTxId(12345)
312​
313// With custom timeout (default is 15 seconds)
314await todosCollection.utils.awaitTxId(12345, 10000)
315```
316​
317This is useful when you need to ensure a mutation has been synchronized before proceeding with other operations.
318​
319### `awaitMatch(matchFn, timeout?)`
320​
321Wait for a custom match function to find a matching message:
322​
323```typescript
324import { isChangeMessage } from '@tanstack/electric-db-collection'
325​
326// Wait for a specific message pattern
327await todosCollection.utils.awaitMatch(
328 (message) => {
329 return isChangeMessage(message) &&
330 message.headers.operation === 'insert' &&
331 message.value.text === 'New Todo'
332 },
333 5000 // timeout in ms
335```
336​
337### Cleanup and resume safety
338​
339Transaction evidence and pending `awaitTxId`/`awaitMatch` calls belong to one
340collection lifecycle. Explicit cleanup and automatic garbage collection reject
341pending waits with `StreamAbortedError`; callbacks from the retired stream cannot
342settle waits in a restarted collection. Observe these promises even when the
343component or collection may be disposed before they settle.
344​
345Persisted resumes wait for the cached row baseline to finish hydrating. If the
346persistence wrapper cannot verify hydration completion, Electric starts a fresh
347snapshot instead of using the saved offset and handle. It warns once per options
348descriptor; update the persistence adapter alongside Electric to enable safe resume.
349Fresh eager snapshots wait for hydration, then replace the cached rows at the
350snapshot's commit boundary. Rows omitted from that snapshot do not survive in
351the collection or its persisted cache, even when the fresh snapshot is empty.
352​
353Tag membership is kept in memory, not restored from cached row headers. A cold
354restart therefore fetches a full snapshot when the saved state needs tags, or
355comes from an older version that did not record whether tags were used. Untagged
356shapes can still resume from their saved offset. Cached rows remain visible until
357the replacement snapshot completes; a partial batch or subset completion cannot
358publish that replacement early. Interrupting recovery leaves a durable reset
359marker so the next start still refetches. This recovery also requests a full shape
360snapshot in on-demand mode, at the cost of fetching more than the active subsets.
361​
362An eager or progressive resume cannot apply a partial update to an unknown row.
363The adapter rejects that batch, enters an error state, and records a reset so the
364next sync starts from a full snapshot. This does not silently retry the failed
365stream. Complete updates from an explicit `replica: 'full'` stream remain valid.
366On-demand streams can observe updates outside their loaded subsets; unknown
367partial rows are ignored, while transaction acknowledgement evidence is retained.
368Complete rows published by persistence reloads or another tab are valid baselines
369for subsequent partial updates. Pending deletions and resets still take precedence
370over an older row that remains publicly visible.
371​
372Reusing Electric collection options, including a spread of those options, does
373not share transaction waiters or tag visibility between collections. Tag state
374survives a compatible resume of the same collection and clears on a fresh
375snapshot or `must-refetch`.
376​
377### Helper Functions
378​
379The package exports helper functions for use in custom match functions:
380​
381- `isChangeMessage(message)`: Check if a message is a data change (insert/update/delete)
382- `isControlMessage(message)`: Check if a message is a control message (up-to-date, must-refetch)
383​
384```typescript
385import { isChangeMessage, isControlMessage } from '@tanstack/electric-db-collection'
386​
387// Use in custom match functions
388const matchFn = (message) => {
389 if (isChangeMessage(message)) {
390 return message.headers.operation === 'insert'
391 }
392 return false
394```
395​
396## Debugging
397​
398### Common Issue: awaitTxId Stalls or Times Out
399​
400A frequent issue developers encounter is that `awaitTxId` (or the transaction's `isPersisted.promise`) stalls indefinitely, eventually timing out with no error messages. The data persists correctly to the database, but the optimistic mutation never resolves.
401​
402**Root Cause:** This happens when the transaction ID (txid) returned from your API doesn't match the actual transaction ID of the mutation in Postgres. This mismatch occurs when you query `pg_current_xact_id()` **outside** the same transaction that performs the mutation.
403​
404### Enable Debug Logging
405​
406To diagnose txid issues, enable debug logging in your browser console:
407​
408```javascript
409localStorage.debug = 'ts/db:electric'
410```
411​
412This will show you when mutations start waiting for txids and when txids arrive from Electric's sync stream.
413​
414This is powered by the [debug](https://www.npmjs.com/package/debug) package.
415​
416**When txids DON'T match (common bug):**
417```
418ts/db:electric awaitTxId called with txid 124
419ts/db:electric new txids synced from pg [123]
420// Stalls forever - 124 never arrives!
421```
422​
423In this example, the mutation happened in transaction 123, but you queried `pg_current_xact_id()` in a separate transaction (124) that ran after the mutation. The client waits for 124 which will never arrive.
424​
425**When txids DO match (correct):**
426```
427ts/db:electric awaitTxId called with txid 123
428ts/db:electric new txids synced from pg [123]
429ts/db:electric awaitTxId found match for txid 123
430// Resolves immediately!
431```
432​
433### The Solution: Query txid Inside the Transaction
434​
435You **must** call `pg_current_xact_id()` inside the same transaction as your mutation:
436​
437**❌ Wrong - txid queried outside transaction:**
438```typescript
439// DON'T DO THIS
440async function createTodo(data) {
441 const txid = await generateTxId(sql) // Wrong: separate transaction
442​
443 await sql.begin(async (tx) => {
444 await tx`INSERT INTO todos ${tx(data)}`
445 })
446​
447 return { txid } // This txid won't match!
449```
450​
451**✅ Correct - txid queried inside transaction:**
452```typescript
453// DO THIS
454async function createTodo(data) {
455 let txid!: Txid
456​
457 const result = await sql.begin(async (tx) => {
458 // Call generateTxId INSIDE the transaction
459 txid = await generateTxId(tx)
460​
461 const [todo] = await tx`
462 INSERT INTO todos ${tx(data)}
463 RETURNING *
464 `
465 return todo
466 })
467​
468 return { todo: result, txid } // txid matches the mutation
470​
471async function generateTxId(tx: any): Promise<Txid> {
472 const result = await tx`SELECT pg_current_xact_id()::xid::text as txid`
473 const txid = result[0]?.txid
474​
475 if (txid === undefined) {
476 throw new Error(`Failed to get transaction ID`)
477 }
478​
479 return parseInt(txid, 10)
481```
482​
483See working examples in:
484- `examples/react/todo/src/routes/api/todos.ts`
485- `examples/react/todo/src/api/server.ts`