Open History to see the last commit
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 })
33)
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 })
101)
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 })
135)
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 })
160)
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)
181}
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 })
229}
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
339)
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
358Persisted resumes wait for the cached row baseline to finish hydrating. If the
359persistence wrapper cannot verify hydration completion, Electric starts a fresh
360snapshot instead of using the saved offset and handle. It warns once per options
361descriptor; update the persistence adapter alongside Electric to enable safe resume.
362Fresh eager snapshots wait for hydration, then replace the cached rows at the
363snapshot's commit boundary. Rows omitted from that snapshot do not survive in
364the collection or its persisted cache, even when the fresh snapshot is empty.
365
366Tag membership is kept in memory, not restored from cached row headers. A cold
367restart cannot use a saved cursor that needs tags or comes from an older version
368that did not record whether tags were used. A changed shape, malformed saved
369state, or incomplete key-set evidence also invalidates the saved cursor.
370Untagged shapes with complete resume evidence can still resume from their saved
371offset.
372
373Eager and progressive recovery fetch a full snapshot. Cached rows remain visible
374until that replacement completes; a partial batch or subset completion cannot
375publish it early. An on-demand collection with the current SQLite persistence
376wrapper instead retires the persisted cache generation and clears the source
377Collection's uncertified rows. A run with a valid claim can continue using the
378retired generation; new runs claim an empty generation. That local clear does
379not mark the Collection ready. Electric source evidence supplies readiness. It
380starts a changes-only stream at the current position and
381requests snapshots for active subset demands. Each demand completes after its
382snapshot rows apply, including an empty snapshot. Later demands cannot rehydrate
383old cache rows without a fresh source snapshot. With no active demand, recovery
384does not read all cached rows or download the full shape. The durable reset marker
385remains until a complete baseline can justify a global resume cursor. A cache
386generation created after claim expiry can lack that marker; its incompatible
387key-set evidence also requires scoped recovery on the next cold start, even
388when the caller supplies an explicit Electric offset or handle. Those source
389cursor options do not certify cached rows. A wrapper
390without scoped recovery support continues to use full-shape recovery. An
391interrupted recovery keeps the reset marker for the next start.
392Until a complete baseline is certified, each later cold start repeats scoped
393recovery. Uncertified cached rows from earlier starts are not shown offline.
394Retired new-format storage is reclaimed by the next cache-claim collection
395operation after its claims release or expire; clock passage alone does not
396run SQLite work. A paused run whose claim expires must reload its demanded
397subsets from the source when it resumes. Pre-upgrade on-demand storage is
398isolated but needs a separate cross-version cleanup policy while older tabs
399may still use it. Scoped recovery
400does not certify the new generation for offline reuse.
401
402During scoped recovery, coordinator notifications about SQLite changes do not
403hydrate, truncate, or replace public source rows. The Electric change stream
404and demanded source snapshots own those rows until the sync run ends. A change
405made in another tab may therefore become public when Electric delivers it,
406rather than when its durable-cache notification arrives. Outside scoped
407recovery, coordinator invalidation retains its normal behavior.
408
409An eager or progressive resume cannot apply a partial update to an unknown row.
410The adapter rejects that batch, enters an error state, and records a reset so the
411next sync starts from a full snapshot. This does not silently retry the failed
412stream. Complete updates from an explicit `replica: 'full'` stream remain valid.
413On-demand streams can observe updates outside their loaded subsets; unknown
414partial rows are ignored, while transaction acknowledgement evidence is retained.
415Outside scoped recovery, complete rows published by persistence reloads or
416another tab are valid baselines for subsequent partial updates. Uncertified
417cached rows in scoped recovery are not. Pending deletions and resets still take
418precedence over an older row that remains publicly visible.
419
420Reusing Electric collection options, including a spread of those options, does
421not share transaction waiters or tag visibility between collections. Tag state
422survives a compatible resume of the same collection and clears on a fresh
423snapshot or `must-refetch`.
424
425### Helper Functions
426
427The package exports helper functions for use in custom match functions:
428
429- `isChangeMessage(message)`: Check if a message is a data change (insert/update/delete)
430- `isControlMessage(message)`: Check if a message is a control message (up-to-date, must-refetch)
431
432```typescript
433import { isChangeMessage, isControlMessage } from '@tanstack/electric-db-collection'
434
435// Use in custom match functions
436const matchFn = (message) => {
437 if (isChangeMessage(message)) {
438 return message.headers.operation === 'insert'
439 }
440 return false
441}
442```
443
444## Debugging
445
446### Common Issue: awaitTxId Stalls or Times Out
447
448A 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.
449
450**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.
451
452### Enable Debug Logging
453
454To diagnose txid issues, enable debug logging in your browser console:
455
456```javascript
457localStorage.debug = 'ts/db:electric'
458```
459
460This will show you when mutations start waiting for txids and when txids arrive from Electric's sync stream.
461
462This is powered by the [debug](https://www.npmjs.com/package/debug) package.
463
464**When txids DON'T match (common bug):**
465```
466ts/db:electric awaitTxId called with txid 124
467ts/db:electric new txids synced from pg [123]
468// Stalls forever - 124 never arrives!
469```
470
471In 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.
472
473**When txids DO match (correct):**
474```
475ts/db:electric awaitTxId called with txid 123
476ts/db:electric new txids synced from pg [123]
477ts/db:electric awaitTxId found match for txid 123
478// Resolves immediately!
479```
480
481### The Solution: Query txid Inside the Transaction
482
483You **must** call `pg_current_xact_id()` inside the same transaction as your mutation:
484
485**❌ Wrong - txid queried outside transaction:**
486```typescript
487// DON'T DO THIS
488async function createTodo(data) {
489 const txid = await generateTxId(sql) // Wrong: separate transaction
490
491 await sql.begin(async (tx) => {
492 await tx`INSERT INTO todos ${tx(data)}`
493 })
494
495 return { txid } // This txid won't match!
496}
497```
498
499**✅ Correct - txid queried inside transaction:**
500```typescript
501// DO THIS
502async function createTodo(data) {
503 let txid!: Txid
504
505 const result = await sql.begin(async (tx) => {
506 // Call generateTxId INSIDE the transaction
507 txid = await generateTxId(tx)
508
509 const [todo] = await tx`
510 INSERT INTO todos ${tx(data)}
511 RETURNING *
512 `
513 return todo
514 })
515
516 return { todo: result, txid } // txid matches the mutation
517}
518
519async function generateTxId(tx: any): Promise<Txid> {
520 const result = await tx`SELECT pg_current_xact_id()::xid::text as txid`
521 const txid = result[0]?.txid
522
523 if (txid === undefined) {
524 throw new Error(`Failed to get transaction ID`)
525 }
526
527 return parseInt(txid, 10)
528}
529```
530
531See working examples in:
532- `examples/react/todo/src/routes/api/todos.ts`
533- `examples/react/todo/src/api/server.ts`