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

electric-collection.md

556 lines20.0 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: { id: string }) => 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: { id: string }) => 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​
319For a collection wrapped with SQLite persistence, `awaitTxId` observes the
320transaction in the Electric stream. It can resolve before the local SQLite
321write completes. Do not use it as a local durability acknowledgment: if the
322page closes in that gap, reopening may need Electric to recover the row.
323​
324### `awaitMatch(matchFn, timeout?)`
325​
326Wait for a custom match function to find a matching message:
327​
328```typescript
329import { isChangeMessage } from '@tanstack/electric-db-collection'
330​
331// Wait for a specific message pattern
332await todosCollection.utils.awaitMatch(
333 (message) => {
334 return isChangeMessage(message) &&
335 message.headers.operation === 'insert' &&
336 message.value.text === 'New Todo'
337 },
338 5000 // timeout in ms
340```
341​
342### Cleanup and resume safety
343​
344Transaction evidence and pending `awaitTxId`/`awaitMatch` calls belong to one
345collection lifecycle. Explicit cleanup and automatic garbage collection reject
346pending waits with `StreamAbortedError`; callbacks from the retired stream cannot
347settle waits in a restarted collection. Observe these promises even when the
348component or collection may be disposed before they settle.
349​
350An on-demand Collection with managed SQLite persistence can also replace its
351Electric provider session within the same Collection sync run when its cached
352resume evidence becomes invalid or its cache claim expires. This replacement
353rejects pending `awaitTxId` and `awaitMatch` waits with `StreamAbortedError`.
354A mutation handler waiting on one of them rejects; a later handler can wait for
355evidence from the replacement session. The replacement reloads demanded
356subsets and does not treat acknowledgements from the retired session as current.
357​
358Before constructing a replacement `ShapeStream`, Electric releases the
359adapter-owned resources of the retired provider session, including its
360subscriptions and host lifecycle listeners. The replacement starts after cache
361rotation completes. An HTTP request that ignores cancellation may still finish
362later; its response cannot publish rows or settle waits for the replacement
363session.
364​
365Persisted resumes wait for the cached row baseline to finish hydrating. If the
366persistence wrapper cannot verify hydration completion, Electric starts a fresh
367snapshot instead of using the saved offset and handle. It warns once per options
368descriptor; update the persistence adapter alongside Electric to enable safe resume.
369Fresh eager snapshots wait for hydration, then replace the cached rows at the
370snapshot's commit boundary. Rows omitted from that snapshot do not survive in
371the collection or its persisted cache, even when the fresh snapshot is empty.
372​
373Tag membership is kept in memory, not restored from cached row headers. A cold
374restart cannot use a saved cursor that needs tags or comes from an older version
375that did not record whether tags were used. A changed shape, malformed saved
376state, or incomplete key-set evidence also invalidates the saved cursor.
377Untagged shapes with complete resume evidence can still resume from their saved
378offset.
379​
380Eager and progressive recovery fetch a full snapshot. Cached rows remain visible
381until that replacement completes; a partial batch or subset completion cannot
382publish it early. An on-demand collection with the current SQLite persistence
383wrapper instead retires the persisted cache generation and clears the source
384Collection's uncertified rows. A run with a valid claim can continue using the
385retired generation; new runs claim an empty generation. That local clear does
386not mark the Collection ready. Electric source evidence supplies readiness. It
387starts a changes-only stream at the current position and
388requests snapshots for active subset demands. Each demand completes after its
389snapshot rows apply, including an empty snapshot. Later demands cannot rehydrate
390old cache rows without a fresh source snapshot. With no active demand, recovery
391does not read all cached rows or download the full shape. The durable reset marker
392remains until a complete baseline can justify a global resume cursor. A cache
393generation created after claim expiry can lack that marker; its incompatible
394key-set evidence also requires scoped recovery on the next cold start, even
395when the caller supplies an explicit Electric offset or handle. Those source
396cursor options do not certify cached rows. A wrapper
397without scoped recovery support continues to use full-shape recovery. An
398interrupted recovery keeps the reset marker for the next start.
399Until a complete baseline is certified, each later cold start repeats scoped
400recovery. Uncertified cached rows from earlier starts are not shown offline.
401Retired new-format storage is reclaimed by the next cache-claim collection
402operation after its claims release or expire; clock passage alone does not
403run SQLite work. A paused run whose claim expires must reload its demanded
404subsets from the source when it resumes. Pre-upgrade on-demand storage is
405isolated but needs a separate cross-version cleanup policy while older tabs
406may still use it. Scoped recovery
407does not certify the new generation for offline reuse.
408​
409With `initialRender: { strategy: 'network-first' }`, an on-demand or
410progressive Collection can render a demand offline from SQLite after that exact
411demand settled online in an earlier session. Each demand keeps its own
412coverage in the current persisted cache generation. Scoped recovery, cache-claim
413expiry, and a must-refetch end it, so after any of them a demand waits for the
414network again. A demand that loads during the rest of a scoped-recovery sync
415run records no coverage. See [On-demand Collections offline](../guides/sqlite-persistence.md#on-demand-collections-offline).
416​
417During scoped recovery, coordinator notifications about SQLite changes do not
418hydrate, truncate, or replace public source rows. The Electric change stream
419and demanded source snapshots own those rows until the sync run ends. A change
420made in another tab may therefore become public when Electric delivers it,
421rather than when its durable-cache notification arrives. Outside scoped
422recovery, coordinator invalidation retains its normal behavior.
423​
424An eager or progressive resume cannot apply a partial update to an unknown row.
425The adapter rejects that batch, stops the stream, and records a reset so the
426next sync starts from a full snapshot. Before the Collection is ready, this
427fails the first load (`status: 'error'`); after it, the rows stay and the
428source node shows an `error` in `collection.health` and in each live query's
429`health` tree. This does not silently retry the failed stream;
430`collection.reload()` refetches.
431​
432While the Electric stream retries a failed request, the Collection reports
433nothing: it stays `loading` before its first up-to-date, and keeps its health tree
434unchanged afterward. When the stream gives up, it calls `fail()`: a failed first load
435before readiness, or the source node's `error` after it. Complete updates from an explicit `replica: 'full'` stream remain valid.
436On-demand streams can observe updates outside their loaded subsets; unknown
437partial rows are ignored, while transaction acknowledgement evidence is retained.
438Outside scoped recovery, complete rows published by persistence reloads or
439another tab are valid baselines for subsequent partial updates. Uncertified
440cached rows in scoped recovery are not. Pending deletions and resets still take
441precedence over an older row that remains publicly visible.
442​
443Reusing Electric collection options, including a spread of those options, does
444not share transaction waiters or tag visibility between collections. Tag state
445survives a compatible resume of the same collection and clears on a fresh
446snapshot or `must-refetch`.
447​
448### Helper Functions
449​
450The package exports helper functions for use in custom match functions:
451​
452- `isChangeMessage(message)`: Check if a message is a data change (insert/update/delete)
453- `isControlMessage(message)`: Check if a message is a control message (up-to-date, must-refetch)
454​
455```typescript
456import { isChangeMessage, isControlMessage } from '@tanstack/electric-db-collection'
457​
458// Use in custom match functions
459const matchFn = (message) => {
460 if (isChangeMessage(message)) {
461 return message.headers.operation === 'insert'
462 }
463 return false
465```
466​
467## Debugging
468​
469### Common Issue: awaitTxId Stalls or Times Out
470​
471A frequent issue developers encounter is that `awaitTxId` (or the transaction's `when('settled')`) stalls indefinitely, eventually timing out with no error messages. The data persists correctly to the database, but the optimistic mutation never resolves.
472​
473**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.
474​
475### Enable Debug Logging
476​
477To diagnose txid issues, enable debug logging in your browser console:
478​
479```javascript
480localStorage.debug = 'ts/db:electric'
481```
482​
483This will show you when mutations start waiting for txids and when txids arrive from Electric's sync stream.
484​
485This is powered by the [debug](https://www.npmjs.com/package/debug) package.
486​
487**When txids DON'T match (common bug):**
488```
489ts/db:electric awaitTxId called with txid 124
490ts/db:electric new txids synced from pg [123]
491// Stalls forever - 124 never arrives!
492```
493​
494In 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.
495​
496**When txids DO match (correct):**
497```
498ts/db:electric awaitTxId called with txid 123
499ts/db:electric new txids synced from pg [123]
500ts/db:electric awaitTxId found match for txid 123
501// Resolves immediately!
502```
503​
504### The Solution: Query txid Inside the Transaction
505​
506You **must** call `pg_current_xact_id()` inside the same transaction as your mutation:
507​
508**❌ Wrong - txid queried outside transaction:**
509```typescript
510// DON'T DO THIS
511async function createTodo(data) {
512 const txid = await generateTxId(sql) // Wrong: separate transaction
513​
514 await sql.begin(async (tx) => {
515 await tx`INSERT INTO todos ${tx(data)}`
516 })
517​
518 return { txid } // This txid won't match!
520```
521​
522**✅ Correct - txid queried inside transaction:**
523```typescript
524// DO THIS
525async function createTodo(data) {
526 let txid!: Txid
527​
528 const result = await sql.begin(async (tx) => {
529 // Call generateTxId INSIDE the transaction
530 txid = await generateTxId(tx)
531​
532 const [todo] = await tx`
533 INSERT INTO todos ${tx(data)}
534 RETURNING *
535 `
536 return todo
537 })
538​
539 return { todo: result, txid } // txid matches the mutation
541​
542async function generateTxId(tx: any): Promise<Txid> {
543 const result = await tx`SELECT pg_current_xact_id()::xid::text as txid`
544 const txid = result[0]?.txid
545​
546 if (txid === undefined) {
547 throw new Error(`Failed to get transaction ID`)
548 }
549​
550 return parseInt(txid, 10)
552```
553​
554See working examples in:
555- `examples/react/todo/src/routes/api/todos.ts`
556- `examples/react/todo/src/api/server.ts`