AppZyra AppZyra
Distributed Data • Published: 2026-02-02 • 13 min read

Offline Data Synchronization with Conflict-Free Replicated Data Types (CRDTs) and SQLite

Engineering multi-master, peer-to-peer data replication in mobile applications. State-based vs Op-based CRDTs, Last-Write-Wins registers with Hybrid Logical Clocks (HLC), and real-world SQLite integration.

Vaibhave — Principal Engineer & Founder

Architectural Key Takeaways

  • Traditional centralized database locks fail in distributed mobile systems where devices remain offline for hours or days.
  • Conflict-Free Replicated Data Types (CRDTs) mathematically guarantee that replicas converge to an identical state regardless of message arrival order.
  • Hybrid Logical Clocks (HLC) prevent clock skew on client devices from corrupting causality in Last-Write-Wins (LWW) conflict resolution.
  • Embedding CRDT metadata columns directly into SQLite tables enables transparent conflict resolution using standard SQL UPSERT syntax.
Table of Contents
  1. The Multi-Master Concurrency Dilemma
  2. Mathematical Foundations: Semilattices and Monotonicity
  3. Physical Clocks vs Hybrid Logical Clocks (HLC)
  4. Implementing LWW-Element-Set Directly in SQLite
  5. Sync Conflict Telemetry in Real-World Deployment

The Multi-Master Concurrency Dilemma

When multiple mobile devices operate offline, concurrent writes to the same entity are inevitable. A user edits a workout regimen on their iPad while on a flight, while simultaneously completing habit streaks on their iPhone. When both devices reconnect to the internet hours later, which state wins?

Centralized databases solve this through transactions, row-level locks, and two-phase commits. But on decentralized mobile devices with intermittent connectivity, locking a remote server is impossible. Without a formal mathematical model for convergence, systems descend into silent data loss or complex merge conflict dialogues that frustrate end users.

Mathematical Foundations: Semilattices and Monotonicity

CRDTs (Conflict-Free Replicated Data Types) solve this through bounded semilattice mathematics. Any binary merge operation between two states must satisfy three properties:

1. Commutativity: A ⊔ B = B ⊔ A (the order in which devices exchange messages does not matter).

2. Associativity: (A ⊔ B) ⊔ C = A ⊔ (B ⊔ C) (message grouping and batching does not alter the outcome).

3. Idempotence: A ⊔ A = A (duplicate network messages do not produce phantom side-effects).

If a merge function satisfies these three axioms, any cluster of devices is mathematically guaranteed to reach Strong Eventual Consistency as soon as all mutations have replicated, with zero central coordinator involvement.

Physical Clocks vs Hybrid Logical Clocks (HLC)

A naive approach to Last-Write-Wins (LWW) assigns `Date.now()` to mutations. However, physical hardware quartz clocks on smartphones are notoriously unreliable. Users manually adjust time zones, NTP synchronization steps clocks backwards, and hardware temperature drift introduces seconds of clock skew.

Hybrid Logical Clocks (HLC) combine physical wall time with Lamport logical counters. An HLC timestamp is strictly monotonic: it never moves backwards, even if the device’s physical clock jumps into the past.

Listing 1: Hybrid Logical Clock (HLC) Timestamp Implementation typescript
export class HybridLogicalClock {
  private lastPhysical: number = 0;
  private logicalCounter: number = 0;
  private readonly nodeId: string;

  constructor(nodeId: string) {
    this.nodeId = nodeId;
  }

  public now(): string {
    const physical = Date.now();
    if (physical > this.lastPhysical) {
      this.lastPhysical = physical;
      this.logicalCounter = 0;
    } else {
      this.logicalCounter += 1;
    }

    const p = this.lastPhysical.toString(16).padStart(12, '0');
    const c = this.logicalCounter.toString(16).padStart(4, '0');
    return `${p}:${c}:${this.nodeId}`;
  }

  public update(remoteTimestamp: string): void {
    const [remotePStr, remoteCStr] = remoteTimestamp.split(':');
    const remoteP = parseInt(remotePStr, 16);
    const remoteC = parseInt(remoteCStr, 16);
    const physical = Date.now();

    this.lastPhysical = Math.max(physical, this.lastPhysical, remoteP);
    if (this.lastPhysical === remoteP) {
      this.logicalCounter = Math.max(this.logicalCounter, remoteC) + 1;
    } else {
      this.logicalCounter = 0;
    }
  }
}

Implementing LWW-Element-Set Directly in SQLite

Rather than maintaining an abstract memory graph, we embed CRDT metadata columns directly into SQLite tables. Each mutable column or row is paired with an HLC timestamp and a tombstone flag for soft deletions.

Incoming replication batches merge directly through SQLite’s native `INSERT ... ON CONFLICT DO UPDATE` statement, ensuring that writes with older HLC timestamps are rejected at the database engine level.

Listing 2: Deterministic CRDT Merge Query in SQLite sql
INSERT INTO habit_logs (
  id, habit_id, status, hlc_timestamp, is_deleted
) VALUES (
  :id, :habit_id, :status, :hlc_timestamp, :is_deleted
)
ON CONFLICT(id) DO UPDATE SET
  status = CASE WHEN excluded.hlc_timestamp > habit_logs.hlc_timestamp THEN excluded.status ELSE habit_logs.status END,
  is_deleted = CASE WHEN excluded.hlc_timestamp > habit_logs.hlc_timestamp THEN excluded.is_deleted ELSE habit_logs.is_deleted END,
  hlc_timestamp = CASE WHEN excluded.hlc_timestamp > habit_logs.hlc_timestamp THEN excluded.hlc_timestamp ELSE habit_logs.hlc_timestamp END;

Production Telemetry in Real-World Deployment

In production across HabLoop’s cross-device users, concurrent write events occur in approximately 1.8% of daily sync transactions. Under the CRDT-HLC model, 100% of these occurrences resolved deterministically without throwing exceptions or corrupting relational foreign keys.

By leveraging mathematical guarantees directly inside the device’s local SQLite database, engineering teams eliminate edge-case bug tickets and deliver an unflinching, always-on software experience.

V
Authored by
Vaibhave
Principal Engineer & Founder
Principal Systems Architect at AppZyra. Specializing in high-throughput React Native, local-first SQLite runtimes, and distributed state synchronization.