All writing
Engineering12 min read

PGlite and the Case for Local-First Web Apps

PGlite brings a real PostgreSQL engine to the browser via WASM, and that changes what a web interface can promise: instant reads, honest optimistic writes, and a working copy that survives the network.

The Database Is the UX: PGlite and the Case for Local-First Web Apps

Open a list of records, type three characters into the filter, and watch the spinner. It is tempting to blame React, the API, or the network. Often the real problem is simpler: the data lives somewhere else. Every keystroke has to cross a boundary before the interface can answer.

PGlite moves that boundary. It is a real PostgreSQL build compiled to WebAssembly and running inside the browser. Not a SQL-shaped cache, not a key-value store with a query parser bolted on. The same planner, executor, transactions, JSONB, CTEs, window functions, and extension system that teams rely on server-side are available in the tab. That sounds like a novelty until you use it in an interface where latency is visible. Then it becomes an architectural choice.

What PGlite actually is

PGlite is Postgres compiled to WASM, with no Linux VM underneath. It runs in the browser, Node.js, Bun, and Deno, and it can be ephemeral or persistent. In the browser, persistence is provided by IndexedDB (idb://) or, in a worker, OPFS (opfs-ahp://). The current 0.5.x line tracks PostgreSQL 18.6, so the semantics are not an approximation: constraints, indexes, transactions, jsonb, full-text search, and extensions such as pgvector are part of the same engine.

The cost is payload. PGlite is a few megabytes gzipped; the docs describe it as under 3 MB, while the 0.5.10 package reports 3.7 MB. The number that matters is the one you measure in your bundle, after compression and caching. For a data-rich application with long sessions, that is a one-time download. For a marketing page, it is the wrong trade.

What PGlite is not

PGlite is not a sync engine. It gives you a correct local database; it does not decide which rows belong on the client, how to merge concurrent edits, or what to do when two devices write the same field. Those are product decisions that need a sync layer. PGlite's own docs point to Electric for that.

Why it changes the UX

One dialect, fewer translation bugs

Most browser data layers ask you to translate. The server speaks PostgreSQL; the client speaks IndexedDB, a bespoke cache, or a subset of SQL. Every translation is a place where behavior drifts. A query that works in staging fails in the browser because the client engine does not support the same function, the same collation, or the same transaction semantics.

PGlite removes that class of bug. The same schema definitions, the same Drizzle models, the same SQL, and the same migration discipline can run on both sides. That is not just a developer convenience. It means the data rules the UI depends on are the data rules the server enforces. When a constraint rejects a write locally, it will reject it remotely too. When a query returns rows in a particular order locally, it can return them in the same order remotely.

Transactions make optimistic UI honest

Optimistic UI is easy to demo and hard to make correct. You update the screen before the server confirms, then hope the request succeeds. If it fails, you roll back, but the rollback is often a second guess: which parts of the screen changed, which cache entries are now stale, which pending writes depended on the failed one?

A local Postgres gives you a real transaction boundary. You can write the optimistic change and the outbox record in one transaction. If the write violates a constraint, nothing is committed and the UI can show the error immediately. If it succeeds, the outbox is the durable record of what still needs to reach the server. The UI is not pretending the write happened; it is reading the same committed state that will later be synchronized.

Cache vs. working copy

A cache is something you invalidate. A working copy is something you can reason about. That distinction is the whole argument for local-first.

Local reads change the latency budget

The fastest network request is the one that never happens. When the list, the filter, the detail view, and the command palette all read from a local database, the interaction budget stops being "how fast is the API?" and becomes "how fast is this query?" For indexed queries over a working set that fits on a device, that is often single-digit milliseconds or less. The network disappears from the critical path.

That does not make the network unimportant. It moves it. Sync latency, conflict resolution, and initial hydration become the new performance surface. But those are background concerns; they do not sit between the user and the next keystroke. A spinner on first load is acceptable. A spinner on every filter change is a design failure.

The boring parts are production-grade

The interesting demo is SELECT * FROM tasks. The production problem is migrations. PGlite gives you the same migration primitives as Postgres, and this project uses them seriously: a migration ledger, an advisory transaction lock, name and hash checks, and a refusal to run if an applied migration is no longer shipped. That last rule is important. It treats the browser database as a deployed system with a history, not as disposable cache that can be silently rebuilt.

Silent schema drift is the enemy

If the client can silently drift from the server schema, every bug becomes a heisenbug. The right response is a loud, recoverable failure — not a quiet rebuild that throws away the user's data.

How sync-disc uses it

This repository is a useful case study because the database is not bolted on at the edge. It is part of the boot path.

The client opens a PGliteWorker with dataDir: "idb://sync-disc" and the Electric sync extension, then wraps the result in Drizzle:

const worker = new PGliteWorkerCtor({ name: "pglite" });

const pg = await PGliteWorker.create(worker, {
  dataDir: "idb://sync-disc",
  extensions: { electric: electricSync() },
});

The worker matters. PGlite is fast, but it is still a database; running it on the main thread would put query work in the same queue as rendering. The worker keeps the UI thread free and gives the database a stable home across component trees.

Boot is treated as a state machine, not an implicit side effect:

  1. Acquire a cross-tab lock

    Prevents two tabs from running migrations concurrently against the same IndexedDB database.

  2. Race boot against a timeout

    startClientApp races the full boot sequence — WASM init, database open, migrations — against a deadline. A hung boot surfaces as a recoverable error, not a blank screen.

  3. Render the boot gate

    While booting, the UI shows a deliberate "Preparing your local workspace" state. On failure it offers reload and reset rather than leaving the user stuck.

  4. Hand off to the app

    On success the lock is held for the tab's lifetime, the Drizzle client is ready, and Electric sync begins in the background.

The schema shows the local-first architecture clearly. There is an outbox table for pending writes, a local_settings table for device-scoped state, and a local_migrations ledger. The client is not just reading a copy of server data; it is maintaining the state needed to write safely while offline and reconcile later.

Finally, the service worker precaches the app shell and content-hashed assets. The database and the shell are separate caches with separate lifecycles: the shell makes the app loadable, the database makes it useful. Both need to be designed, and both need a reset path.

The costs, honestly

PGlite is not free. The payload is the obvious cost, but it is not the only one.

Boot is visible

WASM compilation, database open, and migrations take time on first load. Hide it with a real boot state, cache aggressively, and make recovery possible.

Writes are heavier than SQLite

Postgres brings more machinery. For UI-sized writes this is usually invisible; for bulk imports, batch in transactions and measure.

Storage is a browser concern

IndexedDB and OPFS are subject to quotas and eviction. Safari is stricter than Chromium. Design for export, backup, and reset — not just persistence.

Tabs are a coordination problem

PGlite has a single connection. Multi-tab access needs a worker or a lock, and writes from two tabs need a plan.

Sync is still your job

PGlite does not resolve conflicts. A local database makes sync easier to reason about; it does not make it disappear.

The comparison with the other browser databases is mostly about workload. Kanopy Labs' comparison is a useful starting point for the order-of-magnitude differences: SQLite wins on payload and simple CRUD, DuckDB wins on large aggregations, and PGlite wins when PostgreSQL compatibility is the requirement. Its engine-version details are a snapshot from an earlier release; the current 0.5.x line has moved on to PostgreSQL 18.

PGliteSQLite WASMDuckDB WASM
Sweet spotPostgres parity, relational and JSONB data, sync-friendly appsSmall, fast CRUD with broad browser reachLarge analytical scans, Parquet/CSV, dashboards
CostMulti-megabyte payload, heavier writesSmallest payload, simpler engineMulti-megabyte payload, higher memory, not OLTP
Choose whenYour server is Postgres and the client needs the same semanticsPayload budget dominates and CRUD is the coreThe product is analytics, not transactions
Browser database comparison — the right choice depends on your workload

The right answer still depends on your workload, your users' devices, and how much of the data actually needs to live locally.

Where to take it next

The current implementation is a solid foundation. The next gains are mostly about removing the remaining network-shaped habits from the UI.

The point

PGlite is often framed as "Postgres in the browser," which is accurate but undersells the architectural shift. The interesting part is not that a database can run in a tab. The interesting part is that the tab can have a real working copy of the data, with real transactions, real constraints, and a real migration history.

That changes what the UI can promise. It can answer immediately. It can survive a tunnel. It can tell the user what is saved locally and what is still in flight. It can fail loudly and recover cleanly. None of that requires a server round trip on every interaction.

The network is still there. It is just no longer in the middle of every keystroke. For data-rich applications, that is the difference between an interface that feels fast and one that merely looks fast.

Sources