Local-First Web Apps: PGlite (WASM Postgres) & Real-Time Sync
course lessons.
1 Section · 5 LessonsCore Architecture & Production Implementation
- 1.1Running Real Postgres in the Browser with PGlite (WASM) & OPFS
Why wait 150 milliseconds for a cloud API round-trip just to filter a table of 5,000 rows? Let's boot genuine PostgreSQL compiled to WebAssembly right inside the browser with PGlite and OPFS.
RustPostgreSQLPGlite▶ Video + LessonStart Lesson → - 1.2Reactive SQL Subscriptions with PGlite Live Queries & Multi-Tab Broadcast
Keeping multiple browser tabs and React components in sync after a local database write usually turns into event-emitter spaghetti. Let's replace manual cache invalidation with PGlite Live Queries and multi-tab worker election.
ReactSQLPGlite+1▶ Video + LessonStart Lesson → - 1.3Streaming Cloud Postgres to the Browser with ElectricSQL Shapes
Writing your own real-time sync engine between cloud Postgres and the browser is a notorious distributed-systems trap. Let's stream filtered subsets of cloud Postgres directly into PGlite using ElectricSQL Shapes.
PostgreSQLPGlite▶ Video + LessonStart Lesson → - 1.4The Local-First Write Path: Optimistic Outbox, Rollbacks & Conflict Resolution
Read-path sync is easy, but what happens when a user edits ten records offline, closes their laptop, and reconnects hours later? Let's engineer a rock-solid Local-First write path with a durable OPFS outbox.
PGlite▶ Video + LessonStart Lesson → - 1.5Zero-Backend Hybrid Search in the Browser with PGlite pgvector & Full-Text RRF
You don't need a two-hundred-dollar-a-month cloud vector database to give users semantic search over their workspace. Let's combine PGlite's built-in pgvector extension with Postgres full-text search using Reciprocal Rank Fusion right inside the browser.
SupabasePostgreSQLPGlite+2▶ Video + LessonStart Lesson →
course overview.
1. Production Architecture Problem & Why We Built This Course
Run full Postgres inside the browser via WebAssembly with PGlite, persist to OPFS, sync state in real time with ElectricSQL Shapes, and build zero-latency offline-capable web apps. In production engineering teams, the gap between a quick weekend demo and a resilient, multi-tenant system comes down to three architectural boundaries: cold-start latency, compile-time contract validation, and predictable operational cost. Throughout Local-First Web Apps: PGlite (WASM Postgres) & Real-Time Sync, we strip away marketing buzzwords and build the exact TypeScript, edge compute, and structured data patterns that power CodingCat.dev in production.
Every lesson in this course pairs a dark-mode Architecture Diagram (contrasting the legacy anti-pattern on the left against the recommended 2026 production pattern on the right) with copy-pasteable TypeScript modules, automated verification checks, and an explicit Trade-Off Matrix. Whether you are reading the official PGlite by ElectricSQL: Official WebAssembly Postgres Documentation or pairing this course with our deep dive on Course: The Odin Project 7: Relational Databases, SQL Indexing & Drizzle ORM, you can apply every pattern directly to your own repository today.
🐾 AJ's Course Architecture Rule: Never adopt a tool just because it trended on social media. Measure its cold start in milliseconds, verify its TypeScript schema boundary at compile time, and check what happens to your cloud bill when traffic spikes 100x.
2. Lesson-by-Lesson Architectural Walkthrough (5 Lessons)
Work through the lessons in sequence to build the complete system from first principles, or jump directly to the specific architectural boundary you are solving right now:
- Lesson 1: Running Real Postgres in the Browser with PGlite (WASM) & OPFS: Replaces the
NETWORK ROUND-TRIP TAX (120ms API Fetch, IndexedDB Key-Value, Offline Crash)anti-pattern withnew PGlite('opfs://') -> OPFS File System + Web Worker Hostinsidesrc/db/pglite-worker.ts. Why wait 150 milliseconds for a cloud API round-trip just to filter a table of 5,000 rows? Let's boot genuine PostgreSQL compiled to WebAssembly right inside the browser with PGlite and OPFS. - Lesson 2: Reactive SQL Subscriptions with PGlite Live Queries & Multi-Tab Broadcast: Replaces the
MANUAL CACHE BUSTING (Stale Tab State, Full Table Re-Fetch, Custom Event Bus)anti-pattern withdb.live.incrementalQuery -> PGliteWorker Leader + Sub-Millisecond Diffinsidesrc/hooks/useLiveTasks.ts. Keeping multiple browser tabs and React components in sync after a local database write usually turns into event-emitter spaghetti. Let's replace manual cache invalidation with PGlite Live Queries and multi-tab worker election. - Lesson 3: Streaming Cloud Postgres to the Browser with ElectricSQL Shapes: Replaces the
CUSTOM WEBSOCKET GLUE (Bespoke Sync Server, Dropped Socket Gaps, No CDN Caching)anti-pattern withElectric HTTP Shapes -> Offset Cursor Resume + pg.electricSync()insidesrc/db/sync-shapes.ts. Writing your own real-time sync engine between cloud Postgres and the browser is a notorious distributed-systems trap. Let's stream filtered subsets of cloud Postgres directly into PGlite using ElectricSQL Shapes. - Lesson 4: The Local-First Write Path: Optimistic Outbox, Rollbacks & Conflict Resolution: Replaces the
NAIVE OPTIMISTIC UI (Ghost Writes, Server Rejects, Race Conditions)anti-pattern withLocal Shadow + Outbox -> Persisted Mutation Queue + Deterministic Rebaseinsidesrc/db/outbox-mutator.ts. Read-path sync is easy, but what happens when a user edits ten records offline, closes their laptop, and reconnects hours later? Let's engineer a rock-solid Local-First write path with a durable OPFS outbox. - Lesson 5: Zero-Backend Hybrid Search in the Browser with PGlite pgvector & Full-Text RRF: Replaces the
CLOUD VECTOR TAX ($200/mo Vector DB, Privacy Leakage, Keyword Blindness)anti-pattern withpgvector + tsvector -> HNSW Cosine Index + BM25 + Semantic RRFinsidesrc/db/hybrid-search.sql. You don't need a two-hundred-dollar-a-month cloud vector database to give users semantic search over their workspace. Let's combine PGlite's built-in pgvector extension with Postgres full-text search using Reciprocal Rank Fusion right inside the browser.
3. Alex's 2026 Ecosystem & Architectural Tier List
Before writing a single line of configuration, you need to know how the available platforms and patterns stack up in real production environments. Here is how I rank the ecosystem from S-Tier (our default production choice on CodingCat.dev) down to D-Tier anti-patterns to avoid:
Alex's 2026 Local-First Database & Sync Engine Tier List
Evaluating client-side persistence, sync latency, relational query power, and offline resilience for modern web apps.
PGlite (OPFS Web Worker) + ElectricSQL HTTP Shape Sync + Drizzle ORM ↗
Local-First Relational Postgres StackRuns genuine PostgreSQL and pgvector inside a Web Worker backed by OPFS, streams tenant-scoped deltas via HTTP Shapes, and updates React UI in under 1 millisecond.
Cloudflare D1 Read Replication + TanStack Query Optimistic Updates ↗
Edge-First SQLite ArchitectureIdeal when you want zero client WASM download size while still achieving 5ms-15ms edge SQLite reads and optimistic UI mutations.
Raw IndexedDB Object Stores with Manual Event Listeners ↗
Low-Level Browser Key-Value APIBuilt into every browser, but lacks relational JOINs, full-text search, vector similarity, and reactive query subscriptions.
Blocking 300ms Cloud REST Round-Trips on Every Keystroke or Checkbox Toggle
Spinner-Heavy Legacy Anti-PatternForces users to stare at loading spinners on every interaction and loses unsaved work whenever Wi-Fi drops on a plane or train.
4. Production Starter Configuration & Local Setup
To follow along with the code examples in Local-First Web Apps: PGlite (WASM Postgres) & Real-Time Sync, start with this baseline src/db/local-pglite.ts configuration. It enables strict TypeScript verification, observability tracing, and local development bindings that match production 1-to-1:
import { PGlite } from "@electric-sql/pglite";
import { live } from "@electric-sql/pglite/live";
import { vector } from "@electric-sql/pglite/vector";
export const localPg = await PGlite.create({
dataDir: "opfs-ahp://codingcat-local-pg",
extensions: { live, vector },
});5. Course-Wide Production Trade-Off Matrix
Every architectural decision involves trade-offs. Use this reference table during design reviews with your team to justify why we choose edge-native TypeScript, explicit schema validation, and deterministic workflows over legacy alternatives:
| Architectural Dimension | 2026 CodingCat.dev Course Pattern | Legacy Industry Default | Production Impact at Scale |
|---|---|---|---|
| Compute & Cold Starts | V8 Isolates / Native Browser Compositor (< 5ms) | Heavy Container VMs / Main-Thread JS Bloat (500ms+) | Eliminates tail-latency spikes on every request and interaction. |
| Contract & Type Safety | End-to-End TypeScript + Zod / GROQ TypeGen | Untyped JSON payloads & manual interface drift | Catches breaking schema changes in CI before deployment. |
| State & Database Topology | Cloudflare D1 Batch / Durable SQLite / Sanity Content Lake | Exhausted TCP pools & unindexed N+1 loops | Predictable sub-10ms reads with zero connection pool errors. |
| Security & Multi-Tenancy | OAuth 2.1 PKCE + Better-Auth Scoped Sessions | Shared static API keys & unescaped DOM strings | Zero-trust tenant isolation and $0 per-MAU SaaS tax. |
| AI & Agent Readiness | Streamable HTTP MCP + WebMCP + RFC 9727 + Daily Spend Caps | 20k-token headless DOM scraping & uncapped retry loops | Cuts token spend by 95%+ while preventing runaway bills. |
6. Official Specifications, Docs & Related CodingCat.dev Deep Dives
Bookmark these official specifications and related CodingCat.dev Courses, Blog Posts, and Podcast Episodes as you work through the lessons:
- Course: The Odin Project 7: Relational Databases, SQL Indexing & Drizzle ORM: Master relational normalization, B-Tree indexes, and Drizzle ORM schema design.
- Course: TanStack Start, Router & Drizzle ORM: Type-Safe Full-Stack React: Combine local-first PGlite reactivity with type-safe TanStack Router views.
- Course: Hybrid Web AI Architecture (Prompt API, WebGPU, Firebase & Workers): Pair in-browser pgvector semantic search with local WebGPU embeddings.
- Blog Post: Hybrid Web AI Routing with Local Browser Inference: How to run zero-cost local AI models alongside edge fallback routes.
- Podcast Episode: Firebase SQL with Data Connect: Why relational PostgreSQL schemas and vector extensions dominate modern app architectures.
- PGlite by ElectricSQL: Official WebAssembly Postgres Documentation: Running real PostgreSQL 17 and pgvector in the browser with OPFS persistence.
- ElectricSQL HTTP Shape Sync Engine Documentation: Streaming partial Postgres logical replication Shapes into local clients over HTTP.
- MDN Web Docs: Origin Private File System (OPFS) API: High-performance synchronous file access inside Web Workers for local SQLite and Postgres.
- pgvector Official GitHub Repository & HNSW Indexing Guide: Exact and approximate nearest-neighbor cosine similarity search inside PostgreSQL.
Ready to write code? Jump straight into Lesson 1: Running Real Postgres in the Browser with PGlite (WASM) & OPFS →
how this course connects together.
Follow AJ from first principles to production-ready architecture.
