Tekko

Language

Get in Touch →

Usually respond within 24 hours

Back to BlogArchitecture

Local-First Sync: Building Reactive Apps with Electric SQL and PGLite

7 min read
PostgreSQLLocal-FirstElectricSQLPGLiteTypeScript
Local-First Sync: Building Reactive Apps with Electric SQL and PGLite

For the better part of a decade, the standard blueprint for web applications has been the "Cloud-First" model: a thin client making REST or GraphQL requests to a central server, which in turn talks to a database. While this model is familiar, it introduces inherent latency, complex state management for loading/error transitions, and a complete failure mode when the user goes offline.

The industry is currently shifting toward the "Local-First" paradigm. In this model, the client owns a local database, interactions happen at the speed of the local CPU/memory, and data synchronizes in the background. Until recently, implementing this meant compromising on the database engine (e.g., using IndexedDB or SQLite) and writing custom synchronization logic.

With the emergence of PGLite and Electric SQL, we can now run a full PostgreSQL engine in the browser and synchronize it with a server-side Postgres instance with minimal boilerplate. This article explores how to architect these systems and why this stack is a massive leap forward for developer productivity and user experience.

The Core Components: PGLite and Electric SQL

To understand this architecture, we first need to look at the two technologies making it possible.

PGLite: Postgres in the Browser

Historically, running a database in the browser meant using IndexedDB—a low-level, awkward API—or using a WASM-compiled version of SQLite. While SQLite is excellent, it lacks the advanced features of PostgreSQL (like JSONB support, sophisticated indexing, and specific extensions) that many developers rely on in the backend.

PGLite is a WASM build of Postgres packaged into a client-side library. It isn't a proxy; it is the actual Postgres engine running in the browser's memory or persisted via IndexedDB. It allows you to run standard SQL queries, use triggers, and maintain a schema that matches your backend exactly.

Electric SQL: The Sync Engine

If PGLite is the storage engine, Electric SQL is the nervous system. Electric is a sync layer that sits between your central Postgres database and your local PGLite instances.

Electric uses a concept called Shapes. A Shape is a subset of your database—specific tables and filtered rows—that a client subscribes to. When data in that Shape changes on the server, Electric pushes those changes to the client. When the client makes local changes to its PGLite instance, Electric captures those changes and replicates them back to the server.

Why This Matters: The Death of the Loading Spinner

In a traditional app, every action involves a round-trip to the server:

  1. User clicks "Save."
  2. UI shows a loading spinner.
  3. Request travels to the server.
  4. Database updates.
  5. Response travels back.
  6. UI updates to a success state.

In a local-first app using PGLite and Electric:

  1. User clicks "Save."
  2. The app writes to the local PGLite instance (instant).
  3. The UI updates immediately because it is reactively bound to the local database.
  4. Electric SQL handles the background synchronization to the server whenever connectivity allows.

This architecture eliminates perceived latency and makes "Offline Mode" a default feature rather than a difficult add-on.

Implementation Strategy

Let’s look at how to implement a reactive task management system using this stack.

1. Defining the Schema

Your schema remains standard PostgreSQL. Because PGLite is Postgres, you don't need to map between different dialects.

-- On your central server CREATE TABLE projects ( id UUID PRIMARY KEY, name TEXT NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); CREATE TABLE tasks ( id UUID PRIMARY KEY, project_id UUID REFERENCES projects(id), title TEXT NOT NULL, completed BOOLEAN DEFAULT FALSE, updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() );

2. Setting up the Electric Sync Service

Electric works by consuming the Postgres logical replication stream. You point the Electric sync service at your Postgres database and define which tables are "electrified."

Using the Electric SDK, you can then define a "Shape." This is a critical optimization: you don't want to sync the entire 500GB production database to a user's phone. You only sync what they need.

// Client-side subscription logic const shape = await electric.sync({ table: 'tasks', where: "project_id = 'some-uuid'", include: { projects: true } });

3. Integrating PGLite in the Frontend

With PGLite, you initialize the database and pass it to the Electric client. In a React environment, you might use a hook to ensure the UI stays in sync with the database state.

import { PGLite } from '@electric-sql/pglite'; import { useShape } from '@electric-sql/react'; const pg = new PGLite('idb://my-app-db'); function TaskList({ projectId }) { // useShape reactively updates the component when the local DB changes const { data: tasks } = useShape({ table: 'tasks', where: `project_id = '${projectId}'` }); const toggleTask = async (id, status) => { await pg.query( 'UPDATE tasks SET completed = $1 WHERE id = $2', [!status, id] ); // The UI updates instantly because of the reactive local-first loop }; return ( <ul> {tasks.map(task => ( <li key={task.id} onClick={() => toggleTask(task.id, task.completed)}> {task.title} {task.completed ? '✅' : '⬜'} </li> ))} </ul> ); }

Handling Conflicts

One of the biggest hurdles in local-first development is conflict resolution. If User A and User B both edit the same task while offline, what happens when they reconnect?

Electric SQL simplifies this by using LWW (Last Write Wins) at the column level by default, but it is built on a foundation of Rich-CRDTs (Conflict-free Replicated Data Types). Because the sync happens at the database level, Electric can ensure causal consistency. If you delete a project, Electric ensures that all related tasks are handled correctly across all clients according to your referential integrity rules.

Architectural Advantages

Reduced Server Load

In a local-first world, the server is no longer responsible for serving every read request. Once a client has synced a Shape, all subsequent reads happen against the local PGLite instance. This significantly reduces the CPU and I/O load on your primary database.

Simplified State Management

Gone are the days of complex Redux or TanStack Query configurations to manage cache invalidation. The database is the state. When you execute a SQL INSERT, your reactive hooks detect the change in the local PGLite storage and re-render the UI. The "cache" and the "source of truth" are the same thing.

Superior User Experience

Users on high-latency mobile connections or flaky Wi-Fi see no difference in performance. The app feels "snappy" because the UI never waits for the network.

Considerations and Trade-offs

While powerful, this stack isn't a silver bullet for every use case:

  1. Storage Limits: Browsers impose limits on IndexedDB storage (usually a percentage of disk space). While PGLite is efficient, storing millions of rows locally is not feasible.
  2. Initial Sync Latency: The first time a user opens the app, they must download the initial "Shape." For large datasets, this requires a thoughtful loading strategy.
  3. Security: Since the database engine is on the client, you must use robust Row-Level Security (RLS) on the server. Electric SQL integrates with Postgres RLS to ensure users only sync data they are authorized to see.

Conclusion: The Path Forward

The combination of PGLite and Electric SQL represents a fundamental shift in how we build data-driven applications. By moving the database to the edge, we resolve the tension between developer productivity and user experience.

Actionable Next Steps:

  1. Audit your current app: Identify features where users experience the most "loading friction." These are prime candidates for a local-first pilot.
  2. Experiment with PGLite: Replace a small piece of complex localStorage or IndexedDB logic with PGLite to see how SQL simplifies your client-side data handling.
  3. Explore Electric Shapes: Review the Electric SQL documentation on Shapes to understand how to partition your data for efficient synchronization.

We are moving toward an era where the network is a background utility, not a foreground dependency. Embracing PGLite and Electric SQL today positions your architecture for that future.