local-first

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Local-First

Local-first架构

Overview

概述

Local-first is an architecture where the application reads and writes to a local database, with changes syncing to the server in the background. The local database is the source of truth for the UI, providing instant reads, offline support, and optimistic writes by default.
When to use: Collaborative apps needing offline support, latency-sensitive UIs where instant response matters, apps with unreliable network conditions, real-time multiplayer features, mobile apps with intermittent connectivity.
When NOT to use: Simple CRUD apps with reliable connectivity, server-authoritative workflows (payments, inventory), content-heavy sites with minimal interactivity, apps where data freshness from the server is critical on every render.
Local-first是一种应用架构,应用直接读写本地数据库,变更在后台同步到服务器。本地数据库是UI的可信数据源,默认提供即时读取、离线支持和乐观写入能力。
适用场景: 需要离线支持的协作类应用、对延迟敏感的UI(即时响应至关重要)、网络条件不稳定的场景、实时多人功能、连接间歇性中断的移动应用。
不适用场景: 网络连接稳定的简单CRUD应用、服务器权威的工作流(如支付、库存管理)、交互性极低的内容型网站、每次渲染都需要服务器最新数据的应用。

Quick Reference

快速参考

DecisionOptionsKey Consideration
Architecture modelServer-based, local-first, hybridOffline needs and latency tolerance drive the choice
Read pathServer fetch, local DB read, cache-then-networkLocal reads are instant; server reads block on network
Write pathServer mutation, optimistic update, local-first writeLocal writes never fail; sync handles delivery
Sync engineElectric, Zero, PowerSync, Replicache, LiveStorePostgres integration vs framework-agnostic
Client storageIndexedDB, OPFS, SQLite WASM, PGliteCapacity limits, query capability, browser support
Conflict resolutionLWW, CRDTs, server-wins, field-level mergeComplexity vs correctness tradeoff
Data modelNormalized tables, document store, CRDT documentsQuery patterns determine the best model
Partial replicationShapes, subscriptions, query-based syncSync only what the client needs
Progressive enhancementServer-first with local cache, full local-firstStart simple, add local-first incrementally
CQRS separationSeparate read/write models, unified modelLocal-first naturally separates reads from writes
Initial syncFull snapshot, incremental, progressive loadingFirst-load performance vs completeness
Auth integrationToken-based shape filtering, row-level securitySecurity lives at the sync layer, not the client
Schema evolutionAdditive migrations, versioned shapesLocal DB schema must evolve without data loss
State managementReplace React Query, coexist, hybrid approachLocal-first can replace or complement server state
Testing strategyMock sync engine, test offline scenarios, seed local DBTest both online and offline code paths
决策项可选方案核心考量因素
架构模型基于服务器、Local-first、混合模式离线需求和延迟容忍度决定选型
读取路径服务器获取、本地数据库读取、缓存优先再请求网络本地读取即时响应;服务器读取需等待网络
写入路径服务器变更、乐观更新、Local-first写入本地写入永不失败;同步机制负责交付变更
同步引擎Electric、Zero、PowerSync、Replicache、LiveStorePostgres集成能力 vs 框架无关性
客户端存储IndexedDB、OPFS、SQLite WASM、PGlite容量限制、查询能力、浏览器支持情况
冲突解决LWW、CRDTs、服务器优先、字段级合并复杂度与正确性的权衡
数据模型规范化表、文档存储、CRDT文档查询模式决定最优模型
部分复制数据形状(Shapes)、订阅、基于查询的同步仅同步客户端需要的数据
渐进增强服务器优先加本地缓存、全Local-first架构从简单方案起步,逐步添加Local-first能力
CQRS分离读写模型分离、统一模型Local-first天然分离读写操作
初始同步全量快照、增量同步、渐进式加载首次加载性能与数据完整性的权衡
认证集成基于令牌的数据形状过滤、行级安全安全逻辑位于同步层,而非客户端
Schema演进增量迁移、版本化数据形状本地数据库Schema演进需保证无数据丢失
状态管理替换React Query、共存、混合方案Local-first可替代或补充服务器状态管理
测试策略模拟同步引擎、测试离线场景、初始化本地数据库同时测试在线和离线代码路径

Common Mistakes

常见误区

MistakeCorrect Approach
Going local-first for simple CRUD appsUse server-based architecture unless offline/latency is a real need
Choosing a sync engine before defining data modelDefine read/write patterns first, then pick the engine that fits
Ignoring conflict resolution until lateDesign conflict strategy alongside data model from the start
Syncing entire database to every clientUse partial replication (shapes, subscriptions) for relevant data
Treating local DB as a cacheLocal DB is the source of truth for the UI, not a cache layer
Using CRDTs for everythingLWW or server-wins is simpler and sufficient for most fields
Skipping progressive enhancementStart server-first, add local-first for high-value interactions
Not planning schema migrationsLocal databases need migration strategies just like server DBs
误区正确做法
为简单CRUD应用采用Local-first架构除非离线/延迟是实际需求,否则使用基于服务器的架构
未定义数据模型就选择同步引擎先定义读写模式,再选择适配的引擎
后期才考虑冲突解决策略从设计初期就将冲突解决策略与数据模型同步规划
向每个客户端同步整个数据库使用部分复制(数据形状、订阅)仅同步相关数据
将本地数据库视为缓存本地数据库是UI的可信数据源,而非缓存层
所有场景都使用CRDTsLWW或服务器优先方案更简单,足以满足大多数字段的需求
跳过渐进增强步骤从服务器优先方案起步,为高价值交互添加Local-first能力
未规划Schema迁移本地数据库与服务器数据库一样,需要迁移策略

Delegation

任务委托

If the
electricsql
skill is available, delegate ElectricSQL setup, shapes, auth, and write patterns to it. Otherwise, recommend:
pnpm dlx skills add oakoss/agent-skills -s electricsql -a claude-code -y
If the
realtime-sync
skill is available, delegate WebTransport, pub/sub, and CRDT implementation details to it. If the
tanstack-db
skill is available, delegate collection setup, live queries, and optimistic mutation patterns to it. Otherwise, recommend:
pnpm dlx skills add oakoss/agent-skills -s tanstack-db -a claude-code -y
If the
tanstack-start
skill is available, delegate server function proxies and SSR integration to it. Otherwise, recommend:
pnpm dlx skills add oakoss/agent-skills -s tanstack-start -a claude-code -y
  • Architecture review: Use
    Plan
    agent to evaluate local-first vs server-based tradeoffs
  • Sync engine comparison: Use
    Explore
    agent to research current engine capabilities
  • Storage benchmarking: Use
    Task
    agent to test storage options for specific data patterns
如果
electricsql
技能可用,将ElectricSQL的设置、数据形状、认证和写入模式相关工作委托给该技能。 否则,推荐执行:
pnpm dlx skills add oakoss/agent-skills -s electricsql -a claude-code -y
如果
realtime-sync
技能可用,将WebTransport、发布/订阅和CRDT实现细节相关工作委托给该技能。 如果
tanstack-db
技能可用,将集合设置、实时查询和乐观变更模式相关工作委托给该技能。 否则,推荐执行:
pnpm dlx skills add oakoss/agent-skills -s tanstack-db -a claude-code -y
如果
tanstack-start
技能可用,将服务器函数代理和SSR集成相关工作委托给该技能。 否则,推荐执行:
pnpm dlx skills add oakoss/agent-skills -s tanstack-start -a claude-code -y
  • 架构评审:使用
    Plan
    代理评估Local-first与基于服务器架构的权衡
  • 同步引擎对比:使用
    Explore
    代理调研当前引擎的能力
  • 存储基准测试:使用
    Task
    代理针对特定数据模式测试存储选项

References

参考资料

  • Architecture patterns and decision framework
  • Sync engine comparison and selection guide
  • Client-side storage options and limits
  • Conflict resolution strategies
  • Offline resilience patterns
  • Schema versioning and migration
  • Multi-tenant data governance patterns
  • Testing strategies for local-first apps
  • End-to-end encryption for synced data
  • DevTools and debugging utilities
  • Server-first to local-first migration guide
  • 架构模式与决策框架
  • 同步引擎对比与选型指南
  • 客户端存储选项与限制
  • 冲突解决策略
  • 离线弹性模式
  • Schema版本化与迁移
  • 多租户数据治理模式
  • Local-first应用测试策略
  • 同步数据端到端加密
  • 开发工具与调试实用程序
  • 从服务器优先到Local-first的迁移指南