惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
有赞技术团队
有赞技术团队
S
Securelist
Attack and Defense Labs
Attack and Defense Labs
T
Threat Research - Cisco Blogs
L
LINUX DO - 最新话题
The GitHub Blog
The GitHub Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
S
Security Affairs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
WordPress大学
WordPress大学
美团技术团队
量子位
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
GbyAI
GbyAI
O
OpenAI News
IT之家
IT之家
F
Full Disclosure
W
WeLiveSecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Palo Alto Networks Blog
P
Privacy International News Feed
Webroot Blog
Webroot Blog
C
CERT Recently Published Vulnerability Notes
Latest news
Latest news
月光博客
月光博客
博客园 - 【当耐特】
N
News | PayPal Newsroom
Cloudbric
Cloudbric
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
The Exploit Database - CXSecurity.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Hugging Face - Blog
Hugging Face - Blog
博客园 - 三生石上(FineUI控件)
K
Kaspersky official blog
云风的 BLOG
云风的 BLOG
宝玉的分享
宝玉的分享
博客园 - 叶小钗
TaoSecurity Blog
TaoSecurity Blog
Martin Fowler
Martin Fowler
Simon Willison's Weblog
Simon Willison's Weblog
A
Arctic Wolf
Apple Machine Learning Research
Apple Machine Learning Research
D
Docker
aimingoo的专栏
aimingoo的专栏
Microsoft Security Blog
Microsoft Security Blog
PCI Perspectives
PCI Perspectives
Microsoft Azure Blog
Microsoft Azure Blog
雷峰网
雷峰网

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building an Efficient Local-First Developer Workflow with Offline-First Sync and Conflict Resolution
Rizwan Saleem · 2026-06-02 · via DEV Community

Rizwan Saleem

Building an Efficient Local-First Developer Workflow with Offline-First Sync and Conflict Resolution

Building an Efficient Local-First Developer Workflow with Offline-First Sync and Conflict Resolution

In modern software, developers juggle local experimentation, CI/CD pipelines, and remote collaboration. A local-first workflow emphasizes working primarily offline or on a local device, with eventual synchronization to remote services. This approach reduces friction in flaky networks, speeds up iteration, and provides a robust fallback during outages. This guide shows you how to design and implement a productive local-first workflow for a typical web app using a concrete stack: SQLite for local storage, a drift-tolerant synchronization protocol, and a simple conflict resolution strategy. It includes practical patterns, code snippets, and a step-by-step plan you can adapt to your project.

What you’ll learn

  • How to architect a local-first data model and sync layer
  • How to implement offline-first reads and writes with a local database
  • How to design a resilient, end-to-end synchronization protocol
  • How to handle conflicts deterministically and user-friendly
  • How to test offline-first behavior and simulate network partitions

Thoughtful preparation: choose your data model

  • Scope your data: identify the subset that benefits from local-first behavior. Typically this includes user notes, configurations, ephemeral app state, and cached API responses.
  • Use a single-source-of-truth per device: each device owns its own data, and changes are synchronized to others and the cloud.
  • Design for eventual consistency: accept that remote updates may arrive out of order or concurrently.

Stack overview (example)

  • Local store: SQLite (via an embedded driver) or a lightweight local-first database like SQLite with a simple ORM.
  • Sync layer: a background sync process that negotiates changes with a remote service using a resilient protocol (pull-based, push-based, or hybrid).
  • Remote backend: an API that supports optimistic updates, per-row versioning, and conflict metadata.
  • Timestamping and versioning: use vector clocks or per-record last_modified timestamps plus a per-device replica ID.

Section 1: Data model and local database setup

  • Model design
    • Each record has: id (UUID), type, payload (JSON), last_modified (ISO timestamp), deleted flag, and owner_device_id.
    • Implement a per-record versioning field to help resolve conflicts.
  • Database schema (SQL)
    • Create a table “items” to store domain objects.
    • Create a “changes” table to track local edits for syncing. Code example (SQLite schema):
  • CREATE TABLE items ( id TEXT PRIMARY KEY, type TEXT NOT NULL, payload TEXT NOT NULL, last_modified INTEGER NOT NULL, deleted INTEGER NOT NULL DEFAULT 0, owner_device_id TEXT NOT NULL );
  • CREATE TABLE changes ( id INTEGER PRIMARY KEY AUTOINCREMENT, item_id TEXT NOT NULL, change_type TEXT NOT NULL, timestamp INTEGER NOT NULL, payload TEXT, FOREIGN KEY(item_id) REFERENCES items(id) );

Section 2: Local read/write primitives

  • Write path
    • On write, upsert into items, set last_modified to now, push a change event into changes.
  • Read path
    • Reads return the latest non-deleted records, respecting a query predicate. Code sketch (TypeScript with a SQLite wrapper):
  • interface Item { id: string; type: string; payload: any; last_modified: number; deleted: boolean; owner_device_id: string; }
  • async function upsertItem(db, item: Item) { await db.run("REPLACE INTO items (id, type, payload, last_modified, deleted, owner_device_id) VALUES (?, ?, ?, ?, ?, ?)", [item.id, item.type, JSON.stringify(item.payload), item.last_modified, item.deleted ? 1 : 0, item.owner_device_id]); await db.run("INSERT INTO changes (item_id, change_type, timestamp, payload) VALUES (?, ?, ?, ?)", [item.id, "upsert", item.last_modified, JSON.stringify(item.payload)]); }
  • async function queryItems(db, whereClause, params) { return db.all("SELECT * FROM items WHERE deleted = 0 AND " + whereClause, params).then(rows => rows.map(r => ({ ...r, payload: JSON.parse(r.payload) }))); }

Section 3: The sync protocol: pull, push, and conflict handling

  • Core ideas
    • Each device maintains a local log of changes.
    • Sync happens in cycles: pull remote changes since last_sync, apply to local store; push local changes that aren’t yet acknowledged by the remote.
    • Solve conflicts deterministically using a "last writer wins" with version/timestamp tie-breakers, augmented by device_id to break ties.
  • Remote API expectations
    • GET /changes?since=TIMESTAMP to fetch remote changes
    • POST /changes with a batch of local changes
    • Each change carries: item_id, change_type, timestamp, payload, origin_device_id
  • Conflict resolution approach
    • If both sides modified the same item since last sync, compare last_modified and origin_device_id.
    • Implement a deterministic rule: the item with the higher last_modified wins; if equal, compare origin_device_id lexicographically.
    • We preserve a conflict log for user awareness if necessary.
  • Sync loop outline
    1. Pull: fetch remote_changes since last_sync.
    2. Apply: for each remote change, merge into local items using the resolution rule.
    3. Push: push unsynced local_changes to remote.
    4. Update last_sync to now.

Code sketch (pseudo-API):

  • async function pullChanges(remote, since) { const remoteChanges = await remote.getChanges(since); for (const c of remoteChanges) applyRemoteChange(c); }
  • function applyRemoteChange(change) { // resolve using local last_modified, etc. const local = await db.getItem(change.item_id); if (!local) upsertItem({ id: change.item_id, type: change.type, payload: JSON.parse(change.payload), last_modified: change.timestamp, deleted: false, owner_device_id: change.origin_device_id }); else { if (change.timestamp > local.last_modified) { // remote is newer upsertItem({ id: change.item_id, type: change.type, payload: JSON.parse(change.payload), last_modified: change.timestamp, deleted: false, owner_device_id: change.origin_device_id }); } else { // local newer, do nothing, or mark that a local change exists to push } } }
  • async function pushChanges(remote) { const changes = await db.getUnsentChanges(); await remote.postChanges(changes); markChangesAsSynced(changes); }

Section 4: Conflict resolution details and UX

  • Deterministic policy
    • Use last_modified as primary comparator; if equal, compare origin_device_id.
    • When conflicts are detected (both sides modified since last_sync), record a conflict object: { item_id, local, remote, resolution, timestamp } for auditing.
  • UX patterns
    • Silent autosync with occasional gala conflicts: present a non-intrusive “conflicts resolved automatically” log.
    • Offer a manual conflict reviewer UI for power users: show a list of items with a mini-diff and allow the user to pick which version to keep.
  • Optional: user-mediated resolution
    • If the app is note-taking or task management, you can surface a compare view and let users choose.

Section 5: Testing offline-first behavior

  • Create deterministic test scaffolding
    • Mock time and network: simulate offline, partial sync, dropouts.
    • Validate end-to-end: local write, go offline, write conflicting remote change, go online, run sync, verify correct final state per policy.
  • Test strategies
    • Unit tests for merge logic with synthetic item histories.
    • Integration tests that run a mock remote server to verify push/pull semantics.
    • Chaos testing: simulate partitions, delays, and reordering of events. Code example: a small unit test outline (pseudo-JS/TS)
  • function testConflictResolution() { // Set up two devices: A and B // Device A creates item X at t1 // Device B also edits item X at t1+1000 // Sync A pulls B’s change; apply merge rule // Assert final state matches last_modified winner }

Section 6: Performance and data considerations

  • Batching and compression
    • Batch changes to reduce network chatter; compress payloads with gzip or similar if sizes grow.
  • Throttling
    • Limit push frequency to avoid overwhelming the remote API; exponential backoff on failures.
  • Storage hygiene
    • Prune old changes after a retention window; consider a tombstone strategy for deletions.
  • Security and privacy
    • Encrypt sensitive payloads at rest; ensure transport uses TLS; authenticate devices with per-user credentials.

Section 7: Practical integration: a minimal runnable example

  • Project layout
    • src/
    • db.ts (SQLite wrapper and data models)
    • sync.ts (sync protocol)
    • api.ts (remote API client for changes)
    • models.ts (Item type definitions)
    • tests/
    • sync.test.ts (conflict resolution tests)
  • Minimal code snippets Code snippet: Item and change models
  • export interface Item { id: string; type: string; payload: any; last_modified: number; deleted: boolean; owner_device_id: string; }
  • export interface ChangeLog { id: number; item_id: string; change_type: string; timestamp: number; payload?: string; synced?: boolean; }

Code snippet: Applying a remote change (simplified)

  • async function applyRemoteChange(change: ChangeLog) { const local = await db.getItem(change.item_id); if (!local) { await upsertItem({ id: change.item_id, type: change.change_type, payload: JSON.parse(change.payload!), last_modified: change.timestamp, deleted: false, owner_device_id: change.origin_device_id }); } else if (change.timestamp > local.last_modified) { await upsertItem({ id: change.item_id, type: change.change_type, payload: JSON.parse(change.payload!), last_modified: change.timestamp, deleted: false, owner_device_id: change.origin_device_id }); } // else current local is newer; may want to mark conflict }

Section 8: Rollout plan and maintenance

  • Start small
    • Pick a feature or module that benefits most from offline work (e.g., notes, drafts).
    • Implement local-first support for that module and test end-to-end.
  • Gradual expansion
    • Extend to more data types and refine conflict handling.
  • Observability
    • Instrument metrics: number of conflicts resolved, push/pull durations, sync success rate.
    • Add user-facing logs for sync events to aid debugging.

Illustration: concept of local-first sync lifecycle

  • Local write creates a new record and logs a change.
  • The background sync pulls remote changes, merges using the deterministic rule, and pushes local changes that are not yet acknowledged.
  • Over time, devices converge to a consistent state, with conflicts resolved deterministically and user data preserved.

What to adapt for your project

  • Choose a suitable local store: SQLite is a solid default; you can also explore IndexedDB for web-only contexts.
  • Decide on a conflict policy that matches your domain: note edits may prefer latest change, while task assignments may require explicit user choice.
  • Ensure the remote API supports change history and per-record versioning to enable robust synchronization.

If you’d like, I can tailor this to your tech stack (React, React Native, Node.js, or a backend language you’re using), provide a concrete codebase skeleton, and a step-by-step migration plan for turning an existing app into a local-first experience.

Would you like a starter repository with a runnable example in your preferred language and framework? If yes, tell me your stack (e.g., React + SQLite via Expo, Node.js backend, or a full-stack setup) and whether you want a notes app, a task manager, or another domain as the example.

-

Rizwan Saleem | https://rizwansaleem.co