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