<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Markiian Halabut: building local-first a]]></title><description><![CDATA[Markiian Halabut: building local-first a]]></description><link>https://markiianhalabut.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 19:41:28 GMT</lastBuildDate><atom:link href="https://markiianhalabut.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[A local-first sync engine for React Native with one HTTP endpoint and SQLite triggers]]></title><description><![CDATA[How we sync notes across iOS, Android and web with SQLite triggers, a per-user sequence and long polling. No WebSockets, no CRDT library.]]></description><link>https://markiianhalabut.hashnode.dev/a-local-first-sync-engine-for-react-native-with-one-http-endpoint-and-sqlite-triggers</link><guid isPermaLink="true">https://markiianhalabut.hashnode.dev/a-local-first-sync-engine-for-react-native-with-one-http-endpoint-and-sqlite-triggers</guid><category><![CDATA[React Native]]></category><category><![CDATA[SQLite]]></category><category><![CDATA[local first]]></category><category><![CDATA[offline first]]></category><category><![CDATA[Expo]]></category><dc:creator><![CDATA[Markiian Halabut]]></dc:creator><pubDate>Wed, 02 Dec 2026 11:06:28 GMT</pubDate><content:encoded><![CDATA[<p>Most "local-first" tutorials end at the point where it gets hard: two phones edit the same note offline, one of them dies halfway through an upload, and the user signs into a different account on the same device. We hit all three while building <a href="https://fluxo.today/">Fluxo</a>, a notes and spaced-repetition app that runs on iOS, Android and the web from one React Native codebase. This post is about the sync engine we ended up with: one HTTP endpoint, SQLite triggers and a per-user sequence number. No WebSockets, no CRDT library, no third-party sync service.</p>
<h2>The shape of the problem</h2>
<p>The app reads and writes its local SQLite database only. Screens never wait for the network. A background coordinator pushes local changes and pulls remote ones. We wanted four properties:</p>
<ol>
<li><strong>The app writes to its tables as usual.</strong> No "remember to call <code>sync()</code>" in every service.</li>
<li><strong>Works offline indefinitely</strong> and converges when the device comes back.</li>
<li><strong>Survives crashes and lost responses.</strong> A request that timed out may or may not have been applied.</li>
<li><strong>Cheap for the server.</strong> Most polls find nothing new, so an idle poll must cost almost nothing.</li>
</ol>
<h2>Capture writes with triggers, not with code</h2>
<p>Every synced table carries three columns: a text <code>id</code> (a UUID v7 minted on the client, never reused), a <code>version</code> (the last version the server confirmed, 0 means "never synced") and <code>updated_at</code>.</p>
<p>When the engine installs, it creates three triggers per synced table:</p>
<ul>
<li><code>AFTER INSERT</code> writes an <code>insert</code> row to an outbox table with the full row as <code>json_object(...)</code>.</li>
<li><code>AFTER UPDATE</code> (when a column other than <code>version</code> changed) writes an <code>update</code> with the new row and the list of changed columns.</li>
<li><code>AFTER DELETE</code> writes a <code>delete</code>.</li>
</ul>
<p>Because the capture runs inside the same SQLite transaction as the write, it cannot be skipped. It covers the ORM, raw SQL and foreign-key cascades alike. Each outbox row also records <code>base_version = OLD.version</code>, which the server uses to detect conflicts.</p>
<p>There is one catch: when the engine itself applies changes it pulled from the server, those writes must not be captured again, or every pull would echo back as a push. A single-row control table holds an <code>applying</code> flag that the triggers check. That flag only works if every statement, from the app and from the engine, goes through one serial SQL executor. A query that slips into the engine's apply transaction from somewhere else runs with capture suppressed and silently never syncs. We learned to enforce the single executor instead of documenting it.</p>
<p><strong>There is no</strong> <code>is_deleted</code> <strong>column on the client.</strong> A local delete is a real <code>DELETE</code>. The tombstone lives in the outbox and on the server. App queries stay simple and local <code>ON DELETE CASCADE</code> keeps working.</p>
<h2>One endpoint: push, then pull</h2>
<pre><code class="language-ts">SyncRequest  = { clientId, scope, cursor, mutations /* ≤ 200 */ }
SyncResponse = { acks, changes, cursor, hasMore, reset }
</code></pre>
<p>The client sends its pending mutations and the last cursor it saw. The server applies the mutations, then returns everything that changed after the cursor, including the client's own writes (applying them again is idempotent).</p>
<p><code>scope</code> is the user id the client believes it is syncing for. If it does not match the auth token, the server answers 409. That one check made a whole class of bugs impossible: a batch built while user A was signed in can never land in user B's data after a fast account switch.</p>
<h2>Ordering without clocks</h2>
<p>Timestamps lose writes: clocks drift and commits land late. Instead, every user has a row with a <code>head_seq</code> counter on the server.</p>
<ol>
<li>A push starts a transaction with an upsert on that row (<code>ON CONFLICT DO UPDATE ... RETURNING head_seq</code>). The row lock serializes pushes for one user.</li>
<li>Every written record takes <code>seq = ++head</code>.</li>
<li>Since allocation is serialized per user, sequence order is commit order. After a pull read up to <code>n</code>, no later commit can appear below <code>n</code>.</li>
</ol>
<p>A pull is then <code>WHERE seq &gt; cursor ORDER BY seq LIMIT n + 1</code>. And if <code>head &lt;= cursor</code>, the server answers at once: <strong>an idle poll is a single primary-key read.</strong> The cursor also carries an epoch. Restoring a backup rotates the epoch, and clients with an old cursor get <code>reset: true</code> and pull from scratch instead of trusting a sequence that went backwards.</p>
<h2>Conflicts: boring on purpose</h2>
<p>Each entity picks a policy:</p>
<ul>
<li><code>merge</code> (the default): the server applies the patch on top of the current record and bumps the version. This is field-level last-writer-wins. If one phone renames a note while another moves it into a folder, both changes survive.</li>
<li><code>reject</code>: a stale <code>base_version</code> is refused with <code>conflict</code> and the current record, and the client resolves it.</li>
</ul>
<p><strong>Delete always wins.</strong> An update to a tombstone is answered with <code>deleted</code>.</p>
<p>Mutations that belong to one user action (say, "create a deck and its first ten cards") share a group id. If the server refuses any member, none of the group is written. The refused one gets its reason and the rest get <code>aborted</code>. Without this, a half-applied command leaves orphans that are very hard to clean up later.</p>
<h2>Surviving lost responses</h2>
<p>Every mutation carries its own UUID. The server remembers processed mutation ids for 90 days. When a phone loses the response to a push and retries the same batch, the server finds the ids it has already seen and returns the stored outcome with the record's current state instead of applying them twice.</p>
<p>On the server, a push reads what it needs in two queries (ids already seen, records touched), decides the whole batch in memory and writes it in one multi-row upsert. That is a fixed handful of statements per request, not per mutation. Only if the database refuses that write does it replay mutation by mutation in savepoints, so one bad record is rejected instead of the whole batch. Errors that are not about the data, such as a lost connection or a deadlock, fail the request so the device retries rather than dropping work.</p>
<h2>Real time without WebSockets</h2>
<p>While the app is open, the client keeps a long poll (<code>POST /sync/wait</code>) that returns as soon as the user has changes past the cursor. On the backend, that is Postgres <code>LISTEN/NOTIFY</code> or Redis. When the app is in the background, polling backs off to 5 minutes. For a notes app this feels instant, and the server stays a stateless HTTP service that scales like any other.</p>
<h2>What we'd tell our past selves</h2>
<ul>
<li><strong>Make the database do the capture.</strong> Every "call sync after you save" approach leaks.</li>
<li><strong>Ids come from the client.</strong> Uniqueness that needs the server cannot work offline. We even refuse UNIQUE indexes on synced tables: two offline devices can create the same value, and the local index would reject the pull forever.</li>
<li><strong>Order by a server sequence, not by time.</strong></li>
<li><strong>Treat retries as normal.</strong> Idempotent mutation ids are cheaper than any clever "did it land?" logic.</li>
<li><strong>Keep the server dumb about the domain.</strong> It validates columns against the same table definitions the client uses, stores records and fans them out. Adding a synced table means declaring it once, not writing new endpoints.</li>
</ul>
<p>The engine syncs every note, folder and review in Fluxo across iOS, Android and <a href="https://app.fluxo.today/">the web app</a>. If you are building something similar and want to compare notes, I'm happy to answer questions in the comments.</p>
]]></content:encoded></item></channel></rss>