<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Mobile craftsmanship stories</title>
    <link>https://jenicek.dev</link>
    <description>Mobile craftsmanship stories</description>
    <language>en</language>
    <atom:link href="https://jenicek.dev/feed.xml" rel="self" type="application/rss+xml"/>
    <item>
      <title><![CDATA[Shared Logic Is Not Free]]></title>
      <link>https://jenicek.dev/posts/offline-first-type-boundary</link>
      <guid>https://jenicek.dev/posts/offline-first-type-boundary</guid>
      <pubDate>Sun, 08 Nov 2026 01:00:00 GMT</pubDate>
      <description><![CDATA[One Kotlin module runs our business rules on iOS, Android and a Node.js backend, so the rules cannot drift. But sharing it charges a toll in three currencies: `Long` narrows to `Double`, every database value arrives as a string, and coroutines become Promises driving a transaction whose rollback is yours on every exit path. Design the API narrow, and pay each toll on purpose.]]></description>
      <content:encoded><![CDATA[<p><em>"One module, three runtimes" is true for the rules. It is not free at the type boundary.</em></p>
<p class="tldr"><strong>TL;DR</strong> We ship one Kotlin module to iOS, Android, and a Node.js backend, so the business rules exist in
exactly one place and cannot drift. That is real and worth it. But sharing it charges a toll in three
currencies. Two are paid at the Kotlin-to-JavaScript boundary: numbers lose precision (<code>Long</code> becomes <code>Double</code>),
and coroutines become Promises driving a transaction on a connection the server owns, so every way out has to
end in a rollback. The third comes from one engine reading two different databases: every value arrives as a
string. Design the API narrow, and pay each toll on purpose.</p>
<blockquote>
<p>Part 15 of the <strong>Offline-First KMP</strong> series: field notes from a production winery app built on Kotlin
Multiplatform (KMP). <a href="https://jenicek.dev/posts/offline-first-witness-not-judge#the-kicker-the-same-kotlin-runs-on-a-nodejs-server">Part 11</a>
lands the headline: our backend runs the same Kotlin engine our phones run, compiled to JavaScript. This
post is the honest invoice for that, the three costs the headline skips.</p>
</blockquote>
<h2 id="the-setup-one-kotlin-module-three-runtimes">The Setup: One Kotlin Module, Three Runtimes</h2>
<p>The engine that validates events and derives state is one KMP module. It already compiled to Android and
iOS; we added a single JavaScript target, and the same source now builds a Node library, published as an npm
package the backend imports. This post is about what happens at the seam where compiled Kotlin meets
hand-written JavaScript.</p>
<h2 id="toll-1-kotlin-long-becomes-a-javascript-double">Toll 1: Kotlin <code>Long</code> Becomes a JavaScript <code>Double</code></h2>
<p>Kotlin has a real <code>Long</code>. JavaScript has one number type, an IEEE 754 double, and Kotlin/JS does not smuggle
a 64-bit integer across intact. So anything that is a <code>Long</code> on the Kotlin side crosses the boundary as a
<code>Double</code>.</p>
<p>You can see it in the facade signatures. A timestamp that is a <code>Long</code> internally is exposed to JavaScript as
a <code>Double</code>, and narrowed back with <code>.toLong()</code> on the inside:</p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#D73A49">public</span><span style="color:#D73A49"> fun</span><span style="color:#6F42C1"> validateIntake</span><span style="color:#24292E">(</span></span>
<span class="line"><span style="color:#6A737D">    // ...</span></span>
<span class="line"><span style="color:#6A737D">    // Long on the inside, Double at the boundary</span></span>
<span class="line"><span style="color:#24292E">    intakeDateMillis: </span><span style="color:#6F42C1">Double</span><span style="color:#24292E">?,</span></span>
<span class="line"><span style="color:#24292E">): </span><span style="color:#6F42C1">Array</span><span style="color:#24292E">&#x3C;</span><span style="color:#6F42C1">String</span><span style="color:#24292E">> </span><span style="color:#D73A49">=</span></span>
<span class="line"><span style="color:#24292E">    validator.</span><span style="color:#6F42C1">validateIntake</span><span style="color:#24292E">(</span><span style="color:#6A737D">/* ... */</span><span style="color:#24292E">, intakeDateMillis?.</span><span style="color:#6F42C1">toLong</span><span style="color:#24292E">())</span></span></code></pre>
<p>A <code>Double</code> carries integers exactly up to <code>2^53</code>, about 9 × 10¹⁵:</p>
<div class="diagram">
<div class="diagram-head">Which Longs survive as a Double</div>
<div class="diagram-rows">
<div class="diagram-row"><span class="diagram-row-name">Epoch-milliseconds timestamp</span><span class="diagram-tag">about 1.8 × 10¹²: fits with room to spare</span></div>
<div class="diagram-row is-derived"><span class="diagram-row-name">Large counter</span><span class="diagram-tag">can pass 2^53: rounded silently</span></div>
<div class="diagram-row is-derived"><span class="diagram-row-name">Synthetic id packed into an integer</span><span class="diagram-tag">can pass 2^53: rounded silently</span></div>
<div class="diagram-row is-derived"><span class="diagram-row-name">Nanosecond clock</span><span class="diagram-tag">about 1.8 × 10¹⁸: already past it</span></div>
</div>
</div>
<p>So for our data this is safe. But "safe for our data" is a decision, not a freebie: past that range the
boundary silently rounds, and you will not get a compile error telling you so. Know which of your numbers
are genuinely 64-bit, and keep them out of the arithmetic that crosses.</p>
<h2 id="toll-2-every-database-value-arrives-as-a-string">Toll 2: Every Database Value Arrives as a String</h2>
<p>The engine reads its database through one small interface, and that interface has exactly one way to read a
column:</p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#6A737D">/** Platform-agnostic row accessor for query results. */</span></span>
<span class="line"><span style="color:#D73A49">public</span><span style="color:#D73A49"> interface</span><span style="color:#6F42C1"> Row</span><span style="color:#24292E"> {</span></span>
<span class="line"><span style="color:#6A737D">    // every column, always a string</span></span>
<span class="line"><span style="color:#D73A49">    public</span><span style="color:#D73A49"> fun</span><span style="color:#6F42C1"> getString</span><span style="color:#24292E">(name: </span><span style="color:#6F42C1">String</span><span style="color:#24292E">): </span><span style="color:#6F42C1">String</span><span style="color:#24292E">?</span></span>
<span class="line"><span style="color:#24292E">}</span></span></code></pre>
<p>Numbers, booleans, timestamps, JSON: the engine receives them all as strings and parses them itself. The
reason is not the JavaScript boundary, or not only. The same engine reads SQLite on the phone and Postgres on
the server, and the two disagree about types: a boolean comes back as <code>1</code> or <code>0</code> from one and as <code>true</code> or
<code>false</code> from the other, and dates and JSON come back in different shapes too. A string is the one form both
databases can always produce, so the shared code asks for nothing else. On the server, the bridge that NestJS
hands the engine does the flattening before the engine sees a value:</p>
<div class="diagram">
<div class="diagram-head">Server bridge: Postgres value → string</div>
<div class="diagram-rows">
<div class="diagram-row"><span class="diagram-row-name">Dates</span><span class="diagram-tag"><code>toISOString()</code></span></div>
<div class="diagram-row"><span class="diagram-row-name">Numbers and booleans</span><span class="diagram-tag"><code>String(value)</code></span></div>
<div class="diagram-row"><span class="diagram-row-name">JSON columns</span><span class="diagram-tag"><code>JSON.stringify</code></span></div>
</div>
</div>
<p>So this toll is not strictly the price of crossing into JavaScript, and the phone pays it as well. It is the
price of one engine over two databases, which is the same bargain as one engine over three runtimes, seen from
the storage side.</p>
<p>The phone's upload path has a cousin of this problem: PowerSync keeps every local value as text, so we keep a
small, deliberate coercion layer that turns a string into the right JSON shape: a numeric-looking string
becomes a JSON number, a value that starts with <code>{</code> or <code>[</code> gets parsed as structured JSON, and everything else
stays a string. There is even a variant that keeps numeric-looking values <em>as strings</em> on purpose, for the
columns where "10.4" must not become a float. <a href="https://jenicek.dev/posts/offline-first-adapter-layer">Part 6</a> tells that story,
and <a href="https://jenicek.dev/posts/offline-first-generated-file">Part 7</a> is the bug you get from putting one column on the wrong side
of that split.</p>
<h2 id="toll-3-coroutines-become-promises-and-the-rollback-is-yours">Toll 3: Coroutines Become Promises, and the Rollback Is Yours</h2>
<p>Kotlin's concurrency is coroutines; JavaScript's is Promises. A <code>suspend</code> function cannot cross as-is, so the
facade wraps each one in <code>GlobalScope.promise { }</code>, which turns a suspending body into a real Promise the Node
code can <code>await</code> (<a href="#design-a-narrow-facade-and-let-the-host-own-the-database">the facade itself is below</a>). The
<code>GlobalScope</code> is deliberate rather than the usual code smell: the caller is Node, there is no parent Kotlin
scope to inherit, and the returned Promise <em>is</em> the lifetime handle.</p>
<p>What crosses with it is a transaction. <code>processEvent</code> runs its whole dispatch as one database transaction, on a
connection the server owns, opened and closed by Kotlin through the bridge. So every way out of that block has
to end in a rollback, and Kotlin decides what "every way out" means.</p>
<p>We learned that from a <code>TODO()</code>. Early on, a few event types were still unimplemented branches, and <code>TODO()</code>
throws <code>NotImplementedError</code>: an <code>Error</code>, not an <code>Exception</code>. Both the dispatcher and the bridge adapter caught
<code>Exception</code>:</p>
<div class="diagram">
<div class="diagram-head">A TODO() branch throws NotImplementedError</div>
<div class="diagram-fork">
<div class="diagram-branch">
<div class="diagram-branch-title">catch (e: Exception)</div>
<div class="diagram-branch-rule">back then, in two places</div>
<div class="diagram-line">the Error walks past both catches</div>
<div class="diagram-line">no rollback, no <code>PROCESSING_FAILURE</code></div>
<div class="diagram-line">event row stuck at <code>NOT_PROCESSED</code></div>
<div class="diagram-verdict is-bad">Transaction left to the host.</div>
</div>
<div class="diagram-branch">
<div class="diagram-branch-title">catch (e: Throwable)</div>
<div class="diagram-branch-rule">the fix: one word, twice</div>
<div class="diagram-line">the Error is caught like any failure</div>
<div class="diagram-line">rollback runs, the failure is recorded</div>
<div class="diagram-line">row locks released</div>
<div class="diagram-verdict is-ok">Kotlin closes what it opened.</div>
</div>
</div>
</div>
<p>Our server has a backstop, a <code>finally</code> that rolls back any judge connection still open. A host without one
keeps the transaction open, with its row locks held.</p>
<p>The same review asked which other exit could skip the cleanup, and the answer was cancellation. A cancelled
coroutine cannot suspend again: its next <code>await</code> throws <code>CancellationException</code> at once, and the rollback is an
<code>await</code> on the server's Promise. Nothing cancels these calls today, but the first timeout someone adds will. So
the adapter finishes its rollback outside cancellation:</p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#24292E">js.</span><span style="color:#6F42C1">beginTransaction</span><span style="color:#24292E">().</span><span style="color:#6F42C1">await</span><span style="color:#24292E">()</span></span>
<span class="line"><span style="color:#D73A49">try</span><span style="color:#24292E"> {</span></span>
<span class="line"><span style="color:#D73A49">    val</span><span style="color:#24292E"> result </span><span style="color:#D73A49">=</span><span style="color:#6F42C1"> block</span><span style="color:#24292E">()</span></span>
<span class="line"><span style="color:#24292E">    js.</span><span style="color:#6F42C1">commitTransaction</span><span style="color:#24292E">().</span><span style="color:#6F42C1">await</span><span style="color:#24292E">()</span></span>
<span class="line"><span style="color:#D73A49">    return</span><span style="color:#24292E"> result</span></span>
<span class="line"><span style="color:#24292E">} </span><span style="color:#D73A49">catch</span><span style="color:#24292E"> (e: </span><span style="color:#6F42C1">Throwable</span><span style="color:#24292E">) {          </span><span style="color:#6A737D">// not Exception: a TODO() is an Error</span></span>
<span class="line"><span style="color:#6F42C1">    withContext</span><span style="color:#24292E">(NonCancellable) { </span><span style="color:#6A737D">// finish even if we were cancelled</span></span>
<span class="line"><span style="color:#24292E">        js.</span><span style="color:#6F42C1">rollbackTransaction</span><span style="color:#24292E">().</span><span style="color:#6F42C1">await</span><span style="color:#24292E">()</span></span>
<span class="line"><span style="color:#24292E">    }</span></span>
<span class="line"><span style="color:#D73A49">    throw</span><span style="color:#24292E"> e</span></span>
<span class="line"><span style="color:#24292E">}</span></span></code></pre>
<h2 id="design-a-narrow-facade-and-let-the-host-own-the-database">Design a Narrow Facade, and Let the Host Own the Database</h2>
<p>None of this is an argument against the approach. It is an argument for building the boundary on purpose.
The engine writes every SQL statement itself, but never opens a database connection. It hands each statement
to one small interface, <code>DbExecutor</code>, and each host implements that interface to run the SQL on its own
database:</p>
<div class="diagram">
<div class="diagram-head">One engine, two hosts, one database interface</div>
<div class="diagram-fork">
<div class="diagram-branch">
<div class="diagram-branch-title">On the phone</div>
<div class="diagram-branch-rule">Kotlin all the way down, no gate</div>
<div class="diagram-line"><span class="diagram-key">database</span> PowerSync over SQLite</div>
<div class="diagram-line"><span class="diagram-key">implements</span> <code>PowerSyncDbExecutor</code></div>
<div class="diagram-line"><span class="diagram-key">runs</span> the engine's SQL on the device</div>
<div class="diagram-line"><span class="diagram-key">calls</span> the engine's suspend functions</div>
<div class="diagram-verdict is-ok">Provisional projection.</div>
</div>
<div class="diagram-branch">
<div class="diagram-branch-title">On the server</div>
<div class="diagram-branch-rule">NestJS, through the JavaScript gate</div>
<div class="diagram-line"><span class="diagram-key">database</span> Postgres, via TypeORM</div>
<div class="diagram-line"><span class="diagram-key">implements</span> <code>JsDbExecutor</code> in TypeScript</div>
<div class="diagram-line"><span class="diagram-key">runs</span> the engine's SQL on the server</div>
<div class="diagram-line"><span class="diagram-key">calls</span> <code>WineryJudgeJs</code>: strings in, Promises out</div>
<div class="diagram-verdict is-ok">Authoritative state.</div>
</div>
</div>
</div>
<p>On the phone there is no gate at all. The app wires the engine to SQLite and calls the same processor the
server runs, with typed Kotlin. Same judge, different weight: on the phone its answer is only provisional, a
projection that holds until the server's authoritative state syncs back:</p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#6A737D">// Wiring (Koin): the phone's DbExecutor is PowerSync over SQLite</span></span>
<span class="line"><span style="color:#6F42C1">single</span><span style="color:#24292E"> { </span><span style="color:#6F42C1">PowerSyncDbExecutor</span><span style="color:#24292E">(</span><span style="color:#D73A49">get&#x3C;</span><span style="color:#24292E">PowerSyncDatabase</span><span style="color:#D73A49">></span><span style="color:#24292E">()) }</span></span>
<span class="line"><span style="color:#6F42C1">single</span><span style="color:#24292E"> { </span><span style="color:#6F42C1">WineryProcessorEngine</span><span style="color:#24292E">(</span><span style="color:#D73A49">get&#x3C;</span><span style="color:#24292E">PowerSyncDbExecutor</span><span style="color:#D73A49">></span><span style="color:#24292E">(), </span><span style="color:#6A737D">/* ... */</span><span style="color:#24292E">) }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A737D">// Renaming a docket on the phone (simplified)</span></span>
<span class="line"><span style="color:#6A737D">// 1. check: a local no is real</span></span>
<span class="line"><span style="color:#D73A49">val</span><span style="color:#24292E"> errors </span><span style="color:#D73A49">=</span><span style="color:#24292E"> validationEngine.</span><span style="color:#6F42C1">validateDocket</span><span style="color:#24292E">(</span><span style="color:#6A737D">/* ... */</span><span style="color:#24292E"> name </span><span style="color:#D73A49">=</span><span style="color:#24292E"> event.name)</span></span>
<span class="line"><span style="color:#D73A49">if</span><span style="color:#24292E"> (errors.</span><span style="color:#6F42C1">isNotEmpty</span><span style="color:#24292E">()) </span><span style="color:#D73A49">return</span><span style="color:#24292E"> Result.</span><span style="color:#6F42C1">failure</span><span style="color:#24292E">(</span><span style="color:#6A737D">/* ... */</span><span style="color:#24292E">)</span></span>
<span class="line"><span style="color:#6A737D">// 2. witness: the event uploads</span></span>
<span class="line"><span style="color:#24292E">eventEngine.</span><span style="color:#6F42C1">recordDocketUpdate</span><span style="color:#24292E">(workspaceId, docketId, event, userId)</span></span>
<span class="line"><span style="color:#6A737D">// 3. provisional projection: the same rules, stays on the phone</span></span>
<span class="line"><span style="color:#24292E">processorEngine.</span><span style="color:#6F42C1">processDocketUpdate</span><span style="color:#24292E">(workspaceId, event)</span></span></code></pre>
<p>Typed events and suspend functions: no strings, no Promises. The server runs the same engine but reaches it
through the gate, in two small pieces. First, in Kotlin, one exported class whose methods take strings and
numbers. The event arrives as raw JSON and is decoded <em>inside</em>, where the sealed classes and generics are real
again:</p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#6F42C1">@JsExport</span></span>
<span class="line"><span style="color:#D73A49">public</span><span style="color:#D73A49"> class</span><span style="color:#6F42C1"> WineryJudgeJs</span><span style="color:#24292E">(db: </span><span style="color:#6F42C1">JsDbExecutor</span><span style="color:#24292E">) {</span></span>
<span class="line"><span style="color:#6A737D">    // Promises in, suspend out, rollback guaranteed</span></span>
<span class="line"><span style="color:#D73A49">    private</span><span style="color:#D73A49"> val</span><span style="color:#24292E"> dbAdapter </span><span style="color:#D73A49">=</span><span style="color:#6F42C1"> JsDbExecutorAdapter</span><span style="color:#24292E">(db)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#D73A49">    public</span><span style="color:#D73A49"> fun</span><span style="color:#6F42C1"> processEvent</span><span style="color:#24292E">(</span></span>
<span class="line"><span style="color:#24292E">        eventId: </span><span style="color:#6F42C1">String</span><span style="color:#24292E">,</span></span>
<span class="line"><span style="color:#24292E">        workspaceId: </span><span style="color:#6F42C1">String</span><span style="color:#24292E">,</span></span>
<span class="line"><span style="color:#24292E">        eventType: </span><span style="color:#6F42C1">String</span><span style="color:#24292E">,</span></span>
<span class="line"><span style="color:#24292E">        eventData: </span><span style="color:#6F42C1">String</span><span style="color:#24292E">,      </span><span style="color:#6A737D">// raw JSON, decoded inside</span></span>
<span class="line"><span style="color:#24292E">        schemaVersion: </span><span style="color:#6F42C1">Int</span><span style="color:#24292E">,</span></span>
<span class="line"><span style="color:#24292E">    ): </span><span style="color:#6F42C1">Promise</span><span style="color:#24292E">&#x3C;</span><span style="color:#6F42C1">Unit</span><span style="color:#24292E">> </span><span style="color:#D73A49">=</span><span style="color:#24292E"> GlobalScope.</span><span style="color:#6F42C1">promise</span><span style="color:#24292E"> {</span></span>
<span class="line"><span style="color:#6A737D">        // decode and validate, then write: Kotlin generates the SQL</span></span>
<span class="line"><span style="color:#24292E">        dbAdapter.</span><span style="color:#6F42C1">execute</span><span style="color:#24292E">(</span></span>
<span class="line"><span style="color:#032F62">            "UPDATE docket SET name = ? WHERE id = ?"</span><span style="color:#24292E">,</span></span>
<span class="line"><span style="color:#6F42C1">            listOf</span><span style="color:#24292E">(name, docketId),</span></span>
<span class="line"><span style="color:#24292E">        )</span></span>
<span class="line"><span style="color:#24292E">    }</span></span>
<span class="line"><span style="color:#24292E">}</span></span></code></pre>
<p>Then, in TypeScript, the host. It never writes SQL. It runs what Kotlin sends, on a connection it owns (simplified):</p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#D73A49">const</span><span style="color:#005CC5"> db</span><span style="color:#D73A49">:</span><span style="color:#6F42C1"> JsDbExecutor</span><span style="color:#D73A49"> =</span><span style="color:#24292E"> {</span></span>
<span class="line"><span style="color:#6A737D">  // Toll 2: every value becomes a string</span></span>
<span class="line"><span style="color:#6F42C1">  getAll</span><span style="color:#24292E">: </span><span style="color:#D73A49">async</span><span style="color:#24292E"> (</span><span style="color:#E36209">sql</span><span style="color:#24292E">, </span><span style="color:#E36209">params</span><span style="color:#24292E">) </span><span style="color:#D73A49">=></span></span>
<span class="line"><span style="color:#24292E">    (</span><span style="color:#D73A49">await</span><span style="color:#24292E"> runner.</span><span style="color:#6F42C1">query</span><span style="color:#24292E">(sql, params)).</span><span style="color:#6F42C1">map</span><span style="color:#24292E">(</span><span style="color:#E36209">row</span><span style="color:#D73A49"> =></span><span style="color:#24292E"> ({</span></span>
<span class="line"><span style="color:#6F42C1">      getString</span><span style="color:#24292E">: </span><span style="color:#E36209">name</span><span style="color:#D73A49"> =></span><span style="color:#6F42C1"> toText</span><span style="color:#24292E">(row[name]),</span></span>
<span class="line"><span style="color:#24292E">    })),</span></span>
<span class="line"><span style="color:#6A737D">  // Kotlin's SQL, run as-is</span></span>
<span class="line"><span style="color:#6F42C1">  execute</span><span style="color:#24292E">: </span><span style="color:#D73A49">async</span><span style="color:#24292E"> (</span><span style="color:#E36209">sql</span><span style="color:#24292E">, </span><span style="color:#E36209">params</span><span style="color:#24292E">) </span><span style="color:#D73A49">=></span><span style="color:#24292E"> { </span><span style="color:#D73A49">await</span><span style="color:#24292E"> runner.</span><span style="color:#6F42C1">query</span><span style="color:#24292E">(sql, params) },</span></span>
<span class="line"><span style="color:#6A737D">  // connection affinity: one pooled connection, kept until</span></span>
<span class="line"><span style="color:#6A737D">  // commit or rollback</span></span>
<span class="line"><span style="color:#6F42C1">  beginTransaction</span><span style="color:#24292E">: </span><span style="color:#D73A49">async</span><span style="color:#24292E"> () </span><span style="color:#D73A49">=></span><span style="color:#24292E"> {</span></span>
<span class="line"><span style="color:#24292E">    runner </span><span style="color:#D73A49">=</span><span style="color:#24292E"> dataSource.</span><span style="color:#6F42C1">createQueryRunner</span><span style="color:#24292E">()</span></span>
<span class="line"><span style="color:#D73A49">    await</span><span style="color:#24292E"> runner.</span><span style="color:#6F42C1">connect</span><span style="color:#24292E">()</span></span>
<span class="line"><span style="color:#D73A49">    await</span><span style="color:#24292E"> runner.</span><span style="color:#6F42C1">startTransaction</span><span style="color:#24292E">()</span></span>
<span class="line"><span style="color:#24292E">  },</span></span>
<span class="line"><span style="color:#6A737D">  // commitTransaction, rollbackTransaction, lockRows</span></span>
<span class="line"><span style="color:#24292E">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#D73A49">const</span><span style="color:#005CC5"> judge</span><span style="color:#D73A49"> =</span><span style="color:#D73A49"> new</span><span style="color:#6F42C1"> WineryJudgeJs</span><span style="color:#24292E">(db)</span></span>
<span class="line"><span style="color:#D73A49">await</span><span style="color:#24292E"> judge.</span><span style="color:#6F42C1">processEvent</span><span style="color:#24292E">(</span></span>
<span class="line"><span style="color:#24292E">  event.id, workspaceId, eventType, </span><span style="color:#005CC5">JSON</span><span style="color:#24292E">.</span><span style="color:#6F42C1">stringify</span><span style="color:#24292E">(eventData), version,</span></span>
<span class="line"><span style="color:#24292E">)</span></span></code></pre>
<p>That inversion is what lets one Kotlin module drive a Node backend without dragging Kotlin's runtime
assumptions across the wire with it.</p>
<h2 id="the-takeaways">The Takeaways</h2>
<ul>
<li><strong>"Shared logic, zero drift" is true for the logic, and only the logic.</strong> One implementation of the rules
is a real, large win: client and server cannot disagree, because there is no second copy to disagree. That
property survives the boundary perfectly. The <em>types</em> do not.</li>
<li><strong>A cross-language boundary is a boundary; budget for it.</strong> Numbers narrow to <code>Double</code>, and coroutines
become Promises, with a rollback you must guarantee on every exit path. One level down, one engine over two
databases means every value arrives as a string. None of these throws a compile error at you, so each one is
a decision you make on purpose or a bug you find in production.</li>
<li><strong>Narrow the gate deliberately.</strong> Cross primitives and JSON strings, decode to real types on the inside,
and let the host own the database connection. Anyone who sells you the boundary as seamless is selling you
the headline and skipping the invoice.</li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[Not Everything Deserves a Ledger]]></title>
      <link>https://jenicek.dev/posts/offline-first-not-everything-ledger</link>
      <guid>https://jenicek.dev/posts/offline-first-not-everything-ledger</guid>
      <pubDate>Sun, 08 Nov 2026 00:00:00 GMT</pubDate>
      <description><![CDATA[Event sourcing is not an on/off switch for the whole app, it is a per-operation decision. Our entities fall into three groups: ledger, where every write is an event; hybrid, where creating and deleting ride the plain sync queue but every edit goes through the ledger; and read-only lookups. The hybrid is not an unfinished migration: conflict detection has nothing to compare against on a row that did not exist a moment ago.]]></description>
      <content:encoded><![CDATA[<p><em>We event-source the entities whose history is the product. The interesting group is the one in between.</em></p>
<p class="tldr"><strong>TL;DR</strong> Event sourcing is usually discussed as an on/off switch for the whole app. In practice you decide it
per operation. Our entities fall into three groups: <strong>ledger</strong> entities, where every write is an event;
<strong>hybrid</strong> entities, where creating and deleting go through the plain sync queue but every edit goes through the
ledger; and <strong>read-only</strong> lookups that no device writes. The hybrid group looks like an unfinished migration. It
isn't: a row being created has no earlier version, so conflict detection has nothing to compare it against.</p>
<blockquote>
<p>Part 14 of the <strong>Offline-First KMP</strong> series: field notes from a production winery app built on Kotlin
Multiplatform (KMP), whose architecture <a href="https://jenicek.dev/posts/offline-first-witness-not-judge">Part 11</a> maps end to end.
It assumes <a href="https://jenicek.dev/posts/offline-first-auto-resolve">Part 13</a>: you know what a version snapshot is and how the
disjoint-column check works. This is the question that comes next, which nobody asks until they have built
one of these: <em>which</em> entities actually deserve that machinery.</p>
</blockquote>
<h2 id="three-entity-groups-ledger-hybrid-read-only">Three Entity Groups: Ledger, Hybrid, Read-Only</h2>
<p>Our entities fall into three groups, and the group decides how a write reaches the server, if it reaches it at
all.</p>
<div class="diagram">
<div class="diagram-head">Three entity groups, by write path</div>
<div class="diagram-rows">
<div class="diagram-row"><span class="diagram-row-name">Ledger: six entities</span><span class="diagram-tag">every write is an event</span></div>
<div class="diagram-row is-derived"><span class="diagram-row-name">Hybrid: eight entities</span><span class="diagram-tag">create and delete: sync queue<br>edit: event</span></div>
<div class="diagram-row"><span class="diagram-row-name">Read-only: a few dozen lookup tables</span><span class="diagram-tag">server-seeded, never written by a device</span></div>
</div>
</div>
<p><strong>Ledger.</strong> Dockets, wines, vessels, bottle runs, docket analyses, and docket certifications. The
client never uploads these rows directly at all. It records an event and paints a provisional projection
so the screen updates instantly; the server's engine derives the authoritative row and syncs it back.</p>
<p><strong>Hybrid.</strong> Growers, varietals, additive definitions, manufacturers, and the packaging types. You can create
one of these offline and the sync layer uploads the row directly, the ordinary way, and you can delete one the
same way. But you cannot edit one that way. A local edit is applied for the screen and then dropped before the
wire; the edit travels as an event instead, so the server stays the authoritative writer for every change.</p>
<p><strong>Read-only.</strong> Status tables, type lookups, the genuinely static rows. A few dozen of them, seeded
for each workspace by the server, synced down, and never written by a device. Customising them for a winery
is a server-side migration, not something the app does. The connector does not upload them and the server would
refuse the row if it did. No events, no versions, and no conflicts, because the phone is never the writer.</p>
<p>Yes, creating and deleting catalog rows is the plain queue this series has spent several posts criticising, and
we shipped it on purpose: last write wins only loses data when there is something to lose.</p>
<h2 id="why-hybrid-entities-split-create-from-edit">Why Hybrid Entities Split Create From Edit</h2>
<p>The hybrid group is the one that raises eyebrows, so here is the actual reason, and it is not gradual migration.</p>
<p>Conflict detection works by comparison. An event carries a version snapshot of what the user was looking at, and
on sync the server compares that snapshot against the current state. That comparison is the whole mechanism.</p>
<p>Now try to apply it to a row being created. There is no previous version. There is nothing on the server to
compare the snapshot against, because a moment ago the row did not exist. The machinery is not expensive here,
it is <em>inapplicable</em>. You are paying for a comparison that has no second operand.</p>
<p>The failure modes differ too, and that is the part that decides the trade:</p>
<div class="diagram">
<div class="diagram-head">Two people, one grower, both offline</div>
<div class="diagram-fork">
<div class="diagram-branch">
<div class="diagram-branch-title">Both create it</div>
<div class="diagram-branch-rule">plain sync queue</div>
<div class="diagram-line">both uploads succeed: two growers</div>
<div class="diagram-line">a duplicate anyone can see</div>
<div class="diagram-verdict is-ok">Visible, and a human can fix it.</div>
</div>
<div class="diagram-branch">
<div class="diagram-branch-title">Both edit it</div>
<div class="diagram-branch-rule">if it rode the queue too</div>
<div class="diagram-line">last write wins: one edit is gone</div>
<div class="diagram-line">no duplicate, no flag, no log</div>
<div class="diagram-verdict is-bad">Silent data loss.</div>
</div>
</div>
</div>
<p>So the hybrid group gives each operation the mechanism its failure calls for. Creating a grower rides the plain queue,
because its worst case is a duplicate somebody will see. Editing one goes through the ledger, because its worst
case is an edit nobody will ever know was lost.</p>
<h2 id="event-sourcing-per-operation-not-per-entity">Event Sourcing per Operation, Not per Entity</h2>
<p>That is the transferable part, and it is why "do you event-source everything?" is the wrong question.</p>
<p>Two questions decide a path, and they are independent:</p>
<ol>
<li><strong>Will somebody need to audit this operation later?</strong> Grapes arriving as a docket is part of the winery's
story; someone will eventually ask who moved that wine and when. Adding a row to the varietal list is data
entry, and nobody has ever asked me to audit the history of a lookup table.</li>
<li><strong>Can this operation destroy work somebody else did?</strong> Edits can. Creations mostly cannot; the worst case
is a duplicate.</li>
</ol>
<p>Put together, the two answers pick the path:</p>
<div class="diagram">
<div class="diagram-head">Two questions, three paths</div>
<div class="diagram-rows">
<div class="diagram-row"><span class="diagram-row-name">Audited later, and can destroy work</span><span class="diagram-tag">ledger</span></div>
<div class="diagram-row is-derived"><span class="diagram-row-name">Creating can't destroy work, editing can</span><span class="diagram-tag">hybrid</span></div>
<div class="diagram-row"><span class="diagram-row-name">Not audited, can't destroy work</span><span class="diagram-tag">plain sync queue</span></div>
</div>
</div>
<p>The middle row is our hybrid group: common, and rarely modelled. The bottom row is not a compromise, it is
correct; none of our entities needs it, because the lookups skip the question entirely: no device writes them.</p>
<p>A ledger is not free: every event type costs a payload, a validator, a processor and a test. Spend that on
renaming a bottle size and event sourcing earns its reputation for being heavy.</p>
<h2 id="doesnt-the-event-ledger-slow-down-as-it-grows">Doesn't the Event Ledger Slow Down as It Grows?</h2>
<p>No, and the reason is the sync layer. The server applies each event once, when it arrives, and the phone reads
state from rows that are already computed:</p>
<div class="diagram">
<div class="diagram-head">One event, from arrival to screen</div>
<div class="diagram-timeline">
<div class="diagram-tick"><div class="diagram-tick-label">Event arrives</div><div class="diagram-tick-tag">appended to the ledger</div></div>
<div class="diagram-window" style="flex-grow: 1">
<div class="diagram-window-ticks">
<div class="diagram-tick is-compare"><div class="diagram-tick-label">Engine applies it once</div><div class="diagram-tick-tag">writes the entity rows</div></div>
</div>
<div class="diagram-window-label">On the server</div>
</div>
<div class="diagram-tick"><div class="diagram-tick-label">Sync streams the rows</div><div class="diagram-tick-tag">to every phone</div></div>
<div class="diagram-tick"><div class="diagram-tick-label">Phone reads the rows</div><div class="diagram-tick-tag">plus its own<br>unsent events</div></div>
<div class="diagram-tick is-skip"><div class="diagram-tick-label">Replay the ledger</div><div class="diagram-tick-tag">never on a device</div></div>
</div>
</div>
<p>No device ever replays the ledger to learn what is in a tank. The log is left with two jobs: the timeline,
and a conflict check that only looks back to the version the user saw.</p>
<h2 id="declare-each-entitys-group-in-one-place">Declare Each Entity's Group in One Place</h2>
<p>Once entities live in different groups, the group decides how every one of their writes travels. Yet no
single place says which group an entity is in: it is spread over three lists that have to agree. Say next
season you add barrel suppliers to the catalog, as a hybrid entity like growers:</p>
<div class="diagram">
<div class="diagram-head">Making barrel suppliers a hybrid entity</div>
<div class="diagram-fork">
<div class="diagram-branch">
<div class="diagram-branch-title">Three lists, kept by hand</div>
<div class="diagram-branch-rule">each one edited separately</div>
<div class="diagram-line"><span class="diagram-key">conflict check</span> tracks its versions</div>
<div class="diagram-line"><span class="diagram-key">upload connector</span> accepts its creates</div>
<div class="diagram-line"><span class="diagram-key">upload rule</span> sends its edits as events</div>
<div class="diagram-verdict is-bad">Miss one, and writes get refused.</div>
</div>
<div class="diagram-branch">
<div class="diagram-branch-title">One entry per table</div>
<div class="diagram-branch-rule">the three lists are derived from it</div>
<div class="diagram-line"><code>barrel_supplier</code> &rarr; hybrid</div>
<div class="diagram-line">all three settings follow</div>
<div class="diagram-line">a new table can't land half set up</div>
<div class="diagram-verdict is-ok">Nothing to keep in step.</div>
</div>
</div>
</div>
<p>Forget the upload rule on the left, and the phone uploads direct edits that the server refuses. So if you build
one of these, write each entity's group down once and derive the three lists from it, or at least add a test
that fails when they disagree. It is the same idea as <a href="https://jenicek.dev/series/offline-first-kmp#part-16">Part 16</a>: when
correctness depends on metadata staying in step, let the build check it, not the next person's memory.</p>
<h2 id="the-takeaways">The Takeaways</h2>
<ul>
<li><strong>Event sourcing is a per-operation decision, not an architecture-wide one.</strong> Ask it per write, not per app,
and expect the answer to differ between creating a thing and changing it.</li>
<li><strong>Conflict detection needs something to compare against.</strong> On creation there is no previous version, so the
machinery is not costly there, it is inapplicable. That alone justifies the hybrid group.</li>
<li><strong>Match the mechanism to the failure mode.</strong> Duplicate rows and silent lost edits are different problems.
Paying ledger prices to prevent duplicates is overkill; paying queue prices and losing edits is negligence.</li>
<li><strong>Declare each entity's group in one place.</strong> Spread over several lists, it drifts; derive them from one
declaration, so the next table you add lands in the right group.</li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[A Version Bump Is Not a Conflict]]></title>
      <link>https://jenicek.dev/posts/offline-first-auto-resolve</link>
      <guid>https://jenicek.dev/posts/offline-first-auto-resolve</guid>
      <pubDate>Sun, 01 Nov 2026 01:00:00 GMT</pubDate>
      <description><![CDATA[When two people edit the same entity offline, the server tries to auto-resolve first: disjoint columns mean no real disagreement. Simple on paper. In production it broke three times, on the intervening window, equal values and concurrency, and each break taught the same lesson: a version mismatch is not yet a conflict, and when unsure, fail closed and ask a human.]]></description>
      <content:encoded><![CDATA[<p><em><a href="https://jenicek.dev/posts/offline-first-witness-not-judge#conflict-as-a-decision">Part 11</a> showed you auto-resolve in one clean line. Here's everything that clean line hides.</em></p>
<p class="tldr"><strong>TL;DR</strong> When two people edit the same entity offline, our server tries to auto-resolve before bothering
anyone: if their edits touched <em>disjoint</em> columns, there is no real disagreement, so it applies both. Simple
on paper. In production the idea broke three times, and each break taught the same lesson: a version
mismatch is not yet a conflict, and when you are unsure whether it is one, you ask a human rather than guess.</p>
<blockquote>
<p>Part 13 of the <strong>Offline-First KMP</strong> series: field notes from a production winery app built on Kotlin
Multiplatform (KMP). <a href="https://jenicek.dev/posts/offline-first-witness-not-judge#conflict-as-a-decision">Part 11</a> sums up
conflict auto-resolution in one line: <em>disjoint columns resolve themselves, real overlaps go to a
human.</em> That line is true, but not the whole story. This post covers the three things that broke it in
production, and why the safe answer is to fail closed.</p>
</blockquote>
<h2 id="the-clean-version-version-snapshots-and-disjoint-columns">The Clean Version: Version Snapshots and Disjoint Columns</h2>
<p>Every event our client records carries a <strong>version snapshot</strong>: the version of each entity the user was
looking at when they acted. Two cellar hands edit the same docket offline, both at v3. The first edit lands
and makes v4. The second arrives still claiming v3: a mismatch, but only a <em>suspicion</em>. So the server
compares the columns the two edits wrote:</p>
<div class="diagram">
<div class="diagram-head">Second edit arrives: v3 ≠ v4</div>
<div class="diagram-fork">
<div class="diagram-branch">
<div class="diagram-branch-title">Disjoint columns</div>
<div class="diagram-branch-rule">one renamed, the other changed the date</div>
<div class="diagram-line"><span class="diagram-key">first</span> wrote <code>name</code></div>
<div class="diagram-line"><span class="diagram-key">second</span> wrote <code>date</code></div>
<div class="diagram-verdict is-ok">No disagreement: both apply.</div>
</div>
<div class="diagram-branch">
<div class="diagram-branch-title">Same column, different values</div>
<div class="diagram-branch-rule">both renamed the docket</div>
<div class="diagram-line"><span class="diagram-key">first</span> wrote <code>name</code></div>
<div class="diagram-line"><span class="diagram-key">second</span> wrote <code>name</code></div>
<div class="diagram-verdict is-bad">A real conflict: a human decides.</div>
</div>
</div>
</div>
<p>That is the clean version. Here is what it leaves out.</p>
<h2 id="break-1-only-edits-you-havent-seen-can-conflict">Break 1: Only Edits You Haven't Seen Can Conflict</h2>
<p><strong>The point: compare an event only against the edits its user hadn't seen yet.</strong> Anything older is already
part of the version they acted on, so it can't disagree with them.</p>
<p>Our first query got this wrong. It loaded the entity's whole history, not just the edits made after the
user's snapshot:</p>
<div class="diagram">
<div class="diagram-head">One docket, two windows</div>
<div class="diagram-timeline">
<div class="diagram-window">
<div class="diagram-window-ticks">
<div class="diagram-tick is-compare"><div class="diagram-tick-label">Someone renames the docket</div><div class="diagram-tick-tag">makes v3<br>same column: clash</div></div>
<div class="diagram-tick"><div class="diagram-tick-label">You rename it again, offline</div><div class="diagram-tick-tag">you saw v3</div></div>
<div class="diagram-tick"><div class="diagram-tick-label">Another user changes the date</div><div class="diagram-tick-tag">makes v4<br>other column: fine</div></div>
</div>
<div class="diagram-window-label">First query: whole history</div>
</div>
<div class="diagram-tick is-compare"><div class="diagram-tick-label">Your rename is checked</div><div class="diagram-tick-tag">v3 ≠ v4<br>false conflict</div></div>
</div>
<div class="diagram-timeline">
<div class="diagram-tick is-skip"><div class="diagram-tick-label">Someone renames the docket</div><div class="diagram-tick-tag">makes v3<br>already seen</div></div>
<div class="diagram-tick"><div class="diagram-tick-label">You rename it again, offline</div><div class="diagram-tick-tag">you saw v3</div></div>
<div class="diagram-window" style="flex-grow: 1">
<div class="diagram-window-ticks">
<div class="diagram-tick"><div class="diagram-tick-label">Another user changes the date</div><div class="diagram-tick-tag">makes v4<br>other column: fine</div></div>
</div>
<div class="diagram-window-label">Fix: since you looked</div>
</div>
<div class="diagram-tick"><div class="diagram-tick-label">Your rename is checked</div><div class="diagram-tick-tag">v3 ≠ v4<br>auto-resolves</div></div>
</div>
</div>
<p>The first rename made v3, the version you were looking at, so it can't have raced you. The fix drops every
event your snapshot already contains; what is left is the <em>intervening window</em>. When the server can't prove
an event is already in your snapshot, it keeps it: at worst, a human gets asked.</p>
<p>The check also trusts each event's own list of the columns it writes, and hand-written lists rot;
<a href="https://jenicek.dev/series/offline-first-kmp#part-16">Part 16</a> is how we stop that from happening quietly.</p>
<h2 id="break-2-the-same-value-is-not-a-disagreement">Break 2: The Same Value Is Not a Disagreement</h2>
<p>The check assumes two writes to the same column clash. They don't if the values match. Two devices mark the
same docket as received offline, both writing <code>status</code> = received. The columns overlap, so the naive check
asks a human to settle a disagreement that doesn't exist.</p>
<p>Now an overlap with an <em>identical</em> value is a no-op: recorded as resolved, nothing applied, nobody asked. A
conflict requires a difference, not just a collision.</p>
<h2 id="break-3-row-locks-so-the-check-survives-concurrency">Break 3: Row Locks So the Check Survives Concurrency</h2>
<p>Everything above assumes a stable history. On our server, several batches process events for the same
workspace in parallel, so another batch could change a docket while the auto-resolver is reading it. So the
whole check runs in one transaction that locks every entity in the snapshot first:</p>
<div class="diagram">
<div class="diagram-head">One auto-resolve, start to finish</div>
<div class="diagram-timeline">
<div class="diagram-tick"><div class="diagram-tick-label">Mismatch found</div><div class="diagram-tick-tag">v3 ≠ v4</div></div>
<div class="diagram-window" style="flex-grow: 4">
<div class="diagram-window-ticks">
<div class="diagram-tick is-compare"><div class="diagram-tick-label">Lock the rows</div><div class="diagram-tick-tag">in id order</div></div>
<div class="diagram-tick"><div class="diagram-tick-label">Re-check the snapshot</div><div class="diagram-tick-tag">versions moved?</div></div>
<div class="diagram-tick"><div class="diagram-tick-label">Scan the window</div><div class="diagram-tick-tag">now stable</div></div>
<div class="diagram-tick"><div class="diagram-tick-label">Apply, or ask a human</div><div class="diagram-tick-tag">disjoint or not</div></div>
</div>
<div class="diagram-window-label">Rows locked: other batches wait</div>
</div>
<div class="diagram-tick"><div class="diagram-tick-label">Commit</div><div class="diagram-tick-tag">locks released</div></div>
</div>
</div>
<p>The lock is one statement:</p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#D73A49">SELECT</span><span style="color:#005CC5"> 1</span><span style="color:#D73A49"> FROM</span><span style="color:#D73A49"> &#x3C;table></span><span style="color:#D73A49"> WHERE</span><span style="color:#24292E"> id </span><span style="color:#D73A49">IN</span><span style="color:#24292E"> (...) </span><span style="color:#D73A49">ORDER BY</span><span style="color:#24292E"> id </span><span style="color:#D73A49">FOR</span><span style="color:#D73A49"> UPDATE</span></span></code></pre>
<p><code>ORDER BY id</code> makes every transaction take its locks in the same order, so two of them can't deadlock. The
re-check catches a version that moved just before the lock; versions only go up, so it can only find more
conflicts, never fewer.</p>
<p>Locking is <strong>strict by default</strong>: if the database adapter can't take row locks, auto-resolve doesn't run at
all. A loud failure beats concurrent batches silently skipping conflict detection.</p>
<h2 id="fail-closed-when-unsure-ask-a-human">Fail Closed: When Unsure, Ask a Human</h2>
<p><strong>The point: auto-resolve may only apply an edit when it is sure. Everything else goes to a human.</strong></p>
<p>Three breaks in one small feature taught us not to trust it to be clever. So every case it can't be sure
about ends the same way, as a conflict for a person:</p>
<ul>
<li>more than ten intervening events on the entity</li>
<li>an event type it doesn't know, or a payload it can't decode</li>
<li>an entity that no longer exists</li>
</ul>
<p>Ten is a number we picked: today's cellars never come close, and if real use does, we raise it. The point is
that a limit exists, and crossing it falls toward a person.</p>
<p>That makes its mistakes one-sided:</p>
<div class="diagram">
<div class="diagram-head">The two ways auto-resolve can be wrong</div>
<div class="diagram-fork">
<div class="diagram-branch">
<div class="diagram-branch-title">Too careful</div>
<div class="diagram-branch-rule">asks when it didn't need to</div>
<div class="diagram-line">a person reviews a false conflict</div>
<div class="diagram-verdict is-ok">Allowed: an annoyance.</div>
</div>
<div class="diagram-branch">
<div class="diagram-branch-title">Too confident</div>
<div class="diagram-branch-rule">applies when it shouldn't have</div>
<div class="diagram-line">a real conflict is written silently</div>
<div class="diagram-verdict is-bad">Never: it corrupts data.</div>
</div>
</div>
</div>
<p>When the machine is not certain two humans agreed, it asks them.</p>
<p>One caveat: everything above makes the auto-resolver's mistakes harmless; none of it proves the column
comparison asks the right question. Two edits can touch different columns and still not make sense together;
<a href="https://jenicek.dev/series/offline-first-kmp#part-17">Part 17</a> is where that bites.</p>
<h2 id="the-takeaways">The Takeaways</h2>
<ul>
<li><strong>A version mismatch is a question, not an answer.</strong> Disjoint columns are the easy part. The window,
equal values and concurrency are where the correctness lives.</li>
<li><strong>Only edits the user hadn't seen can conflict.</strong> Compare against what changed since their snapshot,
not against the entity's whole history.</li>
<li><strong>Fail closed, loudly.</strong> An auto-resolver that over-asks is an annoyance. One that under-asks corrupts
data silently.</li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[A Shared ID Must Travel]]></title>
      <link>https://jenicek.dev/posts/offline-first-shared-id</link>
      <guid>https://jenicek.dev/posts/offline-first-shared-id</guid>
      <pubDate>Sun, 01 Nov 2026 00:00:00 GMT</pubDate>
      <description><![CDATA[A client-minted id only unifies client and server if it travels in the payload. Mint the same id independently on both sides and you get two ids that merely look alike, so anything referencing that entity points at the wrong one. And in an event-sourced system you can't migrate the past: a fix only helps future events, so old and new have to coexist.]]></description>
      <content:encoded><![CDATA[<p><em>Why the server rejected a wine that plainly existed: the root cause promised in <a href="https://jenicek.dev/posts/offline-first-silent-success#nothing-is-lost-at-the-door-either">Part 5</a>.</em></p>
<p class="tldr"><strong>TL;DR</strong> A client-minted id only unifies client and server if it travels in the payload. Mint the same
id independently on both sides and you get two ids that merely look alike, so anything referencing that
entity points at the wrong one. And in an event-sourced system you can't migrate the past: a fix to your
events only helps future events, so it has to make old and new coexist.</p>
<blockquote>
<p>Part 12 of the <strong>Offline-First KMP</strong> series, and the capstone of its immutability arc: field notes from a
production winery app built on Kotlin Multiplatform (KMP). It's the war story underneath the "mint the
ID, and make it travel" section of <a href="https://jenicek.dev/posts/offline-first-witness-not-judge#mint-the-id-and-make-it-travel">Part 11</a>, the map of the
whole architecture.</p>
<p><a href="https://jenicek.dev/posts/offline-first-silent-success#reading-the-logs-where-the-200-lied">Part 5</a> told the surface of this bug, an HTTP 200 that lied and a
sync connector that silently dropped the failure, and left one thread deliberately unpulled: <em>why</em> the
server rejected a wine that plainly existed. This post pulls it. It builds on the model from Parts 2 to 4:
an uploaded <a href="https://jenicek.dev/posts/offline-first-two-writes#write-1-the-event-what-happened">event plus a local projection</a>,
<a href="https://jenicek.dev/posts/offline-first-minting-ids#what-the-client-minted-id-buys-you">client-minted ids</a>, and
<a href="https://jenicek.dev/posts/offline-first-write-checkpoints#what-happens-when-the-checkpoint-gate-opens">checkpoints that sweep the provisional rows away</a>.</p>
</blockquote>
<h2 id="where-part-5-left-off-the-missing-timeline-breadcrumb">Where Part 5 Left Off: The Missing Timeline Breadcrumb</h2>
<p>A quick recap of <a href="https://jenicek.dev/posts/offline-first-silent-success#the-breadcrumb">Part 5</a>, so this stands on its own.</p>
<p>Some actions create a wine as a <em>side effect</em>: assign a docket to a tank, or transfer wine into an
occupied tank, and a new wine comes out. Each time, the processor also emits a marker event,
<code>CELLAR_WINE_CREATED</code>, so the wine's timeline can show a "wine created" row. A breadcrumb.</p>
<p>Those rows kept going missing, while the wine itself was fine. The upload logs showed why: the batch
returned HTTP 200, but the breadcrumb inside it had failed validation.</p>
<pre><code>POST /v1/powersync/write
  HARVEST_DOCKET_ASSIGN  → 200 {"success":1,"error":0}
  CELLAR_WINE_CREATED    → 200 {"success":0,"error":1}
      results[1].error:
        "wine_id 159e8928… does not reference an existing wine"
</code></pre>
<p>The connector logged it and moved on. So why did the server say the wine didn't exist, when it plainly
did?</p>
<h2 id="the-root-cause-two-wines-two-ids">The Root Cause: Two Wines, Two IDs</h2>
<p>There were <strong>two</strong> wines, and the breadcrumb pointed at the wrong one.</p>
<p>Normally the client mints an entity's id, sends it inside the event, and the server reuses it
(<a href="https://jenicek.dev/posts/offline-first-minting-ids#what-the-client-minted-id-buys-you">Part 3</a>). Back then, the
side-effect wine skipped that step: its id was never in the event payload. Here is what one offline
assign did:</p>
<div class="diagram">
<div class="diagram-head">One offline assign, back then</div>
<div class="diagram-timeline">
<div class="diagram-tick"><div class="diagram-tick-label">Assign on the device</div><div class="diagram-tick-tag">wine A<br>breadcrumb → A</div></div>
<div class="diagram-tick"><div class="diagram-tick-label">Upload</div><div class="diagram-tick-tag">assign<br>+ breadcrumb</div></div>
<div class="diagram-window" style="flex-grow: 2">
<div class="diagram-window-ticks">
<div class="diagram-tick is-compare"><div class="diagram-tick-label">Server runs the assign</div><div class="diagram-tick-tag">wine B,<br>no breadcrumb</div></div>
<div class="diagram-tick is-compare"><div class="diagram-tick-label">Server checks the breadcrumb</div><div class="diagram-tick-tag">no wine A:<br>rejected</div></div>
</div>
<div class="diagram-window-label">On the server</div>
</div>
<div class="diagram-tick"><div class="diagram-tick-label">Batch returns 200</div><div class="diagram-tick-tag">failure dropped</div></div>
<div class="diagram-tick is-compare"><div class="diagram-tick-label">Next sync</div><div class="diagram-tick-tag">wine B,<br>row missing</div></div>
</div>
</div>
<p>The result: the wine is there, with the right volume, in the right tank, but its "wine created" row is
missing from the timeline. The 200 that hid the rejection is
<a href="https://jenicek.dev/posts/offline-first-silent-success#why-the-connector-let-it-go">Part 5</a>'s war story; the sync that swaps
wine A for wine B is <a href="https://jenicek.dev/posts/offline-first-write-checkpoints#the-cleanup-code-you-never-write">Part 4</a>'s
checkpoint.</p>
<p>That happened on <em>every</em> wine-creating event, not now and then. It only looked intermittent because a
missing breadcrumb is cosmetic and the failure was swallowed.</p>
<h2 id="the-fix-the-wine-id-travels-the-breadcrumb-stays">The Fix: The Wine ID Travels, the Breadcrumb Stays</h2>
<p>The fix sorts what the device knows into two piles: what travels to the server, and what stays on the
device.</p>
<div class="diagram">
<div class="diagram-head">One offline assign, today</div>
<div class="diagram-timeline">
<div class="diagram-tick"><div class="diagram-tick-label">Assign on the device</div><div class="diagram-tick-tag">wine A<br>breadcrumb → A</div></div>
<div class="diagram-tick"><div class="diagram-tick-label">Upload</div><div class="diagram-tick-tag">assign + wine A's id<br>breadcrumb stays</div></div>
<div class="diagram-window" style="flex-grow: 2">
<div class="diagram-window-ticks">
<div class="diagram-tick"><div class="diagram-tick-label">Server runs the assign</div><div class="diagram-tick-tag">same id:<br>wine A</div></div>
<div class="diagram-tick"><div class="diagram-tick-label">Server writes the breadcrumb</div><div class="diagram-tick-tag">breadcrumb → A</div></div>
</div>
<div class="diagram-window-label">On the server</div>
</div>
<div class="diagram-tick"><div class="diagram-tick-label">Batch returns 200</div><div class="diagram-tick-tag">nothing failed</div></div>
<div class="diagram-tick"><div class="diagram-tick-label">Next sync</div><div class="diagram-tick-tag">wine A,<br>row present</div></div>
</div>
</div>
<p><strong>The wine id travels.</strong> The assign event now carries wine A's id, and the server creates the wine with
it instead of minting its own:</p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#6A737D">// id = the wineId from the event</span></span>
<span class="line"><span style="color:#D73A49">val</span><span style="color:#24292E"> wineId </span><span style="color:#D73A49">=</span><span style="color:#24292E"> id ?: Uuid.</span><span style="color:#6F42C1">random</span><span style="color:#24292E">().</span><span style="color:#6F42C1">toString</span><span style="color:#24292E">()</span></span></code></pre>
<p>One wine, one id, on both sides. That is what the title means: a client-minted id is only shared if it
travels to the server inside the event that creates the entity.</p>
<p><strong>The breadcrumb stays.</strong> It isn't something the user did; it follows from the assign. So the server
writes its own copy when it processes the assign, and the device's copy is only there for the instant
timeline, like the projection rows in <a href="https://jenicek.dev/posts/offline-first-two-writes#the-part-that-feels-wrong">Part 2</a>.
The checkpoint replaces it with the server's
(<a href="https://jenicek.dev/posts/offline-first-write-checkpoints#what-happens-when-the-checkpoint-gate-opens">Part 4</a>).</p>
<p>The rule behind both: upload what the user did, with the ids of everything it creates. Keep on the device
anything the server will work out for itself.</p>
<h2 id="the-catch-you-cant-migrate-the-past">The Catch: You Can't Migrate the Past</h2>
<p>Look at that line again: <code>id ?:</code>. Events recorded by older clients have no wine id, so for them the server
still mints its own. An append-only log can't be edited to add the id: history that can't be corrupted also
can't be corrected. So the fix covers every event from now on, and the old ones stay as they were recorded.
You don't get to migrate the past; you only get to stop growing the problem.</p>
<h2 id="the-takeaways">The Takeaways</h2>
<ul>
<li><strong>Upload what the user did, with the ids of everything it creates.</strong> An id minted separately on each
side isn't shared: it's two ids that happen to look alike.</li>
<li><strong>Keep what the server derives on the device.</strong> The server writes its own breadcrumb; the device's
copy is only for the instant UI.</li>
<li><strong>You can't migrate the past.</strong> A change to your events fixes the future and leaves the old events as
they are. Make old and new coexist; don't try to rewrite history.</li>
</ul>
<p>The client witnesses, the server judges
(<a href="https://jenicek.dev/posts/offline-first-witness-not-judge#witness-not-judge">Part 11</a>), and the id has to travel for the
two to ever agree.</p>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[Witness, Not Judge]]></title>
      <link>https://jenicek.dev/posts/offline-first-witness-not-judge</link>
      <guid>https://jenicek.dev/posts/offline-first-witness-not-judge</guid>
      <pubDate>Thu, 22 Oct 2026 00:00:00 GMT</pubDate>
      <description><![CDATA[Your offline-first app is not a sync queue. The client witnesses; it never judges: it records what happened as immutable events, and one shared Kotlin engine, the same one the phone runs, derives state and rules on conflicts on a Node.js server. The whole architecture in one read, with the Droidcon Berlin talk and slides.]]></description>
      <content:encoded><![CDATA[<p><em>Your app testifies. It doesn't rule. The whole architecture, in one read.</em></p>
<p class="tldr"><strong>TL;DR</strong> Most "offline-first" apps queue writes and replay them at the server, which quietly loses
information the moment two people act offline. We built a different shape: the client only <em>records what
happened</em> as immutable events, and a separate engine <em>derives</em> state and rules on conflicts. The client
witnesses; it never judges. And the engine that judges is one shared Kotlin module, the same one the phone
runs, compiled to JavaScript for a Node.js server, so client and server can't disagree.</p>
<blockquote>
<p>Part 11 of the <strong>Offline-First KMP</strong> series, and the <strong>written companion to my conference talk</strong> ("Your
offline-first app is not a sync queue."). The earlier parts each went deep on one mechanic or one war
story; this one shows the shape they add up to, with a link to the deep dive in every section. Field
notes from a production winery app built on Kotlin Multiplatform (KMP).</p>
</blockquote>
<h2 id="watch-the-talk-droidcon-berlin-2026">Watch the Talk: Droidcon Berlin 2026</h2>
<p>Prefer to watch? Here is the talk this post accompanies, recorded at Droidcon Berlin.</p>
<div class="youtube-embed" data-youtube-id="2rta1Z3lgso"><a class="youtube-embed-link" href="https://www.youtube.com/watch?v=2rta1Z3lgso" target="_blank" rel="noopener noreferrer" aria-label="Watch on YouTube"><img class="youtube-embed-thumb" src="https://i.ytimg.com/vi/2rta1Z3lgso/hqdefault.jpg" alt="" loading="lazy" /><svg class="youtube-embed-play" viewBox="0 0 68 48" aria-hidden="true" focusable="false"><path d="M66.52 7.74c-.78-2.93-2.49-5.41-5.42-6.19C55.79.13 34 0 34 0S12.21.13 6.9 1.55C3.97 2.33 2.27 4.81 1.48 7.74 0 13.05 0 24 0 24s0 10.95 1.48 16.26c.78 2.93 2.49 5.41 5.42 6.19C12.21 47.87 34 48 34 48s21.79-.13 27.1-1.55c2.93-.78 4.64-3.26 5.42-6.19C68 34.95 68 24 68 24s0-10.95-1.48-16.26z" fill="#f00"/><path d="M45 24L27 14v20z" fill="#fff"/></svg></a></div>
<p>And the slides, if you'd rather click through at your own pace. Click, tap or use the arrow keys.</p>
<div class="slides-embed">
<iframe src="https://jenicek.dev/assets/blog/post/offline-first-witness-not-judge/deck/index.html" title="Witness, Not Judge: slides" loading="lazy" allowfullscreen></iframe>
</div>
<p class="slides-embed-links"><a href="https://jenicek.dev/assets/blog/post/offline-first-witness-not-judge/deck/index.html" target="_blank" rel="noopener">Open the slides full page</a> · <a href="https://jenicek.dev/assets/blog/post/offline-first-witness-not-judge/witness-not-judge-slides.pdf" target="_blank" rel="noopener">Download as PDF</a></p>
<p class="slides-embed-links">Cover photo (left): Volkmar Otto / <a href="https://www.flickr.com/photos/194372122@N07/55586737831/" target="_blank" rel="noopener noreferrer">next.app devCon Berlin 2026</a></p>
<h2 id="the-queue-that-quietly-loses">The Queue That Quietly Loses</h2>
<p>A queue-and-replay client stores <em>mutations</em>. Here is how that loses data:</p>
<ol>
<li>Tank 12 holds a thousand kilos.</li>
<li>Paula, offline, tips in 300 from docket 41. Her phone records 1,300.</li>
<li>Ben, offline too and close enough to wave, tips in 400 from his own delivery. His phone records 1,400.</li>
<li>They reconnect, the queues flush, and Ben's write lands last. The tank reads 1,400.</li>
</ol>
<p>Nothing looks wrong and nothing is flagged. But seventeen hundred kilos went in, and Paula's three hundred
are in nobody's records.</p>
<p>That is not their mistake; it is the model. A queue of mutations cannot know two writes were about the same
real fact, and "last write wins" assumes somebody has to win. That is a queue's idea, not your domain's:
both taps were correct where they stood. So the question underneath this whole post is: when your user taps
Save with no signal, is your app writing down what <em>happened</em>, or casting a vote about what's <em>true</em>?</p>
<p>The queue has a second way to lose. A batch upload can come back <code>HTTP 200</code> while an operation inside it
was refused, and the queue crosses it off as done. <a href="https://jenicek.dev/posts/offline-first-silent-success">Part 5</a> tells that
war story: "200" is a fact about HTTP, not about your <em>operation</em>.</p>
<h2 id="witness-not-judge">Witness, Not Judge</h2>
<p>The fix started as a principle before it was any code. <strong>The client witnesses; it never judges.</strong> A witness
records "Paula assigned Docket 41 to Tank 12 at 14:03" as an immutable fact.</p>
<p>Checking is not judging. Her phone checks every tap against the server's own rules and refuses what they
forbid, a closed docket or a zero amount, so a local <em>no</em> is real. But her phone cannot see Ben's tap on the
other side of the cellar, so a local <em>yes</em> is only provisional. Nobody waits on it: whether her work can be
<em>applied</em> is decided later, by something that sees everyone's testimony, and the outcome is written on the
event.</p>
<p>The reason is practical. An offline client is the worst-informed party in the system, so it should not give
the most consequential answer. Move the ruling to where the information is.</p>
<p>So the client doesn't write a row in a <code>vessel</code> table. It writes an <em>event</em>: intent, frozen, in one
append-only log. You never edit or delete one; you append a correction that defines reality forward. A fact
that can never change is safe to throw away and rebuild from;
<a href="https://jenicek.dev/posts/offline-first-two-writes">Part 2</a> unpacks why.</p>
<h2 id="two-writes-for-every-tap">Two Writes for Every Tap</h2>
<p>The event is only half of what a tap does. The client also writes a provisional projection: the state the
phone shows, and the state it checks your next tap against. The screen updates instantly, no spinner. We
call it Zero-Flicker.</p>
<p>Only the event leaves the device. The server computes its own authoritative state and sends it back down,
and the provisional row falls away with <strong>no cleanup code of ours</strong>: PowerSync's reconciliation removes it
(<a href="https://jenicek.dev/posts/offline-first-write-checkpoints">Part 4</a>). Two writes per tap: one you read, one you trust.</p>
<h2 id="the-pipe-between-them">The Pipe Between Them</h2>
<p>"The event uploads" sounds like one line of code. It is a layer:</p>
<ul>
<li>What your device stores and what your write endpoint accepts are rarely the same shape, so the upload path
inlines junction rows, drops operations that must travel as events, and strips server-owned columns
(<a href="https://jenicek.dev/posts/offline-first-adapter-layer">Part 6</a>).</li>
<li>The column types behind that live in a generated file, the wrong place to fix anything
(<a href="https://jenicek.dev/posts/offline-first-generated-file">Part 7</a>).</li>
<li>Coming back down, a row the sync layer cannot address by <code>id</code> does not survive the trip
(<a href="https://jenicek.dev/posts/offline-first-join-table-id">Part 8</a>).</li>
<li>All of it is easier to reason about once the sync stack runs on your laptop
(<a href="https://jenicek.dev/posts/offline-first-local-stack">Part 9</a>).</li>
</ul>
<p>None of that is architecture. It is plumbing, and it is where the architecture either works or quietly does
not.</p>
<h2 id="mint-the-id-and-make-it-travel">Mint the ID, and Make It Travel</h2>
<p>For that swap to work, both sides have to agree on <em>identity</em>. The client mints the real, permanent UUID at
creation, before any server has heard of the entity, so an offline user can create a docket and reference it
right away, with no temporary id to rewrite later
(<a href="https://jenicek.dev/posts/offline-first-minting-ids">Part 3</a>). The collision fear is folklore.</p>
<p>A single tap can mint more than one id: one for the event, and one for each entity the event creates,
nested in the event payload. That nesting is what matters. A client-minted id only unifies the two sides if
it <em>travels in the payload</em>; an id minted separately on each side is two ids that merely look alike. The
ones most likely to go missing are side-effect entities nobody remembers to include. It bit us in
production: <a href="https://jenicek.dev/posts/offline-first-shared-id">Part 12</a> is that war story, plus the sting in the tail, that an
event-sourced system can't migrate its own past.</p>
<h2 id="conflict-as-a-decision">Conflict as a Decision</h2>
<p>Each event carries a <strong>version snapshot</strong>: the version of every entity it read, at the moment the user acted.
On sync the server compares it with the current state. A mismatch is only a suspicion:</p>
<ul>
<li><strong>Disjoint columns:</strong> a rename and a re-assignment don't conflict. They auto-resolve silently.</li>
<li><strong>A real overlap</strong>, two different values in the same field, goes to a human. They see their change beside
the current state and define reality forward with a new corrective event; history is never rewritten.
The screen offers what reality still accepts: retry if the target merely changed, discard if it was
archived while you were offline.</li>
</ul>
<p>Most "conflicts" are false positives the server settles on its own. The real ones become a decision with an
author and a timestamp, not a merge bug in a queue.</p>
<h3 id="why-not-a-crdt">Why Not a CRDT?</h3>
<p>Conflict-free replicated data types (CRDTs) converge without ever showing that screen, so the question comes
up every time. Our event log already <em>is</em> one: append-only, immutable, merged by union. What we refused to
make convergent is the projection.</p>
<p>Paula and Ben both tip grapes into tank 12, and each phone says one tank, one wine. A merge can pick one
docket, add the kilos, or keep both. But the tank actually holds a new wine, a blend of both, that neither
phone recorded and no merge rule can vouch for. In a regulated cellar, provenance <em>is</em> the product. A merge
answers the phones' question, not the cellar's.</p>
<p>So here is the line. When all you need is the result, as with a text, a whiteboard or a shopping list, merge
it. When the testimony is the product, as with a wine, a stock or an account, record it, and let someone put
their name on it.</p>
<p>Going deeper:</p>
<ul>
<li><a href="https://jenicek.dev/posts/offline-first-auto-resolve">Part 13</a>: everything those paragraphs hide.</li>
<li><a href="https://jenicek.dev/posts/offline-first-not-everything-ledger">Part 14</a>: which entities get this treatment at all.</li>
<li><a href="https://jenicek.dev/series/offline-first-kmp#part-16">Part 16</a>: keeping the declarations it rests on from rotting.</li>
<li><a href="https://jenicek.dev/series/offline-first-kmp#part-17">Part 17</a>: where the disjoint-column idea runs out.</li>
<li><a href="https://jenicek.dev/series/offline-first-kmp#part-18">Part 18</a>: what a server owes a user when it refuses.</li>
</ul>
<h2 id="the-kicker-the-same-kotlin-runs-on-a-nodejs-server">The Kicker: The Same Kotlin Runs on a Node.js Server</h2>
<p>Across nine earlier parts I have said "the server derives its own authoritative state" without once saying <em>how</em>.
That was deliberate. It runs <em>the same code the phone ran</em>, on a <strong>Node.js server</strong>. Not a Kotlin backend,
not the Java Virtual Machine (JVM): a plain Node.js backend. The processor and validator are one Kotlin
Multiplatform module.</p>
<p>Before any backend existed, that module already compiled natively for Android and iOS, so the rules could not
fork between the two apps. Going server-side then cost five lines: one JavaScript target, so the same source
also compiles to a Node.js library, published as an npm package our backend imports.</p>
<ul>
<li><strong>No second implementation to drift.</strong> One pure Kotlin engine processes sixty-four event types; none is
reimplemented on the server.</li>
<li><strong>Not even across versions.</strong> The package version's suffix is a hash of the module's source. Same hash,
same rules.</li>
<li><strong>Not free at the type boundary.</strong> <code>Long</code> narrows to <code>Double</code>, and coroutines become Promises with a
rollback hazard attached. And one engine reading two databases gets every value as a string, a cost the
phone pays too. <a href="https://jenicek.dev/posts/offline-first-type-boundary">Part 15</a> covers what that boundary charges.</li>
</ul>
<p>But the property it buys is absolute: the client cannot disagree with the server, because they are the same
judge.</p>
<h2 id="the-whole-thing-in-five-lines">The Whole Thing, in Five Lines</h2>
<p>Five things to actually do when the testimony is the product:</p>
<ul>
<li>Store immutable events, not mutations, and derive state from them. You stop losing what actually happened.</li>
<li>The client witnesses and never blocks real work; a separate engine judges, where it can see everyone.</li>
<li>Mint identity at creation and make it travel, or the two sides only <em>look</em> like they agree.</li>
<li>A version snapshot turns most conflicts into silent auto-resolves and the rest into human decisions.</li>
<li>One rule, one implementation, compiled to every runtime, even JavaScript on your Node.js server.</li>
</ul>
<p>Your app records testimony it can always stand behind, and leaves the ruling to something that can see the
whole courtroom. Your app testifies. It doesn't rule.</p>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[HTTP 500 Is Not a Retry]]></title>
      <link>https://jenicek.dev/posts/offline-first-two-failure-contracts</link>
      <guid>https://jenicek.dev/posts/offline-first-two-failure-contracts</guid>
      <pubDate>Tue, 06 Oct 2026 02:00:00 GMT</pubDate>
      <description><![CDATA[A batch write endpoint that reports some failures per operation and others as a status code does not have a contract, it has two. A status code cannot tell the client whether you refused its data or broke while processing it, and a batch verdict is a verdict on every operation at once. The only channel that can carry a per-operation failure is the body. Get it wrong and the client does not retry slowly, it stops.]]></description>
      <content:encoded><![CDATA[<p><em>The same endpoint, two failure contracts, and the one that was never wired.</em></p>
<p class="tldr"><strong>TL;DR</strong> A batch write endpoint that reports some outcomes per operation and others as a batch status
code does not have a contract, it has two. A status code cannot tell the client whether you refused its
data or broke while processing it, and no better status code fixes that: a batch verdict is a verdict on
all fifty operations at once. The only channel that can carry a per-operation failure is the body. Get it
wrong and the client does not retry slowly, it stops.</p>
<p>This is the last field note from down in the pipes, before the series zooms out to the architecture
underneath it all. <strong>Dropping in here?</strong> The stack: one Kotlin Multiplatform (KMP) codebase for iOS and
Android, with <a href="https://www.powersync.com" target="_blank" rel="noopener noreferrer">PowerSync</a> as the sync layer in front of a Postgres backend
(<a href="https://jenicek.dev/posts/offline-first-kmp">Part 1</a> is why we picked it). PowerSync keeps a SQLite database on the device
and puts every local write into an upload queue. What drains that queue is a <strong>connector</strong>, our code, which
posts batches of queued rows to our write endpoint.</p>
<p><a href="https://jenicek.dev/posts/offline-first-silent-success">Part 5</a> told you that HTTP 200 is not success. This is the other
half, and it points the opposite way.</p>
<h2 id="the-error-that-was-not-the-error">The Error That Was Not the Error</h2>
<p>A user assigned part of a harvest docket into a tank. The wine appeared on their device and never
confirmed. Here is what our logs said, in order:</p>
<pre><code>AWS batch upload response [500 Internal Server Error]:
  {"code":"INTERNAL_SERVER_ERROR",
   "message":"Failed to apply PowerSync write batch operation"}

AWS batch upload transient failure (500 Internal Server Error), will retry.
AWS upload backing off 2000ms (transient failure #1)

Dropped PUT operational_event/e9e2… [HTTP 200, CONFLICT]:
  Write conflict on operational_event/e9e2…:
  operational_event is append-only; PUT is allowed only for new rows
</code></pre>
<p>Read that last line the way anyone would. It is specific, it names a table, it states a rule, and it
sounds like a diagnosis. A write conflict on an append-only table means something tried to overwrite a row
that already existed.</p>
<p>Nothing overwrote anything. There was no conflict. That message describes a duplicate write which only
happened because of the retry above it, and the retry only happened because of the 500 above that. The
most confident-sounding line in the log was the furthest from the cause.</p>
<p>The actual failure was a not-null constraint. Deep inside processing the event, the server tried to write
a row with a required column left empty, Postgres refused, and the transaction rolled back. That sentence
appears nowhere in anything the client could see.</p>
<h2 id="two-failure-contracts-one-endpoint">Two Failure Contracts, One Endpoint</h2>
<p>Once we knew where to look, the shape of the problem was obvious, and it was not really a bug in any one
place. Our write endpoint has two entirely different ways of saying no, depending on where in its own
pipeline the failure happens.</p>
<div class="diagram">
<div class="diagram-head">One endpoint, two ways of saying no</div>
<div class="diagram-fork">
<div class="diagram-branch">
<div class="diagram-branch-title">Refused at the door</div>
<div class="diagram-branch-rule">before the row is stored</div>
<div class="diagram-line"><span class="diagram-key">200</span> with a per-operation error in <code>results[]</code></div>
<div class="diagram-line">client: terminal, report it, drain the queue</div>
<div class="diagram-verdict is-ok">Correct.</div>
</div>
<div class="diagram-branch">
<div class="diagram-branch-title">Fails while processing</div>
<div class="diagram-branch-rule">after the row is committed</div>
<div class="diagram-line"><span class="diagram-key">500</span> batch level, no per-operation detail</div>
<div class="diagram-line">client: transient, back off, retry the batch</div>
<div class="diagram-verdict is-bad">Wrong.</div>
</div>
</div>
</div>
<p><a href="https://jenicek.dev/posts/offline-first-silent-success">Part 5</a> was about the left branch: the endpoint tells you an operation failed, inside a response that says
200, and if you only check the status code you never hear it. The fix was to read the body.</p>
<p>This is the right branch, and reading the body does not help. The body says <code>INTERNAL_SERVER_ERROR</code>. The
status says 500. Both are honest, and both describe a transport problem that did not occur.</p>
<p>A status code is a statement about the request. It cannot express "your data was fine and our processor
broke", which is a completely different instruction to the client than "your data was refused". One says
try again later, the other says never send this again. They arrive looking identical.</p>
<h2 id="why-the-client-believed-the-500">Why the Client Believed the 500</h2>
<p>Our connector classifies terminal statuses explicitly:</p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#D73A49">val</span><span style="color:#24292E"> TERMINAL_STATUSES </span><span style="color:#D73A49">=</span><span style="color:#6F42C1"> setOf</span><span style="color:#24292E">(BadRequest, Conflict, UnprocessableEntity)</span></span></code></pre>
<p>Everything else is treated as transient: back off, keep the batch, let PowerSync retry. That is the right
default. A 500 usually means the server had a bad moment, and giving up on the user's data because a
container restarted would be much worse than waiting.</p>
<p>So the client did exactly what it should have done with the information it was given. It was given the
wrong information. No amount of care on the client fixes this, because the distinction it needs was never
transmitted.</p>
<p>There is also no status code that fixes it, which is the part that took us longest to see. A batch carries
up to fifty operations, so any verdict on the status line is a verdict on all of them at once. Our
connector treats <code>400</code>, <code>409</code> and <code>422</code> as terminal for the <em>entire batch</em>, dropping every operation in it
from the queue, so switching the server to a tidy <code>422</code> would have taken forty-nine good writes down with
the one bad one. The failures are per operation, so the channel has to be per operation too, and the only
per-operation channel in an HTTP response is the body.</p>
<h2 id="the-upload-queue-stall-nobody-sees">The Upload Queue Stall Nobody Sees</h2>
<p>Here is the part that turns an annoying log line into a user-visible outage.</p>
<p><a href="https://jenicek.dev/posts/offline-first-write-checkpoints">Part 4</a> covered the write-checkpoint gate: PowerSync will not
apply a downloaded checkpoint while your upload queue still has pending local writes. That post frames the
scary log line as reassuring, and it is. It is the mechanism that stops a half-synced database.</p>
<pre><code>Could not apply checkpoint due to local data.
Will retry at completed upload or next checkpoint.
</code></pre>
<p>Now hold that gate open with a write that can never succeed. The queue does not drain, so the gate does
not lift, so nothing comes down either. The device stops sending and stops receiving, at the same time,
for the same reason. Throughout all of it the sync status cheerfully reports <code>connected: true</code>, because it
is connected. It is just not moving.</p>
<p>The backoff doubled from two seconds toward a five-minute ceiling, and the failure counter lived on the
connector rather than on the operation, so an unrelated failure inherited the previous one's delay.
Reproducing this a few times in a row walked the delay up through two, four, eight, sixteen and thirty-two
seconds, with the client frozen in both directions for every one of them.</p>
<p>The same gate, unchanged, correct, and doing its job. What changed is that the thing it waits for stopped
being able to happen.</p>
<h2 id="the-bug-that-holds-it-upright">The Bug That Holds It Upright</h2>
<p>One more turn, and it is the part I would want somebody to notice before they tidy anything.</p>
<p>There was no permanent deadlock. The retry did eventually terminate, the queue did eventually drain, and
the only reason is an accident of ordering. The server commits the event row <strong>before</strong> it runs the
processing step. So when the client retries, the row is already there, the append-only guard fires, and
that guard returns a proper per-operation error, which the client correctly treats as terminal.</p>
<p>The misleading error message is what saves us from the deadlock. They are the same mechanism.</p>
<p>Which means the obvious cleanup, wrapping the insert and the processing in one transaction so a failed
event does not leave a committed row behind, quietly removes the escape hatch. The retry would then
reproduce the same 500 forever, and the client would sit frozen at a five-minute heartbeat with no signal
at all. A reviewer would ask for that change. It reads like a straightforward correctness fix. It would
turn a confusing log line into a stuck app.</p>
<p>Nothing tests for this. No comment says "this ordering is load-bearing". The system is being held upright
by a property nobody chose.</p>
<h2 id="what-was-never-actually-lost">What Was Never Actually Lost</h2>
<p>Worth saying plainly, because the failure sounds worse than it is: the event itself is fine. It reached
the server, it was stored, and it carries a stored <code>processing_state</code> recording exactly how it ended. That
state syncs back down to the device within seconds. Nothing was silently eaten.</p>
<p>Which is the sharpest version of the lesson. We had a complete, durable, queryable record of the failure,
sitting in the database, before the client even finished retrying. And we still told the client nothing
useful, because storing a failure and reporting one are different capabilities, and we had built only the
first. A system can be perfectly accountable after the fact and completely mute in the moment.</p>
<h2 id="the-takeaways">The Takeaways</h2>
<ul>
<li><strong>One endpoint, one failure contract, and it has to be the granular one.</strong> If any outcome is reported
per operation, all of them must be. You cannot unify upward onto the status line, because a batch verdict
is a verdict on every operation in the batch. You can only unify downward.</li>
<li><strong>A status code cannot carry a business verdict.</strong> "We refused your data" and "we broke processing it"
demand opposite client behaviour and look identical over the wire. Decide where that distinction lives
and make it explicit.</li>
<li><strong>Check what your queue blocks when it cannot drain.</strong> An upload gate that also holds downloads turns one
poison write into a device that is silently frozen in both directions while reporting itself healthy.</li>
<li><strong>Storing a failure is not reporting one.</strong> Durable failure state is worth having and does not, on its
own, tell anybody anything.</li>
<li><strong>Look for the accidents holding your system up.</strong> The most dangerous ones look like defects, so the fix
arrives as a tidy-up in an unrelated pull request.</li>
</ul>
<p>Next up (<a href="https://jenicek.dev/posts/offline-first-witness-not-judge">Part 11</a>): the series stops looking at pipes and starts looking at what all of this was built to
protect.</p>
<h2 id="reference">Reference</h2>
<ul>
<li>PowerSync — <a href="https://docs.powersync.com/configuration/app-backend/client-side-integration" target="_blank" rel="noopener noreferrer">Integrating with your backend</a></li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[Your Sync Stack Fits in Three Containers]]></title>
      <link>https://jenicek.dev/posts/offline-first-local-stack</link>
      <guid>https://jenicek.dev/posts/offline-first-local-stack</guid>
      <pubDate>Tue, 06 Oct 2026 01:00:00 GMT</pubDate>
      <description><![CDATA[An offline-first app is a distributed system wearing a mobile app's clothes, so develop it like one. Standing our sync stack up locally took three Docker containers, and the database was the easy part. The time went into the seams a cloud provider hides from you: the token contract the sync service enforces, and the host networking between the app and the machine.]]></description>
      <content:encoded><![CDATA[<p><em>We put our offline-first sync stack into three Docker containers, and the database was the easy part.</em></p>
<p class="tldr"><strong>TL;DR</strong> An offline-first app is a distributed system wearing a mobile app's clothes: a database, a REST
write path, a sync service, and an auth contract between them. For months we developed against a shared
cloud instance because it was the fastest way to start. Standing the stack up locally later took three
Docker containers, with a plain REST layer standing in for our write API, and the surprises were not in the
database. They were in auth and host networking, the two seams a cloud provider hides from you.</p>
<p>This one is a dev-environment note, not a war story, and it closes the plumbing run
<a href="https://jenicek.dev/posts/offline-first-adapter-layer">Part 6</a> opened. It reads fine on its own.</p>
<h2 id="the-shared-cloud-trap">The Shared-Cloud Trap</h2>
<p>When you pick a sync layer, the fastest way to see it work is to point every developer at one hosted
instance. It ships in an afternoon and it demos beautifully. It is also the decision that quietly gets
expensive.</p>
<p>A shared remote database means every developer's writes land in the same place. Schema changes are a
negotiation. You cannot reset to a clean slate without stepping on a colleague, so nobody does, and the data
drifts into a state no fresh install would ever produce. Worst of all, you cannot see the <em>seams</em> of your
own system: the cloud provider terminates auth, routes your writes, and runs the sync service, so the parts
you most need to understand are the parts you never touch.</p>
<p>A hermetic local stack fixes all of that, and it is cheap to build on day one. It is painful to retrofit on
day three hundred, once every test and habit assumes the cloud. We learned that in the retrofit direction.
Learn it in the other.</p>
<h2 id="the-sync-stack-is-three-containers">The Sync Stack Is Three Containers</h2>
<p>Here is the thing the cloud hides: the stack an offline-first client syncs against is small. Ours is three
containers plus a token endpoint.</p>
<div class="diagram">
<div class="diagram-head">The local stack</div>
<div class="diagram-rows">
<div class="diagram-row"><span class="diagram-row-name">Postgres · 5432</span><span class="diagram-tag">app database and the sync service's bucket storage</span></div>
<div class="diagram-row is-derived"><span class="diagram-row-name">PostgREST · 3001</span><span class="diagram-tag">REST over the tables, stands in for our write API · uploads go here</span></div>
<div class="diagram-row is-derived"><span class="diagram-row-name">PowerSync · 8080</span><span class="diagram-tag">sync-down stream and checkpoints · downloads come from here</span></div>
<div class="diagram-row"><span class="diagram-row-name">token-server · 3002</span><span class="diagram-tag">nginx shim serving a signed JWT, stands in for Firebase · local scaffolding</span></div>
</div>
</div>
<p>The single most clarifying thing about running it yourself is seeing that <strong>uploads and downloads use
different services</strong>. The client writes <em>up</em> to <a href="https://postgrest.org" target="_blank" rel="noopener noreferrer">PostgREST</a>, plain REST straight at
the tables, and the sync service streams changes back <em>down</em>. Production splits them the same way, the sync
service on one URL and our own write API on another, but from inside the app they feel like one system. On
two local ports, the architecture stops being a diagram and becomes two things you can <code>curl</code>
independently. That mental model alone was worth the exercise.</p>
<p>One thing the local stack is not: a copy of the write path. In production, uploads go to a single batch
endpoint on our own API, which checks and processes every write before it is stored. Locally, PostgREST
takes the rows straight into the tables. That is enough to develop the client against, and it means
anything the server's processing would catch, the local stack will not.</p>
<h2 id="localizing-is-a-connector-not-a-rewrite">Localizing Is a Connector, Not a Rewrite</h2>
<p>The app never talked to "the cloud" directly. It talked to a connector: a small class the sync SDK calls to
fetch credentials and to upload a batch of local changes. That indirection is what makes localizing cheap.
We did not rewrite the app. We wrote a second connector pointed at localhost and selected it in the
development build flavor.</p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#D73A49">class</span><span style="color:#6F42C1"> LocalConnector</span><span style="color:#24292E">(</span></span>
<span class="line"><span style="color:#D73A49">    private</span><span style="color:#D73A49"> val</span><span style="color:#24292E"> httpClient: </span><span style="color:#6F42C1">HttpClient</span><span style="color:#24292E">,</span></span>
<span class="line"><span style="color:#24292E">) : </span><span style="color:#6F42C1">PowerSyncBackendConnector</span><span style="color:#24292E">() {</span></span>
<span class="line"></span>
<span class="line"><span style="color:#D73A49">    override</span><span style="color:#D73A49"> suspend</span><span style="color:#D73A49"> fun</span><span style="color:#6F42C1"> fetchCredentials</span><span style="color:#24292E">(): </span><span style="color:#6F42C1">PowerSyncCredentials</span><span style="color:#24292E"> {</span></span>
<span class="line"><span style="color:#D73A49">        val</span><span style="color:#24292E"> token </span><span style="color:#D73A49">=</span><span style="color:#24292E"> httpClient.</span><span style="color:#6F42C1">get</span><span style="color:#24292E">(</span><span style="color:#032F62">"http://</span><span style="color:#005CC5">$localSyncHost</span><span style="color:#032F62">:3002/token"</span><span style="color:#24292E">)</span></span>
<span class="line"><span style="color:#24292E">            .</span><span style="color:#6F42C1">bodyAsText</span><span style="color:#24292E">()</span></span>
<span class="line"><span style="color:#24292E">            .</span><span style="color:#6F42C1">trim</span><span style="color:#24292E">()</span></span>
<span class="line"><span style="color:#D73A49">        return</span><span style="color:#6F42C1"> PowerSyncCredentials</span><span style="color:#24292E">(</span></span>
<span class="line"><span style="color:#24292E">            endpoint </span><span style="color:#D73A49">=</span><span style="color:#032F62"> "http://</span><span style="color:#005CC5">$localSyncHost</span><span style="color:#032F62">:8080"</span><span style="color:#24292E">,</span></span>
<span class="line"><span style="color:#24292E">            token </span><span style="color:#D73A49">=</span><span style="color:#24292E"> token,</span></span>
<span class="line"><span style="color:#24292E">        )</span></span>
<span class="line"><span style="color:#24292E">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A737D">    // POST/PATCH/DELETE to PostgREST</span></span>
<span class="line"><span style="color:#D73A49">    override</span><span style="color:#D73A49"> suspend</span><span style="color:#D73A49"> fun</span><span style="color:#6F42C1"> uploadData</span><span style="color:#24292E">(database: </span><span style="color:#6F42C1">PowerSyncDatabase</span><span style="color:#24292E">) {</span></span>
<span class="line"><span style="color:#6A737D">        /* ... */</span></span>
<span class="line"><span style="color:#24292E">    }</span></span>
<span class="line"><span style="color:#24292E">}</span></span></code></pre>
<p>The production upload half (one batch endpoint, and why a <code>200</code> from it is not the same as success) is its
own topic the series already covered (<a href="https://jenicek.dev/posts/offline-first-silent-success">Part 5</a>,
<a href="https://jenicek.dev/posts/offline-first-adapter-layer">Part 6</a>). What matters here is the shape: the backend is a swappable
dependency, and a hermetic environment is one implementation of it. If your sync layer does not give you
that seam, that is the thing to fix first, before you build a local anything.</p>
<h2 id="surprise-one-jwt-auth-is-the-hard-part-not-the-database">Surprise One: JWT Auth Is the Hard Part, Not the Database</h2>
<p>Postgres in a container is a solved problem. The seam that actually took thought was the token.</p>
<p>The sync service authenticates the client with a signed JWT, and two constraints fell out of that. First,
<strong>you cannot bake the token into the app.</strong> PowerSync rejects any token that lives longer than 24 hours, so
a build-time constant would expire mid-afternoon and never refresh. The connector has to <em>fetch</em> the token
at runtime, which is why there is a token-server at all. The SDK re-invokes <code>fetchCredentials()</code> on
reconnect, so a freshly minted token is picked up without a rebuild.</p>
<p>Second, and this is the one that cost me a silent stretch of debugging: the token's <code>sub</code> claim has to
match the seeded user id, because the sync stream resolves <code>auth.user_id()</code> to a workspace through that
claim. Get it wrong and the stream does not error. It returns <em>empty buckets</em>. No <code>401</code>, no failed request,
just an app that syncs nothing and says nothing about why. Auth in a sync system fails the same way
everything else in this series fails: quietly, with plausible-looking emptiness instead of a crash.</p>
<p>Bypassing Firebase for local dev was easy. Reproducing the <em>contract</em> the sync service checks (audience,
key id, subject, expiry) was the actual work. That contract is exactly what a cloud provider does for you,
which is exactly why you should build it once yourself.</p>
<h2 id="surprise-two-localhost-is-three-different-hosts">Surprise Two: "localhost" Is Three Different Hosts</h2>
<p>The other tax nobody warns you about is that the developer machine's <code>127.0.0.1</code> is not the app's
<code>127.0.0.1</code>.</p>
<ul>
<li><strong>iOS simulator</strong> shares the host network, so loopback reaches the stack directly.</li>
<li><strong>Android</strong> (emulator or a USB device) does not. It reaches the host through <code>adb reverse</code>, which
forwards the ports over the debug bridge. Re-run it every time the device reconnects.</li>
<li><strong>A physical iOS device</strong> has neither and needs the machine's real LAN IP, same Wi-Fi, firewall open.</li>
</ul>
<p>We hid the difference behind a one-line <code>expect/actual</code> that resolves the host per platform, and settled on
loopback everywhere with <code>adb reverse</code> on Android because it is the one recipe that covers both Android
cases. Small thing, but it is the difference between "run the app" and a stretch of <code>Connection refused</code>.</p>
<h2 id="the-takeaways">The Takeaways</h2>
<ul>
<li><strong>An offline-first architecture is a distributed system, so develop it like one.</strong> The client is only
half of it. A database, a write API, a sync service, and an auth contract are the other half, and you
should be able to stand up the stack your client talks to on one laptop, reset it to a clean slate, and
read its logs. A stack you can inspect is a stack you can debug.</li>
<li><strong>Build the hermetic environment early.</strong> It is a couple of containers on day one and a painful retrofit
once every test assumes a shared cloud. The cost only goes up.</li>
<li><strong>The database is the easy part.</strong> The seams worth your attention are the ones the cloud hides: the token
contract the sync service enforces, and the host networking between the app and the machine. Those are
where the time goes, and understanding them is most of the point of doing it yourself.</li>
</ul>
<p>That closes the plumbing run. Four parts spent inside the pipe between device and server, and later in the
series we climb back out of it, to the architecture all this plumbing exists to serve.</p>
<p>Next up (<a href="https://jenicek.dev/posts/offline-first-two-failure-contracts">Part 10</a>): one last failure from down in the pipes before we do. <a href="https://jenicek.dev/posts/offline-first-silent-success">Part 5</a> said HTTP 200 is not
success; <a href="https://jenicek.dev/posts/offline-first-two-failure-contracts">Part 10</a> is the other half, where a 500 is not a retry.</p>
<h2 id="reference">Reference</h2>
<ul>
<li>PowerSync — <a href="https://docs.powersync.com/intro/self-hosting" target="_blank" rel="noopener noreferrer">Self-hosting</a></li>
<li>PowerSync — <a href="https://docs.powersync.com/configuration/auth/custom" target="_blank" rel="noopener noreferrer">Custom authentication</a></li>
<li>PowerSync — <a href="https://docs.powersync.com/configuration/app-backend/client-side-integration" target="_blank" rel="noopener noreferrer">Integrating with your backend</a></li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[Every Synced Row Needs an ID]]></title>
      <link>https://jenicek.dev/posts/offline-first-join-table-id</link>
      <guid>https://jenicek.dev/posts/offline-first-join-table-id</guid>
      <pubDate>Tue, 06 Oct 2026 00:00:00 GMT</pubDate>
      <description><![CDATA[A row with no identity of its own cannot survive a sync layer that addresses everything by id. A composite key is enough for the database, which only has to find the row. It is not enough for a system that has to name the row to move it, and the id PostgreSQL calls redundant is load-bearing for the engine that carries the row across the wire.]]></description>
      <content:encoded><![CDATA[<p><em>Three certification types went up, one came back down, and nothing anywhere reported a problem.</em></p>
<p class="tldr"><strong>TL;DR</strong> PowerSync tracks every synced row by a single <code>id</code>. A many-to-many join table is keyed by its
two foreign keys and has no <code>id</code> of its own, so PowerSync handed every one of its rows the <em>same</em> empty
identifier. On sync-down each row overwrote the one before it, and only the last link per parent survived.
Nothing threw. We fixed it twice: first with a synthetic id the sync stream built by concatenating the two
foreign keys, then durably by adding a real <code>id</code> column server-side, a column PostgreSQL considers
redundant but the sync layer cannot ship the row without.</p>
<p><a href="https://jenicek.dev/posts/offline-first-adapter-layer">Part 6</a> told the <em>upload</em> side of junction tables: fold the rows into
an array on their parent, then drop them before they go up. This is the mirror image, on the way <em>down</em>,
where the sync layer insists on addressing every row by an <code>id</code> the table was never built to have. It is
the third stop on the plumbing run.</p>
<h2 id="the-symptom-many-to-many-links-lost-on-sync-down">The Symptom: Many-to-Many Links Lost on Sync-Down</h2>
<p>The relationship that caught it was a docket's certification record and the types on it. That is a classic
many-to-many: one certification record can carry several certification types, so the pairs live in a join
table, <code>docket_certification_certification_type_lookup</code>, one row per (certification record, type) link.</p>
<p>A user would tag a docket certification with three types, everything looked right on the device, and the
data synced. Then, from the server's copy, it came back down with <strong>one</strong> type on it. Not the wrong data,
not a blank, not an error toast. Two of the three links were simply gone, and the one that remained was
always the last one written. On the server all three rows were sitting there, correct and intact. The loss
happened in transit, and no layer on either side raised a hand.</p>
<p>That is the through-line of this whole series. The dangerous failures are not the ones that crash. They are
the ones that hand you data that looks plausible and is quietly missing a piece.</p>
<h2 id="the-root-cause-a-composite-key-has-no-single-id">The Root Cause: A Composite Key Has No Single ID</h2>
<p>PowerSync's sync protocol identifies every row in a synced table by a single <code>id</code>. That is the unit it
tracks, diffs, and applies. It is not a suggestion you can model around; it is the address space the whole
sync engine operates in.</p>
<p>Our join tables were modelled the ordinary relational way: a composite primary key over the two foreign
keys, no surrogate <code>id</code> column. From PostgreSQL's point of view that is complete and correct. The pair
<code>(docket_certification_id, certification_type_id)</code> uniquely identifies a row, and adding a separate id
column would be redundant. The database has everything it needs.</p>
<p>The sync layer does not. With no <code>id</code> column to read, PowerSync gave every row of the table the same empty
<code>object_id</code>. And when every row shares one address, they are not three rows to the sync engine. They are one
address written three times, last-write-wins:</p>
<div class="diagram">
<div class="diagram-head">Three links, one address</div>
<div class="diagram-fork">
<div class="diagram-branch">
<div class="diagram-branch-title">PostgreSQL</div>
<div class="diagram-branch-rule">keyed by the foreign-key pair</div>
<div class="diagram-line">(cert, type A)</div>
<div class="diagram-line">(cert, type B)</div>
<div class="diagram-line">(cert, type C)</div>
<div class="diagram-verdict is-ok">Three distinct rows.</div>
</div>
<div class="diagram-branch">
<div class="diagram-branch-title">PowerSync</div>
<div class="diagram-branch-rule">keyed by a single id</div>
<div class="diagram-line"><span class="diagram-key">""</span> ← type A</div>
<div class="diagram-line"><span class="diagram-key">""</span> ← type B, overwrites A</div>
<div class="diagram-line"><span class="diagram-key">""</span> ← type C, overwrites B</div>
<div class="diagram-verdict is-bad">One row arrives: type C.</div>
</div>
</div>
</div>
<p>So the pairs collapsed on the way down, and the survivor was whichever row landed last. The information the
server held perfectly could not be <em>represented</em> on the wire, because the rows had no identities to keep
them apart.</p>
<p><a href="https://jenicek.dev/posts/offline-first-adapter-layer">Part 6</a> used that same fact to justify upload-side inlining. There it was about wire format. Here it is
about identity: a row that cannot be named cannot be moved.</p>
<h2 id="the-quick-fix-mint-the-id-in-the-sync-stream">The Quick Fix: Mint the ID in the Sync Stream</h2>
<p>The row needs an id of its own, and the fastest place to make one is out of the two values that already
make it unique. The composite key that satisfied Postgres becomes the raw material for the single id
PowerSync wants. The stream's query, the server-side definition of what each client is allowed to see,
concatenates the two foreign keys into a deterministic synthetic id:</p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#D73A49">SELECT</span><span style="color:#24292E"> docket_certification_id </span><span style="color:#D73A49">||</span><span style="color:#032F62"> '_'</span><span style="color:#D73A49"> ||</span><span style="color:#24292E"> certification_type_id </span><span style="color:#D73A49">AS</span><span style="color:#24292E"> id,</span></span>
<span class="line"><span style="color:#24292E">       docket_certification_id, certification_type_id</span></span>
<span class="line"><span style="color:#D73A49">FROM</span><span style="color:#24292E"> docket_certification_certification_type_lookup</span></span>
<span class="line"><span style="color:#D73A49">WHERE</span><span style="color:#24292E"> docket_certification_id </span><span style="color:#D73A49">IN</span><span style="color:#24292E"> (</span></span>
<span class="line"><span style="color:#D73A49">  SELECT</span><span style="color:#24292E"> id </span><span style="color:#D73A49">FROM</span><span style="color:#24292E"> docket_certification</span></span>
<span class="line"><span style="color:#D73A49">  WHERE</span><span style="color:#24292E"> workspace_id </span><span style="color:#D73A49">IN</span><span style="color:#24292E"> (</span><span style="color:#D73A49">SELECT</span><span style="color:#24292E"> id </span><span style="color:#D73A49">FROM</span><span style="color:#24292E"> active_workspaces)</span></span>
<span class="line"><span style="color:#24292E">)</span></span></code></pre>
<p>Now every row carries a stable, unique <code>id</code> before it leaves the server, PowerSync tracks each one
independently, and all three links arrive intact. The id is derived rather than stored: it lives in the
sync stream, not in a column, so nothing in the database schema had to change to ship the fix. It is
<strong>deterministic</strong>, so the same pair always resolves to the same id and updates land on the row they should
instead of spawning a duplicate, and it is <strong>derivable from data the row already carries</strong>, so no
coordination with whoever wrote the row is required.</p>
<p>The bug first surfaced on docket certifications, and the synthetic id went in for that one table. What
turned a patch into a lesson came a couple of weeks later. Three more many-to-many relationships were
landing at once: manufacturers to their categories, growers to their certifications, additive definitions
to their allergens. Every one of them was a composite-key join table. Every one of them was about to walk
into the identical trap, silently, with no test failing to warn us, because the failure mode produces
plausible data rather than a crash. So the fix generalized to all four join tables in one pass. This was
never a quirk of certifications. It is what happens to <em>any</em> row that has no identity of its own the moment
you put it on a sync layer that addresses everything by id.</p>
<h2 id="the-durable-fix-a-real-id-postgresql-calls-redundant">The Durable Fix: A Real ID PostgreSQL Calls Redundant</h2>
<p>The synthetic id worked, but it lived in the wrong place. Encoding identity in a sync stream means the
stream now carries logic about how each junction table is keyed, and the id exists only for tables the
stream remembers to special-case. The row's identity ought to be a property of the row, not of the query
that happens to ship it. So the durable fix moved it into the data: a real
<code>id uuid DEFAULT gen_random_uuid()</code> column on each junction table, server-side.</p>
<p>That is not a change the app team can make alone. The junction tables live in a PostgreSQL schema the
backend team owns, so this meant asking them to add a column their model does not want. From PostgreSQL's
side the column is genuinely redundant: the composite foreign-key pair already uniquely identifies the row,
and a surrogate id buys the relational model nothing. The case for adding it is entirely about the layer
above. The engine that ships the row across the wire addresses everything by <code>id</code>, and without one the row
cannot travel intact, however complete it looks at rest in the database.</p>
<p>Once the column existed, the sync stream got simpler, not more complex. The concatenation disappeared, and
the query just reads the real id straight off the table:</p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#D73A49">SELECT</span><span style="color:#005CC5"> docket_certification_certification_type_lookup</span><span style="color:#24292E">.</span><span style="color:#005CC5">id</span><span style="color:#24292E">,</span></span>
<span class="line"><span style="color:#24292E">       docket_certification_certification_type_lookup</span></span>
<span class="line"><span style="color:#24292E">         .docket_certification_id,</span></span>
<span class="line"><span style="color:#24292E">       docket_certification_certification_type_lookup</span></span>
<span class="line"><span style="color:#24292E">         .certification_type_id</span></span>
<span class="line"><span style="color:#D73A49">FROM</span><span style="color:#24292E"> docket_certification_certification_type_lookup</span></span>
<span class="line"><span style="color:#D73A49">INNER JOIN</span><span style="color:#24292E"> docket_certification dc</span></span>
<span class="line"><span style="color:#D73A49">        ON</span><span style="color:#005CC5"> dc</span><span style="color:#24292E">.</span><span style="color:#005CC5">id</span><span style="color:#D73A49"> =</span><span style="color:#24292E"> docket_certification_certification_type_lookup</span></span>
<span class="line"><span style="color:#24292E">                     .docket_certification_id</span></span>
<span class="line"><span style="color:#D73A49">WHERE</span><span style="color:#005CC5"> dc</span><span style="color:#24292E">.</span><span style="color:#005CC5">workspace_id</span><span style="color:#D73A49"> IN</span><span style="color:#24292E"> (</span><span style="color:#D73A49">SELECT</span><span style="color:#24292E"> id </span><span style="color:#D73A49">FROM</span><span style="color:#24292E"> active_workspaces)</span></span></code></pre>
<p>That is the shape the production sync config runs today, for all of the join tables. The synthetic-id trick
did its job as a bridge and is gone.</p>
<h2 id="the-takeaways">The Takeaways</h2>
<ul>
<li><strong>A row with no identity of its own cannot survive a sync layer that addresses everything by id.</strong> A
composite key is enough for the database, which only ever has to <em>find</em> the row. It is not enough for a
system that has to <em>name</em> the row to move it. Those are different jobs, and the relational model only
signs up for the first.</li>
<li><strong>"Redundant" is relative to the layer asking.</strong> The id PostgreSQL calls unnecessary is load-bearing for
the engine that carries the row across the wire, so the durable fix meant persuading the backend team to
add a column their model rejects on its own terms. <a href="https://jenicek.dev/posts/offline-first-adapter-layer">Part 6</a> met the same shape from the wire-format side, a
declaration cosmetic in one place and load-bearing in another; here it lands on identity and
addressability instead. Same lesson, different axis: what one layer can safely omit, the next layer down
cannot.</li>
<li><strong>Silent, again.</strong> Like <a href="https://jenicek.dev/posts/offline-first-silent-success">Part 5</a>'s dropped breadcrumb and <a href="https://jenicek.dev/posts/offline-first-adapter-layer">Part 6</a>'s
rejected <code>"770.0"</code>, this degraded without a sound: right-looking data, a missing piece, no error. If there
is one habit this series keeps arguing for, it is to distrust the failures that do not announce
themselves. Those are the ones that reach your users.</li>
</ul>
<p>Next up (<a href="https://jenicek.dev/posts/offline-first-local-stack">Part 9</a>): the last stop on the plumbing run, and the one we should have made first: standing the
whole sync stack up on a laptop, and the two seams a cloud provider hides from you.</p>
<h2 id="reference">Reference</h2>
<ul>
<li>PowerSync — <a href="https://docs.powersync.com/sync/advanced/client-id" target="_blank" rel="noopener noreferrer">Client ID</a></li>
<li>PowerSync — <a href="https://docs.powersync.com/sync/rules/many-to-many-join-tables" target="_blank" rel="noopener noreferrer">Many-to-many and join tables</a></li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[You Cannot Fix a Generated File]]></title>
      <link>https://jenicek.dev/posts/offline-first-generated-file</link>
      <guid>https://jenicek.dev/posts/offline-first-generated-file</guid>
      <pubDate>Sun, 06 Sep 2026 00:00:00 GMT</pubDate>
      <description><![CDATA[A generated file is an input, not a place to put decisions. Whatever you write there has a lifetime bounded by the next regeneration, and that regeneration arrives inside somebody else's unrelated pull request. Hold the exception in code the generator cannot reach, and point the guard at the upstream source of truth rather than the artifact.]]></description>
      <content:encoded><![CDATA[<p><em>A wrong column type broke our uploads. A teammate fixed it in one word. Sixteen days later my pull
request quietly undid it.</em></p>
<p class="tldr"><strong>TL;DR</strong> Our local database schema is generated from a dashboard and carries a banner telling you not to
edit it. A teammate edited it anyway, because the declaration was wrong and correcting it took one word.
Sixteen days later I regenerated that file inside a pull request about something else entirely, silently
reverted them, and re-broke a bug we had already closed. The lesson is not "read the banner." It is that a
generated file is an <em>input</em>, which makes it the wrong place to put a decision. Put the decision somewhere
regeneration cannot reach, and anchor your guard to the upstream truth instead of the artifact.</p>
<p><a href="https://jenicek.dev/posts/offline-first-adapter-layer">Part 6</a> argued that the gap between your local schema and your wire
format is a real architectural layer, and closed by flagging one trap it did not open: the schema file
driving all of it is generated, not hand-written. This is that trap, and the second stop on the plumbing
run.</p>
<h2 id="the-schema-file-only-uploads-obey">The Schema File Only Uploads Obey</h2>
<p>Our client schema is generated per environment from the sync service's dashboard. It declares every synced
table and the type of every column, and it opens with a comment telling you it is machine-written.</p>
<p>Here is what makes it feel harmless: the local database ignores it.
<a href="https://www.powersync.com" target="_blank" rel="noopener noreferrer">PowerSync</a> keeps every value as text internally, so a wrongly declared column
behaves perfectly on the device. The upload path is where the same declaration stops being cosmetic. What
drains the upload queue there is our connector, the code that turns queued local rows into calls against
our write endpoint, and it reads those declarations to decide how to serialize each value:</p>
<div class="diagram">
<div class="diagram-head">One column, declared TEXT</div>
<div class="diagram-fork">
<div class="diagram-branch">
<div class="diagram-branch-title">Local database</div>
<div class="diagram-branch-rule">SQLite, ignores the declared type</div>
<div class="diagram-line">every value kept as text</div>
<div class="diagram-line">screens render, queries pass</div>
<div class="diagram-verdict is-ok">Nothing is wrong.</div>
</div>
<div class="diagram-branch">
<div class="diagram-branch-title">Upload connector</div>
<div class="diagram-branch-rule">our code, obeys the declared type</div>
<div class="diagram-line"><span class="diagram-key">TEXT</span> ships as a JSON string</div>
<div class="diagram-line"><span class="diagram-key">others</span> coerced to a JSON number</div>
<div class="diagram-verdict is-bad">"770.0" is rejected on the wire.</div>
</div>
</div>
</div>
<p>One declaration, two consumers, and they disagree about how much it matters. The local database can
afford to be wrong about a column type. The connector cannot. That is the whole setup.</p>
<p>The connector configuration and the wire format rules live in shared common Kotlin, so this single decision
covers both the iOS and the Android client. One place to get it right, and one place to get it wrong.</p>
<h2 id="the-fix-that-lasted-sixteen-days">The Fix That Lasted Sixteen Days</h2>
<p>The bug was a bottle volume. In production the dashboard had been hand-forced to declare that column
numeric; in staging, where nobody had done that, the same column in the same table came out as text. So
staging serialized the value as the string <code>"770.0"</code>, our write endpoint validated it as a number, and it
failed.</p>
<p>Nothing failed on the phone. Bottles were created, screens updated, and the local database was perfectly
happy. The rejection happened on the wire, and thanks to the lesson in
<a href="https://jenicek.dev/posts/offline-first-silent-success">Part 5</a>, it happened quietly.</p>
<p>Finding it was the expensive part. Fixing it took one word: a teammate changed the column type in the
staging schema file from text to a numeric type, uploads started passing, and the ticket closed.</p>
<p>Four weeks after the ticket closed, the same bug came back. Not a regression in our code, and not a new
column. A pull request of mine, merged sixteen days in and shipping a feature that had nothing to do with
bottles, needed three new columns, so it pulled a fresh schema from the staging dashboard. That dashboard
still described the volume column as text, because the underlying environment had never been migrated. So
my regeneration was correct, the one-word fix was overwritten, and a closed bug reopened itself with nobody
having typed anything wrong.</p>
<p>That is the moment worth keeping. The fix was not incomplete or sloppy, and the regeneration that undid it
was not careless. Both were correct. One of them was applied in a place that has no memory.</p>
<h2 id="the-dashboard-fix-works-once">The Dashboard Fix Works Once</h2>
<p>The obvious next move is to fix the dashboard instead, so the next regeneration produces the right file. We
tried that, and it works exactly once, per column, per environment.</p>
<p>Our sync service always maps a Postgres <code>numeric</code> column to a client text column, deliberately, to preserve
arbitrary precision. It is not a bug and it is not going to change. Which means every numeric column in the
schema is declared text on the client, every regeneration re-declares them text, and every one of them
would upload as a string if the connector believed the file.</p>
<p>So the choice was never "correct declaration versus wrong declaration." It was: fight the generator, per
column, per environment, forever, and pay that cost again every time somebody regenerates. Any fix whose
lifetime is bounded by the next regeneration is not a fix. It is a countdown.</p>
<h2 id="where-regeneration-cannot-reach">Where Regeneration Cannot Reach</h2>
<p>What we do now is treat the generated schema as one input among several, and hold the part it gets wrong
somewhere it cannot be touched.</p>
<p>The connector's configuration makes that concrete, and the interesting thing about it is where each piece
comes from:</p>
<div class="diagram">
<div class="diagram-head">Connector configuration</div>
<div class="diagram-rows">
<div class="diagram-row"><span class="diagram-row-name">Tables allowed to upload</span><span class="diagram-tag">hand-written</span></div>
<div class="diagram-row"><span class="diagram-row-name">Server-owned columns</span><span class="diagram-tag">hand-written</span></div>
<div class="diagram-row"><span class="diagram-row-name">Per-table upload rules</span><span class="diagram-tag">hand-written</span></div>
<div class="diagram-row is-derived"><span class="diagram-row-name">Text columns</span><span class="diagram-tag">derived from the generated schema</span></div>
</div>
<div class="diagram-formula">text columns = derive(<span class="is-fragile">generated schema</span>) &minus; <span class="is-safe">SERVER_NUMERIC_COLUMNS</span></div>
<div class="diagram-legend"><span><span class="is-fragile">&#9632;</span> overwritten by every regeneration</span><span><span class="is-safe">&#9632;</span> hand-written, out of reach</span></div>
</div>
<p>Three hand-written inputs, including the per-table upload rules
<a href="https://jenicek.dev/posts/offline-first-adapter-layer">Part 6</a> walks through, and one derived. Only the derived one ever
needed rescuing, and in hindsight that is not a coincidence: the derived input is the fragile one, so it is
the one that needs an escape hatch.</p>
<p>The derivation is worth keeping, because for genuinely textual columns it is exactly right and costs
nothing to maintain as the schema grows. What we subtract from it is <code>SERVER_NUMERIC_COLUMNS</code>, a small
hand-written map of the columns the server expects as numbers. Those are coerced to JSON numbers instead,
whatever the generated file happens to say this week. Nobody has to remember to add to that map, which is
the only reason a hand-written list is allowed anywhere near this problem.</p>
<p>The map is keyed by table, not by column name, and that detail is load-bearing: the same column name can be
genuinely numeric in one table and genuinely textual in another. A flat list of names would have quietly
broken the second case while fixing the first.</p>
<p>The regeneration still overwrites the schema file. It just no longer overwrites the decision.</p>
<h2 id="what-the-drift-test-refuses-to-trust">What the Drift Test Refuses to Trust</h2>
<p>A hand-written map is a rot risk. So we solved it the way this codebase solves every rot risk: make drift
fail the build.</p>
<p>The guard is a test, and what matters is what it reads. It does not check the map against the generated
schema, because the generated schema is the thing we already decided not to trust. It parses the database's
own <code>schema.sql</code>, the actual upstream source of truth, and compares that against the generated files for
every environment we ship.</p>
<p>It checks both directions, which matters more than it sounds:</p>
<ul>
<li>A synced column that is numeric upstream but is not in the map would upload as a string. This is the
case that matters most, because it is the one that arrives on its own: every numeric column added
upstream from now on starts life missing from the map. The build fails the first time it is synced, and
the message names the table and column to add.</li>
<li>An entry in the map that is not actually numeric upstream is either stale, because the column was renamed
or removed, or wrong, because somebody listed a genuinely textual column. One check catches both.</li>
</ul>
<p>It also fails loudly rather than skipping if it cannot locate <code>schema.sql</code>. A guard that can silently pass
is worse than no guard, because it converts a real check into a reassuring noise.</p>
<p>The proof that this landed is a detail I like more than the fix itself. In the generated file, the column
that started all of this is still declared as a numeric type, and that declaration no longer decides
anything, because the map covers the column either way. A future regeneration is free to drift it back to
text. That drift is the exact event that re-broke the bug once, and today it does nothing at all.</p>
<h2 id="the-takeaways">The Takeaways</h2>
<ul>
<li><strong>A generated file is an input, not a place to put decisions.</strong> Whatever you write there has a lifetime
bounded by the next regeneration, and that regeneration will arrive inside somebody else's unrelated pull
request.</li>
<li><strong>When a generator is reliably wrong about one thing, stop arguing with it.</strong> Derive what it gets right,
and hold the exception in code it cannot reach. Fighting a tool per case, per environment, is a recurring
cost disguised as a one-time fix.</li>
<li><strong>Point your guard at the upstream truth, not the artifact.</strong> Our test reads the database schema, because
checking the generated file against the generated file would only prove that codegen is deterministic.</li>
<li><strong>A fix has landed when its cause is allowed to come back.</strong> Not when the symptom disappears; that is
only the bug going quiet. The generated file is free to declare our column wrong again, because nothing
on the upload path asks it about that column any more.</li>
</ul>
<p>Next up (<a href="https://jenicek.dev/posts/offline-first-join-table-id">Part 8</a>): the junction row that needed an id of its own, and what sync down does to a table whose
primary key is two foreign keys.</p>
<h2 id="reference">Reference</h2>
<ul>
<li>PowerSync — <a href="https://docs.powersync.com/installation/client-side-setup/define-your-schema" target="_blank" rel="noopener noreferrer">Define your schema</a></li>
<li>PowerSync — <a href="https://docs.powersync.com/usage/sync-rules/types" target="_blank" rel="noopener noreferrer">Types</a></li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[Your Schema Is Not Your Payload]]></title>
      <link>https://jenicek.dev/posts/offline-first-adapter-layer</link>
      <guid>https://jenicek.dev/posts/offline-first-adapter-layer</guid>
      <pubDate>Thu, 20 Aug 2026 00:00:00 GMT</pubDate>
      <description><![CDATA[Your upload path is a translation layer whether you planned one or not. What your device stores and what your write endpoint accepts are rarely the same shape, and every difference is work that has to happen somewhere: inlining junction tables, dropping updates that must flow through events, stripping server-owned columns. Treat it as declarative, testable code, and watch which 'cosmetic' schema declarations secretly drive the wire.]]></description>
      <content:encoded><![CDATA[<p><em>Three mismatches on the upload path, and the day a bottle volume left the phone as the string "770.0".</em></p>
<p class="tldr"><strong>TL;DR</strong> Your upload path is a translation layer whether you planned one or not. What your device stores
and what your write endpoint accepts are rarely the same shape, and every difference is work that has to
happen somewhere: ours inlines junction tables, drops updates that must flow through events, and strips
server-owned columns. Treat it as declarative, testable code, and watch which "cosmetic" schema
declarations secretly drive the wire.</p>
<p><a href="https://jenicek.dev/posts/offline-first-silent-success">Part 5</a> was the first war story: a write the server turned away
while everything on the device reported green. This post stays on the upload path and asks the plainer
question underneath it: what, exactly, goes up?</p>
<p>The stack, for anyone joining here: one Kotlin Multiplatform (KMP) codebase for iOS and Android, with
<a href="https://www.powersync.com" target="_blank" rel="noopener noreferrer">PowerSync</a> as the sync layer in front of a Postgres backend
(<a href="https://jenicek.dev/posts/offline-first-kmp">Part 1</a> is why we picked it). PowerSync keeps a SQLite database on the
device, streams server changes down into it, and puts every local write into an upload queue. What
drains that queue is a <strong>connector</strong>: our code, not the library's, turning queued rows into calls
against our write endpoint. This one is about the least glamorous layer in the stack, and it opens a run
of posts on how the pipe between device and server actually gets built.</p>
<h2 id="why-the-local-db-to-server-arrow-is-a-lie">Why the Local-DB-to-Server Arrow Is a Lie</h2>
<p>Every offline-sync tutorial draws the same picture: local DB on the left, server on the right, a tidy
arrow between them labelled "sync." Writes flow right, truth flows left, everyone's happy.</p>
<p>The arrow is a lie. Or rather, the arrow is where a surprising amount of the actual work lives. What your
device writes to its local database and what your server's write endpoint is willing to accept are rarely
the same shape, and wherever they differ, <em>something</em> has to translate on every upload. In our stack that
something is the connector's upload path: the one segment of the sync loop PowerSync hands to you rather
than handling itself. It grew a whole small subsystem I never anticipated when I drew my own version of
the tidy arrow.</p>
<p>Here's what forced it into existence.</p>
<h2 id="mismatch-1-the-local-shape-isnt-the-wire-shape">Mismatch #1: The Local Shape Isn't the Wire Shape</h2>
<p>Take a many-to-many relationship, say a docket's certification record, which can carry several
certification types. Locally, we store that the way SQLite wants it: a junction table, one row per
(certification record, type) pair, so local joins and <code>GROUP_CONCAT</code> queries are cheap.</p>
<p>The write endpoint wants none of that. It wants the types <em>inlined</em> on the parent as an array
(<code>certification_type_ids: ["…", "…"]</code> on the docket-certification PUT), not a pile of separate junction
rows. On top of that, PowerSync needs every synced row to have a single <code>id</code> column, and a junction row
keyed by two foreign keys doesn't naturally have one. That second fact gets its own war story on the way
back <em>down</em>, later in the series; here it's just one more reason the local shape can't go up as-is.</p>
<p>So the upload path has to reach into the batch, collect the junction rows, fold them into an array on the
parent entry, and drop the junction rows before they go up. That's not a data model decision: it's a
<em>translation</em> decision, and it has to happen at upload time, per table.</p>
<h2 id="mismatch-2-some-updates-arent-allowed-to-go-up-at-all">Mismatch #2: Some Updates Aren't Allowed to Go Up at All</h2>
<p>Remember the event-sourcing rule from <a href="https://jenicek.dev/posts/offline-first-two-writes">Part 2</a>: for a lot of our
entities, <em>updates flow through events</em>, not through direct writes. A grower, a packaging type, an
additive definition: you can create one directly offline, but you can't just PATCH its fields and sync
that. Changes to it are supposed to travel as an <code>operational_event</code> the server's engine processes.</p>
<p>Except the local app still does a direct PATCH, because we want the optimistic UI to update instantly.
So locally there's a PATCH; but that PATCH must <strong>not</strong> reach the server, or you'd have two competing
update paths (the direct write and the event) racing each other.</p>
<p>So the upload path has to <em>drop</em> certain operations for certain tables. The PATCH is real, it drives the
local UI, and it's filtered out of the upload batch. The event carries the actual change.</p>
<h2 id="mismatch-3-some-columns-are-the-servers-to-write-not-yours">Mismatch #3: Some Columns Are the Server's to Write, Not Yours</h2>
<p>A few columns are <em>derived server-side</em>: computed by the backend from event payloads. An allergen flag
derived from an additive's allergen associations, for instance. The local projection fills those columns
in optimistically (again, instant UI), but if the client's optimistic value went up in a PUT, it would
overwrite the server's authoritative derivation with a guess.</p>
<p>So those columns get <em>stripped</em> from the outgoing payload. The device may compute them for display; it is
not allowed to tell the server what they are.</p>
<h2 id="three-levers-a-declarative-per-table-upload-rule-layer">Three Levers: A Declarative Per-Table Upload Rule Layer</h2>
<p>Three different mismatches, all resolved at the same point in the pipeline, all per-table. What started
as "just upload the queue" turned into a small, declarative rule layer: each table that needs special
handling declares what to do to its entries before they go up. It's common Kotlin, so this whole
translation layer is written once for both apps instead of reimplemented per platform. This is exactly
the fiddly per-table code you'd hate to maintain in two places. The levers, roughly:</p>
<ul>
<li><strong>Rewrite the batch:</strong> an escape hatch that sees the whole batch and can fold junction rows into their
parent (mismatch #1).</li>
<li><strong>Drop operations:</strong> e.g. "filter out PATCH for this table" (mismatch #2).</li>
<li><strong>Strip columns:</strong> e.g. "remove these server-derived columns from PUTs" (mismatch #3).</li>
</ul>
<p>The connector applies them in that order: the batch-rewrite pass first, then drop and strip per entry.
Each table's quirks live in one small rule object instead of being smeared through a giant <code>if</code> in the
upload function.</p>
<p>And (because this is a codebase that likes to sleep at night) there's a build-time test that fails if
the rules drift out of sync with the set of tables the server accepts. A table that's allowed up but has
no rule to constrain it is a leak; the test catches it before a human has to.</p>
<p>It's not clever. It's just honest about the fact that the wire format has opinions.</p>
<h2 id="the-bug-that-was-one-wrong-column-type">The Bug That Was One Wrong Column Type</h2>
<p>Here's how sharp those opinions get. This one cost me an unreasonable amount of time and came down to a
single wrong type in a schema file.</p>
<p>PowerSync's local database stores everything as TEXT internally: it genuinely does not care about your
declared column types for local operation. So a column declared as text instead of a number <em>works
perfectly locally</em>. Every screen renders. Every query returns. Nothing is wrong on the device.</p>
<p>But that schema file isn't cosmetic. Our connector derives, from the declared types, how to serialize
each column for upload: text columns ship as JSON strings, everything else gets coerced to a JSON number.
So a numeric column mistakenly declared as text uploaded its value as <code>"770.0"</code> (a <em>string</em>), and the
server's numeric validation rejected it. On the device: flawless. On the wire: type error. And thanks to
the lesson from <a href="https://jenicek.dev/posts/offline-first-silent-success">Part 5</a>, that rejection was quiet.</p>
<p>The fix was one type in one file. Finding it meant understanding that the same declaration drives two
completely different things: local storage (which ignores it) and upload serialization (which lives and
dies by it).</p>
<p><em>(There's a second trap here: that schema file is generated, not hand-authored, so "just edit the type" is
the wrong fix. <a href="https://jenicek.dev/posts/offline-first-generated-file">Part 7</a> is that story, and what we changed so a
regeneration can't re-break it.)</em></p>
<h2 id="the-shape-to-take-away">The Shape to Take Away</h2>
<ul>
<li><strong>The gap between your local schema and your wire format is real work.</strong> Plan for a translation layer
on the upload path; don't assume the shapes match. Junction tables, filtered operations, and
server-owned columns are the usual suspects.</li>
<li><strong>Make the per-table rules declarative and testable.</strong> One small rule object per table beats a sprawl
of special cases, and a drift test beats discovering a leak in production.</li>
<li><strong>A column type can be a no-op in one place and load-bearing in another.</strong> Ours is ignored by the local
store and decisive for upload serialization. Know which of your "cosmetic" declarations are secretly
driving the wire.</li>
</ul>
<p>That's the plumbing run's first stop. Next up (<a href="https://jenicek.dev/posts/offline-first-generated-file">Part 7</a>): why the
one-word fix above didn't stay fixed, and where a decision has to live so a regeneration can't reach it.
Parts <a href="https://jenicek.dev/posts/offline-first-join-table-id">8</a> and <a href="https://jenicek.dev/posts/offline-first-local-stack">9</a> stay down here in the plumbing too, then the series zooms out to the architecture
underneath it all.</p>
<h2 id="reference">Reference</h2>
<ul>
<li>PowerSync — <a href="https://docs.powersync.com/installation/client-side-setup/integrating-with-your-backend" target="_blank" rel="noopener noreferrer">Integrating with your backend</a></li>
<li>PowerSync — <a href="https://docs.powersync.com/installation/client-side-setup/define-your-schema" target="_blank" rel="noopener noreferrer">Define your schema</a></li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[HTTP 200 Is Not Success]]></title>
      <link>https://jenicek.dev/posts/offline-first-silent-success</link>
      <guid>https://jenicek.dev/posts/offline-first-silent-success</guid>
      <pubDate>Mon, 10 Aug 2026 00:00:00 GMT</pubDate>
      <description><![CDATA[A batch upload can return HTTP 200 while an operation inside it failed, and a sync connector must acknowledge those failures or wedge its queue. So data can vanish with everything reporting green. 'Success' is a per-operation outcome your transport cannot report for you: you have to build a channel to hear the failures you actually care about, and a place to keep the work they refused.]]></description>
      <content:encoded><![CDATA[<p><em>The event the server silently ate.</em></p>
<p class="tldr"><strong>TL;DR</strong> A batch upload endpoint can return HTTP 200 while an operation inside it failed, and a sync
connector must acknowledge those failures or wedge its queue. So data can vanish with everything
reporting green. "Success" is a per-operation outcome your transport cannot report for you: build a
channel to hear the failures you actually care about, and a place to keep the work they refused.</p>
<p><a href="https://jenicek.dev/posts/offline-first-two-writes">Part 2</a> established the two-write model, an uploaded event plus a
local projection. <a href="https://jenicek.dev/posts/offline-first-minting-ids">Part 3</a> had the client mint the ids. <a href="https://jenicek.dev/posts/offline-first-write-checkpoints">Part
4</a> let checkpoints sweep the provisional rows away. Those three
posts built the model. <strong>This is the first war story</strong>: <em>what happened when that model quietly failed and
still returned HTTP 200 while doing it.</em></p>
<h2 id="a-bug-with-no-error">A Bug With No Error</h2>
<p>The best bugs don't throw. This one didn't throw anywhere. No crash, no red log, no failed request. A
piece of data just wasn't there, sometimes, and everything upstream reported success.</p>
<p>The symptom: on the wine timeline (the history of everything that happened to a given wine), a
"wine created" entry was occasionally missing. The wine existed. Its volume was right. Its location was
right. But the little breadcrumb that says "this wine came into being here" wasn't on the timeline.</p>
<p>Everything that <em>mattered</em> was correct. Only a cosmetic marker was gone. Which is exactly why it took a
while to notice: everything we were watching — the HTTP status, the UI — said success. The failure was
sitting in the response body all along; back then, nothing was acting on it.</p>
<h2 id="the-breadcrumb">The Breadcrumb</h2>
<p>Quick context. Some of our actions create a wine as a <em>side effect</em>. Assign a docket to a tank and a
new wine is born in that tank. Transfer wine into an occupied tank and the blend produces a new wine.
The user didn't say "create a wine"; they said "assign" or "transfer." But a wine came out the far
side.</p>
<p>To make the timeline readable, whenever one of these side-effect wines is created we also emit a little
marker event: <code>CELLAR_WINE_CREATED</code>. It mutates nothing. Its only job is to give the timeline a row to
render: <em>a wine was created, here, by this action.</em> A breadcrumb.</p>
<p>And breadcrumbs were vanishing.</p>
<h2 id="reading-the-logs-where-the-200-lied">Reading the Logs: Where the 200 Lied</h2>
<p>The action itself always worked. Here's what a plain docket-to-tank assign <em>used to</em> do — online, no
conflict:</p>
<pre><code>record HARVEST_DOCKET_ASSIGN → operational_event (uploaded)
mint wine locally            → wine row          (local-only projection)
emit CELLAR_WINE_CREATED     → operational_event (uploaded)
</code></pre>
<p>Two events went up. Watching the upload batch:</p>
<pre><code>POST /v1/powersync/write
  HARVEST_DOCKET_ASSIGN  → 200 {"success":1,"error":0}
  CELLAR_WINE_CREATED    → 200 {"success":0,"error":1}
      results[1].error:
        "wine_id 159e8928… does not reference an existing wine"
</code></pre>
<p>The assign succeeded. The breadcrumb <em>failed validation on the server</em>, and the whole batch still came
back HTTP 200.</p>
<p>That's the first lesson, and it's a big one for anyone building a custom sync connector: <strong>for anything
our write endpoint turns away at the door, it returns 200 for the batch and reports the per-operation
failure inside the body.</strong> One failed op doesn't fail the request. If your connector only checks the HTTP
status, it sees green.</p>
<p>Failures on the other side of that door, after the row is accepted and stored, come back a different way
entirely. <a href="https://jenicek.dev/posts/offline-first-two-failure-contracts">Part 10</a> takes that one apart.</p>
<h2 id="why-the-connector-let-it-go">Why the Connector Let It Go</h2>
<p>Ours (one connector in common Kotlin, shared by both apps) did a little better than checking the status
blindly: it noticed the failed op and logged it. But then it did the only sane thing a
connector can do with a <em>permanently</em> rejected op: it acknowledged the batch and moved on.</p>
<p>Acknowledging is what clears the upload queue. Here's the bind you're in. If a rejected op is
<em>permanent</em> (it will fail identically no matter how many times you resend it) and you <em>don't</em>
acknowledge it, that one poison op wedges the queue forever, blocking every future upload behind it. The
user's next hundred actions never sync because op #1 keeps bouncing. So a connector essentially has to
acknowledge failures to stay alive.</p>
<p>But "acknowledge and move on" means a permanently rejected op is <strong>silently dropped after one attempt.</strong>
No retry. No user-visible error. No queue damage, and no trace unless you went looking in the logs. Our
breadcrumb was rejected, logged, acknowledged, and gone.</p>
<p>This is the first crack in a comfortable idea: that an offline-first app is <em>just a sync queue</em> — a
buffer you can trust to hold your writes until they land. It isn't. It's a queue that sometimes has to
drop what it can't deliver, and it drops it quietly. "The queue drained" and "your data arrived" turn out
to be two different claims.</p>
<h2 id="nothing-is-lost-at-the-door-either">Nothing Is Lost at the Door Either</h2>
<p>None of which means we shrugged. The breadcrumb bug is fixed, and a write the server turns away at the door
now goes to two places instead of a log line.</p>
<p>The first is an alert. A rejection at the door almost always means the two sides disagree about something
they should agree on: an inconsistency, or a bug. So the connector raises a Crashlytics non-fatal the moment
it sees one. That channel is for us. The team hears about it without the person in the cellar having to
notice anything, let alone report it.</p>
<p>The second is a ledger, and it is the part that changes what "acknowledge" means. The connector still
acknowledges the batch, because it has to. But before it does, it writes the refused operation to a table of
its own on the device: the operation's data, every column as the app wrote it; the error code and message
the server returned; the HTTP status; and when it was first and last refused, and how many times.
Acknowledging clears the queue. It no longer clears the record. If a later download proves the server has
the row after all, the entry retires itself. Otherwise the work is held, so that once whatever refused it is
fixed it can be replayed instead of retyped from memory. That replay is the recovery screen's job, and
<a href="https://jenicek.dev/series/offline-first-kmp#part-19">Part 19</a> is about that screen. "Acknowledge and move on" stopped meaning "gone".</p>
<p>Past the door, the record was already safe. That door is the only place an event can slip through; once the
server ingests one it can't silently disappear, because it always ends in a definite, stored
<code>processing_state</code> on its own row. Most version conflicts auto-resolve, the genuine ones are parked in
<code>CONFLICT_RESOLUTION_REQUESTED</code> for a human decision, and anything that can't be processed is parked in a
terminal <code>PROCESSING_FAILURE</code> or <code>VALIDATION_FAILED</code>, sitting in the server database, queryable and there to
act on. Showing both kinds of held work to the person who did it is that same screen.</p>
<p><em>Why</em> the two ids diverged, and the identity-minting fix behind it, is a bigger thread than this post wants
to pull, so it gets its own: <a href="https://jenicek.dev/posts/offline-first-shared-id">Part 12</a>.</p>
<h2 id="the-takeaways">The Takeaways</h2>
<ul>
<li><strong>HTTP 200 is not success.</strong> If your backend reports per-operation results in the body, your connector
must inspect the body, not the status code. It's the single easiest place to lose data without knowing.</li>
<li><strong>A sync connector has to acknowledge failures, or it wedges the queue.</strong> A permanent rejection you
refuse to acknowledge blocks everything behind it; a permanent rejection you <em>do</em> acknowledge is
dropped, unless you keep it yourself. There's no free option on the queue, so decide, deliberately,
which failures you want to be loud, and keep the refused work somewhere the acknowledgement can't reach.</li>
<li><strong>The nastiest offline bugs are the ones where everything reports success.</strong> No throw, no red log,
just an absence. Build the observability to see absences, because your error handling won't.</li>
</ul>
<p>Next up (<a href="https://jenicek.dev/posts/offline-first-adapter-layer">Part 6</a>): the layer nobody warns you about, the messy
adapter between your local database and your actual write endpoint, and the one-line schema mistake that
shipped <code>"770.0"</code> as a string.</p>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[The Write You Never Clean Up]]></title>
      <link>https://jenicek.dev/posts/offline-first-write-checkpoints</link>
      <guid>https://jenicek.dev/posts/offline-first-write-checkpoints</guid>
      <pubDate>Mon, 03 Aug 2026 00:00:00 GMT</pubDate>
      <description><![CDATA[Your optimistic local row gets replaced by the server's authoritative one with no cleanup code of yours. PowerSync write checkpoints hold incoming server state until your uploads are accounted for, then reconcile the local database to match — sweeping away any row the server never knew about.]]></description>
      <content:encoded><![CDATA[<p><em>Provisional state should be disposable: let the sync layer reconcile it, don't write cleanup.</em></p>
<p class="tldr"><strong>TL;DR</strong> In an offline-first app you can write throwaway optimistic rows and never clean them up.
PowerSync's <strong>write checkpoints hold incoming server state until your uploads are accounted for</strong>,
then reconcile the local database to match, sweeping away any local row the server never knew about. You
lean on that one mechanism instead of writing reconciliation code by hand.</p>
<p><a href="https://jenicek.dev/posts/offline-first-two-writes">Part 2</a> established the two-write model (an uploaded event plus a
local-only projection) and made a promise I didn't cash: your provisional local row gets replaced by the
server's authoritative one <em>with no cleanup code of yours</em>. This post is where that promise gets paid,
and it's the one I most misunderstood when I first read the logs.</p>
<h2 id="the-cleanup-code-you-never-write">The Cleanup Code You Never Write</h2>
<p>Here's that two-write model again, on a fresh example. You perform an action offline, such as
recording a fruit intake. The client writes a local, provisional copy of the resulting entity, a
<code>docket</code> row, so the UI updates instantly. That row is never uploaded. Eventually the event syncs and the
server processes it. The server writes its authoritative version of that docket, reusing the very id the
client already minted for it (<a href="https://jenicek.dev/posts/offline-first-minting-ids">Part 3</a>), and syncs it back down.</p>
<p>Two rows now describe the same docket: your local guess and the server's truth. The claim is that they
resolve to one, the server's, and <strong>you write no code to make that happen.</strong> No diffing. No "if the
server row arrived, delete my local one." Nothing.</p>
<p>The first time someone tells you this, it sounds like hand-waving. It isn't. It's a specific PowerSync
mechanism called <strong>write checkpoints</strong>, and understanding it is the difference between trusting the
architecture and quietly wondering whether those provisional rows ever really get cleaned up, or are
just silently piling up in your database.</p>
<h2 id="why-could-not-apply-checkpoint-is-not-an-error">Why "Could Not Apply Checkpoint" Is Not an Error</h2>
<p>When I first watched the sync logs, I saw this and panicked:</p>
<pre><code>Could not apply checkpoint due to local data.
Will retry at completed upload or next checkpoint.
</code></pre>
<p>I read "could not apply" as an error. It looks like one. It's not. It's the mechanism working exactly
as designed. To see why, you have to know what a checkpoint <em>is</em>.</p>
<h2 id="the-upload-queue-and-the-checkpoint-gate">The Upload Queue and the Checkpoint Gate</h2>
<p>PowerSync keeps a local upload queue: every local change you make that's meant to sync gets an entry in
it. Uploading drains the queue by handing those changes to your connector, which POSTs them to your
backend.</p>
<p>Downloading is separate. The server periodically publishes a <strong>checkpoint</strong>, a consistent snapshot of
what your buckets of data should contain. When the client receives one, it reconciles the local database
to match it.</p>
<p>Now the crucial rule, the one that makes everything work:</p>
<blockquote>
<p><strong>PowerSync will not apply a downloaded checkpoint while your local upload queue still has pending
changes.</strong></p>
</blockquote>
<p>Think about why that has to be true. If the client applied server state on top of local un-uploaded
edits, it would clobber writes the user made offline that the server hasn't even seen yet. So PowerSync
gates: pending local writes hold the checkpoint, and it retries once the queue is drained. That log line
I panicked over is the gate doing its job.</p>
<h2 id="what-happens-when-the-checkpoint-gate-opens">What Happens When the Checkpoint Gate Opens</h2>
<p>So the sequence for one of our offline actions is:</p>
<ol>
<li>You act. The client writes the event (queued for upload) <strong>and</strong> the local-only projection row.</li>
<li>Upload runs. The connector (common Kotlin, one copy for both apps) sends the event. The projection
row is local-only, so the connector filters it out of the batch. Critically, it still marks the whole
batch complete. As far as PowerSync is concerned, your local writes are accounted for and the queue
drains.</li>
<li>With the queue empty, the gate opens. The next checkpoint applies.</li>
</ol>
<p>And here's the payoff. When the checkpoint applies, PowerSync reconciles the local database to <em>exactly</em>
what the server says your buckets contain. Your provisional projection row is <strong>not</strong> in any server
bucket, because you never uploaded it. So PowerSync removes it. In the same reconcile, the server's
authoritative docket row (which <em>is</em> in a bucket now, because the server processed your event and created
it) lands. One row out, one row in.</p>
<pre><code>Validated and applied checkpoint
</code></pre>
<p>That's the sibling log line to the one that scared me. Gate closed, then gate opened. From your code's
perspective: you wrote a row, and later it was quietly replaced by the real one. You wrote nothing to
make that happen.</p>
<p>PowerSync's own docs describe this exact behavior for a local change that never gets persisted upstream:
it "will effectively seem as if [it] was reverted on the server." That's precisely what we're
<em>deliberately</em> leaning on. The revert isn't a failure mode we tolerate; it's the cleanup we designed
around.</p>
<p>Leaning on a revert only feels reckless if you picture the reverted row as something you can't get back.
It isn't. What reverts is the projection, never the event: the event is the immutable record the
two-write model uploads, and it left the device via the upload queue before the sweep ever runs. The
sweep removes a disposable guess; the durable fact was never stored in that row to begin with.</p>
<h2 id="why-the-client-minted-id-has-to-match">Why the Client-Minted ID Has to Match</h2>
<p>This is where the client-minted id pays off. If your local projection and the server's authoritative
row had <em>different</em> ids, the reconcile wouldn't be "one row out, one row in": it'd be your row removed
and a <em>different-looking</em> row added, and for a flicker the UI would lose the entity entirely, or worse,
briefly show two.</p>
<p>Because the client mints the id and the server uses that same id, the two rows are the <em>same</em> row by
primary key. The reconcile is seamless: same id, new (authoritative) contents. The entity never
disappears from the user's view; its data just firms up from "my guess" to "confirmed."</p>
<p>The exact contract that gets the client's id onto the server's row has a subtle edge or two, enough to
fill a later war story in this series. For this post, the thing that matters is only that the ids match,
and we've already covered why minting that id on the client is safe.</p>
<h2 id="the-shape-to-take-away">The Shape to Take Away</h2>
<p>The whole local-only-projection model (instant UI, no cleanup code) rests on a single mechanism:
<strong>PowerSync gates downloaded checkpoints behind a drained upload queue, then reconciles the local database
to server truth, dropping any local row that isn't in a server bucket.</strong></p>
<p>Once you see that, the scary log line becomes reassuring. "Could not apply checkpoint due to local data"
means: <em>your offline writes are safe, I'm holding server state until they're accounted for.</em> And
"Validated and applied checkpoint" means: <em>they're accounted for now, here's the real world.</em> Your
throwaway rows aren't piling up somewhere waiting to bite you. They're swept, exactly once, by the same
sweep that brings you the truth.</p>
<p>That's the mechanism under the "no cleanup code of ours" promise. Later in the series I'll switch from
mechanics to war stories, starting with the time this exact model dropped an event on the floor and
reported success while doing it.</p>
<h2 id="reference">Reference</h2>
<ul>
<li>PowerSync — <a href="https://docs.powersync.com/architecture/consistency" target="_blank" rel="noopener noreferrer">Consistency</a></li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[Minting IDs Before the Server]]></title>
      <link>https://jenicek.dev/posts/offline-first-minting-ids</link>
      <guid>https://jenicek.dev/posts/offline-first-minting-ids</guid>
      <pubDate>Mon, 27 Jul 2026 00:00:00 GMT</pubDate>
      <description><![CDATA[Offline, you can't wait for a server to hand you an id. The client mints it at creation — a random UUID — so a new entity is addressable immediately, referenceable by the very next offline action. That one move deletes temporary ids and a whole class of reference-rewrite bugs.]]></description>
      <content:encoded><![CDATA[<p><em>Identity is asserted by the client, not granted by the server.</em></p>
<p class="tldr"><strong>TL;DR</strong> Offline, you can't wait for a server to hand you an id. The client mints it at creation (a
random UUID), so a new entity is addressable immediately, referenceable by the very next offline action.
That one move deletes temporary ids and the whole class of reference-rewrite bugs that come with them.</p>
<p>In <a href="https://jenicek.dev/posts/offline-first-two-writes">Part 2</a> I covered the two-write model: an immutable event you
upload, and a local projection you render. This one is about a smaller question that turns out to gate
everything — what's the <em>id</em> of a thing you just created offline?</p>
<h2 id="why-offline-apps-cant-wait-for-a-server-assigned-id">Why Offline Apps Can't Wait for a Server-Assigned ID</h2>
<p>Picture a cellar hand at the crush pad with no signal. A truck of fruit arrives; they record an intake.
That creates a docket. Now, immediately (same screen, still offline), they assign that docket to a
tank. The assignment has to <em>refer to the docket that doesn't exist on any server yet</em>.</p>
<p>In a request/response app you'd never hit this. You POST the docket, the server returns its id, you use
that id for the next call. Identity is something the server hands you.</p>
<p>Offline, that model is gone. There is no server in the loop, and there won't be for hours. The docket
needs an id the instant it's created, minted by the device, and that id has to be good enough to build
on: to reference in the very next action, to store in the local projection, to survive until the
network comes back.</p>
<p>So the rule we landed on is blunt: <strong>the client mints the id. Always. At creation time.</strong></p>
<pre class="shiki github-light" style="background-color:#fff;color:#24292e" tabindex="0"><code><span class="line"><span style="color:#D73A49">val</span><span style="color:#24292E"> docketId </span><span style="color:#D73A49">=</span><span style="color:#24292E"> Uuid.</span><span style="color:#6F42C1">random</span><span style="color:#24292E">()</span></span></code></pre>
<p>One line of common Kotlin, so iOS and Android mint ids from one implementation, not two that could
drift. That's it. That's the whole trick. But the objections it raises are the interesting part.</p>
<h2 id="why-uuid-collisions-arent-a-real-risk">Why UUID Collisions Aren't a Real Risk</h2>
<p>This is the first question everyone asks, and it's the wrong thing to be scared of.</p>
<p>A random UUID (v4) is 122 bits of entropy. The number of ids you'd need to generate before a collision
becomes <em>plausible</em> is roughly a quintillion (a billion billion). Our entire userbase, generating dockets
and wines and vessels all day for a century, doesn't get within astronomical distance of that. You are
more likely to lose the database to a meteor.</p>
<p>The instinct to fear client-side ids comes from the world of auto-incrementing integer primary keys,
where two clients both picking "id 47" is a certainty, not a risk. UUIDs exist precisely to kill that
problem. Once you internalize that a random id is <em>safe to invent anywhere</em>, offline creation stops
being scary.</p>
<p>One honest note before we move on: those 122 bits are only as safe as the randomness behind them. If a
device's random numbers are predictable — a weak generator, or two devices that happen to start from the
same seed — the ids can collide no matter how large the keyspace is. <code>Uuid.random()</code> sidesteps that by
pulling from each platform's <em>cryptographically secure</em> random source: the kind hardened for generating
keys and passwords, not the fast-but-predictable kind you'd use to shuffle a playlist (concretely:
<code>SecureRandom</code> on Android/JVM, the system secure source on iOS and the server). So the 122 bits of
entropy are real, and the math above actually holds.</p>
<h2 id="what-happens-if-two-ids-collide">What Happens If Two IDs Collide</h2>
<p>Say the cosmic-ray case actually lands: two devices mint the same id for two genuinely different entities.
Nothing merges and nothing corrupts. The id is the primary key, and entities are written with a plain
<code>INSERT</code>, not an upsert, so the second create hits the key constraint, rolls back, and the event is
parked: still recorded on the server, still logged for us to see, just never materialized into a row. Two
real things can't silently collapse into one. And because it's parked on the same event-sourced substrate
we use for conflicts, it stays resolvable.</p>
<h2 id="what-the-client-minted-id-buys-you">What the Client-Minted ID Buys You</h2>
<p>With the fear out of the way, the positive case is where it gets interesting. The id isn't just a local
convenience — it's the thing that makes the next three problems solvable.</p>
<p><strong>1. You can reference a thing the moment it exists.</strong> Docket assigned to a vessel in the same offline
session? The assignment event just carries the docketId that was minted a second ago. No "temporary id"
you have to rewrite later when the server responds. No placeholder. The id is real from birth.</p>
<p><strong>2. Your local projection has a stable primary key.</strong> Remember from
<a href="https://jenicek.dev/posts/offline-first-two-writes">Part 2</a> that we write a local, provisional copy of every entity for
instant UI. That row needs a primary key <em>now</em>, and it needs to be the <em>same</em> key the entity will have
forever, including after the server gets involved. Client-minted id gives you exactly that.</p>
<p><strong>3. References survive offline chains.</strong> Create a wine, split it into three, move one of the children,
add an analysis to another, all offline, all before a single byte reaches the server. Every one of
those actions refers to ids minted moments earlier on the same device. The whole chain is internally
consistent because every id in it is real from the moment it was invented.</p>
<h2 id="the-temporary-id-trap-we-avoided">The Temporary-ID Trap We Avoided</h2>
<p>The usual alternative (I've written it, years ago, and regretted it) is a temporary id: create the entity
as <code>temp_1</code>, and when the server returns the "real" id, rewrite every reference to it.</p>
<p>That breaks on offline chains. <code>temp_1</code> is referenced by <code>temp_2</code>, which is referenced by <code>temp_3</code>, the
network comes back mid-chain, and you're rewriting a graph while new writes still land. Worse, <code>temp_1</code> is
baked into an event you already recorded, and events are append-only
(<a href="https://jenicek.dev/posts/offline-first-two-writes">Part 2</a>). You can't rewrite it at all.</p>
<p>Client-minted ids remove the problem: the id the client minted <em>is</em> the real id. It travels with the event
and the server reuses it, so both sides agree. That holds only if the server reuses the client's id for
<em>every</em> entity an event creates.
<a href="https://jenicek.dev/posts/offline-first-shared-id#the-root-cause-two-wines-two-ids">Part 12</a> is what happened when it minted
its own id for one wine instead.</p>
<h2 id="the-shape-to-take-away">The Shape to Take Away</h2>
<p><strong>Identity is not something the server grants you: it's something the client asserts.</strong> In an
offline-first app, an entity has to be fully addressable at the instant of creation, using an id good
enough to build a chain of further actions on, before any server has heard of it. Random UUIDs make that
safe. Once you stop treating identity as a server privilege, a whole category of offline bugs (temporary
ids, reference rewrites, "which id is the real one") simply never gets written.</p>
<p>Next up (<a href="https://jenicek.dev/posts/offline-first-write-checkpoints">Part 4</a>): you've got a local row with a client-minted id, and eventually the server sends down
its own authoritative version. How does your provisional row get out of the way, with no cleanup code
of yours? The answer is a PowerSync mechanism that looks, at first, like a bug.</p>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[Two writes for every tap]]></title>
      <link>https://jenicek.dev/posts/offline-first-two-writes</link>
      <guid>https://jenicek.dev/posts/offline-first-two-writes</guid>
      <pubDate>Fri, 17 Jul 2026 00:00:00 GMT</pubDate>
      <description><![CDATA[The write your UI reads is not the write your server trusts. In an offline-first app, every user action produces two local writes — an immutable event you upload, and a provisional projection you render so the UI updates instantly.]]></description>
      <content:encoded><![CDATA[<p><em>The write your UI reads is not the write your server trusts.</em></p>
<p class="tldr"><strong>TL;DR</strong> Every user action produces <strong>two local writes</strong> — an immutable event you upload, and a
provisional projection you render so the UI updates instantly. The event is what the server trusts; the
projection is a disposable guess. Keep them separate and the app behaves identically whether the device
is online or off.</p>
<h2 id="the-problem-with-just-sync-it">The Problem With "Just Sync It"</h2>
<p>In <a href="https://jenicek.dev/posts/offline-first-kmp">Part 1</a> I picked <strong>PowerSync</strong> and hand-waved the hard part: choosing a sync engine is the easy 20%. The
other 80% is deciding what your app writes, when, and what the user sees while the server hasn't heard
about any of it yet.</p>
<p>Here's the constraint that shapes everything. Our users are cellar hands: people moving wine between
tanks, recording intake at the crush pad, blending, bottling. Half the time they're down in the
cellar with no signal. When someone taps "move this wine to Tank 7," the app cannot wait for a
server to agree. The screen has to update <em>now</em>, on a device that might not reconnect for hours.</p>
<p>So the naive model (tap, send request, wait, update UI) is dead on arrival. What replaces it is a
pattern that felt strange the first time I wrote it: <strong>every user action produces two local writes.</strong></p>
<h2 id="write-1-the-event-what-happened">Write #1: The Event (What Happened)</h2>
<p>The first write is an immutable record of <em>intent</em>. Not "wine X is now in Tank 7," but "at 14:32, this
user moved wine X to Tank 7." A fact about the past, in an append-only log. We call it an
<code>operational_event</code>.</p>
<pre><code>User taps "Move to Tank 7"
  │
  └─ record CELLAR_WINE_TRANSFER → operational_event row
</code></pre>
<p>This row is the thing that gets uploaded. It's the only thing the server ultimately trusts. Everything
else in the local database is, in a sense, a guess.</p>
<p>The reason it's an <em>event</em> and not a <em>state update</em> is a whole topic of its own, and one I'll set aside
here to keep this post about the mechanics. For now the takeaway is enough: we write down what the user
did, not what we think the world now looks like.</p>
<h2 id="write-2-the-projection-what-you-see">Write #2: The Projection (What You See)</h2>
<p>But an event log doesn't render a screen. The user doesn't want to see "you recorded a transfer event."
They want to see wine X sitting in Tank 7, right now, with the right volume.</p>
<p>So the second write takes that event and <em>projects</em> it into the entity tables the UI reads from:
<code>wine</code>, <code>vessel</code>, <code>docket</code>, all rows in PowerSync's local database. A local engine reads the transfer
event and updates the local rows: Tank 7 now shows wine X, the source vessel shows empty, volumes adjust.</p>
<pre><code>User taps "Move to Tank 7"
  │
  ├─ record CELLAR_WINE_TRANSFER → operational_event row (uploaded)
  │
  └─ project it                  → wine / vessel rows    (local-only)
</code></pre>
<p>The screen updates instantly because the rows it reads from just changed, with no network in the loop.
We call this Zero-Flicker: the UI never shows a spinner waiting for a round trip, and it never shows the
old state for a frame before snapping to the new one.</p>
<p>The engine that does this projection is common Kotlin: iOS and Android share one definition of what a
transfer <em>means</em>, instead of each platform reimplementing it. It's deliberately dumb about the network;
it just derives current state from an event.</p>
<h2 id="the-part-that-feels-wrong">The Part That Feels Wrong</h2>
<p>Here's the detail that trips people up: <strong>the projection is never uploaded.</strong></p>
<p>Only the event goes to the server. The <code>wine</code> and <code>vessel</code> rows you just wrote locally stay local. They
exist purely to paint the screen while you wait for the server to process your event and send back its
own authoritative version of those same rows.</p>
<p>The first reaction is always "so I'm writing data I'm going to throw away?" Yes. Exactly that. The local
projection is a provisional answer: a bet that the server will agree. When the server's version syncs
back, it replaces your local guess.</p>
<p>The reason this is safe, the part that made me trust this architecture, is that the projection is
disposable <em>by construction</em>: the event it came from is permanent. It's an append-only fact that never
gets edited or deleted, so the projection is always re-derivable from it. Throwing away the local guess
costs nothing, because nothing was ever really <em>stored</em> there — the truth lives in the event log, and
the projection is just the log read out loud.</p>
<p>And <em>because</em> the projection is re-derivable, you don't even write the reconciliation. You don't diff,
you don't delete your optimistic row when the real one arrives. The sync layer reverts your local guess
when the authoritative row syncs down, through a mechanism I unpack in
<a href="https://jenicek.dev/posts/offline-first-write-checkpoints">Part 4</a>.</p>
<h2 id="why-split-it-this-way">Why Split It This Way</h2>
<p>You could imagine collapsing the two writes into one: just update the entity tables and sync those. Lots
of offline apps do exactly that. Here's what you lose.</p>
<ul>
<li><strong>The event is the truth; the entity is a view.</strong> If a projection is wrong (a bug, a bad assumption
about current state), you fix the projection logic and re-derive. You correct the view, never the
history — a display bug never becomes a reason to rewrite what the user actually did.</li>
<li><strong>The server can be late without being wrong.</strong> Because the client and server both derive state from
the same events, "the device is ahead of the server" is a normal, expected condition, not a
desync bug. The device shows its best guess; the server confirms or corrects; they converge.</li>
<li><strong>Conflicts have somewhere to live.</strong> When two cellar hands move the same wine on two disconnected
phones, you have two events, both real, both recorded. Nothing is lost. What happens next is a
genuinely interesting problem, and too big to bury in a subsection here.</li>
</ul>
<h2 id="the-shape-to-take-away">The Shape to Take Away</h2>
<p>If you remember one thing: <strong>in an offline-first app, the write your UI reads and the write your server
trusts are not the same write.</strong> One is a provisional projection for instant feedback; the other is an
immutable fact you upload. Keeping them separate is what lets the app behave identically on a plane and
at a desk.</p>
<p>Next up (<a href="https://jenicek.dev/posts/offline-first-minting-ids">Part 3</a>): those local rows need IDs before any server has
heard of them. Minting identity on the client, and why UUID-collision anxiety is misplaced.</p>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[Your API key is not a secret]]></title>
      <link>https://jenicek.dev/posts/your-api-key-is-not-a-secret</link>
      <guid>https://jenicek.dev/posts/your-api-key-is-not-a-secret</guid>
      <pubDate>Fri, 05 Jun 2026 00:00:00 GMT</pubDate>
      <description><![CDATA[We have been hiding API keys in Android apps for a decade — with BuildConfig tricks, NDK, obfuscation libraries. None of it works. The fix is not better hiding; it is treating the key as a public identifier and proving the app is genuine instead.]]></description>
      <content:encoded><![CDATA[<p>I just gave a talk at mDevCamp called <em>Your API Key Is Not a Secret</em>. This is the short version for anyone who missed it — or who watched it and wants the ideas without the stage banter.</p>
<div class="youtube-embed" data-youtube-id="q7kYt-WPTwQ"><a class="youtube-embed-link" href="https://www.youtube.com/watch?v=q7kYt-WPTwQ" target="_blank" rel="noopener noreferrer" aria-label="Watch on YouTube"><img class="youtube-embed-thumb" src="https://i.ytimg.com/vi/q7kYt-WPTwQ/hqdefault.jpg" alt="" loading="lazy" /><svg class="youtube-embed-play" viewBox="0 0 68 48" aria-hidden="true" focusable="false"><path d="M66.52 7.74c-.78-2.93-2.49-5.41-5.42-6.19C55.79.13 34 0 34 0S12.21.13 6.9 1.55C3.97 2.33 2.27 4.81 1.48 7.74 0 13.05 0 24 0 24s0 10.95 1.48 16.26c.78 2.93 2.49 5.41 5.42 6.19C12.21 47.87 34 48 34 48s21.79-.13 27.1-1.55c2.93-.78 4.64-3.26 5.42-6.19C68 34.95 68 24 68 24s0-10.95-1.48-16.26z" fill="#f00"/><path d="M45 24L27 14v20z" fill="#fff"/></svg></a></div>
<h2 id="the-reframe">The reframe</h2>
<p>Here is the question I opened with: <strong>what is the difference between a password and a username?</strong></p>
<p>You would say one is secret and one is not. But that is not a property of the string. The same thirty-two characters can be a password if I keep them, or a username if I publish them. <em>Secret</em> is not something the string is — it is something we do to the string.</p>
<p>So the obvious follow-up: which one is the API key in your Android app?</p>
<p>It ships inside the APK. Anyone who downloads it from the Play Store gets a copy. Apktool will surface it in seconds. BuildConfig wrappers, NDK, string obfuscation, key splitting — these are speed bumps, not secrets. <strong>A key you have published to every device on Earth is a username.</strong> It just happens to be one we have been treating like a password.</p>
<h2 id="a-different-question">A different question</h2>
<p>The API key was supposed to answer one question: <em>is this request authorized?</em></p>
<p>It cannot, because you cannot keep it. So instead of trying harder to hide it, ask a different question:</p>
<blockquote>
<p>Is this request coming from my genuine app, on a genuine device, at this moment?</p>
</blockquote>
<p>That is not a question a key can answer. That is a question that needs proof from <em>outside the app</em> — proof an attacker cannot replicate by copying bytes out of your APK.</p>
<p>On Android, that proof comes from Google Play. Your app asks Google for a token. Google looks at the binary, the device, and the account, and hands back a signed verdict. Your app forwards the verdict to your backend. Your backend asks Google to decode it. If the verdict says <em>yes, this is your real app on a real device</em>, the request goes through. Otherwise, 403.</p>
<p>Three parties instead of two. The third one — Google Play — is the notary. It cannot be bribed by the attacker, because it is not running attacker code.</p>
<h2 id="the-pattern-in-three-lines">The pattern in three lines</h2>
<ol>
<li>App asks Google for proof of genuineness.</li>
<li>App sends that proof to your backend together with the request.</li>
<li>Your backend trusts Google, not the app.</li>
</ol>
<p>The API key still exists. It still ships in the APK. But it is doing nothing load-bearing — it is just a label, a username. The thing that actually authorizes the request is the verdict from Google, bound to that specific request, valid only for a few minutes.</p>
<p>A stolen key is no longer enough. To replay the request, the attacker needs a verdict — and to get a verdict they need a genuine, unmodified, Play-Store-installed copy of your app running on a real device. That is a very different shopping list from "copy a string out of an APK."</p>
<h2 id="when-this-pattern-actually-matters">When this pattern actually matters</h2>
<p>This is the part I want to dwell on, because it is where teams over-apply or under-apply the pattern.</p>
<p>The right question is not <em>"is this endpoint sensitive?"</em> but <strong>"what is the blast radius if it gets abused?"</strong></p>
<p>Imagine an app with no login. Every screen makes API calls, but those calls fall into two very different categories:</p>
<ul>
<li>
<p><strong>The app calls a third-party public API directly</strong> — for example, CoinGecko for the coin catalog, or Coinbase for live prices. The upstream sees the abuser's IP and rate-limits <em>them</em>. Your other users keep working fine. The blast radius is the abuser, not your user base. <strong>You do not need integrity here.</strong> Skip the complexity. Their backend, their business.</p>
</li>
<li>
<p><strong>The app calls <em>your</em> backend, which is hiding a paid third-party key</strong> — a news endpoint fronting a paid NewsAPI key, an error-reporting endpoint forwarding to your Sentry quota. The upstream sees one account: yours. If someone hammers it, NewsAPI throttles your project, the feature breaks for <em>every</em> user of your app, and you eat the bill. <strong>This is exactly where the pattern earns its keep.</strong> Your backend, your secrets.</p>
</li>
</ul>
<p>Same app. Same user. Two architectures, two intentional decisions. The rule of thumb: <strong>wrap an endpoint in integrity when the cost of abuse lands on you, not on the upstream.</strong></p>
<h2 id="what-about-authenticated-requests">What about authenticated requests?</h2>
<p>A reasonable objection: <em>"My API is behind login. Each user has a token. Isn't that enough?"</em></p>
<p>For most apps, yes — and that is a good thing. A logged-in user already has a per-user identity, per-user rate limiting, and a clear blast radius (one account). Integrity verification on every authenticated call is rarely worth the operational complexity it adds.</p>
<p>Where integrity <em>still</em> helps after login is the <strong>signup, login, and password-reset endpoints themselves</strong> — the small set of routes that have to be reachable without a session and that attackers love (credential stuffing, fake account creation, OTP spam). Treat those like the no-login case. The endpoints behind them, once a real user is authenticated, can usually rely on the auth token alone.</p>
<h2 id="what-the-pattern-does-not-do">What the pattern does not do</h2>
<p>Two things to be honest about.</p>
<p><strong>It is not unbreakable.</strong> On a rooted device with kernel-level tooling, motivated attackers can spoof some of the device verdicts. What the pattern does is move attacker cost from <em>"apktool plus curl, twelve seconds, zero dollars"</em> to <em>"rooted device, custom kernel modules, ongoing maintenance per device."</em> For almost every app that is not a bank, that is the right trade.</p>
<p>And there is a second shift worth naming. A scraped key lets one attacker hide inside an anonymous flood — every request looks like any other call from your app, and you cannot tell abuse apart from real users. A bypass attacker does not get that anonymity: each compromised device has a real cost to set up, and each one carries a fingerprint your backend can see and ban. The damage stops being a faceless wave and becomes a small set of trackable, blockable instances. That is a very different incident to triage at 3am.</p>
<p><strong>It excludes some users.</strong> Non-Play installs — F-Droid, sideloaded debug builds, GrapheneOS, Huawei without GMS — fail the verdict. Know your audience before you ship this. If half your users are on alternative app stores, this pattern is not for you.</p>
<h2 id="the-takeaway">The takeaway</h2>
<p>You will still have an API key in your app. That is fine. <strong>Stop treating it like a password.</strong> It is a username — a public identifier — and the moment you accept that, the rest of the architecture falls into place.</p>
<p>Move real secrets to a backend. Prove the app is genuine — not the key. Use the pattern where the blast radius of abuse lands on you, and skip it where the upstream is already self-policing.</p>
<p>The platform changes. The architecture does not.</p>
<p><img src="https://jenicek.dev/assets/blog/post/api-key-not-secret/link-screen.jpg" alt="Resources from the talk: sample Android app and sample BFF (Kotlin / Ktor) on GitHub at github.com/MjDevCz"></p>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[Choosing an offline-first sync layer for KMP]]></title>
      <link>https://jenicek.dev/posts/offline-first-kmp</link>
      <guid>https://jenicek.dev/posts/offline-first-kmp</guid>
      <pubDate>Sun, 12 Apr 2026 00:00:00 GMT</pubDate>
      <description><![CDATA[When your mobile app must work without internet as a standard — not an edge case — picking the right sync layer becomes the most critical architectural decision. Here is how we evaluated the landscape.]]></description>
      <content:encoded><![CDATA[<p class="tldr"><strong>TL;DR</strong> When your mobile app must work without internet as a <strong>standard, not an edge case</strong>, picking the right sync layer becomes the most critical architectural decision. This is the story of how we evaluated the offline-first landscape for a Kotlin Multiplatform (KMP) project.</p>
<h2 id="the-requirements">The requirements</h2>
<p>We needed a solution that supports <strong>KMP (iOS &#x26; Android)</strong>, handles <strong>bidirectional sync</strong> with a cloud database, respects <strong>relational data</strong> with complex entity relationships, and fits within a tight timeline — 4 months, 2 mobile engineers.</p>
<p>That last constraint was key. Whatever we chose had to provide enough out of the box that we wouldn't spend half the project building sync infrastructure.</p>
<h2 id="the-landscape">The landscape</h2>
<p>The offline-first space is evolving fast. For a great overview of the movement and the people behind it, check out <a href="https://youtu.be/10d8HxS4y_g?si=pKNmaYKTfCRPo6fK" target="_blank" rel="noopener noreferrer">this video</a>.</p>
<p>We evaluated seven tools. Here's what we found.</p>
<p><strong><a href="https://www.powersync.com" target="_blank" rel="noopener noreferrer">PowerSync</a></strong> — infrastructure-agnostic DB bridge with complete KMP bidirectional sync support. SQL-based sync rules. This one checked every box.</p>
<p><strong><a href="https://electric-sql.com" target="_blank" rel="noopener noreferrer">Electric SQL</a></strong> — promising middleware with a solid sync layer, but missing a mobile solution for the write path. Engineers would be responsible for building the upload queue, network retries, background sync, and global causal consistency manually. Too much plumbing for our timeline.</p>
<p><strong><a href="https://ditto.live" target="_blank" rel="noopener noreferrer">Ditto</a></strong> — direct device-to-device sync over Bluetooth, WiFi, WAN — no internet needed. A fascinating concept built on a distributed mesh of JSON documents. Great as an additional mechanism, but our project needed structured relational data as the primary model, not NoSQL documents.</p>
<p><strong><a href="https://livestore.dev" target="_blank" rel="noopener noreferrer">LiveStore</a></strong> — a reactive database acting as a global state store with CRDT-based conflict resolution. Heavily skewed toward the TypeScript/Web ecosystem. Hard to integrate with Room, limited conflict resolution for relations, and zero traceability for debugging sync issues.</p>
<p><strong><a href="https://codemyriad.io" target="_blank" rel="noopener noreferrer">Myriad</a></strong> — a plumbing framework between Kotlin server and Kotlin client. Could be a nice competitor for PowerSync — if you have a Kotlin server. We didn't.</p>
<p><strong><a href="https://jazz.tools" target="_blank" rel="noopener noreferrer">Jazz</a></strong>, <strong><a href="https://overtone.pro" target="_blank" rel="noopener noreferrer">Overtone</a></strong> — no KMP support. Non-starters.</p>
<h2 id="why-powersync-won">Why PowerSync won</h2>
<p>Beyond the KMP support and bidirectional sync, PowerSync gave us <strong>SQL-based sync rules</strong> — which meant we could scope exactly what data syncs to each client. In a multi-tenant app with workspace isolation, this is essential.</p>
<p>It also meant we could focus our engineering effort on what actually matters: the <strong>domain logic</strong>, not the sync plumbing.</p>
<h2 id="the-real-challenge-starts-after-choosing-the-tool">The real challenge starts after choosing the tool</h2>
<p>Picking the sync layer was just the first decision. The harder questions followed:</p>
<ul>
<li><strong>Event sourcing vs. CRUD</strong> — how do you preserve user intent when two people work offline on the same data?</li>
<li><strong>Optimistic projections</strong> — how do you give instant UI feedback while the server hasn't confirmed the action yet?</li>
<li><strong>Conflict resolution</strong> — when offline edits collide, do you silently merge or surface the conflict for human review?</li>
</ul>
<p>We chose an <strong>event-first architecture</strong> where the mobile client records immutable operational events (user intent), while a shared KMP processing engine runs on both client and server to produce deterministic state. The client gets instant feedback. The server remains the authoritative judge. And conflicts carry enough context to be resolved meaningfully — not just last-write-wins.</p>
<h3 id="kmp-beyond-mobile-sharing-logic-with-the-server">KMP beyond mobile: sharing logic with the server</h3>
<p>One advantage of building the processing engines in Kotlin Multiplatform is that they don't have to stay on the phone. We compile the same validation and state-projection logic to <strong>Kotlin/JS</strong> and ship it as a library to our colleagues running the Node.js server. The mobile client and the server literally execute the same code — so an event processed optimistically on the device produces the exact same result when the server processes it after sync.</p>
<p>This eliminates an entire class of bugs where client and server disagree on business rules. The only case where the outcome can differ is a genuine conflict — another user modified the same entity while you were offline — and for that we surface the conflict for human review rather than silently merging.</p>
<h2 id="the-takeaway">The takeaway</h2>
<p>The offline-first ecosystem is maturing, but it's still fragmented. Most tools assume a web-first, NoSQL, or single-platform world. If you're building for <strong>KMP with relational data</strong>, the options narrow quickly.</p>
<p>Choose your sync layer based on what it lets you <strong>skip building</strong> — not just what it provides. The months you save on plumbing are the months you spend on the logic that makes your app actually useful.</p>
]]></content:encoded>
    </item>
    <item>
      <title><![CDATA[Share iOs string resources with Android]]></title>
      <link>https://jenicek.dev/posts/shared-string-resource</link>
      <guid>https://jenicek.dev/posts/shared-string-resource</guid>
      <pubDate>Sat, 08 Apr 2023 00:00:00 GMT</pubDate>
      <description><![CDATA[There might be a requirement for mobile string resources to be defined or adjusted by management or copywriters. There also might be a requirement to add localization later by those roles. And on top of that strings should be synced across platforms.]]></description>
      <content:encoded><![CDATA[<p>This is a story about one project where Android platform is catching up iOS when using shared string resources. And how
this can be solved by custom gradle plugin.</p>
<h2 id="localization-platform">Localization platform</h2>
<p>At the beginning there was a requirement where string resources in the mobile app should be easily reviewable, updatable
and in sync
across mobile platforms.</p>
<p>So we started to discuss some localization platform and translation management system.
There is a plenty of localization platforms. Let's mention some:</p>
<ul>
<li><a href="https://phrase.com/" target="_blank" rel="noopener noreferrer">Phrase</a></li>
<li><a href="https://poeditor.com/" target="_blank" rel="noopener noreferrer">PoEditor</a></li>
<li><a href="https://lokalise.com/" target="_blank" rel="noopener noreferrer">Lokalise</a></li>
<li><a href="https://www.transifex.com/" target="_blank" rel="noopener noreferrer">Transifex</a></li>
<li><a href="https://crowdin.com/" target="_blank" rel="noopener noreferrer">Crowdin</a></li>
<li>...</li>
</ul>
<p>Here we can skip discussion about which platform is better than the other. We can state the fact that
<strong><a href="https://poeditor.com/" target="_blank" rel="noopener noreferrer">PoEditor</a></strong> variant was chosen. And on top of that, it was decided to <strong>import all existing
strings from iOS</strong> including iOS specific string resource keys and parameter placeholders into the PoEditor platform. In
order to save money and use free tier to maximum, <strong>Android should use imported iOS variants</strong>.</p>
<h2 id="integrate-poeditor-in-android">Integrate PoEditor in Android</h2>
<p>There are some tips
on <a href="https://poeditor.com/kb/how-to-keep-ios-and-android-strings-in-the-same-localization-project" target="_blank" rel="noopener noreferrer">how to translate iOS and Android apps in the same project</a>.</p>
<p>There are also already available <a href="https://github.com/hyperdevs-team/poeditor-android-gradle-plugin" target="_blank" rel="noopener noreferrer">gradle plugins</a>
treating standard cases.</p>
<p>But I was in the situation described above, which means <strong>convert keys, parameters, split strings to
modules, etc.</strong></p>
<h2 id="custom-poeditor-gradle-plugin">Custom PoEditor gradle plugin</h2>
<p>For situation when there is a need for custom data post-processing, <strong>the best way is to create customized convention
plugin</strong> and implement any processing specifically to the project needs.</p>
<p>For anyone interested in implementation details,
check <a href="https://github.com/mjDevCz/kotox-android/blob/main/build-logic/README-POEDITOR.md" target="_blank" rel="noopener noreferrer">my GitHub repository custom PoEditor Android plugin implementation</a></p>
<h2 id="why-using-gradle-plugin-at-all">Why using gradle plugin at all?</h2>
<p>Why I am not using some easy scripting like python or ruby? For PoEditor there is
e.g. <a href="https://github.com/NijiDigital/poesie" target="_blank" rel="noopener noreferrer">Poesie</a> available. So Why not to use it?</p>
<p>Well, that's also an option.</p>
<p>But by using gradle plugin I am using the advantage of
the <a href="https://proandroiddev.com/exploring-now-in-android-gradle-convention-plugins-91983825bcd7" target="_blank" rel="noopener noreferrer">convention plugins</a>
already used by the project and let project define which module wants import shared string resources. Not mentioning
advantage of writing logic in Kotlin.</p>
<p>With the string resources import integrated as the gradle plugin it's a small step to connect this action in the CI
server and automate it.</p>
<p>So the sharing string resources begun.<br>
Happy coding!<br>
MJ</p>
]]></content:encoded>
    </item>
  </channel>
</rss>
