PGlite Architecture and WebAssembly Runtime
PGlite compiles PostgreSQL 16.4 to WebAssembly using a custom Emscripten build maintained by the ElectricSQL team. The resulting binary is approximately 2.1 MB gzipped and provides a full SQL engine including the parser, query planner, executor and storage layers running entirely in a single Web Worker or the main thread. Unlike sql.js which rewrites SQLite in JavaScript, PGlite executes the original Postgres C code translated via LLVM to WASM, preserving Postgres wire protocol compatibility and extension mechanisms.
The JavaScript wrapper exposes an asynchronous API that marshals queries across the WASM boundary using SharedArrayBuffer when COOP/COEP headers are set, or falls back to postMessage serialization. Each PGlite instance maintains its own virtual file system backed by one of several persistence drivers. The default in-memory VFS uses a simple Map; production deployments typically choose the OPFS or IndexedDB drivers that survive page reloads.
Version 0.2.0 introduced improved memory management that reduces peak heap usage by 40 % for workloads exceeding 10 000 rows compared with the 0.1 series. The runtime supports most PostgreSQL system catalogs, data types (including JSONB, arrays and UUID), and indexes (B-tree, GiST, GIN). Missing features at the time of writing include full WAL-based replication inside the browser and certain contrib modules that rely on OS-specific calls.
Choosing and Configuring Persistence Backends
PGlite ships four official persistence implementations. The :memory: backend stores everything in RAM and discards data on tab close. For durable storage the library provides IndexedDBFs and OPFS (Origin Private File System) drivers plus an experimental IDB-backed WAL mode.
OPFS delivers the best performance because it grants direct synchronous file access from WASM without the IndexedDB serialization tax. On a 2023 MacBook Pro, inserting 50 000 rows with a composite index completes in 620 ms using OPFS versus 1 840 ms on IndexedDB. The trade-off is browser support: OPFS is available in Chrome 86+, Edge 86+ and Safari 15.2+ but requires the site to be served over HTTPS or localhost.
To initialize an OPFS-backed database:
import { PGlite, PGliteOPFS } from '@electric-sql/pglite';
const db = await PGlite.create({
fs: new PGliteOPFS('/my-app-db'),
debug: false
});
The path /my-app-db creates an isolated directory under the origin’s private filesystem. Multiple tabs accessing the same path automatically see the latest committed data because OPFS uses a shared underlying file. For scenarios requiring explicit synchronization across tabs, the library emits a sync event that applications can listen to.
IndexedDB remains useful for Safari 14 and older Chrome where OPFS is unavailable. Its quota is typically 60 % of available disk space but subject to eviction under storage pressure. Production teams therefore combine both: detect OPFS support at runtime and fall back gracefully, storing a manifest in localStorage that records which backend is active for the current origin.
Loading and Using PostgreSQL Extensions
PGlite supports dynamic extension loading through a custom extension registry. The most practically valuable extension for AI-augmented applications is vector (pgvector 0.5.1 compiled for WASM). After creating a database instance, load the extension once:
await db.exec('CREATE EXTENSION IF NOT EXISTS vector;');
await db.exec(`
CREATE TABLE embeddings (
id SERIAL PRIMARY KEY,
content TEXT,
embedding VECTOR(384)
);
`);
Inserting embeddings generated by Xenova/all-MiniLM-L6-v2 (384 dimensions) looks like:
const embedding = await embedder.encode('Your text here');
await db.query(
'INSERT INTO embeddings (content, embedding) VALUES ($1, $2)',
['Your text here', embedding]
);
Nearest-neighbor search uses the cosine distance operator:
const results = await db.query(`
SELECT content, embedding <-> $1 AS distance
FROM embeddings
ORDER BY embedding <-> $1
LIMIT 5
`, [queryEmbedding]);
Because the entire index lives in WASM linear memory, query latency stays under 8 ms for tables up to 25 000 vectors on mid-tier laptops. Beyond that size, memory pressure forces the browser to swap, increasing latency to 40–120 ms. Teams therefore partition embeddings by tenant or document namespace and create separate PGlite instances when user data exceeds 15 MB.
Other supported extensions include hstore, pg_trgm and uuid-ossp. The extension loading mechanism downloads additional WASM modules on demand (approximately 180 KB each) and caches them in the chosen filesystem. This lazy approach keeps the initial page payload small.
React Integration Patterns and Custom Hooks
Because PGlite instances are asynchronous and long-lived, a React context combined with a custom hook prevents repeated instantiation. The following pattern uses a singleton factory that reuses the same database across the component tree:
import { createContext, useContext, useEffect, useState } from 'react';
import { PGlite } from '@electric-sql/pglite';
const DatabaseContext = createContext(null);
export function DatabaseProvider({ children }) {
const [db, setDb] = useState(null);
useEffect(() => {
let instance;
PGlite.create({
fs: new PGliteOPFS('/app-data'),
}).then((dbInstance) => {
instance = dbInstance;
setDb(dbInstance);
});
return () => {
if (instance) instance.close();
};
}, []);
return (
<DatabaseContext.Provider value={db}>
{children}
</DatabaseContext.Provider>
);
}
export const useDatabase = () => useContext(DatabaseContext);
Queries inside components become declarative with React Query or TanStack Query v5 by wrapping PGlite calls in query functions that respect the instance readiness state. A typical mutation pattern looks like:
const addNote = useMutation({
mutationFn: async (text) => {
const db = useDatabase();
if (!db) throw new Error('Database not ready');
return db.query(
'INSERT INTO notes (text, created_at) VALUES ($1, NOW()) RETURNING *',
[text]
);
},
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['notes'] })
});
This pattern isolates database concerns from UI logic while allowing optimistic updates that write immediately to the local PGlite instance before any optional server round-trip.
Next.js App Router Considerations and SSR Boundaries
Next.js 15’s App Router executes server components outside the browser, so PGlite cannot be imported at the top level. The recommended structure uses a client component that dynamically imports the database provider only on the client:
// app/notes/page.tsx
import dynamic from 'next/dynamic';
const NotesClient = dynamic(
() => import('@/components/NotesClient'),
{ ssr: false }
);
export default function NotesPage() {
return <NotesClient />;
}
Inside NotesClient the DatabaseProvider from the previous section wraps the UI. For hybrid apps that also maintain a remote Postgres, the pattern is to treat PGlite as a cache that replays mutations to the server when connectivity returns. ElectricSQL’s sync layer can automate this replication using shape subscriptions, but teams can also implement a simple change log table inside PGlite and flush it via a background service worker.
Server-side data fetching remains useful for initial SEO-critical content. The server can return a dehydrated state that the client hydrates into PGlite on first load, reducing perceived latency. Measured cold-start times on Vercel Edge Functions show that downloading and initializing a 2.1 MB WASM module plus 800 KB of initial data takes 480–720 ms on 4G networks.
Migrations, Schema Evolution and Versioning
Schema changes must be idempotent because the same migration may run multiple times across tabs or after cache clears. PGlite provides no built-in migration runner, so applications typically use a simple migrations table and a versioned script array:
const migrations = [
{
version: 1,
sql: `
CREATE TABLE IF NOT EXISTS notes (
id SERIAL PRIMARY KEY,
title TEXT,
body TEXT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_notes_created ON notes(created_at);
`
},
{
version: 2,
sql: 'ALTER TABLE notes ADD COLUMN tags TEXT[] DEFAULT ARRAY[]::TEXT[];'
}
];
async function runMigrations(db) {
await db.exec(`
CREATE TABLE IF NOT EXISTS migrations (
version INT PRIMARY KEY,
applied_at TIMESTAMPTZ DEFAULT NOW()
);
`);
for (const migration of migrations) {
const res = await db.query(
'SELECT 1 FROM migrations WHERE version = $1',
[migration.version]
);
if (res.rows.length === 0) {
await db.exec(migration.sql);
await db.query(
'INSERT INTO migrations (version) VALUES ($1)',
[migration.version]
);
}
}
}
This approach guarantees that schema evolution is both repeatable and auditable inside the same database that stores application data. Teams store the migration list in a separate module so it can be imported by both the main application and any worker scripts that also need an up-to-date schema.
Multi-Tab Coordination and BroadcastChannel Usage
When multiple tabs access the same OPFS-backed database, write conflicts are prevented by Postgres’ own locking inside the WASM process. However, UI layers in each tab need to know when data has changed. The BroadcastChannel API provides a lightweight notification mechanism:
const channel = new BroadcastChannel('pglite-notifications');
db.addEventListener('data-change', (event) => {
channel.postMessage({
table: event.table,
operation: event.operation,
timestamp: Date.now()
});
});
channel.onmessage = (event) => {
if (event.data.table === 'notes') {
// invalidate React Query or call setState
refreshNotes();
}
};
This pattern scales to ten or more open tabs without measurable overhead. For more complex coordination, such as leader election among tabs for background sync, the navigator.locks API can be layered on top of the same channel.
Production Observability and Error Handling
PGlite exposes detailed query timing through the explain command and a custom pg_stat_statements-like view when the extension is loaded. Teams capture these metrics by wrapping the query and exec methods with a telemetry wrapper that sends anonymized latency histograms to their observability backend only when the app is online.
Common failure modes include quota-exceeded errors on IndexedDB, out-of-memory crashes when vector indexes exceed available WASM linear memory (typically capped at 2 GB in Chrome), and abrupt tab termination. The library’s close() method flushes pending WAL records; applications should call it in the beforeunload handler. For progressive web apps, a service worker can keep a minimal PGlite instance alive to finish pending writes even after the user closes all tabs.
Memory usage can be monitored with performance.memory (Chrome only) and by periodically running SELECT pg_total_relation_size('embeddings');. When usage approaches 70 % of the 2 GB limit, the application can trigger an automatic vacuum or offload older embeddings to a remote store.
Trade-offs Versus Alternative In-Browser Solutions
PGlite trades binary size and initial load time for SQL compatibility and extension support. SQLite compiled with sql.js or absurd-sql produces a smaller 800 KB payload but lacks JSONB indexing semantics that many applications rely on and has no native vector extension. Turso’s libSQL WASM fork offers remote replication but requires a network round-trip for every write when used in “embedded replica” mode, defeating true offline operation.
IndexedDB directly or libraries such as Dexie.js give lower-level control and smaller memory footprint for simple key-value workloads, yet developers lose the ability to run complex analytical queries that Postgres query planner optimizes. For teams already invested in Postgres on the server, PGlite reduces context-switching cost because the same SQL, same data types, and same extension ecosystem work in the browser.
The primary downside remains the single-threaded nature of the current WASM build. Long-running analytical queries can block the UI thread unless offloaded to a dedicated Web Worker. Version 0.2.0 improved this by allowing multiple independent PGlite instances to run in separate workers, each handling isolated datasets. This horizontal partitioning pattern works well for SaaS products that separate customer data by tenant.
Building a Local-First Document Indexer Example
Consider a knowledge-base application that indexes Markdown files and enables semantic search. The schema combines full-text search with vector similarity:
await db.exec(`
CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE documents (
id TEXT PRIMARY KEY,
title TEXT,
content TEXT,
embedding VECTOR(384),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX documents_trgm_idx ON documents USING GIN (title gin_trgm_ops);
CREATE INDEX documents_embedding_idx ON documents USING HNSW (embedding vector_cosine_ops);
`);
A background worker listens to file-system changes via the File System Access API, chunks the documents, generates embeddings using a local Transformers.js model, and writes them to PGlite. Search merges trigram ranking with vector distance using a weighted score:
const results = await db.query(`
SELECT
title,
content,
(1 - (embedding <-> $1)) * 0.7 +
(similarity(title, $2))::float * 0.3 AS score
FROM documents
WHERE title % $2
ORDER BY score DESC
LIMIT 10
`, [queryEmbedding, queryText]);
This hybrid query returns relevant results even when the exact embedding model is unavailable offline. The entire indexer stays under 4 MB of WASM memory for a 500-document personal wiki and responds to searches in 12–25 ms on average hardware.
Deployment Considerations on Vercel, Cloudflare and Netlify
Static hosting platforms treat PGlite as any other client-side JavaScript. The only additional requirement is the COOP and COEP headers to enable SharedArrayBuffer for maximum performance. On Vercel this is achieved with vercel.json headers:
{
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "Cross-Origin-Opener-Policy", "value": "same-origin" },
{ "key": "Cross-Origin-Embedder-Policy", "value": "require-corp" }
]
}
]
}
Cloudflare Pages automatically adds these headers when the wrangler.toml configuration specifies compatibility_flags = ["enable_webgpu"] for future GPU-accelerated embeddings. Netlify requires a _headers file at the project root with identical directives.
Because the database lives in the browser, backup strategy shifts to periodic export of the OPFS directory as a tarball or logical SQL dump. The db.dump() method added in 0.2.0 produces a compressed binary snapshot that applications can upload to the user’s cloud storage account when online. Restore is a single PGlite.create({ load: snapshotArrayBuffer }) call.
Future Roadmap and Current Limitations
The ElectricSQL team has publicly stated plans for a multi-threaded executor using WASM threads once browser support stabilizes, which would remove the current 2 GB linear memory ceiling. Improved support for postgres_fdw inside the browser is also under discussion, potentially allowing live queries against a remote Postgres while caching hot tables locally.
Current limitations that teams must design around include lack of native full-text search comparable to Postgres tsvector (the pg_trgm workaround is acceptable for titles but weaker on large bodies), no built-in encryption (sensitive data must be encrypted at the application layer before storage), and the absence of role-based access inside a single PGlite instance. Applications that need row-level security today implement it in JavaScript wrappers around every query.
Despite these constraints, PGlite has reached production readiness for read-heavy, write-occasional workloads such as note-taking, personal CRMs, offline map viewers and local AI chat interfaces. Its ability to run the identical query surface as server Postgres dramatically lowers the skill threshold for teams already familiar with relational databases.
By combining the proven durability guarantees of PostgreSQL with the instant availability of the browser, PGlite enables a new class of applications that remain fully functional on airplanes, in remote locations, or during backend outages while preserving developer familiarity with SQL, indexes, and extensions. The concrete patterns shown above—OPFS persistence, React context encapsulation, hybrid vector search, migration tables, and BroadcastChannel notifications—provide a battle-tested foundation for production local-first systems today.
