Tech Analysis · Nov 21, 2026 · 12 min read

ElectricSQL: Shape Subscriptions, CRDTs and Postgres Sync Patterns

Tech Analysis

Practical patterns for ElectricSQL 0.9 covering shape-based replication from Postgres to client SQLite, reactive live queries in React, conflict resolution, RLS security, and production trade-offs wit

ElectricSQL: Shape Subscriptions, CRDTs and Postgres Sync Patterns

ElectricSQL Architecture and Replication Model

ElectricSQL replicates data between PostgreSQL and SQLite using a log-based CDC (change data capture) mechanism. The sync service reads the Postgres WAL (Write-Ahead Log) through logical replication, converts transactions into a serialized Electric log format, and delivers deltas to clients based on their subscribed shapes.

Each client maintains an independent SQLite database using the wa-sqlite WebAssembly build or the origin private file system (OPFS) backend when available. The replication protocol is stateful: clients maintain a replication cursor (last seen LSN and shape version) and request only incremental changes. This design keeps bandwidth usage low compared to full snapshot refreshes.

The shape definition determines which rows are eligible for synchronization. A shape is essentially a tree of tables with optional WHERE clauses. When a shape includes a parent table with a WHERE filter, ElectricSQL automatically includes related child rows through foreign keys, avoiding over-fetching.

Current version 0.9 uses a satellite process written in Elixir that can be self-hosted or used via the managed Electric Cloud service. The satellite maintains an in-memory index of active shapes and uses Redis for coordination when running multiple satellite instances for high availability.

Setting Up Postgres and the Electric Sync Service

Start with a PostgreSQL 14+ instance with logical replication enabled. Set wal_level = logical, max_wal_senders = 20 and max_replication_slots = 20 in postgresql.conf. Create a dedicated replication user:

CREATE ROLE electric WITH REPLICATION LOGIN PASSWORD 'password';
GRANT CREATE ON DATABASE postgres TO electric;

Install the Electric sync service using the official Docker image. The minimal docker-compose.yml for local development looks like this:

services:
  postgres:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: postgres
    command: -c 'wal_level=logical'
  electric:
    image: electricsql/electric:0.9.0
    environment:
      DATABASE_URL: postgresql://electric:password@postgres:5432/postgres
      SECRET_KEY_BASE: dev-secret
    ports:
      - "4000:4000"

After starting the services, run the Electric migrations to install the internal tracking tables (electric.shadow, electric.version, etc.). The CLI command electric-cli migrations up handles this. These tables store replication metadata and are excluded from client shapes by default.

The sync service exposes both a WebSocket endpoint for live replication (ws://localhost:4000/v1/shape) and an HTTP endpoint for initial shape snapshots. Clients authenticate using JWTs signed with the same SECRET_KEY_BASE used by the service.

Defining Shapes for Efficient Data Delivery

Shapes are the core abstraction that prevents the "full database sync" anti-pattern. A shape declaration in the client looks like this:

const shape = {
  table: "projects",
  where: "user_id = 'usr_123'",
  include: [
    {
      table: "tasks",
      on: { project_id: "id" },
      where: "status != 'archived'"
    }
  ]
};

This shape delivers all projects belonging to a specific user and their non-archived tasks. ElectricSQL evaluates the WHERE clauses on the server and maintains a materialised view of qualifying primary keys. When a new row matches the predicate, it is automatically added to the client's sync set; when it stops matching, it is deleted locally.

Shape versions are incremented when the definition changes. Clients must handle shape version migration by clearing and resyncing affected tables. In version 0.9 the shape protocol supports up to 64k shapes per client before performance degrades noticeably. Monitor the electric_shape_size metric exposed by the satellite.

For multi-tenant SaaS applications, bind shapes to tenant IDs and combine with Postgres Row Level Security (RLS) policies. This combination ensures that even if a malicious client requests a different tenant's shape, the sync service rejects it before any data leaves the server.

Client-Side TypeScript Integration with ElectricSQL

The official TypeScript client (@electric-sql/client 0.9.1) provides both a low-level API and React hooks. First, generate a typesafe schema from your Postgres tables using the Electric CLI:

npx electric-sql generate --schema ./db/schema.prisma

This produces a electric/schema.ts file containing Table and Column definitions used for type inference. Initialize the database with:

import { ElectricDatabase, electrify } from 'electric-sql';
import { schema } from './generated/client';

const initElectric = async () => {
  const db = await ElectricDatabase.init('app.db');
  const electric = await electrify(db, schema, {
    url: 'ws://localhost:4000/v1/shape',
    auth: { token: jwtToken }
  });
  await electric.connect();
  return electric;
};

The electrify call wraps the SQLite connection with Electric's replication logic. The returned electric object exposes the database under electric.db with additional live query capabilities.

Reactive Live Queries in React Components

The React integration (@electric-sql/react) provides the useLiveQuery hook that subscribes to shape changes and triggers re-renders only when relevant data mutates. Example usage in a task list component:

import { useLiveQuery } from 'electric-sql/react';

function TaskList({ projectId }) {
  const { results: tasks, loading } = useLiveQuery(
    () => electric.db.tasks.liveMany({
      where: { project_id: projectId, completed: false },
      orderBy: { created_at: 'desc' }
    })
  );

  if (loading) return <div>Syncing...</div>;

  return (
    <ul>
      {tasks.map(task => (
        <li key={task.id}>{task.title}</li>
      ))}
    </ul>
  );
}

The hook automatically manages the shape subscription lifecycle. When the component unmounts, the subscription is paused but the local data remains available for offline use. Re-mounting resumes the subscription from the last cursor, fetching only changes that occurred while the component was inactive.

For more complex queries involving joins, ElectricSQL translates them into multiple live queries under the hood and uses React's useMemo to combine results. Avoid complex SQL in live queries; the client only supports a safe subset that can be efficiently maintained incrementally.

Data Mutations and Optimistic Updates

All writes go through the local SQLite first, providing immediate feedback. ElectricSQL then asynchronously syncs the change to Postgres using a transaction log. The mutation API looks like this:

const createTask = async (projectId: string, title: string) => {
  const taskId = uuidv4();
  
  // Optimistic write
  await electric.db.tasks.insert({
    id: taskId,
    project_id: projectId,
    title,
    completed: false,
    created_at: new Date().toISOString()
  });

  // The sync service will pick this up automatically
  return taskId;
};

To implement optimistic UI patterns, combine useLiveQuery with a local pending state. When the sync round-trip completes, ElectricSQL fires another live query update that reconciles any server-generated fields (such as updated_at triggers).

Error handling requires listening to the electric.syncState observable. When a mutation fails due to a constraint violation on the server, the client receives a compensation event that can roll back the local change or show a user-facing error.

Conflict Resolution with CRDTs and Last-Write-Wins

ElectricSQL ships with built-in last-write-wins (LWW) resolution based on server-assigned timestamps. For richer semantics, you can implement CRDTs on top of the primitive types. The library provides helper functions for common CRDTs:

import { crdt } from 'electric-sql';

await electric.db.notes.update({
  id: noteId,
  content: crdt.text('initial content')
});

// Later merge operations
await electric.db.notes.update({
  id: noteId,
  content: crdt.mergeText('additional collaborative edit')
});

The text CRDT uses a Lamport clock per character to preserve intent across concurrent edits. For counters, use crdt.counter() which implements a PN-Counter that tolerates concurrent increments and decrements.

Choosing between LWW and CRDTs involves trade-offs. LWW is simpler and has lower storage overhead on the client (no tombstones or version vectors), but can lose user intent in collaborative scenarios. CRDTs require additional columns (usually hidden) and increase the size of each replication message by 30-60 bytes per operation depending on clock precision.

In version 0.9 the CRDT implementation stores the full history for mergeable types until the shape is compacted. Monitor local database size; run periodic VACUUM on the SQLite side for long-lived clients.

Security Model with Postgres RLS and JWT Claims

ElectricSQL respects Postgres Row Level Security policies. Create policies that use the JWT claims injected by the sync service:

CREATE POLICY user_projects ON projects
  USING (user_id = current_setting('app.current_user')::uuid);

ALTER TABLE projects ENABLE ROW LEVEL SECURITY;

The Electric satellite sets the app.current_user configuration parameter from the sub claim in the JWT before evaluating any shape or replication query. This ensures that even if a client crafts a shape requesting another user's data, the policy prevents it from being included.

Always validate JWT signatures and expiry on the sync service. For sensitive applications, implement short-lived tokens (15 minutes) and refresh them through a separate auth endpoint. The client library automatically reconnects with a fresh token when the current one expires.

Audit logs can be maintained by creating triggers on the internal Electric replication tables. These triggers write to an audit_log table that is excluded from all client shapes.

Performance Characteristics and Bandwidth Optimizations

ElectricSQL's shape protocol sends only changed columns, reducing payload size compared to full row replication. In practice, a typical task update uses approximately 180 bytes over the wire after compression. The protocol uses MessagePack for serialization and gzip when the payload exceeds 512 bytes.

Client-side indexing follows the shape definitions. Each shape creates a composite index on the filtered columns. For a shape with 50,000 rows, expect 8-12 MB of SQLite storage including indexes. The replication lag is typically under 300 ms on a local network and under 800 ms when the satellite runs in a different region from the Postgres instance.

To reduce initial sync time for large datasets, use shape prefetching. The React hook accepts an initialSync option that pre-fetches common shapes during application bootstrap. Combine this with code-splitting so that users only download shapes for the features they actually use.

Network efficiency improves dramatically when multiple shapes share common tables. The satellite deduplicates replication messages across overlapping shapes for the same client.

Offline Support and Background Sync Patterns

Because all data lives in SQLite, the application remains fully functional offline. The electric.isConnected observable lets you show appropriate UI states. Mutations performed while offline are queued and flushed in the order they were made once connectivity returns.

For background sync on mobile, wrap the Electric client with a service worker that keeps the WebSocket alive using periodic wake locks. The official React Native adapter (experimental in 0.9) uses SQLite directly on the file system and background fetch APIs provided by Expo.

Conflict probability increases with longer offline periods. Provide users with a conflict resolution UI that surfaces CRDT merge results and allows manual override when automatic merging is insufficient.

Production Deployment Considerations

Run the Electric satellite close to your Postgres instance to minimize WAL shipping latency. When using managed Postgres (Supabase, Neon, RDS), enable logical replication and whitelist the satellite's IP for replication slots.

Scale horizontally by running multiple satellite instances behind a TCP load balancer. Use Redis as the coordination backend so that shape subscriptions are shared across instances. The configuration key is ELECTRIC_REDIS_URL.

Monitor these Prometheus metrics exposed on port 4001: electric_replication_lag_seconds, electric_active_shapes, electric_bytes_synced_total. Set alerts when lag exceeds 5 seconds or when a single client maintains more than 200 shapes.

Back up the Postgres database normally. Client SQLite databases are disposable; they can always be rebuilt from the server. For compliance requirements that need client data retention, implement an export feature that uploads a SQLite dump to object storage on user request.

Complete Worked Example: Collaborative Task Manager

Consider a team task manager with projects, tasks, comments, and assignments. The schema uses UUID primary keys, proper foreign keys, and timestamp columns with triggers for updated_at.

The shape tree is defined once at app startup:

const appShape = {
  table: 'projects',
  where: 'team_id = ?',
  args: [currentTeamId],
  include: [
    {
      table: 'tasks',
      on: { project_id: 'id' }
    },
    {
      table: 'comments',
      on: { task_id: 'tasks.id' }
    },
    {
      table: 'assignments',
      on: { task_id: 'tasks.id' }
    }
  ]
};

The React root component initializes Electric and provides it via context. Individual screens subscribe only to the slices they need using useLiveQuery with additional filters. When a user drags a task between projects, the foreign key update automatically moves the task and its comments under the new project's shape without additional client code.

Comments use a simple text CRDT so multiple team members can edit the same comment concurrently. The UI displays a merged view and shows attribution using metadata stored alongside the CRDT state.

This example demonstrates that with careful shape design, a traditionally complex real-time backend (WebSockets, presence, conflict resolution) collapses into declarative shape definitions plus local SQLite queries.

Trade-offs Compared to Alternative Approaches

Compared to Supabase realtime, ElectricSQL moves more logic to the client and gives you full SQL on the local database. Supabase is simpler for basic CRUD but lacks offline-first capabilities and complex join support in subscriptions.

WatermelonDB offers similar offline-first capabilities but requires manual sync implementation. ElectricSQL handles the replication layer, reducing boilerplate by roughly 70% for typical applications. However, WatermelonDB works with any backend, while ElectricSQL is Postgres-only.

RxDB with GraphQL replication offers powerful conflict handling but has a steeper learning curve and higher memory usage on the client. ElectricSQL's SQLite foundation is more battle-tested for large datasets (tested with 500k rows locally).

The main drawback is schema rigidity. Because replication depends on declared relationships, schema changes require coordinated client updates. Use Postgres views for complex projections that do not need to be writable.

Another consideration is cost. The managed Electric Cloud charges based on replicated rows and bandwidth. Self-hosting requires careful monitoring of WAL generation; high-write workloads can increase Postgres I/O costs significantly.

Observability and Debugging Patterns

Enable Electric's debug mode in development by setting ELECTRIC_DEBUG=true. This logs every shape subscription and mutation to the console with color-coded output. The devtools extension for Chrome can inspect the local SQLite database directly.

On the server, the satellite exposes a status endpoint at /status showing connected clients, shape counts, and replication lag per tenant. Integrate this with your existing observability stack using OpenTelemetry traces that correlate client session IDs with server-side replication events.

When debugging sync issues, query the electric.shadow table to see the last synced version for a given row. The electric.migrations table tracks which clients have seen which schema versions.

When to Choose ElectricSQL

ElectricSQL excels for applications where users expect native-like performance, work offline, or collaborate in real time without a custom backend for every feature. Examples include field service apps, note-taking tools, CRM systems for sales teams, and internal tools used at remote locations with poor connectivity.

It is less suitable for analytics-heavy workloads that require complex aggregations across millions of rows; those queries should still hit Postgres directly through a read replica. Similarly, applications with strict audit requirements that prohibit local data storage may need additional controls or may not be appropriate for this architecture.

The technology has matured significantly in version 0.9 with improved CRDT support, better TypeScript ergonomics, and production monitoring tools. Teams already invested in the Postgres ecosystem can add local-first capabilities without adopting an entirely new database or query language.

Keep reading

Related Research