Enterprise web and mobile application architecture in 2026 has moved decisively beyond stateless request-response REST and GraphQL polling loops toward local-first sync engines backed by PostgreSQL logical replication. Engineering teams evaluating ElectricSQL, Rocicorp Zero, and PowerSync are no longer comparing simple client-side caches; they are selecting among three fundamentally divergent replication topologies, write-path ownership models, and memory-scaling boundaries. Traditional browser and mobile applications routinely stall behind 150 to 400 millisecond network roundtrips, skeleton loaders, and brittle client cache invalidation graphs whenever network packets drop or concurrent users mutate shared relational state. By projecting filtered subsets of server-side PostgreSQL Write-Ahead Log (WAL) streams directly into embedded client runtimes such as SQLite, PGlite, or indexed reactive stores, modern sync engines collapse UI read latency into sub-2-millisecond local memory operations. For B2B SaaS platforms, multi-user collaborative workspaces, and offline-resilient mobile field applications built across the USA, Canada, Australia, Germany, and Japan, choosing the wrong sync engine introduces severe WAL slot bloat, stale permission boundaries, or unmaintainable client state drift.
Key Takeaways
- Three Divergent Write-Path Philosophies: ElectricSQL restricts its engine strictly to read-path HTTP Shape streaming while delegating mutations to your existing REST, tRPC, or Server Action APIs; PowerSync enforces full-duplex bidirectional SQLite synchronization with managed client upload queues; Rocicorp Zero delivers a server-authoritative ZQL reactive cache with integrated mutator pipelines.
- Sub-Millisecond Client Reactivity: According to Kanopy Labs production evaluations and TanStack DB differential dataflow (
@tanstack/db-ivm) benchmarks, embedded client queries execute in under 2 milliseconds, with incremental view updates across 100,000+ sorted rows completing in 0.7 to <1 millisecond. - PostgreSQL WAL Throughput Scaling: Rocicorp Zero v1.8 replication benchmarks demonstrate 1.8x faster incremental WAL streaming, ~30+ MiB/s bulk transaction throughput on 50,000-row changes, and sustainable write ceilings scaling from 750 to 2,500+ writes per second depending on schema complexity.
- CDN Edge Fan-Out vs. Stateful Sockets: ElectricSQL streams immutable Shape change-logs over standard HTTP chunked transfer encoding, enabling Cloudflare or Fastly CDNs to absorb massive concurrent read surges; PowerSync and Zero maintain stateful WebSocket sessions tracking per-client sync cursors.
- Mobile Offline Reliability Thresholds: ThriveIT field-operations telemetry shows managed local-first outbox architectures achieving a 97/100 field reliability score under simulated 15% 4G packet loss and intermittent offline blackouts, provided local SQLite datasets are scoped under 100,000 active rows per device.
- Postgres Replication Slot Governance: Every logical replication sync engine risks PostgreSQL disk exhaustion if an abandoned consumer holds an inactive replication slot; production topologies require strict
max_slot_wal_keep_sizebounds and automated heartbeat monitoring.
How Do ElectricSQL, Zero, and PowerSync Differ Architecturally?
ElectricSQL, Rocicorp Zero, and PowerSync share PostgreSQL logical replication as their upstream change source, yet they diverge sharply on write-path ownership, transport protocols, and client storage engines. ElectricSQL streams read-only HTTP Shapes, Zero maintains a stateful ZQL reactive cache, and PowerSync orchestrates bidirectional SQLite synchronization.
Understanding this architectural boundary prevents teams from forcing a read-path streamer into an offline mobile conflict-resolution role—or paying the operational cost of a stateful sync cluster when standard HTTP edge caching would suffice.
flowchart TB
PG["PostgreSQL Primary<br/>(WAL Logical Replication Slot)"]
subgraph Electric["ElectricSQL Topology (Read-Path HTTP)"]
EL_SVC["Electric Sync Service<br/>(Stateless Shape Log Producer)"]
CDN["Edge CDN Cache<br/>(HTTP Chunked / Long-Poll)"]
EL_CLI["Browser / TanStack DB / PGlite<br/>(+ Separate REST/tRPC Writes)"]
PG -->|pgoutput WAL| EL_SVC -->|HTTP Shapes| CDN -->|Fan-Out| EL_CLI
EL_CLI -.->|Standard API Mutations| PG
end
subgraph Zero["Rocicorp Zero Topology (Query-Driven Cache)"]
Z_CACHE["zero-cache Server<br/>(SQLite Replica + ZQL IVM)"]
Z_CLI["Client ZQL Store<br/>(Optimistic Mutators)"]
PG -->|WAL Stream| Z_CACHE <-->|Stateful WebSocket| Z_CLI
Z_CLI -.->|Custom Mutators| PG
end
subgraph PowerSync["PowerSync Topology (Full-Duplex Mobile)"]
PS_SVC["PowerSync Service<br/>(Bucket Compiler + Sync Rules)"]
PS_CLI["Embedded Client SQLite<br/>(WAL + Upload Outbox Queue)"]
PG -->|WAL Stream| PS_SVC <-->|WebSocket Buckets| PS_CLI
PS_CLI -.->|CRUD Upload API| PG
end
ElectricSQL: Unbundled Read-Path Shape Streaming
Following its structural redesign into electric-next, ElectricSQL deliberately eliminated multi-master CRDT write synchronization from its core engine. Instead, ElectricSQL operates strictly as a Postgres-to-HTTP data delivery pipe. Applications subscribe to Shapes—declarative subsets of a single PostgreSQL table defined by a table name and an optional WHERE clause filter. Because Shape logs are append-only HTTP streams keyed by offset and handle IDs, standard reverse proxies and global CDNs can cache identical Shape chunks across tens of thousands of concurrent browser clients.
To handle writes and optimistic UI updates, engineering teams pair ElectricSQL with their existing REST, GraphQL, or tRPC mutation endpoints alongside client-side state containers such as TanStack DB or PGlite (WebAssembly PostgreSQL). If your platform already enforces complex RBAC policies, payment webhooks, and validation middleware inside Node.js or Fastify APIs, ElectricSQL lets you add instant real-time UI reactivity without rewriting a single server-side write validator.
Rocicorp Zero: Server-Authoritative Query-Driven Sync
Built by Rocicorp as the successor to Replicache, Zero replaces explicit table subscriptions and bucket manifests with query-driven synchronization. Developers write relational queries on the client using ZQL (Zero Query Language), a TypeScript query builder supporting joins, filters, and nested relations. A dedicated stateful middleware tier called zero-cache tails PostgreSQL logical replication into a fast local replica, evaluates active client ZQL subscriptions via incremental view maintenance (IVM), and streams precise row deltas over WebSockets.
When a client query references data not yet hydrated locally, Zero transparently answers from the local client store immediately while backfilling missing rows from zero-cache in the background. Mutations execute optimistically on the client and dispatch to server-side custom mutators that run authoritatively against PostgreSQL, rolling back optimistic state automatically if a server constraint rejects the transaction.
PowerSync: Batteries-Included Bidirectional SQLite Sync
PowerSync targets offline-critical web, desktop, and mobile applications—especially React Native, Expo, Flutter, and Electron clients—that require deterministic local persistence inside native SQLite. The PowerSync Service consumes PostgreSQL logical replication (and also supports MySQL, MongoDB, and SQL Server connectors), partitioning rows into permission-scoped Sync Buckets declared via sync-rules.yaml or newer Sync Streams.
Unlike ElectricSQL, PowerSync ships an integrated local mutation outbox inside the client SQLite database. Writes committed while a field technician is underground or aboard an aircraft succeed locally in under 2 milliseconds, accumulate in a strictly ordered ps_crud upload queue, and flush sequentially to your backend upload endpoint once connectivity returns.
| Architectural Dimension | ElectricSQL (electric-next) |
Rocicorp Zero (zero-cache) |
PowerSync |
|---|---|---|---|
| Core Sync Scope | Read-path HTTP streaming only | Full-duplex query-driven reactive sync | Full-duplex bucketed bidirectional sync |
| Primary Backend Database | PostgreSQL (native logical replication) | PostgreSQL (native WAL streaming) | PostgreSQL, MySQL, MongoDB, SQL Server |
| Client Storage Engine | TanStack DB, PGlite (WASM), or SQLite | Embedded SQLite / in-memory ZQL cache | Native SQLite (WAL mode on iOS, Android, Web) |
| Subscription Granularity | Single-table SQL WHERE Shapes |
Ad-hoc relational ZQL queries with joins | Parameterized sync-rules.yaml Sync Buckets |
| Write-Path Ownership | External APIs (REST, tRPC, Server Actions) | Integrated server-authoritative custom mutators | Integrated client outbox + backend upload API |
| Transport Protocol | Standard HTTP/1.1, HTTP/2, HTTP/3 chunked/long-poll | Persistent WebSockets (custom binary/JSON protocol) | Persistent WebSockets / HTTP streaming |
| CDN Edge Cacheability | Native (stateless Shape offset URLs) | None (stateful per-connection view state) | Bucket-level CDN partial support, stateful cursors |
| Best Enterprise Fit | Read-heavy SaaS dashboards, Postgres + TanStack stacks | High-reactivity collaborative apps (Linear-style UIs) | Offline-first mobile field ops, POS, logistics apps |
What Do 2026 Sync Engine Latency and Throughput Benchmarks Show?
Public 2026 production benchmarks across ElectricSQL, Rocicorp Zero, and PowerSync demonstrate that local client queries execute in under 2 milliseconds across all three engines, while backend replication throughput diverges by transport model. ElectricSQL leads in CDN-backed read fan-out, whereas Zero v1.8 sustains over 2,500 writes per second.
Because no single neutral third-party consortium maintains an apples-to-apples multi-engine suite across every client runtime, principal architects evaluate empirical telemetry published by each vendor alongside independent production benchmarks from Kanopy Labs, TanStack, and ThriveIT.
Local Client Query Latency and Differential Dataflow
Traditional cloud-backed applications suffer from network physics: a cross-region TLS handshake plus PostgreSQL pool checkout and JSON serialization typically takes 150 to 400 milliseconds at p95. By moving the active working set onto the client device, all three sync engines eliminate network RTT from the read rendering path:
- Embedded Read Execution: Across Kanopy Labs production benchmarks and ThriveIT mobile SQLite evaluations, local client reads against synced SQLite, PGlite, or ZQL stores consistently execute in under 2 to 5 milliseconds, enabling 120 FPS list filtering and instant route transitions.
- TanStack DB Differential Dataflow (
@tanstack/db-ivm): When pairing ElectricSQL Shapes with TanStack DB, client-side live queries rely ond2ts—a TypeScript implementation of differential dataflow. According to TanStack DB and Kanopy Labs benchmarks, mutating or syncing a single row inside a sorted, filtered collection of 100,000+ rows recomputes the active UI projection in 0.7 ms to <1 ms without re-scanning the entire dataset. - Optimistic Mutation Loop: Local optimistic writes in PowerSync SQLite and Zero ZQL commit to the local UI render loop in under 10 milliseconds, masking upstream WAN latency entirely from end users.
PostgreSQL WAL Replication and Bulk Throughput
Synchronizing PostgreSQL Write-Ahead Log events becomes the primary vertical bottleneck during bulk migrations, nightly ETL imports, or high-concurrency B2B tenant bursts.
- Rocicorp Zero v1.8 Replication Speed: Zero engineering benchmarks show that v1.8 incremental WAL streaming runs 1.8x faster than earlier v1.6/v1.7 releases. On standard developer/server hardware (Apple M-series Pro benchmarks reported in Zero's release engineering notes), bulk 50,000-row transaction backfills sustain ~30+ MiB/s replication throughput, while real-world production write ceilings scaled from ~750 writes/sec up to 2,500+ writes/sec depending on relational index depth.
- ElectricSQL Shape Streaming Latency: Because ElectricSQL parses
pgoutputlogical replication frames directly into immutable HTTP Shape logs with minimal per-client state evaluation, steady-state server-to-client propagation sits in the low tens of milliseconds on healthy connections, while Cloudflare or Fastly CDN edge nodes serve cached Shape offsets to tens of thousands of concurrent dashboards without adding CPU load to PostgreSQL. - PowerSync Bucket Compilation and Lag: PowerSync compiles incoming Postgres WAL changes into user-scoped Sync Buckets. Under steady-state workloads, PowerSync maintains single-digit second end-to-end lag and recovers from sudden write bursts within seconds to a minute as WAL frames drain into bucket storage.
Mobile Network Resilience and Dataset Ceilings
Field-operations telemetry from ThriveIT's 2026 offline-first mobile architecture benchmarks tested managed SQLite outbox queues under harsh cellular degradation—specifically 15% packet loss on simulated 4G links and rolling connectivity blackouts. Sync layers equipped with idempotent local outbox queues achieved a 97/100 field reliability score without duplicate mutation side effects.
However, client memory and SQLite query planner limits impose a hard practical ceiling: reactive client datasets perform predictably up to approximately 100,000 active rows per client database. Beyond 100,000 local rows, unindexed reactive re-evaluations and JSON deserialization inside mobile SQLite or browser WASM runtimes introduce main-thread frame drops unless teams enforce strict Shape filters, Sync Bucket partitioning, or explicit pagination.
| Benchmark Metric / Dimension | ElectricSQL + TanStack DB | Rocicorp Zero (v1.8) | PowerSync (SQLite) | Source / Context |
|---|---|---|---|---|
| Client Local Read Latency | < 2 ms (in-memory / PGlite) | < 2 ms (local ZQL store) | < 2 ms to 5 ms (local SQLite) | Kanopy Labs & ThriveIT telemetry |
| 100k-Row Incremental View Update | 0.7 ms – < 1 ms (@tanstack/db-ivm) |
Sub-millisecond ZQL delta | Dependent on SQLite query indexes | TanStack DB d2ts benchmarks |
| WAL Bulk Backfill Throughput | Bound by Postgres pgoutput + HTTP log append |
~30+ MiB/s (50k-row tx) | Bucket compiler throughput-bound | Zero v1.8 release benchmarks |
| Sustainable Production Write Rate | Unconstrained by sync (uses direct APIs) | 2,500+ writes/sec (up from ~750/s) | Scaled via Postgres pool + upload API | Zero v1.8 production telemetry |
| Steady-State Sync Propagation | Low tens of milliseconds (HTTP stream) | Real-time WebSocket delta | Single-digit seconds (bucketed WAL) | Official vendor architecture specs |
| Flaky Network Field Reliability | Requires custom outbox (e.g., TanStack DB) | Optimistic retry queue | 97/100 score (15% 4G packet loss) | ThriveIT mobile resilience suite |
| Recommended Client Row Ceiling | ~100,000 rows per Shape/collection | ~100,000 rows active query graph | ~100,000 rows per scoped device | Community & production scaling limits |
For comparison with how PostgreSQL serverless storage layers behave underneath these sync engines, review our Neon vs Aurora DSQL vs Supabase vs Turso benchmarks, and explore our enterprise Change Data Capture with Debezium, Kafka, and Postgres blueprint for backend WAL pipeline patterns.
How Does PostgreSQL Logical Replication Power Local-First Sync?
PostgreSQL logical replication streams row-level INSERT, UPDATE, and DELETE events from the Write-Ahead Log (wal_level = logical) through the pgoutput decoding plugin into a persistent replication slot. Sync engines consume these decoded transaction frames, filter changes by tenant authorization rules, and fan out ordered deltas to connected clients.
Configuring PostgreSQL correctly is the single highest-leverage Day-1 engineering task for any local-first deployment. Misconfigured REPLICA IDENTITY settings silently omit old primary-key or filter-column values during UPDATE and DELETE operations, breaking Shape filters and Sync Bucket eviction on the client.
Production PostgreSQL WAL and Slot Configuration
Run the following SQL and postgresql.conf baseline on your primary database (tested across PostgreSQL 16 and 17+ managed clusters such as RDS, Cloud SQL, Supabase, and self-hosted Patroni topologies):
-- 1. Verify logical WAL level and slot capacity (requires server restart if changed)
-- In postgresql.conf:
-- wal_level = logical
-- max_replication_slots = 10
-- max_wal_senders = 10
-- max_slot_wal_keep_size = 10GB -- CRITICAL: Prevents WAL disk exhaustion if sync service dies
SHOW wal_level;
SHOW max_slot_wal_keep_size;
-- 2. Create dedicated publication for synced enterprise tables only
CREATE PUBLICATION epsol_sync_pub FOR TABLE
public.workspaces,
public.projects,
public.work_orders,
public.inspection_items;
-- 3. Set REPLICA IDENTITY FULL on tables filtered by non-PK columns (e.g., tenant_id / status)
-- Without FULL, DELETE/UPDATE WAL frames lack old column values needed to evict rows from Shapes!
ALTER TABLE public.work_orders REPLICA IDENTITY FULL;
ALTER TABLE public.inspection_items REPLICA IDENTITY FULL;
-- 4. Monitor replication slot lag and retained WAL bytes continuously
SELECT
slot_name,
active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)) AS flush_lag
FROM pg_replication_slots;
Two operational rules govern production PostgreSQL slots:
- Always bound
max_slot_wal_keep_size: If a staging or preview Electric/Zero/PowerSync container terminates without callingpg_drop_replication_slot(), PostgreSQL refuses to recycle WAL segments needed by that dead slot, eventually filling primary NVMe storage and crashing the database. Settingmax_slot_wal_keep_size = 10GB(or sized to 25% of free disk) forces PostgreSQL to invalidate abandoned slots before disk exhaustion occurs; clients recover gracefully via snapshot re-sync. - Exclude high-churn audit/telemetry tables from the Publication: Never create
FOR ALL TABLESpublications in multi-tenant SaaS databases. High-frequency log tables, session counters, or background job queues bloat WAL decoding CPU even when no client subscribes to them.
When evaluating whether your backend needs distributed multi-region SQL underneath a sync layer, compare trade-offs in our CockroachDB, TiDB, and YugabyteDB distributed SQL architectures guide.
How Do You Implement ElectricSQL Shapes with TanStack DB in Production?
Implementing ElectricSQL with TanStack DB combines HTTP Shape streaming for server-to-client synchronization with @tanstack/db-ivm differential dataflow for sub-millisecond reactive joins and optimistic writes. ElectricSQL streams filtered PostgreSQL rows through an auth-enforcing API proxy, while client mutations route directly to your existing TypeScript backend endpoints.
This architecture excels for teams building React, Next.js, or Next.js 15, React Router 7, and TanStack Start benchmarks workloads where strict RBAC, Zod validation, and complex server business logic already live inside Fastify or Next.js Route Handlers.
Step 1: Secure Shape Authorization Proxy (Never Expose Electric Directly)
ElectricSQL intentionally excludes row-level authentication from its core binary so the sync service stays stateless and horizontally cacheable. Your backend API gateway verifies the user's JWT/session, injects tenant WHERE predicates, and proxies the HTTP stream with proper Vary and Cache-Control headers:
// src/routes/shapes/work-orders.ts (Fastify / Node.js Edge Proxy)
import type { FastifyRequest, FastifyReply } from "fastify";
const ELECTRIC_ORIGIN = process.env.ELECTRIC_URL ?? "http://electric-sync:3000";
export async function proxyWorkOrdersShape(
request: FastifyRequest<{ Querystring: Record<string, string> }>,
reply: FastifyReply
) {
// 1. Authenticate caller via verified enterprise session / JWT
const session = await request.verifyEnterpriseSession();
if (!session?.tenantId) {
return reply.code(401).send({ error: "Unauthorized tenant context" });
}
// 2. Construct Electric Shape URL with server-enforced tenant isolation
const upstreamUrl = new URL("/v1/shape", ELECTRIC_ORIGIN);
upstreamUrl.searchParams.set("table", "public.work_orders");
// Enforce tenant_id filter on the server; never trust client-supplied WHERE clauses
const safeWhere = `tenant_id = '${session.tenantId.replace(/'/g, "''")}' AND archived = false`;
upstreamUrl.searchParams.set("where", safeWhere);
// Forward Electric protocol parameters (offset, handle, live, cursor)
for (const param of ["offset", "handle", "live", "cursor"]) {
const val = request.query[param];
if (val) upstreamUrl.searchParams.set(param, val);
}
const upstreamRes = await fetch(upstreamUrl, {
headers: { Accept: "application/json" },
signal: request.raw.aborted ? AbortSignal.abort() : undefined,
});
// 3. Preserve Electric cache headers and stream body directly to CDN/browser
reply.code(upstreamRes.status);
for (const header of ["content-type", "cache-control", "electric-offset", "electric-handle", "electric-schema", "electric-cursor"]) {
const value = upstreamRes.headers.get(header);
if (value) reply.header(header, value);
}
// Critical: Scope shared CDN caches by Authorization / tenant cookie
reply.header("Vary", "Authorization");
return reply.send(upstreamRes.body);
}
Step 2: TanStack DB Electric Collection with Optimistic TxID Reconciliation
On the client, TanStack DB binds an Electric Shape stream to a live reactive collection. When a user updates a work order, the client applies an optimistic update immediately, posts the mutation to your Fastify API, and returns PostgreSQL's pg_current_xact_id()::xid8 transaction ID (txid) so TanStack DB knows the exact millisecond the Electric WAL stream catches up and confirms the optimistic write:
// src/db/collections/workOrders.ts
import { createCollection } from "@tanstack/db";
import { electricCollectionOptions } from "@tanstack/electric-db-collection";
import { z } from "zod";
export const WorkOrderSchema = z.object({
id: z.string().uuid(),
tenant_id: z.string().uuid(),
title: z.string().min(1),
status: z.enum(["queued", "in_progress", "blocked", "completed"]),
priority: z.number().int().min(1).max(5),
updated_at: z.string(),
});
export type WorkOrder = z.infer<typeof WorkOrderSchema>;
export const workOrdersCollection = createCollection(
electricCollectionOptions<WorkOrder>({
id: "work-orders",
schema: WorkOrderSchema,
getKey: (item) => item.id,
shapeOptions: {
url: "/api/shapes/work-orders",
headers: async () => ({
Authorization: `Bearer ${await getAccessToken()}`,
}),
},
onUpdate: async ({ transaction }) => {
const mutation = transaction.mutations[0];
const res = await fetch(`/api/work-orders/${mutation.key}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(mutation.changes),
});
if (!res.ok) {
throw new Error(`Mutation rejected: ${res.status}`);
}
// Server returns Postgres txid from SELECT pg_current_xact_id()::text
const { txid } = (await res.json()) as { txid: number };
return { txid };
},
})
);
That txid handshake prevents the infamous "optimistic flicker" bug where a client removes its optimistic overlay slightly before the replicated WAL row arrives back down the stream.
How Do Rocicorp Zero ZQL Queries and Custom Mutators Work?
Rocicorp Zero replaces manual Shape URLs and HTTP proxies with a unified TypeScript schema, relational ZQL client queries, and server-authoritative custom mutators coordinated by zero-cache. Clients read and join normalized tables locally in under 2 milliseconds while zero-cache compiles incremental view deltas over WebSockets.
Zero's primary strength is ergonomic relational completeness. When building complex collaborative workspaces—such as Jira-style issue boards, multi-nested BOM editors, or real-time financial ledgers—maintaining five separate Electric Shape URLs and joining them manually can add boilerplate. Zero handles foreign-key traversals and incremental view updates across zero-cache natively.
Defining Zero Permissions, ZQL Queries, and Server Mutators
Below is a production-structured Zero setup featuring schema definition, row-level read permissions, and a transactional custom mutator:
// src/zero/schema.ts
import {
createSchema,
table,
string,
number,
boolean,
relationships,
definePermissions,
ANYONE_CAN,
type ExpressionBuilder,
} from "@rocicorp/zero";
const workspace = table("workspaces")
.columns({
id: string(),
name: string(),
plan_tier: string(),
})
.primaryKey("id");
const workOrder = table("work_orders")
.columns({
id: string(),
workspace_id: string(),
assignee_id: string().optional(),
title: string(),
status: string(),
archived: boolean(),
updated_at: number(),
})
.primaryKey("id");
const workOrderRelationships = relationships(workOrder, ({ one }) => ({
workspace: one({
sourceField: ["workspace_id"],
destField: ["id"],
destSchema: workspace,
}),
}));
export const schema = createSchema({
tables: [workspace, workOrder],
relationships: [workOrderRelationships],
});
export type Schema = typeof schema;
type AuthData = {
sub: string;
workspaceIds: string[];
};
export const permissions = definePermissions<AuthData, Schema>(schema, () => {
const allowWorkspaceMember = (
authData: AuthData,
{ cmp }: ExpressionBuilder<Schema, "work_orders">
) => cmp("workspace_id", "IN", authData.workspaceIds);
return {
workspaces: {
row: { select: ANYONE_CAN },
},
work_orders: {
row: {
select: [allowWorkspaceMember],
// Enforce writes exclusively through server-authoritative custom mutators
},
},
};
});
On the React client, engineers compose relational ZQL queries without writing REST endpoints or cache keys:
// src/components/ActiveWorkOrders.tsx
import { useQuery } from "@rocicorp/zero/react";
import { zeroClient } from "../zero/client";
export function ActiveWorkOrders({ workspaceId }: { workspaceId: string }) {
// Executes locally in <2ms against synced client store; zero-cache streams deltas
const [orders, status] = useQuery(
zeroClient.query.work_orders
.where("workspace_id", "=", workspaceId)
.where("archived", "=", false)
.related("workspace")
.orderBy("updated_at", "desc")
.limit(200)
);
const handleEscalate = (orderId: string) => {
// Runs optimistically on client, then verified by server custom mutator
zeroClient.mutate.work_orders.escalate({ id: orderId });
};
return (
<ul>
{orders.map((wo) => (
<li key={wo.id} onClick={() => handleEscalate(wo.id)}>
[{wo.workspace?.name}] {wo.title} — {wo.status}
</li>
))}
</ul>
);
}
Note the operational caveat with zero-cache: because zero-cache maintains an active SQLite replica and in-memory IVM pipelines for connected client view graphs, Node.js heap allocation (--max-old-space-size) and backpressure limits must be tuned carefully under deep relational joins. Unlike ElectricSQL's stateless HTTP stream, scaling zero-cache horizontally requires partitioning client WebSocket connections across view-syncer replicas backed by shared replication infrastructure.
How Does PowerSync Handle Offline Mobile SQLite Queues and Sync Rules?
PowerSync orchestrates full-duplex synchronization between PostgreSQL and embedded client SQLite databases using declarative sync-rules.yaml bucket definitions and a persistent local outbox table (ps_crud). Offline mutations execute immediately against local SQLite in under 5 milliseconds and flush reliably in strict transaction order once cellular or Wi-Fi connectivity recovers.
For enterprise mobile platforms built with Flutter, React Native, or Expo—where field technicians inspect infrastructure in basements, mines, or rural logistics corridors—HTTP-only sync fails as soon as a user opens a record offline and modifies three child line items.
Declarative Multi-Tenant Bucket Rules (sync-rules.yaml)
PowerSync evaluates parameterized SQL queries inside sync-rules.yaml to compile immutable tenant/user Sync Buckets on the server:
# powersync/sync-rules.yaml
bucket_definitions:
user_work_orders:
# Extract authenticated technician ID and tenant ID from verified JWT claims
parameters:
- SELECT request.jwt() ->> 'tenant_id' AS tenant_id,
request.jwt() ->> 'sub' AS user_id
data:
- SELECT id, tenant_id, title, status, priority, updated_at
FROM public.work_orders
WHERE tenant_id = bucket.tenant_id
AND (assignee_id = bucket.user_id OR status = 'queued')
AND archived = false
order_inspections:
parameters:
- SELECT wo.id AS work_order_id
FROM public.work_orders wo
WHERE wo.tenant_id = request.jwt() ->> 'tenant_id'
AND wo.assignee_id = request.jwt() ->> 'sub'
data:
- SELECT id, work_order_id, checklist_code, passed, notes
FROM public.inspection_items
WHERE work_order_id = bucket.work_order_id
Idempotent Client Outbox Upload Handler
On the mobile or desktop client, PowerSync records every local SQLite INSERT, UPDATE, and DELETE inside ps_crud and passes batched CrudEntry items to your uploadData connector. To prevent duplicate side effects under 15% packet loss or timeout retries, your upload API must attach an idempotency key (op.id or client transaction ID) and resolve conflicts deterministically:
// src/sync/PowerSyncConnector.ts
import {
AbstractPowerSyncDatabase,
PowerSyncBackendConnector,
UpdateType,
} from "@powersync/web"; // or @powersync/react-native
export class EnterprisePowerSyncConnector implements PowerSyncBackendConnector {
async fetchCredentials() {
const res = await fetch("/api/auth/powersync-token", { method: "POST" });
if (!res.ok) throw new Error("Failed to fetch PowerSync credentials");
const { token, endpoint } = await res.json();
return { endpoint, token };
}
async uploadData(database: AbstractPowerSyncDatabase): Promise<void> {
const transaction = await database.getNextCrudTransaction();
if (!transaction) return;
try {
const operations = transaction.crud.map((entry) => ({
opId: `${transaction.transactionId ?? "tx"}-${entry.clientId}`,
table: entry.table,
op: entry.op, // PUT | PATCH | DELETE
id: entry.id,
data: entry.opData ?? {},
}));
const response = await fetch("/api/sync/upload-batch", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": `ps-tx-${transaction.transactionId ?? Date.now()}`,
},
body: JSON.stringify({ operations }),
});
if (!response.ok) {
// 4xx validation errors should dead-letter instead of stalling the queue forever
if (response.status >= 400 && response.status < 500) {
await logDeadLetterTransaction(operations, await response.text());
await transaction.complete();
return;
}
throw new Error(`Transient upstream failure: ${response.status}`);
}
// Mark transaction complete so local outbox clears and awaits WAL confirmation
await transaction.complete();
} catch (error) {
// Throw to pause upload queue and trigger exponential backoff retry
throw error;
}
}
}
Notice the critical 4xx dead-letter guard in uploadData. In naive PowerSync implementations, a single schema validation failure (e.g., an outdated client submitting an invalid enum) returns HTTP 422, throws in uploadData, and permanently blocks every subsequent offline mutation in that user's outbox queue!
What Are the Hidden Production Failure Modes and FinOps Trade-Offs?
Deploying local-first sync engines in production introduces four systemic failure modes: PostgreSQL WAL replication slot bloat, client SQLite schema migration drift, CDN cache poisoning on Shape streams, and outbox head-of-line blocking. Mitigating these risks upfront prevents database outages and runaway cloud egress bills.
Engineering teams frequently underestimate the operational shift from stateless APIs to stateful replication topologies. Compare real-world transport protocols in our WebSockets, SSE, and WebTransport real-time benchmarks alongside the sync-specific failure matrix below.
| Failure Mode | Root Architectural Cause | Affected Engines | Concrete Production Mitigation |
|---|---|---|---|
| PostgreSQL WAL Disk Exhaustion | Crashed or abandoned sync containers leave inactive replication slots holding unrecycled WAL segments. | ElectricSQL, Zero, PowerSync | Enforce max_slot_wal_keep_size = 10GB, alert when retained_wal > 2GB, and use ephemeral slot cleanup hooks. |
| Client Schema Drift & Outbox Poisoning | App update drops/renames a Postgres column while offline mobile clients still queue old PATCH payloads. |
PowerSync, Zero (offline), Custom Outbox | Version mutation payloads (v1/v2), expand-and-contract Postgres schemas, and dead-letter non-retryable 4xx uploads. |
| Multi-Tenant CDN Cache Leak | Proxy strips Vary: Authorization or caches user-specific Electric Shape responses under shared URLs. |
ElectricSQL (behind CDN) | Include hashed tenant_id in Shape query/path keys, enforce Vary: Authorization, and authenticate before edge cache lookup. |
| Client Memory / SQLite Bloat (>100k Rows) | Unbounded Shape WHERE clauses or greedy sync-rules replicate years of historical rows to devices. |
ElectricSQL, Zero, PowerSync | Scope sync windows (updated_at > NOW() - INTERVAL '90 days'), enforce client pagination, and run periodic SQLite VACUUM. |
| Optimistic UI Flicker on Commit | Optimistic mutation clears locally before the async PostgreSQL WAL delta arrives back on the client stream. | ElectricSQL + Custom Writes | Return Postgres pg_current_xact_id()::xid8 from mutation APIs and hold optimistic overlay until stream reaches txid. |
| Upstream Connection Pool Starvation | High write concurrency from thousands of reconnecting mobile outboxes floods primary Postgres connections. | PowerSync, Zero, ElectricSQL | Route upload handlers through PgBouncer/Supavisor transaction pooling and rate-limit reconnect jitter with exponential backoff. |
FinOps & Cloud Infrastructure Cost Reality
From a cloud FinOps perspective, read-heavy B2B SaaS applications see massive database cost reductions with ElectricSQL + CDN edge caching. Instead of scaling read replicas to serve 20,000 dashboard clients polling /api/projects every 5 seconds (4,000 req/sec hitting RDS), a single Electric instance tails one WAL slot and offloads 95%+ of read fan-out to Cloudflare Workers or Fastly CDN POPs.
Conversely, PowerSync and Rocicorp Zero shift infrastructure spend from primary database CPU toward stateful sync-tier memory and WebSocket connection density. When estimating TCO, model the memory per active WebSocket/view-syncer session alongside your PostgreSQL primary IOPS rather than comparing database compute alone.
Which Local-First Sync Engine Should Your Enterprise Architecture Choose?
Selecting between ElectricSQL, Rocicorp Zero, and PowerSync depends on four concrete enterprise architecture criteria: multi-day offline mobile mutation requirements, existing API write-validation ownership, ad-hoc relational ZQL join complexity, and whether HTTP CDN read fan-out outweighs stateful WebSocket view-syncer memory and session management costs.
Use the following decision rubric grounded in 2026 production architecture patterns:
- Choose ElectricSQL (+ TanStack DB or PGlite) when:
- You operate a brownfield or greenfield web SaaS platform deeply invested in PostgreSQL and TypeScript APIs (Fastify, Next.js, NestJS).
- You need massive read fan-out scalability via standard HTTP CDN caching without operating stateful WebSocket view clusters.
- You want to keep 100% of your existing REST/tRPC mutation endpoints, Stripe webhooks, and RBAC validation untouched while upgrading UI reads to sub-2ms
d2tsdifferential dataflow.
- Choose Rocicorp Zero when:
- You are engineering a greenfield, hyper-interactive web workspace (collaborative project management, real-time CRM, design/data grids) where ad-hoc relational ZQL queries with joins eliminate hundreds of manual endpoint definitions.
- Your team wants unified, server-authoritative custom mutators and is prepared to size and monitor stateful
zero-cachememory capacity.
- Choose PowerSync when:
- You are shipping offline-first native mobile or cross-platform apps (Flutter, React Native, Expo, Electron) for field service, healthcare, logistics, or point-of-sale environments.
- Users must capture complex multi-table mutations offline for hours or days and rely on a battle-tested SQLite outbox queue with declarative
sync-rules.yamlsecurity buckets—or when your backend runs MySQL, MongoDB, or SQL Server instead of PostgreSQL.
Partnering with EpsolDev for Production Sync Architecture
Migrating an enterprise platform to local-first synchronization requires rigorous PostgreSQL WAL sizing, zero-downtime schema evolution, idempotent outbox design, and edge-safe authorization proxies. At EpsolDev, we architect and build bespoke custom software, scalable web platforms, and offline-resilient mobile applications for B2B companies and enterprises across the USA, Canada, Australia, Germany, and Japan.
Ready to eliminate loading spinners, cut database read load, or engineer an offline-first mobile architecture? Discuss Your Project with our systems architects, review our EpsolDev Custom Software Services, or Contact Us directly to scope your PostgreSQL sync pipeline.