↑ ↓ navigate↵ selectesc close

Local-First Web Apps: PGlite (WASM Postgres) & Real-Time Sync

course lessons.

1 Section · 5 Lessons
1

Core Architecture & Production Implementation

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 with new PGlite('opfs://') -> OPFS File System + Web Worker Host inside src/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 with db.live.incrementalQuery -> PGliteWorker Leader + Sub-Millisecond Diff inside src/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 with Electric HTTP Shapes -> Offset Cursor Resume + pg.electricSync() inside src/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 with Local Shadow + Outbox -> Persisted Mutation Queue + Deterministic Rebase inside src/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 with pgvector + tsvector -> HNSW Cosine Index + BM25 + Semantic RRF inside src/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:

Real PostgreSQL + pgvector running inside OPFS at 0.3ms query latency feels like magic! 🐾
💡
TIER LIST

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.

SPurrfect
1 pick

Runs 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.

Read Latency:0.2ms to 0.5ms local WASM execution
Offline Support:Transactional outbox + idempotent replay
Vector Search:Built-in pgvector (<=> cosine distance)
AStrong Pick
1 pick
BSolid w/ Caveats
1 pick
CSituational
0 picks
No platforms currently in C-Tier (Niche Fit, Early Preview, or Steep Quotas)
DPass / Caution
1 pick

Blocking 300ms Cloud REST Round-Trips on Every Keystroke or Checkbox Toggle

Spinner-Heavy Legacy Anti-Pattern

Forces users to stare at loading spinners on every interaction and loses unsaved work whenever Wi-Fi drops on a plane or train.

Fix:Write to local OPFS outbox first and sync in background
S: PurrfectA: Production ReadyB: Solid w/ CaveatsC: SituationalD: Pass
Click AJ to celebrate! 🐾

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:

📄 src/db/local-pglite.tstypescript
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 Dimension2026 CodingCat.dev Course PatternLegacy Industry DefaultProduction Impact at Scale
Compute & Cold StartsV8 Isolates / Native Browser Compositor (< 5ms)Heavy Container VMs / Main-Thread JS Bloat (500ms+)Eliminates tail-latency spikes on every request and interaction.
Contract & Type SafetyEnd-to-End TypeScript + Zod / GROQ TypeGenUntyped JSON payloads & manual interface driftCatches breaking schema changes in CI before deployment.
State & Database TopologyCloudflare D1 Batch / Durable SQLite / Sanity Content LakeExhausted TCP pools & unindexed N+1 loopsPredictable sub-10ms reads with zero connection pool errors.
Security & Multi-TenancyOAuth 2.1 PKCE + Better-Auth Scoped SessionsShared static API keys & unescaped DOM stringsZero-trust tenant isolation and $0 per-MAU SaaS tax.
AI & Agent ReadinessStreamable HTTP MCP + WebMCP + RFC 9727 + Daily Spend Caps20k-token headless DOM scraping & uncapped retry loopsCuts 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:

Ready to write code? Jump straight into Lesson 1: Running Real Postgres in the Browser with PGlite (WASM) & OPFS →

✏️ Visual Architecture Diagram

how this course connects together.

Follow AJ from first principles to production-ready architecture.

✏️ Visual Diagram: Local-First Web Apps: PGlite (WASM Postgres) & R…
✓ Good PatternVISUAL DIAGRAM
Visual Diagram: Local-First Web Apps: PGlite (WASM Postgres) & R…Visual architectural diagram showing: Step 1: Core Architecture & Production Implementation (Mental model & why it matters) -> Step 2: Hands-On Implementation (Under the hood & live code) -> Step 3: Ship It Purrfectly (✓ Production trade-offs). Step-by-step diagram breakdown for Local-First Web Apps: PGlite (WASM Postgres) & Real-Time Sync: start with Core Architecture & Production Implementation, implement Hands-On Implementation, and ship to production.✓Step 01Core Architecture & Prod…Mental model & why it matters✓Step 02Hands-On ImplementationUnder the hood & live code✓Step 03Ship It Purrfectly✓ Production trade-offsunroll the yarn✓ production ready
[Diagram Walkthrough]Step-by-step diagram breakdown for Local-First Web Apps: PGlite (WASM Postgres) & Real-Time Sync: start with Core Architecture & Production Implementation, implement Hands-On Implementation, and ship to production.
AAA Contrast Verified