Tekko

Language

Get in Touch →

Usually respond within 24 hours

Back to BlogArchitecture

Local-First Apps with ElectricSQL and PGLite: A Practical Guide

8 min read
PostgreSQLElectricSQLPGLiteLocal-FirstWebAssembly
Local-First Apps with ElectricSQL and PGLite: A Practical Guide

For years, web development has been dominated by the request-response cycle. We build an interface, the user performs an action, we show a loading spinner, wait for a REST or GraphQL API to hit a database, and then update the UI. While we have grown proficient at optimizing this cycle with CDNs and edge functions, the fundamental problem remains: the network is a bottleneck, and latency is the enemy of a great user experience.

Local-first software represents a paradigm shift. Instead of treating the server as the primary source of truth for the UI, we treat a local database inside the browser as the primary source. The server becomes a synchronization engine. Two technologies have recently emerged to make this high-performance architecture viable for Postgres users: ElectricSQL and PGLite.

The Core Problem: The "Loading State" Fatigue

Traditional web apps are fragile. If a user enters a tunnel or has a spotty Wi-Fi connection, the app breaks. Developers try to patch this with complex state management libraries (Redux, TanStack Query) and optimistic UI updates. However, optimistic UI is essentially a manual simulation of what a database does naturally: managing state transitions.

In a local-first architecture, the application code interacts exclusively with a local database. The data is already there, on the device. Reads are instantaneous. Writes are committed locally first and then synchronized in the background. This removes the "loading spinner" from the critical path of user interaction.

Introducing the Stack: PGLite and ElectricSQL

To implement this effectively, we need two components: a robust client-side database and a reliable synchronization protocol.

PGLite: Postgres in the Browser

PGLite is a groundbreaking project that packages the full Postgres engine into a WebAssembly (WASM) module. Unlike previous attempts to bring SQL to the browser (like SQLite via WASM), PGLite is Postgres. It supports many Postgres features, including triggers, window functions, and extensions, all within a single WASM file that is typically less than 4MB compressed.

For developers, this means you can use the same dialect of SQL on the frontend that you use on the backend. You can use the same schemas, the same types, and even some of the same constraints.

ElectricSQL: The Synchronization Engine

ElectricSQL acts as the bridge between your primary cloud Postgres database and your local PGLite instances. It leverages Postgres's logical replication features (the Write-Ahead Log or WAL) to stream data changes in real-time.

Electric doesn't just copy the whole database—which would be a security and performance nightmare. Instead, it uses a concept called Shapes. A Shape is a subset of your database (specific tables and filtered rows) that a particular client is authorized to see. Electric ensures that the local PGLite instance is a perfect, reactive mirror of that Shape.

Architectural Overview

The architecture of an ElectricSQL + PGLite application follows a clear data flow:

  1. Primary Database: A standard Postgres instance (RDS, Supabase, Neon, etc.) with Logical Replication enabled.
  2. Electric Sync Service: A middle-tier service that consumes the Postgres WAL and exposes a synchronization API.
  3. Client-Side PGLite: A WASM-based database running in the user's browser (or mobile app via Capacitor/React Native).
  4. Electric Client SDK: A library that manages the connection between PGLite and the Sync Service, handling the replication protocol and partial data fetching.

Implementing the Sync: A Practical Example

Let’s walk through how you would implement a reactive task management application.

1. Setting up the Backend

First, your Postgres table must be prepared for replication. Electric requires tables to have a primary key and for the REPLICA IDENTITY to be set to FULL or DEFAULT depending on your conflict resolution needs.

CREATE TABLE tasks ( id UUID PRIMARY KEY, title TEXT NOT NULL, is_completed BOOLEAN DEFAULT false, project_id UUID, updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- Enable logical replication for Electric ALTER TABLE tasks REPLICA IDENTITY FULL;

2. Initializing PGLite and Electric

On the client side, you initialize PGLite and wrap it with the Electric client. This sets up the local storage (usually using IndexedDB) to persist the database across page reloads.

import { PGLite } from '@electric-sql/pglite'; import { Electrify } from 'electric-sql/pglite'; // Initialize PGLite const pg = new PGLite('idb://my-app-db'); // Electrify the database const electric = await Electrify.init(pg, { url: 'https://your-electric-service-url.com', appName: 'my-task-app' });

3. Defining and Syncing Shapes

The most powerful part of ElectricSQL is the ability to subscribe to data dynamically. You don't want to sync every task from every user; you only want the tasks relevant to the current project.

const shape = await electric.db.tasks.sync({ where: { project_id: currentProjectId } }); // Wait for the initial sync to complete await shape.synced;

Once shape.synced resolves, the local PGLite instance contains all the relevant data. Your UI can now query PGLite directly.

4. Reactive Queries

Because we are using PGLite, we can use standard SQL to query our data. Most integrations provide a hook-based approach for frameworks like React to make these queries reactive.

// Example of a reactive query hook const { results } = useQuery("SELECT * FROM tasks WHERE is_completed = false ORDER BY updated_at DESC"); return ( <ul> {results.map(task => ( <li key={task.id}>{task.title}</li> ))} </ul> );

When a change happens on the server (e.g., another user updates a task), Electric streams that change to the client, PGLite updates, and the UI automatically re-renders. Conversely, if the user checks a box while offline, PGLite updates instantly, the UI reflects it, and Electric queues the change to sync whenever the connection returns.

Handling Conflicts and Consistency

In any distributed system, conflicts are inevitable. What happens if two users update the same task description while offline?

ElectricSQL defaults to a Last Write Wins (LWW) resolution strategy based on causal timestamps. Because it uses a sophisticated replication protocol, it can guarantee "Causal Consistency." This means that if action A happened before action B, all clients will see the effects of action A before action B.

For more complex scenarios, developers can implement versioning columns or use specific CRDT (Conflict-free Replicated Data Type) patterns within their SQL logic, though Electric's built-in handling covers the vast majority of standard CRUD use cases.

Performance Considerations

While PGLite is remarkably fast, running a database in WASM does have overhead. Here are a few senior-level tips for maintaining performance:

  1. Index Strategically: Just like a server-side DB, PGLite needs indexes for performance. Don't forget to CREATE INDEX on columns used in WHERE clauses.
  2. Shape Granularity: Keep your Shapes small. Don't sync the content column of a blog post if you are only displaying a list of titles. Use Electric’s select capabilities to limit fields.
  3. WASM Cold Start: The first time a user loads the app, they have to download the WASM binary. Use service workers to cache the PGLite binary and the initial data set to make subsequent loads near-instant.
  4. Memory Management: PGLite runs in the browser's memory. For extremely large datasets (hundreds of thousands of rows), consider if the browser is the right place for that data or if you should use more aggressive filtering in your Shapes.

Why This Beats Traditional State Management

As an engineer, the biggest benefit isn't just the offline capability; it's the simplification of the frontend architecture.

In a traditional app, you have:

  • An API layer (Axios/Fetch)
  • A cache management layer (React Query)
  • A global state layer (Zustand/Redux)
  • Local UI state

In a local-first app with ElectricSQL and PGLite, your Database is your State. You no longer need to write complex logic to invalidate queries or manually update a cache after a mutation. You write to the DB, and the UI reacts. This "declarative data flow" significantly reduces the surface area for bugs.

Conclusion: The Path Forward

Local-first is no longer a niche requirement for "offline-only" apps. It is a premium architectural choice for any application where user experience and responsiveness are top priorities. By combining the power of Postgres (via PGLite) with the seamless replication of ElectricSQL, we can finally build web applications that feel as snappy and reliable as native desktop software.

Actionable Next Steps:

  1. Audit your latency: Identify the parts of your app where users spend the most time waiting for spinners.
  2. Experiment with PGLite: Replace a small piece of local state (like a complex filter or a multi-step form) with a PGLite instance to get a feel for SQL in the browser.
  3. Evaluate ElectricSQL: Spin up an Electric sync service against a staging database and see how easily you can replicate a single table to a frontend client.

The transition to local-first requires a shift in mindset, but the result—a resilient, lightning-fast application—is well worth the investment.