Building Offline-Ready Apps with ElectricSQL and PGlite
For years, the standard approach to web application architecture has followed a predictable pattern: a thin client communicates with a remote server via REST or GraphQL, which in turn manages a centralized database. While this model is familiar, it introduces inherent friction—latency, the 'loading spinner' problem, and the fragility of connections in mobile or low-bandwidth environments.
As users demand more responsive, collaborative, and offline-capable experiences, the industry is shifting toward a 'Local-First' paradigm. By moving the primary data source to the client and synchronizing it with the server in the background, we can eliminate latency and provide a seamless user experience. In this article, we will explore how to implement this architecture using two transformative tools: PGlite, a WASM-based Postgres for the browser, and ElectricSQL, a synchronization layer designed to bridge the gap between local and remote databases.
The Local-First Philosophy
Local-first software is not just 'offline mode' as an afterthought; it is a fundamental architectural choice. In a local-first application, the client-side code interacts directly with a local database. The network is used for synchronization, not as a prerequisite for interaction.
This approach offers three primary advantages:
- Zero Latency: UI interactions are instantaneous because they don't wait for a round-trip to the server.
- Offline Resilience: Users can continue working regardless of their connection status.
- Simplified State Management: Instead of managing complex Redux or TanStack Query caches, the developer simply queries a local SQL database.
However, the challenge of local-first has always been synchronization and conflict resolution. This is where Conflict-free Replicated Data Types (CRDTs) and sophisticated sync engines come into play.
PGlite: Postgres in the Browser
Historically, client-side storage was limited to simple key-value stores like LocalStorage or IndexedDB, or the now-deprecated WebSQL. While libraries like RxDB or PouchDB provided better abstractions, they lacked the full power of a relational database.
PGlite changes this. It is a build of Postgres packaged as a WASM module that runs entirely within the browser's main thread or a Web Worker. Unlike previous attempts to run Postgres in WASM, PGlite is remarkably small (~3.7MB compressed) and starts up in milliseconds. It provides a full Postgres engine, including support for extensions, JSONB, and complex relational queries.
Why PGlite Matters
Using PGlite means your frontend and backend can share the same mental model. You can use the same schemas, the same SQL queries, and the same data types on both ends.
import { PGlite } from '@electric-sql/pglite'; const db = new PGlite(); await db.query("CREATE TABLE todos (id SERIAL PRIMARY KEY, task TEXT, done BOOLEAN);"); await db.query("INSERT INTO todos (task, done) VALUES ('Build local-first app', false);"); const result = await db.query("SELECT * FROM todos;"); console.log(result.rows);
ElectricSQL: The Synchronization Engine
Running a database locally is only half the battle. You need a way to synchronize that local data with a central 'source of truth' and other clients. ElectricSQL is a sync layer that sits on top of Postgres. It uses logical replication to stream data between the server-side Postgres and client-side databases like PGlite.
ElectricSQL handles the heavy lifting of:
- Transactional Integrity: Ensuring that data is synced in a consistent state.
- Shapes: Allowing clients to subscribe to specific subsets of the database (e.g., 'only sync the projects this user owns').
- Conflict Resolution: Managing concurrent edits using causal consistency and CRDT-inspired logic.
Implementing the Sync Flow
To build a synchronized application, you typically define a 'Shape.' A Shape is a set of related tables and rows that you want to sync to the client. This prevents the browser from trying to download an entire multi-terabyte production database.
1. Setting up the Server
ElectricSQL runs alongside your existing Postgres database. It listens to the Postgres write-ahead log (WAL) and provides an HTTP API that clients use to fetch updates.
2. Client-Side Integration
On the client, you use the Electric SDK to connect your PGlite instance to the Electric sync service.
import { PGlite } from '@electric-sql/pglite'; import { syncShape } from '@electric-sql/pglite-sync'; const db = new PGlite(); // Sync a specific 'Shape' from the server const shape = await syncShape(db, { url: 'https://api.my-electric-app.com/v1/shape/todos', where: "user_id = 'user_123'", }); // The PGlite instance is now automatically kept in sync // with the server-side 'todos' table for this user.
Handling Conflicts and CRDTs
One of the biggest hurdles in collaborative applications is conflict resolution. If User A and User B both edit the same todo item while offline, what happens when they reconnect?
ElectricSQL employs a sophisticated conflict resolution strategy based on Causal Integrity. While it isn't a pure CRDT library in the way Automerge or Yjs are, it achieves similar goals for relational data. It uses a 'Last Write Wins' (LWW) approach at the column level, backed by causal metadata. This ensures that even if updates arrive out of order, all clients eventually converge on the same state.
For more complex scenarios, such as collaborative text editing within a database field, you can integrate PGlite with specialized CRDT libraries, but for most relational business logic (updating statuses, changing titles, adding rows), the built-in causal consistency of ElectricSQL is sufficient and much easier to reason about.
Practical Example: A Collaborative Task Manager
Imagine a task manager where multiple users can comment on tasks. In a traditional app, you'd see a loading spinner every time you post a comment. In a local-first app using PGlite and ElectricSQL:
- The Write: When a user hits 'Submit,' the comment is immediately inserted into the local PGlite instance. The UI updates instantly.
- The Background Sync: The Electric SDK detects the change in the local WAL and pushes it to the Electric server.
- The Broadcast: The Electric server pushes that change to all other clients who have subscribed to that specific task's shape.
- The Update: Other users' local PGlite instances are updated, and their UI (which is likely observing the database) re-renders automatically.
This flow feels instantaneous to the user and requires significantly less 'glue code' for the developer. You aren't writing code to handle 'optimistic UI'—the UI is simply a reflection of the local database, which happens to be eventually consistent with the server.
Architectural Considerations
While this stack is powerful, it requires a shift in how you think about security and data modeling.
Security and Permissions
Since the client has a full database, you cannot rely on 'security through obscurity.' You must implement robust Row-Level Security (RLS) on the server-side Postgres. ElectricSQL respects these rules, ensuring that a client can only sync the data they are authorized to see.
Data Migrations
Migrations become more complex in local-first apps. If you change the schema on the server, you need a strategy to migrate the local PGlite instances on users' devices. ElectricSQL helps manage this by versioning shapes, but it remains a critical point of planning for any production deployment.
Storage Limits
IndexedDB (the storage backend for PGlite in the browser) has much higher limits than LocalStorage, but it isn't infinite. Developers must be mindful of how much data they are syncing. Using 'Shapes' to limit the scope of synced data is not just a performance optimization; it is a necessity.
The Business Case for Local-First
Beyond the developer experience, why should technical leaders invest in this stack?
- Reduced Server Costs: Much of the query logic is offloaded to the client's CPU. The server becomes a synchronization hub rather than a compute-heavy API.
- Increased Reliability: Your app works in subways, on planes, and in elevators. This leads to higher user retention and satisfaction.
- Faster Development Velocity: Once the sync layer is established, frontend developers spend less time writing API integration code and more time building features. SQL becomes the universal language for data access.
Conclusion
The combination of PGlite and ElectricSQL represents a significant milestone in web architecture. By bringing a full Postgres engine to the browser and providing a robust, transactionally aware sync layer, we can finally build applications that are as responsive as local desktop software while maintaining the collaborative power of the cloud.
To get started, follow these actionable steps:
- Audit your current state management: Identify areas where latency or offline issues frustrate users.
- Prototype with PGlite: Replace a small portion of your client-side state with a local PGlite instance to feel the power of SQL in the browser.
- Explore ElectricSQL Shapes: Look at how you can partition your existing Postgres data into syncable shapes.
Local-first is no longer a niche requirement for specialized tools; it is becoming the expected standard for high-quality web applications. Leveraging Postgres at both ends of the wire is the most pragmatic way to get there.