<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/">
  <channel>
    <title>Mobile Development · Jared Lynskey</title>
    <link>https://jared.lynskey.co.nz/en/tags/mobile-development/</link>
    <description>Short stories of value on software engineering and engineering leadership — performance reviews, hiring and scaling teams, CI/CD, DevOps monitoring and agentic AI. Written from Seoul.</description>
    <generator>Hugo</generator>
    <language>en</language>
    <copyright>© 2026 Jared Lynskey</copyright>
    <lastBuildDate>Sun, 15 Nov 2026 18:30:53 +0900</lastBuildDate>
    <atom:link href="https://jared.lynskey.co.nz/en/tags/mobile-development/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Cloudflare WARP as a Private Network: Connecting My Laptop, Phone and Workstation</title>
      <link>https://jared.lynskey.co.nz/en/posts/2026/2026-10-01-cloudflare-warp-dev-network/</link>
      <guid isPermaLink="true">https://jared.lynskey.co.nz/en/posts/2026/2026-10-01-cloudflare-warp-dev-network/</guid>
      <pubDate>Thu, 01 Oct 2026 00:00:00 +1200</pubDate>
      <dc:creator>Jared Lynskey</dc:creator>
      <category>Cloudflare</category>
      <category>WARP</category>
      <category>Zero Trust</category>
      <category>Cloudflare Tunnel</category>
      <category>Networking</category>
      <category>SSH</category>
      <category>DevOps</category>
      <category>AI Agents</category>
      <category>Ollama</category>
      <category>Mobile Development</category>
      <category>IPv6</category>
      <description>How I use Cloudflare WARP and two Cloudflare Tunnels (Zero Trust) to put a laptop, a phone on 5G and an office GPU workstation on one private network: fixed private IPs, no open ports, and dev servers behind Access.</description>
      <content:encoded><![CDATA[<p>Cloudflare WARP can put your own machines on one private network without opening a single port. Run a Cloudflare Tunnel (<code>cloudflared</code>) on each machine you want to reach, have each tunnel advertise a private IP range, and enroll your laptop and phone in a Zero Trust organisation with the WARP client in include mode. From then on, a phone on 5G can open a plain connection to <code>198.18.42.2</code> and land on the workstation in the office. Below is how mine is set up, and the four things that bit me along the way.</p>
<p>My working setup is three machines that are rarely in the same place. There&rsquo;s a MacBook Air, which goes wherever I go. There&rsquo;s a workstation in the office called devbox, with a real GPU, which runs Ollama, my fine-tuning tools, a small Kubernetes cluster with its own container registry, and whatever agent I&rsquo;ve left grinding through a long job. And there&rsquo;s my phone, which is where the apps I build actually get used, and which spends most of its day on mobile data rather than wifi.</p>
<p>For a long time those three didn&rsquo;t really talk to each other. The laptop could reach devbox when it was on the office LAN and not otherwise. The phone could reach my laptop&rsquo;s dev server when both were on the same wifi, and then only if I remembered to bind to <code>0.0.0.0</code> and typed in whatever DHCP had given the Mac that morning. Everything interesting on the workstation, the Ollama API, the cluster dashboards, the traces, the registry, was bound to localhost or to the cluster network, deliberately, because none of it belongs on the internet.</p>
<p>This post is how I joined them up with Cloudflare WARP and a pair of Cloudflare Tunnels, what it changed about how I build AI features and mobile apps, and the handful of things that broke without telling me.</p>

<h2 class="relative group">What I actually wanted
    <div id="what-i-actually-wanted" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-i-actually-wanted" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Stated as requirements, it&rsquo;s short:</p>
<ol>
<li>The laptop should be a thin client. Anything that needs a GPU, a lot of RAM or hours of runtime should run on devbox, and the laptop should reach it the same way from the office, from home and from a café.</li>
<li>The phone should reach my dev servers and my shells from anywhere, on mobile data, without a VPN I have to remember to switch on and off.</li>
<li>The things I use to see how a system is behaving, dashboards, traces, <code>docker info</code>, model lists, should be reachable by me and nobody else, and should never get a public URL.</li>
<li>No inbound ports. Not on the office router, not on my home router, not anywhere.</li>
</ol>
<p>The fourth one rules out the old answer, which is a port forward and a dynamic DNS name. It also rules out a lot of cleverness: both devbox and my laptop sit behind NAT I don&rsquo;t control, and the laptop is behind a different NAT every few hours.</p>

<h2 class="relative group">Before: a repo of SSH tunnels
    <div id="before-a-repo-of-ssh-tunnels" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#before-a-repo-of-ssh-tunnels" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The first version of this was a small repo of my own, and it&rsquo;s still the base layer. It solves the &ldquo;clean names for things I reach over SSH&rdquo; problem on the laptop and nothing more. dnsmasq answers <code>*.test</code> with <code>127.0.0.1</code>, Caddy routes by hostname to a local port with <code>tls internal</code> so the browser is happy, and a set of autossh launch agents hold the SSH forwards open and reconnect when they drop. The hostnames say where a thing lives:</p>
<table>
	<thead>
			<tr>
					<th>Suffix</th>
					<th>Means</th>
					<th>Carried by</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><code>*.local.test</code></td>
					<td>this Mac</td>
					<td>nothing, it&rsquo;s a dev server</td>
			</tr>
			<tr>
					<td><code>*.ssh.test</code></td>
					<td>a server</td>
					<td>an autossh forward</td>
			</tr>
			<tr>
					<td><code>*.cloud.test</code></td>
					<td>a hosted app</td>
					<td>the hosting platform&rsquo;s own proxy</td>
			</tr>
	</tbody>
</table>
<p>So <code>https://devbox-ollama.ssh.test/api/tags</code> lists the models on the workstation, and <code>https://api.local.test</code> is the API of the app I&rsquo;m working on, running on my own machine.</p>
<p>Subdomains of <code>.test</code>, not new top-level names like <code>.ssh</code> or <code>.cloud</code>, and not <code>.local</code>. RFC 6761 reserves <code>.test</code> for exactly this, and <code>.local</code> belongs to mDNS; take it over and Bonjour discovery stops working on your Mac. dnsmasq already wildcards the whole of <code>*.test</code>, so the extra label costs nothing: one <code>/etc/resolver/test</code> file pointing at <code>127.0.0.1</code> and no further DNS changes, ever.</p>

<h3 class="relative group">HTTPS on names that don&rsquo;t exist
    <div id="https-on-names-that-dont-exist" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#https-on-names-that-dont-exist" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Every one of those names is served over HTTPS with a certificate the browser trusts, which sounds impossible for a hostname that exists only on my laptop. Caddy does it with its own internal certificate authority. <code>tls internal</code> on a site tells Caddy to issue that site&rsquo;s certificate from a local CA instead of asking Let&rsquo;s Encrypt, and <code>caddy trust</code>, run once by the installer, puts the CA&rsquo;s root into the macOS System keychain (Chrome and Safari read it) and into Firefox&rsquo;s own store. From then on <code>https://anything.test</code> opens with no certificate warning, plain <code>http://</code> redirects to it, and nothing leaves the machine.</p>
<p>It isn&rsquo;t just cosmetic. A lot of the web platform now refuses to work on plain HTTP: secure cookies, service workers, the clipboard API, anything with <code>SameSite=None</code>. Testing a web build on plain <code>http://localhost</code> hides the bugs that show up on the real HTTPS domain. Testing on <code>https://app.local.test</code> surfaces them on my laptop instead.</p>
<p>A site block, which is the same for every service apart from the port:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-caddyfile" data-lang="caddyfile"><span class="line"><span class="cl"><span class="gh">devbox-ollama.ssh.test</span>, <span class="gh">devbox-ollama.test</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="k">tls</span> <span class="no">internal</span>
</span></span><span class="line"><span class="cl">	<span class="k">import</span> cors
</span></span><span class="line"><span class="cl">	<span class="k">reverse_proxy</span> <span class="n">127.0.0.1</span><span class="p">:</span><span class="mi">11435</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="k">import</span> proxyhdr
</span></span><span class="line"><span class="cl">		<span class="k">transport</span> <span class="s">http</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">			<span class="k">keepalive</span> <span class="no">off</span>
</span></span><span class="line"><span class="cl">			<span class="k">dial_timeout</span> <span class="mi">5s</span>
</span></span><span class="line"><span class="cl">		<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>The two snippets carry the fiddly parts. <code>cors</code> reflects the caller&rsquo;s <code>Origin</code> back rather than sending <code>*</code>, because <code>*</code> isn&rsquo;t allowed once credentials are involved, and it answers <code>OPTIONS</code> preflights itself with a 204 so the upstream never has to. <code>proxyhdr</code> rewrites the <code>Host</code> header to the dial address. Fussy backends, router admin pages and Chrome&rsquo;s remote-debugging endpoint among them, validate <code>Host</code>, and would otherwise reject <code>devbox-ollama.ssh.test</code> as a name they&rsquo;ve never heard of. Ollama&rsquo;s own origin check accepts loopback on any port, so rewriting <code>Host</code> to <code>127.0.0.1:11435</code> gets it through.</p>
<p><code>keepalive off</code> is the one I&rsquo;d have got wrong. The upstreams are SSH forwards that autossh tears down and rebuilds whenever the network changes. With keep-alive on, Caddy holds a pooled connection to a tunnel that has since died, and it returns baffling 404s until it&rsquo;s reloaded. Off, every request dials fresh, which on loopback costs nothing measurable.</p>
<p>Each service also answers on its old flat name (<code>devbox-ollama.test</code>), so bookmarks from before the suffix scheme still work.</p>

<h3 class="relative group">The menu bar
    <div id="the-menu-bar" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-menu-bar" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>With a dozen forwards held open by launchd, the question I kept asking was &ldquo;is it up?&rdquo;, and the answer lived in three places: <code>launchctl list</code>, <code>lsof</code> and a <code>curl</code>. So a small menu-bar plugin puts it in one place, with a dot next to every hostname:</p>
<ul>
<li>🟢 the service answered a request through the tunnel</li>
<li>🟡 the tunnel is open but the service behind it is silent</li>
<li>🔴 nothing is listening on the local port, so the tunnel itself is down</li>
</ul>
<p>The yellow state is the useful one. A green/red check can&rsquo;t tell &ldquo;the SSH forward died&rdquo; from &ldquo;Ollama crashed on the far end&rdquo;, and those have entirely different fixes. The plugin keeps no list of its own; it reads the same proxy and SSH config as everything else, so adding a service there adds it to the menu too.</p>
<p>The first version was greedy. It refreshed every ten seconds and spawned a few processes per service, about seventy a run, and macOS promptly listed it under &ldquo;apps using significant energy&rdquo;. Taking one snapshot per run and refreshing every few minutes brought it down to about 0.1% of a core. A status light that drains the battery is not helping, so it&rsquo;s worth budgeting for from the start.</p>
<p>The whole setup had one hole, and it was the one that mattered. devbox has no public name. Its SSH forward dialled a <code>192.168.x</code> address, so it only worked while the laptop was on the office LAN. Away from the office the menu bar went red and stayed red, and everything I&rsquo;d moved onto the workstation to save the laptop was out of reach at exactly the times I wasn&rsquo;t sitting next to it.</p>

<h2 class="relative group">Two tunnels, pointing the right way
    <div id="two-tunnels-pointing-the-right-way" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#two-tunnels-pointing-the-right-way" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The fix has three parts, and the first two are Cloudflare Tunnels.</p>
<p>A Cloudflare Tunnel is <code>cloudflared</code> holding an outbound connection to Cloudflare&rsquo;s edge. Cloudflare hands requests back down that connection, so a machine behind any amount of NAT gets reachable without anything listening on a router. It follows a laptop onto hotel wifi and it survives CGNAT.</p>
<p>I run two of them, one per machine, and the reason is worth a sentence. The obvious shortcut was a single tunnel on the laptop with one more ingress rule pointing at devbox&rsquo;s SSH port on the office LAN. That needs nothing installed on devbox at all. It also routes through the laptop, and the laptop is the machine that leaves the office. It would have broken in exactly the case it existed to fix. devbox stays put, so devbox holds its own connection to the edge.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="c"># config.yml on devbox (runs as a systemd service)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="nt">protocol</span><span class="p">:</span><span class="w"> </span><span class="l">auto       </span><span class="w"> </span><span class="c"># prefer QUIC, fall back to HTTP/2 over TCP 443</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="nt">ha-connections</span><span class="p">:</span><span class="w"> </span><span class="m">4</span><span class="w">     </span><span class="c"># mains-powered, its job is to stay reachable</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="nt">warp-routing</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">connectTimeout</span><span class="p">:</span><span class="w"> </span><span class="l">5s</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="nt">ingress</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span>- <span class="nt">hostname</span><span class="p">:</span><span class="w"> </span><span class="l">ssh-devbox.example.com</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">service</span><span class="p">:</span><span class="w"> </span><span class="l">tcp://127.0.0.1:22</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span>- <span class="nt">service</span><span class="p">:</span><span class="w"> </span><span class="l">http_status:404</span></span></span></code></pre></div></div>
<p><code>tcp://</code> rather than <code>ssh://</code> is an easy one to get wrong. <code>ssh://</code> selects Cloudflare&rsquo;s browser-rendered terminal, which wraps the stream for a web page; a normal <code>ssh</code> client fed through it gets the banner and then dies at key exchange. <code>tcp://</code> is the plain byte pipe <code>cloudflared access ssh</code> expects, and as a bonus it carries <code>scp</code>, <code>rsync</code>, git over SSH and port forwards.</p>
<p>That last part is what closed the hole in the SSH layer. The SSH config now picks a route per connection:</p>
<div class="highlight-wrapper"><pre tabindex="0"><code class="language-sshconfig" data-lang="sshconfig">Match originalhost devbox !exec &#34;nc -z -G 1 &lt;office-lan-ip&gt; 22 &gt;/dev/null 2&gt;&amp;1&#34;
    ProxyCommand cloudflared access ssh --hostname ssh-devbox.example.com ...</code></pre></div>
<p>On the office LAN the probe succeeds and SSH goes direct, one hop. Anywhere else it fails and SSH goes through Cloudflare, authenticated with an Access service token so there&rsquo;s no browser login in the way. It&rsquo;s <code>Match originalhost</code>, not <code>Match host</code>: <code>host</code> matches after <code>HostName</code> has been substituted, so by then the name is already an IP and the block never fires. The upshot is that <code>devbox-ollama.ssh.test</code> works in the office, at home and on a train, and the menu bar dot stays green.</p>
<p>The laptop&rsquo;s tunnel goes the other direction. It gives dev servers on the Mac real public HTTPS hostnames: for each app I&rsquo;m working on, its API, its WebSocket server and its web build. Every one of them sits behind Cloudflare Access, which I&rsquo;ll come back to, because it&rsquo;s the part that makes this safe rather than reckless.</p>
<p>The menu bar learned about both tunnels too, and it couldn&rsquo;t do it by probing. An inbound tunnel has no local port to check, one of the two connectors doesn&rsquo;t even run on the laptop, and the obvious test, curling <code>ssh-devbox.example.com</code>, gets an answer from Cloudflare&rsquo;s edge whether or not a connector is attached, so it would read green on a dead tunnel. launchd is no better: <code>cloudflared</code> sits there &ldquo;loaded, exit 0&rdquo; with every edge connection dropped. So for tunnels the menu asks the Cloudflare API whether each one has a healthy connector, since that&rsquo;s what decides whether an <code>ssh</code> lands. If the API can&rsquo;t be reached, the section is left out rather than drawn red. The menu is read at a glance, and a false alarm there costs more than a missing line.</p>

<h2 class="relative group">The third part: WARP makes it a network
    <div id="the-third-part-warp-makes-it-a-network" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-third-part-warp-makes-it-a-network" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Tunnels with hostnames are great for anything that speaks HTTPS, and for SSH from a machine that can run <code>cloudflared</code>. A phone can&rsquo;t. And a tunnel hostname isn&rsquo;t a TCP endpoint: Cloudflare&rsquo;s edge only terminates HTTPS and WebSocket on it, so port 22 at <code>ssh.example.com</code> is closed and no amount of fiddling with Access will open it.</p>
<p>That&rsquo;s the job for WARP. The Cloudflare One Agent (the enterprise WARP client, not the consumer &ldquo;1.1.1.1&rdquo; app, which can&rsquo;t join an organisation) is enrolled on the laptop and the phone in my Zero Trust organisation. Each tunnel advertises private routes, and a device running WARP can then open a plain socket to those addresses and land on the right machine. It stops being &ldquo;reach this service by name&rdquo; and becomes &ldquo;these machines are on a network with me&rdquo;:</p>
<table>
	<thead>
			<tr>
					<th>Address</th>
					<th>Machine</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><code>198.18.42.1</code> / <code>fd12:3456:789a::1</code></td>
					<td>the MacBook Air</td>
			</tr>
			<tr>
					<td><code>198.18.42.2</code> / <code>fd12:3456:789a::2</code></td>
					<td>devbox</td>
			</tr>
			<tr>
					<td><code>198.18.42.3</code> / <code>fd12:3456:789a::3</code></td>
					<td>a second Mac</td>
			</tr>
	</tbody>
</table>
<p>Those addresses are loopback aliases on each machine, created at boot, so they owe nothing to DHCP or whatever router I&rsquo;m behind. <code>198.18.42.2</code> is devbox in the office, from home, and from a phone on 5G. The Mac&rsquo;s real LAN address changes every time I move; this one never does.</p>
<p>The split tunnel is in <strong>include mode</strong> with only those routes in it (plus the Cloudflare ranges WARP needs for itself). That&rsquo;s what makes the client liveable. The default is exclude mode, where WARP carries everything except a list of private ranges, so every byte the phone sends detours through Cloudflare. That has a real battery and latency cost, enough that I&rsquo;d have ended up turning it on only when I needed it, which defeats the point. In include mode, traffic to my three machines goes through WARP and everything else goes out the normal path untouched. So the client just stays on. <code>warp-cli status</code> on the laptop says <code>Connected</code> all day and I don&rsquo;t think about it.</p>
<p>For transport I have it on MASQUE, which is HTTP/3 on UDP 443 with an HTTP/2 fallback, rather than WireGuard on UDP 2408. Some carriers and guest networks block 2408; almost nobody blocks 443. My organisation&rsquo;s policy also has post-quantum key agreement switched on for MASQUE, which I didn&rsquo;t go looking for but won&rsquo;t turn down.</p>

<h2 class="relative group">Why 198.18, and why there&rsquo;s an IPv6 address
    <div id="why-19818-and-why-theres-an-ipv6-address" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#why-19818-and-why-theres-an-ipv6-address" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The addresses look odd, and the first ones I picked were wrong in an instructive way.</p>
<p>My first attempt was <code>10.10.0.1</code>, because that&rsquo;s what you reach for. It fails in both split-tunnel modes. In exclude mode, WARP&rsquo;s default list excludes every RFC 1918 range plus <code>100.64.0.0/10</code>, so the client would have dropped traffic to it before it ever left the device. In include mode it would collide with any real <code>10.x</code> network I happen to join; cafés, co-working spaces and plenty of offices use exactly that range. <code>198.18.0.0/15</code> is the RFC 2544 benchmarking range. It&rsquo;s reserved, it&rsquo;s never routed on the public internet, it isn&rsquo;t in WARP&rsquo;s exclude list, and no ordinary network uses it. The IPv6 addresses are ULA (<code>fd00::/8</code>) for the same reason.</p>
<p>Why there&rsquo;s IPv6 at all is the more interesting story. Once the v4 address worked I tested it from the phone on wifi, it was fine, and I called it done. On 5G it didn&rsquo;t work. The Agent said <em>connected</em>, the tunnel was healthy, Access was fine; the wifi test proved all of that. The problem was that mobile networks are mostly IPv6-only now. The phone had no native IPv4 at all and was reaching the v4 literal through the carrier&rsquo;s 464XLAT translator, which sits <em>outside</em> the tunnel when the include list holds only a v4 prefix. The traffic went out to the public internet, where <code>198.18.0.0/15</code> doesn&rsquo;t route, and was dropped without a sound. No error on the phone, nothing in the connector&rsquo;s log.</p>
<p>The fix is to give every machine a second address the phone can reach natively over IPv6, and add it to the routes and to the include list. Now the <code>fd12:3456:789a::</code> addresses are what my SSH client on the phone actually uses on mobile data.</p>

<h2 class="relative group">Offloading: the laptop as a terminal
    <div id="offloading-the-laptop-as-a-terminal" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#offloading-the-laptop-as-a-terminal" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>This is the part the whole setup exists for.</p>
<p><strong>Models and fine-tuning.</strong> Ollama runs on devbox and binds to <code>127.0.0.1:11434</code>. It&rsquo;s invisible to the rest of the office LAN, let alone the internet. On the laptop it appears at <code>https://devbox-ollama.ssh.test</code>, or as a bare port for tools that want one:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nv">OLLAMA_HOST</span><span class="o">=</span>127.0.0.1:11435 ollama list</span></span></code></pre></div></div>
<p>11435, not 11434, on purpose: 11434 is Ollama&rsquo;s own default, and if the laptop ever runs a local Ollama too, the two would race for the port and I&rsquo;d silently get devbox&rsquo;s answers from the &ldquo;local&rdquo; one depending on which started first.</p>
<p>The practical effect is that when I&rsquo;m building an AI feature, the model it calls is a workstation GPU rather than the laptop&rsquo;s, from wherever I am. Evaluation runs, embedding a pile of documents, a fine-tune: they run on devbox, and the laptop&rsquo;s fan stays off. When I&rsquo;m prototyping an agent, it can point at a local model on the workstation and burn through tool-calling iterations without an API bill, and switch to a hosted model once the loop is right.</p>
<p><strong>Long-running agents.</strong> An agent session that runs for an hour shouldn&rsquo;t depend on my laptop lid staying open. Run it on devbox instead and the laptop is just a window onto it: close the lid, and later <code>ssh devbox</code> from wherever I am, or from the phone, and it&rsquo;s still there. Before the tunnel this only worked in the office, which is exactly where I didn&rsquo;t need it.</p>
<p><strong>Builds and the cluster.</strong> The cluster on devbox has its own registry, so images can be built and pushed on the workstation, next to where they run, rather than uploaded over hotel wifi from a laptop. The cluster dashboard, the ingress dashboard and the registry UI are all <code>*.ssh.test</code> hostnames on the laptop.</p>
<p><strong>The mobile loop.</strong> The phone is on the same private network as the laptop, and the laptop&rsquo;s dev servers also have public hostnames behind Access. So I can take a native build of the app out of the building, on 5G, and it talks to the API running on my desk. Or it talks to the one on devbox, if that&rsquo;s where I left it. The feedback loop on a real device over a real mobile network used to mean deploying to a shared staging server. Now it means saving a file.</p>
<p>There&rsquo;s one trap here worth knowing before you debug it as an app bug. Access protects the WebSocket hostname too, and a native WebSocket client isn&rsquo;t a browser. It carries no <code>CF_Authorization</code> cookie, so the native build&rsquo;s connection to the WebSocket server is rejected at the edge with a 403 that looks nothing like an error from your own server. Browser tabs are fine because they already hold the cookie from logging in. For anything that isn&rsquo;t a browser (the native app, a script, an agent calling a dev API) the answer is an Access <strong>service token</strong>, sent as two headers:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">CF-Access-Client-Id:     &lt;client_id&gt;
</span></span><span class="line"><span class="cl">CF-Access-Client-Secret: &lt;client_secret&gt;</span></span></code></pre></div></div>
<p>The token grants nothing on its own. Access only honours it on apps whose policy names it, so its reach is exactly the list of dev hostnames and nothing wider. I file its policy under the <code>non_identity</code> decision rather than <code>allow</code>, which keeps it visible in the audit log as a bearer secret and not a person who logged in.</p>

<h2 class="relative group">The stats the internet never sees
    <div id="the-stats-the-internet-never-sees" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-stats-the-internet-never-sees" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The other half of what I wanted was visibility. Most of what tells you how a system is behaving is, correctly, not public. On devbox that&rsquo;s:</p>
<ul>
<li>the ingress proxy&rsquo;s dashboard, and the tracing UI that holds its traces</li>
<li>a dashboard for the Kubernetes cluster</li>
<li>the container registry&rsquo;s UI (read-only)</li>
<li>Ollama&rsquo;s model list and what&rsquo;s loaded right now</li>
<li><code>docker info</code> and container stats</li>
</ul>
<p>None of those have a public hostname, and none ever will. They&rsquo;re bound to loopback or to cluster service IPs, reached over an SSH forward that itself rides the tunnel. A monitoring app on my phone reads <code>docker info --format '{{json .}}'</code> over SSH across WARP, so I can see from anywhere whether my containers are up or something has eaten all the memory.</p>
<p>That app is how I found a small bug worth mentioning. The tunnel sshd on the Mac was at <code>LogLevel DEBUG2</code> from when I was debugging it. With <code>-e</code>, sshd logs to stderr, and for a session that stderr <em>is</em> the SSH channel&rsquo;s stderr. Every command&rsquo;s output came back with <code>debug2: do_setup_env: set TMPDIR</code> appended, and the phone app, which merges the two streams, got valid JSON followed by a log line, failed to parse it, and showed the whole thing as an error. <code>LogLevel INFO</code> fixed it. Put log levels back after debugging.</p>
<p>Just as deliberate is what I <em>don&rsquo;t</em> put on this network. The old autossh tunnels also reach a few routers on other people&rsquo;s networks that I help look after. Those get no public hostname and no WARP route. A router admin page on the internet is a liability even behind a login, and it isn&rsquo;t my network to widen.</p>

<h2 class="relative group">Access is not optional
    <div id="access-is-not-optional" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#access-is-not-optional" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>A Cloudflare Tunnel hostname is on the public internet the moment its DNS record exists. There&rsquo;s no firewall in front of it; that&rsquo;s the whole point of not opening a port. The protection has to come from Cloudflare&rsquo;s edge, and that&rsquo;s what Access does. It refuses to forward a request at all until the visitor has proved who they are, so an unauthenticated scanner never reaches the laptop. That matters, because these are dev servers: a debug-mode traceback with settings in it, an open JavaScript bundler. Nothing behind these hostnames was built to face the internet.</p>
<p>The policy allows my own email addresses and nothing else, with a one-time PIN by email and single sign-on as the two ways to prove it. Sessions last eight hours, because the realistic threat is a laptop left open in a café with a day-long cookie, not someone brute-forcing a PIN.</p>
<p>SSH is authenticated twice, by two systems that don&rsquo;t know about each other. Access decides whether a TCP stream may reach sshd at all; sshd still demands my key. Losing either doesn&rsquo;t open the machine. The Mac&rsquo;s tunnel sshd also trusts Cloudflare&rsquo;s SSH CA, so Access can log me in with a short-lived certificate minted from my SSO session, while <code>authorized_keys</code> still works alongside it, so a broken Access config can&rsquo;t lock me out of my own laptop.</p>
<p>The piece I&rsquo;m happiest with is small. Exposure happens when three things line up: a DNS record, a running connector and an active zone. They become true at different times, in an order I don&rsquo;t control; the zone flips to active on its own, some time after the nameservers change, quite possibly while the Mac is asleep. So the launch agent doesn&rsquo;t run <code>cloudflared</code> directly. It runs a preflight that reads the hostnames out of the tunnel&rsquo;s own config, asks the Access API which ones are covered, and refuses to start if any aren&rsquo;t:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nv">HOSTNAMES</span><span class="o">=</span><span class="k">$(</span>grep -E <span class="s1">&#39;^\s*-\s*hostname:&#39;</span> <span class="s2">&#34;</span><span class="nv">$CONFIG</span><span class="s2">&#34;</span> <span class="p">|</span> sed -E <span class="s1">&#39;s/.*hostname:\s*//&#39;</span> <span class="p">|</span> sort -u<span class="k">)</span>
</span></span><span class="line"><span class="cl"><span class="nv">PROTECTED</span><span class="o">=</span><span class="k">$(</span>curl -fsS -H <span class="s2">&#34;Authorization: Bearer </span><span class="nv">$CLOUDFLARE_API_TOKEN</span><span class="s2">&#34;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">    <span class="s2">&#34;https://api.cloudflare.com/client/v4/accounts/</span><span class="nv">$CLOUDFLARE_ACCOUNT_ID</span><span class="s2">/access/apps?per_page=100&#34;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">    <span class="p">|</span> python3 -c <span class="s1">&#39;import sys,json; print(&#34;\n&#34;.join(a.get(&#34;domain&#34;,&#34;&#34;) for a in json.load(sys.stdin)[&#34;result&#34;]))&#39;</span><span class="k">)</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">    <span class="o">||</span> <span class="o">{</span> <span class="nb">echo</span> <span class="s2">&#34;could not reach the Access API. refusing (fail closed).&#34;</span><span class="p">;</span> <span class="nb">exit</span> 1<span class="p">;</span> <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">for</span> h in <span class="nv">$HOSTNAMES</span><span class="p">;</span> <span class="k">do</span>
</span></span><span class="line"><span class="cl">    grep -qxF <span class="s2">&#34;</span><span class="nv">$h</span><span class="s2">&#34;</span> <span class="o">&lt;&lt;&lt;</span><span class="s2">&#34;</span><span class="nv">$PROTECTED</span><span class="s2">&#34;</span> <span class="o">||</span> <span class="o">{</span> <span class="nb">echo</span> <span class="s2">&#34;NOT starting: </span><span class="nv">$h</span><span class="s2"> has no Access app&#34;</span><span class="p">;</span> <span class="nb">exit</span> 1<span class="p">;</span> <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="k">done</span>
</span></span><span class="line"><span class="cl"><span class="nb">exec</span> cloudflared tunnel --config <span class="s2">&#34;</span><span class="nv">$CONFIG</span><span class="s2">&#34;</span> run</span></span></code></pre></div></div>
<p>The launch agent has <code>KeepAlive</code>, so a refusal retries by itself every 30 seconds and the tunnel comes up on its own once the Access apps exist. Failing closed costs an outage. Failing open costs an exposure. I know which of those I&rsquo;d rather explain.</p>

<h2 class="relative group">Four things that bit me
    <div id="four-things-that-bit-me" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#four-things-that-bit-me" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Everything above works now. Getting there, three of the four had the same pattern: the thing that was broken produced no error anywhere, and the parts I could see all reported healthy.</p>
<p><strong>The route and the include list are two different lists.</strong> A tunnel route makes Cloudflare <em>willing</em> to carry an address to the right connector. The WARP include list is what makes the client <em>send</em> it in the first place. devbox was unreachable from the phone because its routes existed but the include list still only had the Mac&rsquo;s addresses. The phone dropped the packets locally, the connector never saw a flow, and every dashboard was green. Every new machine means adding its addresses to both.</p>
<p><strong>IPv4 literals on IPv6-only mobile networks.</strong> Covered above: works on wifi, fails on 5G, no error. If a WARP route works on wifi and not on mobile data, and the Agent shows connected, it&rsquo;s routing, not the tunnel.</p>
<p><strong>macOS sshd behind cloudflared.</strong> macOS starts its sshd with launchd socket activation, one short-lived <code>sshd -i</code> per connection. Behind cloudflared, the banner reaches the client and then the stream is torn down before the client&rsquo;s identification string gets back, so every login dies at <code>kex_exchange_identification</code>. I confirmed it from both ends and reproduced it with a plain TCP relay, which ruled out Cloudflare. The fix is a second, standalone <code>sshd -D</code> on <code>127.0.0.1:2222</code> and the WARP loopback addresses, running as my user, that exists only to be the tunnel&rsquo;s origin. Remote Login in System Settings is untouched. devbox, being Linux with a normal long-lived sshd, never had the problem.</p>
<p><strong>Config fields that stop existing.</strong> Older examples have <code>warp-routing: enabled: true</code> in the tunnel config. cloudflared 2026.8 rejects that field outright. WARP routing is on whenever the block exists and a route points at the tunnel. That one at least produced an error, which after the other three felt almost generous.</p>

<h2 class="relative group">What it changed
    <div id="what-it-changed" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-it-changed" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The honest summary is that I stopped choosing where to work based on where the hardware is. The laptop is a good keyboard and a good screen with a long battery life, and it doesn&rsquo;t need to be more than that. The workstation does the heavy lifting from wherever I am. The phone is a real test device on a real network rather than something tethered to office wifi. And the parts of the system I use to see what it&rsquo;s doing are one click away for me and don&rsquo;t exist for anyone else.</p>
<p>At this size it fits in Cloudflare&rsquo;s free Zero Trust plan. What it cost me was time and a README I&rsquo;m glad I wrote, because every one of the failures above would have been a fresh mystery the second time.</p>
<p>If you&rsquo;re thinking about something similar, these are the questions I&rsquo;d ask of your setup:</p>
<ol>
<li>What runs on your laptop only because the laptop is the one machine you can always reach?</li>
<li>Can your phone reach your dev server on mobile data, not just on the office wifi? Test it on 5G, not wifi.</li>
<li>Which of your dashboards are public because that was the easy way to see them from outside? Each one is a candidate for a private route instead.</li>
<li>If a tunnel hostname came up without its Access app tomorrow, what would stop it? If the answer is &ldquo;I&rsquo;d remember&rdquo;, write the preflight.</li>
<li>Are your private addresses in a range the networks you visit will never use?</li>
</ol>
]]></content:encoded>
      <media:content url="https://jared.lynskey.co.nz/en/posts/2026/2026-10-01-cloudflare-warp-dev-network/featured.jpg" medium="image" type="image/jpeg" />
    </item>
    <item>
      <title>Replacing My Self-Hosted Expo Update Server with Codemagic Patch</title>
      <link>https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/</link>
      <guid isPermaLink="true">https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/</guid>
      <pubDate>Sun, 13 Sep 2026 00:00:00 +0900</pubDate>
      <dc:creator>Jared Lynskey</dc:creator>
      <category>React Native</category>
      <category>Expo</category>
      <category>OTA Updates</category>
      <category>Codemagic Patch</category>
      <category>CodePush</category>
      <category>Self-Hosted</category>
      <category>Mobile Development</category>
      <category>CI/CD</category>
      <description>I moved a real Expo app, native projects and all, from expo-updates to Codemagic Patch: the local stack, the migration, a bug I caused and fixed over the air, and what rollback looks like when a release actually crashes.</description>
      <content:encoded><![CDATA[<blockquote><p><strong>Disclosure.</strong> Codemagic paid me to do this migration and write about it. They get a review pass for factual accuracy, not for tone, and nothing here was changed at their request. Where I hit a problem and reported it, I say so; if it&rsquo;s fixed by the time you read this, it&rsquo;s described as fixed.</p>
</blockquote><blockquote><p><strong>Update, 23 September 2026.</strong> Codemagic&rsquo;s developers have worked through the issues I reported. Most are now fixed, including the iOS version-detection bug, the double-counted installs, the silent first run and the noisy debug command, and the docs now cover committed native projects and the crash-rollback budget. I&rsquo;ve marked each one below where it comes up, and left the few that are still open as they were.</p>
</blockquote><blockquote><p><strong>Update, 16 October 2026.</strong> The first native upgrade since moving to Patch (Expo SDK 58) built an Android release with no Patch configuration in it, and nothing reported an error. What happened and the one-file fix are in <a href="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/#the-first-native-upgrade" >The first native upgrade</a>.</p>
</blockquote><p>In February I wrote about <a href="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/" >building my own Expo update server</a>. It still works. maru, the community app I run, has taken every over-the-air fix through it since, on both platforms, for about a dollar a month.</p>
<p>It also means I own every piece of it: the database tables, the API endpoint, an admin command, a publish script, a shared secret, and a set of gotchas I learned one broken update at a time. When I sat down to plan this, I found that the script had been printing &ldquo;Sent 0 push notifications&rdquo; after every production publish since the day I wrote it, reading a field this server has never returned. Nobody noticed, least of all me. That&rsquo;s roughly what running your own thing turns into.</p>
<p>So when Codemagic asked whether I&rsquo;d try <a href="https://patch.codemagic.io/"  target="_blank" rel="noreferrer sponsored">Patch</a>, their <a href="https://github.com/codemagic-ci-cd/codemagic-patch"  target="_blank" rel="noreferrer sponsored">open-source</a>, self-hostable take on CodePush, I agreed on one condition: a real app rather than a demo. Real signing, real release process, committed native projects with hand edits in them, the lot. Most people moving off EAS Update are moving an app like that, not a fresh template.</p>
<p>This is how that went, with the rough edges left in.</p>
<figure><div class="film-pair">
  <div class="mc-film film-dark">
  <video
    class="my-0 rounded-md"
    controls playsinline preload="none"
    poster="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film-poster.jpg" style="background:url('data:image/webp;base64,UklGRngAAABXRUJQVlA4IGwAAADQBACdASogABIAPw12qkmmI6GYDAQAYxDE9IABUYPdOZbru82h5cj1rTAwl7UkCAD+6LtMSUUTk7Xb87esmRGyzFCtrX13j1gdi5rqnvw7rsZGz3OYwYPBwIvD2aLoLjGuPChToAJcOOivQAA=') center/cover no-repeat"
    width="1280"
    height="720"
    aria-label="A short narrated film of this post">
    <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film.webm" type="video/webm">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film_en.vtt" srclang="en" label="English">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film_ja.vtt" srclang="ja" label="日本語">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film_ko.vtt" srclang="ko" label="한국어">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film_vi.vtt" srclang="vi" label="Tiếng Việt">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film_zh-cn.vtt" srclang="zh-cn" label="简体中文">
  </video>
  </div>
  <div class="mc-film film-light">
  <video
    class="my-0 rounded-md"
    controls playsinline preload="none"
    poster="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film-light-poster.jpg" style="background:url('data:image/webp;base64,UklGRoIAAABXRUJQVlA4IHYAAACQBACdASogABIAPw1sqUemIyIYBABjEMT0gAFRZY1tQKVVHPUfWxkc2Bs75kAA/u+6aABtB+MYV02ZVTPoxBkkmzc3vO1UQaTBYenW4qyDVxhq0vJFiUKvn4G3BTnsUdC0oW9arIFlmI4kbi/flHgAMAOOZAAA') center/cover no-repeat"
    width="1280"
    height="720"
    aria-label="A short narrated film of this post">
    <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film-light.webm" type="video/webm">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film_en.vtt" srclang="en" label="English">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film_ja.vtt" srclang="ja" label="日本語">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film_ko.vtt" srclang="ko" label="한국어">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film_vi.vtt" srclang="vi" label="Tiếng Việt">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/patch-film_zh-cn.vtt" srclang="zh-cn" label="简体中文">
  </video>
  </div>
  <script>(function(){if(window.mcFilm)return window.mcFilm();var a={play:'<path d="M8 5.6v12.8a1 1 0 0 0 1.52.85l10.2-6.4a1 1 0 0 0 0-1.7L9.52 4.75A1 1 0 0 0 8 5.6z"/>',pause:'<rect x="6.5" y="5" width="4" height="14" rx="1.2"/><rect x="13.5" y="5" width="4" height="14" rx="1.2"/>',volume:'<path d="M4 9.5v5a1 1 0 0 0 1 1h3l4.4 3.6a.6.6 0 0 0 1-.47V5.37a.6.6 0 0 0-1-.47L8 8.5H5a1 1 0 0 0-1 1z"/><path d="M16.5 8.5a5 5 0 0 1 0 7M19 6a8.5 8.5 0 0 1 0 12" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>',muted:'<path d="M4 9.5v5a1 1 0 0 0 1 1h3l4.4 3.6a.6.6 0 0 0 1-.47V5.37a.6.6 0 0 0-1-.47L8 8.5H5a1 1 0 0 0-1 1z"/><path d="M16.5 9.5l5 5m0-5l-5 5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>',cc:'<rect x="3" y="5.5" width="18" height="13" rx="3" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M10.5 10.3a2.2 2.2 0 1 0 0 3.4M17 10.3a2.2 2.2 0 1 0 0 3.4" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>',full:'<path d="M4.5 9V5.5a1 1 0 0 1 1-1H9M15 4.5h3.5a1 1 0 0 1 1 1V9M19.5 15v3.5a1 1 0 0 1-1 1H15M9 19.5H5.5a1 1 0 0 1-1-1V15" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/>',exit:'<path d="M9 4.5V8a1 1 0 0 1-1 1H4.5M19.5 9H16a1 1 0 0 1-1-1V4.5M15 19.5V16a1 1 0 0 1 1-1h3.5M4.5 15H8a1 1 0 0 1 1 1v3.5" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/>'},s={en:["Play","Pause","Mute","Unmute","Subtitles","Off","Full screen","Exit full screen","Seek"],ko:["재생","일시정지","음소거","음소거 해제","자막","끄기","전체 화면","전체 화면 종료","탐색"],ja:["再生","一時停止","ミュート","ミュート解除","字幕","オフ","全画面","全画面を終了","シーク"],zh:["播放","暂停","静音","取消静音","字幕","关闭","全屏","退出全屏","进度"],vi:["Phát","Tạm dừng","Tắt tiếng","Bật tiếng","Phụ đề","Tắt","Toàn màn hình","Thoát toàn màn hình","Tua"]},r=(document.documentElement.lang||"en").toLowerCase().slice(0,2),e=s[r]||s.en,t=function(e){return'<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">'+a[e]+"</svg>"},o={},i=function(e,t){if(o[e]||typeof window.gtag!="function")return;o[e]=!0;var n=(t.currentSrc||(t.querySelector("source")||{}).src||"").split("/").pop();window.gtag("event",e,{film:n.replace(/-light(?=\.)/,"")})},n=function(e){(!isFinite(e)||e<0)&&(e=0),e=Math.floor(e);var t=Math.floor(e/3600),n=Math.floor(e%3600/60),s=String(e%60).padStart(2,"0");return t?t+":"+String(n).padStart(2,"0")+":"+s:n+":"+s};function c(s){var a,r,c,d,u,m,p,g,v,b,j,_,w,O,C,E,k,A,o=s.querySelector("video");if(!o)return;s.classList.add("is-ready"),o.controls=!1,o.removeAttribute("controls"),s.insertAdjacentHTML("beforeend",'<button type="button" class="mc-film__big" aria-label="'+e[0]+'">'+t("play")+'</button><div class="mc-film__bar"><button type="button" class="mc-film__btn" data-act="play" aria-label="'+e[0]+'">'+t("play")+'</button><span class="mc-film__time"><span data-cur>0:00</span><span class="mc-film__of"> / </span><span data-dur>0:00</span></span><input class="mc-film__seek" type="range" min="0" max="1000" step="1" value="0" aria-label="'+e[8]+'"><span class="mc-film__cc"><button type="button" class="mc-film__btn" data-act="cc" aria-label="'+e[4]+'" aria-haspopup="true" aria-expanded="false">'+t("cc")+'</button><span class="mc-film__menu" role="menu" hidden></span></span><button type="button" class="mc-film__btn" data-act="mute" aria-label="'+e[2]+'">'+t("volume")+'</button><button type="button" class="mc-film__btn" data-act="full" aria-label="'+e[6]+'">'+t("full")+"</button></div>"),A=s.querySelector(".mc-film__big"),a=s.querySelector(".mc-film__bar"),j=a.querySelector('[data-act="play"]'),p=a.querySelector('[data-act="mute"]'),u=a.querySelector('[data-act="full"]'),d=a.querySelector('[data-act="cc"]'),r=a.querySelector(".mc-film__menu"),c=a.querySelector(".mc-film__seek"),w=a.querySelector("[data-cur]"),O=a.querySelector("[data-dur]"),g=!1,v=0,b=function(){return Array.prototype.filter.call(o.textTracks,function(e){return e.kind==="subtitles"||e.kind==="captions"})},b().length||(d.parentNode.hidden=!0),_=null;function f(e){var n,i,t=!s.classList.contains("is-idle")&&s.classList.contains("is-started");if(e!==!0&&t===_)return;_=t,n=o.clientHeight,i=n?Math.max(40,100-(a.offsetHeight+22)/n*100):85,b().forEach(function(e){if(e.mode!=="showing"||!e.cues)return;for(var n,s=0;s<e.cues.length;s++)n=e.cues[s],t?(n.snapToLines=!1,n.line=i,n.lineAlign="end"):(n.snapToLines=!0,n.line="auto",n.lineAlign="start")})}m=function(){f(!0)},window.addEventListener("resize",m),Array.prototype.forEach.call(o.querySelectorAll("track"),function(e){e.addEventListener("load",m)});function y(){o.paused||o.ended?o.play().catch(function(){}):o.pause()}function l(){s.classList.remove("is-idle"),f(),clearTimeout(v),v=setTimeout(function(){!o.paused&&r.hidden&&!a.querySelector(":focus-visible")&&(s.classList.add("is-idle"),f())},2600)}function M(){clearTimeout(v),h(),s.classList.add("is-idle"),f()}function h(){r.hidden=!0,d.setAttribute("aria-expanded","false")}function F(){var t=b(),n=t.filter(function(e){return e.mode==="showing"})[0];r.innerHTML="",[null].concat(t).forEach(function(s){var o=document.createElement("button");o.type="button",o.setAttribute("role","menuitemradio"),o.setAttribute("aria-checked",String(s?s===n:!n)),o.textContent=s?s.label||s.language:e[5],o.addEventListener("click",function(){t.forEach(function(e){e.mode=e===s?"showing":"disabled"}),h(),setTimeout(m,0),l()}),r.appendChild(o)}),r.hidden=!1,d.setAttribute("aria-expanded","true")}function x(){var n=!o.paused&&!o.ended;s.classList.toggle("is-playing",n),j.innerHTML=t(n?"pause":"play"),j.setAttribute("aria-label",n?e[1]:e[0]),n||l()}function S(){if(w.textContent=n(o.currentTime),!g&&o.duration){var e=o.currentTime/o.duration*1e3;c.value=e,c.style.setProperty("--p",e/10+"%")}}A.addEventListener("click",function(){o.play().catch(function(){})}),C="mouse",s.addEventListener("pointerdown",function(e){C=e.pointerType}),o.addEventListener("click",function(){if(!s.classList.contains("is-started"))return o.play().catch(function(){});if(C==="mouse")return y();s.classList.contains("is-idle")?l():M()}),j.addEventListener("click",y),o.addEventListener("play",function(){s.classList.contains("is-started")||i("film_play",o),s.classList.add("is-started"),x(),l()}),"IntersectionObserver"in window&&(E=new IntersectionObserver(function(e){if(!e.some(function(e){return e.isIntersecting}))return;E.disconnect(),i("film_view",o)},{threshold:.5}),E.observe(s)),o.addEventListener("pause",x),o.addEventListener("ended",x),o.addEventListener("timeupdate",S),o.addEventListener("durationchange",function(){O.textContent=n(o.duration),S()}),o.addEventListener("loadedmetadata",function(){O.textContent=n(o.duration)}),o.addEventListener("volumechange",function(){p.innerHTML=t(o.muted?"muted":"volume"),p.setAttribute("aria-label",o.muted?e[3]:e[2])}),p.addEventListener("click",function(){o.muted=!o.muted}),c.addEventListener("input",function(){g=!0,c.style.setProperty("--p",c.value/10+"%"),o.duration&&(o.currentTime=c.value/1e3*o.duration,w.textContent=n(o.currentTime))}),c.addEventListener("change",function(){g=!1}),d.addEventListener("click",function(e){e.stopPropagation(),r.hidden?F():h()}),document.addEventListener("click",function(e){!r.hidden&&!r.contains(e.target)&&h()}),u.addEventListener("click",function(){document.fullscreenElement||document.webkitFullscreenElement?(document.exitFullscreen||document.webkitExitFullscreen).call(document):s.requestFullscreen?s.requestFullscreen().catch(function(){}):s.webkitRequestFullscreen?s.webkitRequestFullscreen():o.webkitEnterFullscreen&&o.webkitEnterFullscreen()}),k=function(){var n=(document.fullscreenElement||document.webkitFullscreenElement)===s;s.classList.toggle("is-fullscreen",n),u.innerHTML=t(n?"exit":"full"),u.setAttribute("aria-label",n?e[7]:e[6])},document.addEventListener("fullscreenchange",k),document.addEventListener("webkitfullscreenchange",k),s.addEventListener("pointermove",function(e){e.pointerType==="mouse"&&l()}),s.addEventListener("focusin",l),s.addEventListener("keydown",function(e){if(e.target===c&&/^Arrow/.test(e.key))return;var t=e.key.toLowerCase();if(t==="k"||t===" "&&e.target===o)y();else if(t==="arrowleft")o.currentTime=Math.max(0,o.currentTime-5);else if(t==="arrowright")o.currentTime=Math.min(o.duration||0,o.currentTime+5);else if(t==="m")o.muted=!o.muted;else if(t==="f")u.click();else if(t==="escape"&&!r.hidden)h();else return;e.preventDefault(),l()}),o.tabIndex=0}window.mcFilm=function(){document.querySelectorAll(".mc-film:not(.is-ready)").forEach(c)},window.mcFilm()})()</script></div>
  <script>
  new MutationObserver(() => {
    const dark = document.documentElement.classList.contains("dark");
    document.querySelectorAll(".film-pair").forEach((pair) => {
      const from = pair.querySelector(dark ? ".film-light video" : ".film-dark video");
      const to = pair.querySelector(dark ? ".film-dark video" : ".film-light video");
      if (!from || !to || !from.currentTime) return;
      const playing = !from.paused;
      from.pause();
      to.currentTime = from.currentTime;
      [...from.textTracks].forEach((track, i) => { if (to.textTracks[i]) to.textTracks[i].mode = track.mode; });
      if (playing) to.play().catch(() => {});
    });
  }).observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
  </script><figcaption>This post as a nine-minute film, if you&rsquo;d rather watch than read.</figcaption>
</figure>


<h2 class="relative group">What Patch is
    <div id="what-patch-is" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-patch-is" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Patch is a server you run yourself and an SDK you put in your app. The server side is an API, a background worker, Postgres, S3-compatible object storage and a web dashboard, shipped as a Docker Compose stack. The client side is <code>@codemagic/react-native-patch</code>, a TurboModule for iOS and Android with an Expo config plugin, plus a CLI, <code>cmpatch</code>, that bundles your JavaScript and publishes it.</p>
<p>Two design decisions stood out once I&rsquo;d read the source.</p>
<p>The first is that the app never asks the API whether there&rsquo;s an update. When a release is published, the worker writes plain JSON manifests into object storage, and the app just fetches those. An update check is two static GETs against storage or a CDN; the API only receives metrics. My old endpoint was on the request path of every app launch. This one can&rsquo;t be.</p>
<p>The second is that every release names the exact binary version it&rsquo;s for, and the CLI computes a fingerprint of your native project and refuses to publish JavaScript onto a binary whose native code doesn&rsquo;t match. My server had a version string and a lot of hoping.</p>

<h2 class="relative group">Trying it on my laptop first
    <div id="trying-it-on-my-laptop-first" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#trying-it-on-my-laptop-first" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The docs start you on a local evaluation stack, and that&rsquo;s the right place to start.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">npm install -g @codemagic/patch-cli
</span></span><span class="line"><span class="cl">cmpatch selfhost local-eval up</span></span></code></pre></div></div>
<p>The CLI installed in two seconds. The stack took 3 minutes 14 seconds the first time, most of it building the server and dashboard images locally, and in non-interactive mode it prints nothing at all while it does that, which looks exactly like a hang. (Since fixed: it now prints one progress line per step.) Then four healthy containers appeared, all bound to localhost: the dashboard on 8080, the API on 3000, Postgres, and MinIO on 9100. It sensibly avoided the ports my own stack was already using.</p>
<p>Sign-in is disabled in this mode, with a warning on every page not to expose it.</p>
<figure>
  <div class="browser-frame">
    <div class="browser-frame__bar" aria-hidden="true">
      <span class="browser-frame__dots"><i></i><i></i><i></i></span>
      <span class="browser-frame__url">localhost:8080</span>
    </div><span class="browser-frame__shot" style="background:url('data:image/webp;base64,UklGRmwAAABXRUJQVlA4IGAAAACQBACdASogABQAPv1ko0eloqGYBgBbD8TgCzgCWNWXs6T53beCcoRI0PP/N6AA/K7n/8I/+iwVHjl71MVWujkm+9TgA0wAr+PZ+x6+cQcgCHdovZ75vexrOBrFPrvj8AA=') center/cover no-repeat"><img
      class="browser-frame__page"
      src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/local-eval-sign-in_hu_6ee9ddaa0c7c695e.webp"
      srcset="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/local-eval-sign-in_hu_6ee9ddaa0c7c695e.webp 800w, https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/local-eval-sign-in_hu_e5915d9b78052f15.webp 1280w"
      sizes="(min-width: 768px) 50vw, 65vw"
      width="1400" height="875"
      alt="The local evaluation sign-in page, with a pre-filled email and a warning that authentication is disabled"
      loading="lazy" decoding="async"
      data-zoom-src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/local-eval-sign-in_hu_8ae8b3cbcb1d7ae7.webp"></span></div>
  <figcaption>Local evaluation mode swaps GitHub sign-in for a pre-filled email.</figcaption>
</figure>

<p>The stack comes seeded with an app called Example Data, which is worth a look before you&rsquo;ve published anything, because it shows what the dashboard is for. The numbers in the next two screenshots are that seed data, not real users.</p>
<figure>
  <div class="browser-frame">
    <div class="browser-frame__bar" aria-hidden="true">
      <span class="browser-frame__dots"><i></i><i></i><i></i></span>
      <span class="browser-frame__url">localhost:8080</span>
    </div><span class="browser-frame__shot" style="background:url('data:image/webp;base64,UklGRmgAAABXRUJQVlA4IFwAAAAQBACdASogABUAPw1uqkqmIyGYDAQAYxDE9IABUVMfRogwtMiXImNo4AD+1hmAfbeuR0QbIc0lZuw4PBjyhGJq5t/3NdR81x+BG5H496NeiObQODoB8gkWF2AAAA==') center/cover no-repeat"><img
      class="browser-frame__page"
      src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/demo-release-history_hu_dfad23ca3450bc38.webp"
      srcset="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/demo-release-history_hu_dfad23ca3450bc38.webp 800w, https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/demo-release-history_hu_453fd7641ffbc69b.webp 1280w"
      sizes="(min-width: 768px) 50vw, 65vw"
      width="1600" height="1037"
      alt="Release history for the seeded Example Data app, with a 10% canary release and per-release success and failure counts"
      loading="lazy" decoding="async"
      data-zoom-src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/demo-release-history_hu_30abe30dd08f2234.webp"></span></div>
  <figcaption>Seeded demo data: release history with a 10% canary, target versions, and per-release success and failure counts.</figcaption>
</figure>

<figure>
  <div class="browser-frame">
    <div class="browser-frame__bar" aria-hidden="true">
      <span class="browser-frame__dots"><i></i><i></i><i></i></span>
      <span class="browser-frame__url">localhost:8080</span>
    </div><span class="browser-frame__shot" style="background:url('data:image/webp;base64,UklGRoQAAABXRUJQVlA4IHgAAABwBACdASogABcAPw1qrEsmIqIYDAQAYxDE9IBnsglwh49zWML+lyXzzjPEgAD+4AZDuD4GlZfO+rTnJJ+yBUjSHGV1a2gPc+tdTO7IIMf86boVjtRW8VJ7KXLfxZsJzumvn68JtLzOqetoXfqt/I/Omlo4DyEAAAA=') center/cover no-repeat"><img
      class="browser-frame__page"
      src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/demo-deployment-metrics_hu_2e0ff04f94cd5a88.webp"
      srcset="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/demo-deployment-metrics_hu_2e0ff04f94cd5a88.webp 800w, https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/demo-deployment-metrics_hu_91146bb0b6c75d52.webp 1280w"
      sizes="(min-width: 768px) 50vw, 65vw"
      width="1600" height="1155"
      alt="Deployment metrics for the seeded app: version distribution, adoption over time, update outcomes"
      loading="lazy" decoding="async"
      data-zoom-src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/demo-deployment-metrics_hu_1f6ae6ce53428957.webp"></span></div>
  <figcaption>Seeded demo data: which releases devices are actually running, and how installs went.</figcaption>
</figure>

<p>For comparison, my dashboard was an admin list of updates with an &ldquo;active&rdquo; checkbox. I had no idea how many phones had actually taken an update.</p>
<p>Logging the CLI in is a proper browser flow with PKCE and a localhost callback, and the approval page tells you which account is asking and that the code expires in about a minute.</p>
<figure>
  <div class="browser-frame">
    <div class="browser-frame__bar" aria-hidden="true">
      <span class="browser-frame__dots"><i></i><i></i><i></i></span>
      <span class="browser-frame__url">localhost:8080</span>
    </div><span class="browser-frame__shot" style="background:url('data:image/webp;base64,UklGRn4AAABXRUJQVlA4IHIAAADwBACdASogABQAPv1ioUeloqGYBgBbD8TxAFnAEsa4FDLDrochGk8HT/WQ+e1SUMAA/K7n5mOlQFSkxh0DtgfJ9tHRhVgvwu2jEApXgWL2ekdKJHkUb1NzXgNcjv6IA1JC+dF2JqE73QqxENNNeYvZMAA=') center/cover no-repeat"><img
      class="browser-frame__page"
      src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/cli-login-approve_hu_ee30fa96a8ea860e.webp"
      srcset="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/cli-login-approve_hu_ee30fa96a8ea860e.webp 800w, https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/cli-login-approve_hu_c7af1bedbd1fa8b3.webp 1280w"
      sizes="(min-width: 768px) 50vw, 65vw"
      width="1400" height="875"
      alt="The dashboard asking whether to approve a CLI sign-in"
      loading="lazy" decoding="async"
      data-zoom-src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/cli-login-approve_hu_c267548bca14bf21.webp"></span></div>
  <figcaption>cmpatch login asks the dashboard to approve the terminal.</figcaption>
</figure>


<h2 class="relative group">Pointing it at a real app
    <div id="pointing-it-at-a-real-app" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#pointing-it-at-a-real-app" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Patch wants one app per platform, each with a Staging and a Production deployment created for you. I made <code>maru-ios</code> in the dashboard and <code>maru-android</code> with <code>cmpatch app create</code>, mostly to see both. The dialog you get after creating an app is the most useful screen in the product for a migration: both deployment keys, the two URLs the SDK needs, and a note that deployment keys aren&rsquo;t secrets.</p>
<figure>
  <div class="browser-frame">
    <div class="browser-frame__bar" aria-hidden="true">
      <span class="browser-frame__dots"><i></i><i></i><i></i></span>
      <span class="browser-frame__url">localhost:8080</span>
    </div><span class="browser-frame__shot" style="background:url('data:image/webp;base64,UklGRoIAAABXRUJQVlA4IHYAAAAQBQCdASogABQAPuFWmkekIqEb9ABDDgT0gF8kHTL70/EPugF6lMUZ0A+0pWU0WRlAAPpGgpz7VeOvAMdDs/q/I00JZTDCozGF/p+yUbXDUjfdJacA2ZbVan+1M3EfSih3MXlM1+RWV02wNY/nmH4Pte3keQAA') center/cover no-repeat"><img
      class="browser-frame__page"
      src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/app-created-keys_hu_31f66d5c03d282e7.webp"
      srcset="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/app-created-keys_hu_31f66d5c03d282e7.webp 800w, https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/app-created-keys_hu_ec9ad24dac45b7f9.webp 1280w"
      sizes="(min-width: 768px) 50vw, 65vw"
      width="1400" height="875"
      alt="The app created dialog, showing Staging and Production deployment keys and the SDK URLs"
      loading="lazy" decoding="async"
      data-zoom-src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/app-created-keys_hu_bd9fb369cb1053b8.webp"></span></div>
  <figcaption>Everything the SDK needs, on one screen.</figcaption>
</figure>

<p>Two small things. <code>cmpatch init</code> linked a project to apps that already existed, so it couldn&rsquo;t be the first command, whatever the migration guide implied. That&rsquo;s since been fixed: in interactive mode it now creates one app per platform itself. And the dialog gives the API URL as <code>http://localhost:8080</code> while the docs and the CLI say 3000. Both work, because each port serves both, but you&rsquo;ll wonder.</p>
<p>Then I ran <code>cmpatch doctor</code> against the untouched app, and it found a real problem in three seconds. It reported the iOS binary version as 2.0.0. The app is 2.5.1.</p>
<p>The CLI finds every <code>Info.plist</code> under <code>ios/</code> and, if none has &ldquo;test&rdquo; in its path, takes the first alphabetically. maru has a WidgetKit extension whose folder sorts before the app&rsquo;s own, so the CLI picked the extension&rsquo;s <code>Info.plist</code>. That plist was stale at 2.0.0, which is my bug, but the effect is nasty: auto-detection would target every iOS release at a version no phone runs, and nothing would error. Updates would just never arrive, which is exactly the failure I warned about in my self-hosting post. Android read <code>versionName</code> correctly. The workaround is to pass <code>--target-binary-version</code> or <code>--plist-file</code>, and my publish script now passes the version explicitly after checking that <code>app.config.js</code> and both native projects agree. Later, the same bug made <code>doctor</code>&rsquo;s own manifest check fail against a deployment that was working fine, because it went looking for version 2.0.0&rsquo;s manifest. Once I&rsquo;d fixed my stale plist, <code>doctor</code> passed all 24 checks.</p>
<p>Codemagic has since fixed this. The CLI now reads the version from the app target&rsquo;s <code>Info.plist</code>, not an extension&rsquo;s, and if more than one target could be the app, <code>cmpatch</code> asks you which.</p>

<h2 class="relative group">The JavaScript side
    <div id="the-javascript-side" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-javascript-side" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Removing <code>expo-updates</code> and adding the SDK is a two-line change. Replacing what the app did with updates took more thought.</p>
<p>maru checks for updates on launch and whenever it comes back to the foreground, at most every fifteen minutes. If it finds one, it downloads it, and offers to restart; say no and it applies on the next cold start. There&rsquo;s also a manual check in Settings that shows which bundle you&rsquo;re running, and the error reporter tags every report with the update it came from.</p>
<p>The first thing I learned from the SDK source is that it looks up its native module at import time with <code>TurboModuleRegistry.getEnforcing</code>, which throws if the module isn&rsquo;t there. maru also ships a web build, and a top-level import would take the web app down. So everything goes through one small module that loads the SDK lazily, with a <code>.web.ts</code> twin that returns nothing, which also keeps the SDK out of the web bundle entirely.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-ts" data-lang="ts"><span class="line"><span class="cl"><span class="c1">// ota.ts (ota.web.ts exports a patchSdk() that always returns null)
</span></span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">Platform</span> <span class="p">}</span> <span class="kr">from</span> <span class="s2">&#34;react-native&#34;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">type</span> <span class="nx">PatchSdk</span> <span class="o">=</span> <span class="k">typeof</span> <span class="kr">import</span><span class="p">(</span><span class="s2">&#34;@codemagic/react-native-patch&#34;</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="kd">let</span> <span class="nx">sdk</span>: <span class="kt">PatchSdk</span> <span class="o">|</span> <span class="kc">null</span> <span class="o">|</span> <span class="kc">undefined</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">export</span> <span class="kd">function</span> <span class="nx">patchSdk</span><span class="p">()</span><span class="o">:</span> <span class="nx">PatchSdk</span> <span class="o">|</span> <span class="kc">null</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">if</span> <span class="p">(</span><span class="nx">sdk</span> <span class="o">!==</span> <span class="kc">undefined</span><span class="p">)</span> <span class="k">return</span> <span class="nx">sdk</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">  <span class="k">if</span> <span class="p">(</span><span class="nx">Platform</span><span class="p">.</span><span class="nx">OS</span> <span class="o">===</span> <span class="s2">&#34;web&#34;</span><span class="p">)</span> <span class="k">return</span> <span class="p">(</span><span class="nx">sdk</span> <span class="o">=</span> <span class="kc">null</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">  <span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nx">sdk</span> <span class="o">=</span> <span class="kr">require</span><span class="p">(</span><span class="s2">&#34;@codemagic/react-native-patch&#34;</span><span class="p">)</span> <span class="kr">as</span> <span class="nx">PatchSdk</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">  <span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nx">sdk</span> <span class="o">=</span> <span class="kc">null</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="nx">sdk</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>The automatic check itself is mostly <code>sync()</code>, which never throws and resolves to a status:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-ts" data-lang="ts"><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">status</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">patch</span><span class="p">.</span><span class="nx">sync</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">  <span class="nx">installMode</span><span class="o">:</span> <span class="s2">&#34;ON_NEXT_RESTART&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">mandatoryInstallMode</span><span class="o">:</span> <span class="s2">&#34;ON_NEXT_RESUME&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl"><span class="p">});</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="nx">status</span> <span class="o">===</span> <span class="s2">&#34;update-installed&#34;</span><span class="p">)</span> <span class="nx">offerRestart</span><span class="p">();</span></span></span></code></pre></div></div>
<p>The SDK&rsquo;s default for mandatory releases is <code>IMMEDIATE</code>, which reloads the JavaScript wherever the user happens to be. I changed it to apply the next time the app comes back from the background, because losing a half-written post is a worse bug than most fixes are good. At the time, <code>InstallMode</code> was a string union, not the enum object the docs&rsquo; examples suggested; it&rsquo;s now exported as a constants object, so <code>InstallMode.ON_NEXT_RESTART</code> works as documented.</p>

<h2 class="relative group">The native side, when you commit ios/ and android/
    <div id="the-native-side-when-you-commit-ios-and-android" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-native-side-when-you-commit-ios-and-android" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The migration guide says to run <code>npx expo prebuild --clean</code> after adding the config plugin. I ran it in a separate checkout and it deleted bundled images, my Android network security config, the iOS privacy manifest and <code>Podfile.lock</code>, and reverted a test-runner fix in <code>build.gradle</code> along with a few hundred lines of <code>Info.plist</code>. Without <code>--clean</code>, Expo cleared both directories anyway.</p>
<p>This isn&rsquo;t Patch&rsquo;s fault. maru started as a managed Expo app and grew native customisations, so <code>ios/</code> and <code>android/</code> are committed and EAS builds them as they are. But plenty of apps look like that, and the guide didn&rsquo;t warn you. It does now: the Expo migration guide has two paths, prebuild for generated native projects and the exact hand-applied changes for committed ones.</p>
<p>What the plugin actually changes turns out to be small enough to do by hand. On iOS, one import and one line in <code>AppDelegate.swift</code>:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-swift" data-lang="swift"><span class="line"><span class="cl"><span class="k">return</span> <span class="n">CodemagicPatch</span><span class="p">.</span><span class="n">bundleURL</span><span class="p">()</span> <span class="p">??</span> <span class="n">Bundle</span><span class="p">.</span><span class="n">main</span><span class="p">.</span><span class="n">url</span><span class="p">(</span><span class="n">forResource</span><span class="p">:</span> <span class="s">&#34;main&#34;</span><span class="p">,</span> <span class="n">withExtension</span><span class="p">:</span> <span class="s">&#34;jsbundle&#34;</span><span class="p">)</span></span></span></code></pre></div></div>
<p>On Android, one import and one argument in <code>MainApplication.kt</code> (this is the React Native 0.82+ shape; older versions override <code>getJSBundleFile()</code> instead):</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-kotlin" data-lang="kotlin"><span class="line"><span class="cl"><span class="nc">ExpoReactHostFactory</span><span class="p">.</span><span class="n">getDefaultReactHost</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">  <span class="n">jsBundleFilePath</span> <span class="p">=</span> <span class="nc">CodemagicPatch</span><span class="p">.</span><span class="n">getJSBundleFile</span><span class="p">(</span><span class="n">applicationContext</span><span class="p">),</span>
</span></span><span class="line"><span class="cl">  <span class="c1">// ...</span></span></span></code></pre></div></div>
<p>Plus three config values per platform and the removal of the old <code>expo-updates</code> settings: 13 lines added and 20 removed across both projects.</p>
<p>The plugin writes those config values as literals at prebuild time, which, with committed native projects, would mean one hard-coded deployment for every build. I wanted preview builds on Staging and store builds on Production from the same project, so the values come from the build environment instead. In <code>Info.plist</code>, Xcode expands build settings:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="line"><span class="cl"><span class="nt">&lt;key&gt;</span>CodemagicPatchDeploymentKey<span class="nt">&lt;/key&gt;</span>
</span></span><span class="line"><span class="cl"><span class="nt">&lt;string&gt;</span>$(PATCH_IOS_DEPLOYMENT_KEY)<span class="nt">&lt;/string&gt;</span></span></span></code></pre></div></div>
<p>And in <code>android/app/build.gradle</code>:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-groovy" data-lang="groovy"><span class="line"><span class="cl"><span class="kt">def</span> <span class="n">patchEnv</span> <span class="o">=</span> <span class="o">{</span> <span class="n">name</span> <span class="o">-&gt;</span> <span class="n">System</span><span class="o">.</span><span class="na">getenv</span><span class="o">(</span><span class="n">name</span><span class="o">)</span> <span class="o">?:</span> <span class="o">(</span><span class="n">findProperty</span><span class="o">(</span><span class="n">name</span><span class="o">)</span> <span class="o">?:</span> <span class="s2">&#34;&#34;</span><span class="o">)</span> <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="n">resValue</span> <span class="s2">&#34;string&#34;</span><span class="o">,</span> <span class="s2">&#34;CodemagicPatchDeploymentKey&#34;</span><span class="o">,</span> <span class="n">patchEnv</span><span class="o">(</span><span class="s2">&#34;PATCH_ANDROID_DEPLOYMENT_KEY&#34;</span><span class="o">)</span></span></span></code></pre></div></div>
<p>The keys then sit in each <code>eas.json</code> build profile next to the <code>EXPO_PUBLIC_</code> values. An empty value means the SDK quietly does nothing, which is fine for a local build and a disaster for a store build, so <code>app.config.js</code> now throws if a preview or production EAS build is missing them or still points at localhost.</p>

<h2 class="relative group">The first update
    <div id="the-first-update" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-first-update" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>For the first release I changed the onboarding headline, which you can see without signing in, and published it:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">./scripts/publish-update.sh ios --notes <span class="s2">&#34;Onboarding headline over the air&#34;</span></span></span></code></pre></div></div>
<p>That took 30 seconds, most of it Metro and Hermes. The server&rsquo;s worker published the manifest 0.6 seconds after the upload finished. The update is a 7.3 MB compressed tarball, against the 11 MB Hermes bundle plus assets my old export produced.</p>
<p>One thing to get right here: the JavaScript bundle inlines your <code>EXPO_PUBLIC_</code> values when it&rsquo;s built, so an update has to be built with the same values as the binary it lands on, or you ship JavaScript that talks to the wrong backend. My script loads them from the same <code>eas.json</code> profile that built the binary. Patch&rsquo;s CI docs now spell this out too, along with the fact that <code>release-react</code> doesn&rsquo;t read EAS profiles itself.</p>
<p>Then I relaunched the app. The device log showed the whole update check as two requests to object storage, <code>meta.json</code> and <code>2.5.1/manifest.json</code>. The SDK wrote a <code>Downloaded</code> event three seconds after launch and staged the update, and the app offered a restart.</p>
<figure><div class="phone-frame" style="aspect-ratio: 900 / 1840; --screen-radius: 15.7% / 7.2%">
    <video
      class="phone-frame__screen"
      style="left: 5.3333%; top: 2.5%; width: 89.3333%; height: 95%"
      autoplay loop muted playsinline preload="metadata"
      poster="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/app-update-poster.jpg" style="background:url('data:image/webp;base64,UklGRoYBAABXRUJQVlA4IHoBAAAwCgCdASogAEYAPw1oq0omIqIWagaoYxDE9IBo3u6bOACEWXWx1HDG/AwrSOYwsJmgoDuewmmxiJfqdlf28aG4OgV3Vy0nk3lgu8Wi25BY3FxW+lY1wMNQ5gAA/uqWQwe/E/6WeZpIf2UpLel/fKpwqlcmjLMeA7F4ReOblq5eH4qIOx1w7ZF3v0mxWMH8e4hZoalFig747vzom14jgdSClOC5vthxNjGbdjdmv0JuF4Bd3uw2FZbc3Dlojmgl1fUvZqyymqEqzOWLtImgLAZjJhWZgigFmKgGd+GQ0SIKjnJHHdXOZrb/cZMTM1wrOB56DkWBsUxEsixjmVu+Vb3yqJNYglAA21u7aH9XnZ18oNyTlPWugRrsPfZ+/F1gGsmkViDzBGO0f1wXrNBJimlGcHkGkCt7LH9QNjPcy1A9c2dBEltQFPx6XWi1nm9wND9YTEPiTwnjvIduwaNn9YfPJS9b+I1LMURaw77It/AhHjT2gmi4ar24AAA=') center/cover no-repeat"
      width="720"
      height="1566"
      aria-label="The app relaunching on its shipped bundle, offering the update, and restarting into release v1">
      <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/app-update.mp4" type="video/mp4">
    </video>
    <img class="phone-frame__bezel nozoom" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/iphone-17-frame_hu_492bde446de4e1d1.webp" width="900" height="1840" alt="" aria-hidden="true" decoding="async">
  </div><figcaption>Relaunch, the app&rsquo;s own prompt from sync() returning update-installed, then release v1 over the air.</figcaption>
</figure>


<h2 class="relative group">The bug was mine
    <div id="the-bug-was-mine" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-bug-was-mine" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Then I looked at the dashboard. One simulator had installed release v1, and it showed two successful installs and two active users.</p>
<figure>
  <div class="browser-frame">
    <div class="browser-frame__bar" aria-hidden="true">
      <span class="browser-frame__dots"><i></i><i></i><i></i></span>
      <span class="browser-frame__url">localhost:8080</span>
    </div><span class="browser-frame__shot" style="background:url('data:image/webp;base64,UklGRmgAAABXRUJQVlA4IFwAAADwAwCdASogABQAPw1wqUqmIyGYDAQAYxDE9IABUVMd2rf8uKbf68owAP7WGYB/h1ia3xpTYkbuTZlMczaiJLdSTP+17jDH1qfCOJ+8A+IA+QScXzRlnhc+zceAAA==') center/cover no-repeat"><img
      class="browser-frame__page"
      src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/staging-double-counted_hu_4dd1f5d2ff813ace.webp"
      srcset="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/staging-double-counted_hu_4dd1f5d2ff813ace.webp 800w, https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/staging-double-counted_hu_13e5d2d984250bf3.webp 1280w"
      sizes="(min-width: 768px) 50vw, 65vw"
      width="1400" height="875"
      alt="The Staging deployment showing two active users and two successes for one device"
      loading="lazy" decoding="async"
      data-zoom-src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/staging-double-counted_hu_b455b1f0b69680b5.webp"></span></div>
  <figcaption>One simulator, counted twice.</figcaption>
</figure>

<p>The SDK keeps its state and pending metric events as files in the app&rsquo;s container, which made this easy to chase. There were two <code>Success</code> events with identical timestamps and different ids. My hook confirmed the running bundle with <code>notifyAppReady()</code> on mount, and then called <code>sync()</code> straight away, and <code>sync()</code> calls <code>notifyAppReady()</code> itself. The two calls overlapped, each saw the release as pending, and each recorded the events. The server de-duplicates on event id, but these had different ids, so both counted, and those duplicates are permanent.</p>
<p>The fix on my side was one shared confirmation per launch that everything else awaits. The SDK could also guard against overlapping calls itself, and I suggested that. It now does: overlapping <code>notifyAppReady()</code> calls, including the one inside <code>sync()</code>, share a single confirmation, so each install is recorded once. The SDK reference also now says that <code>sync()</code> confirms readiness itself, so an app that uses it doesn&rsquo;t need to call <code>notifyAppReady()</code> separately.</p>
<p>The nice part was shipping the fix. It&rsquo;s a JavaScript-only change, so it went out as release v2, and because a device on v1 can be sent a binary diff, v2 downloaded as a 543 KB patch instead of the 7.3 MB bundle, about 7% of the size. After the restart: one download, one install, one success, one active device.</p>
<figure>
  <div class="browser-frame">
    <div class="browser-frame__bar" aria-hidden="true">
      <span class="browser-frame__dots"><i></i><i></i><i></i></span>
      <span class="browser-frame__url">localhost:8080</span>
    </div><span class="browser-frame__shot" style="background:url('data:image/webp;base64,UklGRmwAAABXRUJQVlA4IGAAAADwAwCdASogABQAPw1qqksmIqGYDAQAYxDE9IABUVMd2rfRI1O5mmXAAP7WGYB/h1ia3xpTYkbuTZlMczaiJLkoVKAckjyruR4hTL7NmaqeP1qAfIJOLnmwKkXiX44AAAA=') center/cover no-repeat"><img
      class="browser-frame__page"
      src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/staging-v1-v2_hu_361247d6f35aa5fc.webp"
      srcset="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/staging-v1-v2_hu_361247d6f35aa5fc.webp 800w, https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/staging-v1-v2_hu_d07d239ec0e34973.webp 1280w"
      sizes="(min-width: 768px) 50vw, 65vw"
      width="1400" height="875"
      alt="Release history showing v1 with inflated numbers and v2 with correct ones"
      loading="lazy" decoding="async"
      data-zoom-src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/staging-v1-v2_hu_dab633c48fa0be46.webp"></span></div>
  <figcaption>v1&rsquo;s duplicates stay; v2 counts correctly.</figcaption>
</figure>


<h2 class="relative group">Breaking it on purpose
    <div id="breaking-it-on-purpose" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#breaking-it-on-purpose" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Rollback is the feature I cared about most, because my old setup had none on the device. A bad update would have crashed every launch until I noticed and un-ticked a checkbox.</p>
<p>So I released a v3 that throws before the first render, which means it can never call <code>notifyAppReady()</code>. The app downloaded it, offered a restart, and died to the home screen.</p>
<figure><div class="phone-frame" style="aspect-ratio: 900 / 1840; --screen-radius: 15.7% / 7.2%">
    <video
      class="phone-frame__screen"
      style="left: 5.3333%; top: 2.5%; width: 89.3333%; height: 95%"
      autoplay loop muted playsinline preload="metadata"
      poster="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/app-crashed-poster.jpg" style="background:url('data:image/webp;base64,UklGRjACAABXRUJQVlA4ICQCAADQDgCdASogAEYAPw1+rU4mJCIhKbqpIMYhieIAuzPq4M7sW3lP/kPxexnET5ASwFv8Htr8DNovWXwo2ZQynTi8ui+9q1qzPLfv97/wPQgMDj/+e/pvE9miOHoCzZC5Gv/U0oN8n33d1NMZxA4+qT/uNT35EBYJZa/w3Ts1AUToAP5vfw4j/pjBP6ZaA8LejegsfSPzEPXc0mvX+J1dMRFcTwhgh8BttzpcI4CRjUDkbGoa6UAnxK5kCSatezNL4gQf4nZeHytilXmRtp2c1xohb5/y8HBhWsukQWCAk8rKnNMQYUQJEVbasq2JgftASZSBFtiUkjtFF9K+EYtO0DOtXBWDPeHJf1TqqEHHwl4CQ1zsv9Cx+l8KPR2tUhRR8Ctso49YsumZzdxVCAKQdb9pNx77EfSYM6ALaYnzRt4qTUeUBf3ENt66RmZKq5nGflJ9lEW0oDnWjx6zoAqeJS44t1nUDDIZm1gayu9+nhUWZE+InoYr7YlMmmXX2kklVMVsT0s5xOQqPPlW4UoSUv0NgFVDavqEtwMzPqNuUIjjfwXToJhzDbgUidZqS0gSOrBna2Xj2XcOmf2KfPjtTFgKpl74NNsPw+SkvLP+XIfGRP7f4DZ3SF5r4kITD9QK1Mb4Z3frLXQeA432gyyslKobZUjhHzgpw6Lsv1z4B+zVfYG/nF6OiGZ+SPJQMFRe2LmOB4/oyDsE7meakIUBZvS1zSAAAA==') center/cover no-repeat"
      width="720"
      height="1566"
      aria-label="The simulator home screen after the app crashed on the bad release">
      <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/app-crashed.mp4" type="video/mp4">
    </video>
    <img class="phone-frame__bezel nozoom" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/iphone-17-frame_hu_492bde446de4e1d1.webp" width="900" height="1840" alt="" aria-hidden="true" decoding="async">
  </div><figcaption>v3 crashing on launch.</figcaption>
</figure>

<p>The next launch booted v3 again and crashed again, which surprised me, because the docs say a bundle that crashes before <code>notifyAppReady()</code> is rolled back. The source explains it: the SDK allows three unconfirmed launches before deciding it&rsquo;s a crash, because one unconfirmed launch can just mean iOS killed a healthy process before any JavaScript ran. The fourth launch came back up on v2.</p>
<figure><div class="phone-frame" style="aspect-ratio: 900 / 1840; --screen-radius: 15.7% / 7.2%">
    <video
      class="phone-frame__screen"
      style="left: 5.3333%; top: 2.5%; width: 89.3333%; height: 95%"
      autoplay loop muted playsinline preload="metadata"
      poster="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/app-rolled-back-poster.jpg" style="background:url('data:image/webp;base64,UklGRsABAABXRUJQVlA4ILQBAABQCgCdASogAEYAPw1mq0umIqGU2q7YYxDE9IBowO6mweBInrUPWk42PSTT65hMmOGGOXZWA/sd5q9BGdjSK2j84FuUL93nyJVQuphNZ6mwXQhv8NVWhs+Q6BIAAP74ukd3WXEH+9Z7Rrx8W8zZkkK5+g1e2Lc8Yi325om3Qy3bb7uYsUutPzhS99cwA1kptzZhyUOs2MW6lH9eP8+SPePVMJGvfSIxSO6tL43kYr+PfLzJw/oJabDsUcKslfz5t3nFCXsiVKRSWBi80g/4Y8CJZiDrEvRejhn6wF7DlE4cfLc64tC8OpWtwMjLNLzfe0pK5MjRdPbq4v5sKsY7T49CjMzJz033ddGNJ1Vmp+9decCnIDCYl2pLqRBhrM5E+D4Cw6TfkPAN/WpX0LXCs9Wr8ACcRRwajxQnbjxLU1tKX+yJyrshjPphgACyyYJKjidt2xw5zVQZcF6XykRe430a0dWMKdcBvnMqq2qBswoqRDNp4NIHmM7r87FSOG3y5ScC9wPZH2OoU+6Am86Nz+s2Tk/J+sj1gZFVQqfqXFWH4AEGF/cO+yLfluiKfZvqAOcwbgAA') center/cover no-repeat"
      width="720"
      height="1566"
      aria-label="The app running v2 again after the automatic rollback">
      <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/app-rolled-back.mp4" type="video/mp4">
    </video>
    <img class="phone-frame__bezel nozoom" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/iphone-17-frame_hu_492bde446de4e1d1.webp" width="900" height="1840" alt="" aria-hidden="true" decoding="async">
  </div><figcaption>Fourth launch: rolled back to v2 without anyone touching the server.</figcaption>
</figure>

<p>The device then reported the failure itself, as <code>crash_rollback</code>, and the dashboard showed it against v3. That&rsquo;s a sensible design, but it&rsquo;s worth being plain about what it means: a bad release costs each user three crashed launches before they recover, and at the time the docs didn&rsquo;t mention the number. They do now, and the budget is configurable, with <code>CodemagicPatchMaxLaunchAttempts</code> natively or the Expo plugin&rsquo;s <code>maxLaunchAttempts</code>. That&rsquo;s the case for Staging first and a small Production rollout second.</p>
<p>Stopping a bad release for everyone else is one command, and it took under a second:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">cmpatch release rollback --app maru-ios --deployment Staging</span></span></code></pre></div></div>
<p>It doesn&rsquo;t rewrite history. It publishes the previous release again as a new one (v4, marked as a rollback of v2), so the crashing release stays in the list with its failure count, which is the honest record. The dashboard does the same from a dialog.</p>
<figure>
  <div class="browser-frame">
    <div class="browser-frame__bar" aria-hidden="true">
      <span class="browser-frame__dots"><i></i><i></i><i></i></span>
      <span class="browser-frame__url">localhost:8080</span>
    </div><video
      class="browser-frame__page"
      autoplay loop muted playsinline preload="metadata"
      poster="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/dashboard-rollback-poster.jpg"
      style="background:url('data:image/webp;base64,UklGRmwAAABXRUJQVlA4IGAAAABwBACdASogABQAPw1qp0emIyGYBABjEMT0gGfQEs2nvxX7EOeFbRn3H5Si4AD+1iXJGzIunVk/ewlUVdIUbFiwAGX5QAkFFcZDl2at4PkETvjCXCOVoXFdscz2ut9AAAA=') center/cover no-repeat"
      width="1280"
      height="800"
      aria-label="Rolling back Staging from the dashboard: the previous release is republished as v4">
      <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/dashboard-rollback.mp4" type="video/mp4">
    </video></div>
  <figcaption>Rolling back from the dashboard: v2 comes back as v4, and v3 stays in the list.</figcaption>
</figure>

<figure>
  <div class="browser-frame">
    <div class="browser-frame__bar" aria-hidden="true">
      <span class="browser-frame__dots"><i></i><i></i><i></i></span>
      <span class="browser-frame__url">localhost:8080</span>
    </div><span class="browser-frame__shot" style="background:url('data:image/webp;base64,UklGRmoAAABXRUJQVlA4IF4AAAAwBACdASogABQAPw1op0emIyGYBABjEMTygAFRZbu1b6Gdq9jYHm/TLAAA/tYZgH+HWJrfGlNiRvwNU+RVn1Uhl5QjE2FNRxQPa3YDnfLX9O0wDNn7xOtAkLPDgAAA') center/cover no-repeat"><img
      class="browser-frame__page"
      src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/staging-after-rollback_hu_6a96ca1588cc6310.webp"
      srcset="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/staging-after-rollback_hu_6a96ca1588cc6310.webp 800w, https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/staging-after-rollback_hu_5552e433d6a65a3f.webp 1280w"
      sizes="(min-width: 768px) 50vw, 65vw"
      width="1400" height="875"
      alt="Release history after the rollback, with v4 marked as a rollback and v3 showing one failure"
      loading="lazy" decoding="async"
      data-zoom-src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/staging-after-rollback_hu_5066c51b1ba693c2.webp"></span></div>
  <figcaption>v4 is the rollback; v3 keeps its failure.</figcaption>
</figure>


<h2 class="relative group">Android
    <div id="android" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#android" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Android had two surprises, neither Patch&rsquo;s. The R8 keep rule I&rsquo;d added for the SDK lived in <code>app.config.js</code>, which only reaches the native project through prebuild, so my first release build accidentally tested whether the SDK survives R8 without one. It does: R8 renamed all its classes, and updates downloaded, installed and rolled back fine. And the emulator, freshly cold-booted with Gradle still holding memory, was so slow that my first test gave up 45 seconds before the SDK finished the download it had already started.</p>
<p>Release v1 applied, with one success and one active device, and a crashing v2 rolled back after the same three-launch budget.</p>
<figure>
  <div class="phone-frame" style="aspect-ratio: 900 / 1892; --screen-radius: 9.85% / 4.43%"><span class="phone-frame__screen phone-frame__ph" aria-hidden="true" style="left: 4.889%; top: 2.326%; width: 90.222%; height: 95.349%; background:url('data:image/webp;base64,UklGRsgBAABXRUJQVlA4ILwBAABQCwCdASogAEcAPw1wr06mIqIhJngMAMYhiekAzRAKJZ22yvEtm7/GFRCOt1Z6YnyGNWf+i7i0ewagB55W+rOp9DBjbctVlnDXK6lGDu9FH315DSWJUMBYkPGJY2+xw/B5QDAA/vURG5LVrYKJoO2SXy+UxQiUlovs8pxF48eKxgmVxH4hV0qd23H4fTbOXId4reHVkO/ZtsoHNdCHkv0JWiIqSQvxGntYFegdbOEkel+at+Jvs/b4yghmeIXnBH7M31JdyN1H2WvMPx2TwLZfiUh7Vs/c0xs3ET28MPX4PV32jfA2Qo55LcWZBHZVnPmnDwZLLo2Dv++B0SqBKWqbTWPQKOgzF+6YGKB7vcORmV6iyLh5aW30GEJ6lcPq8nat/61jd9i9CZePrzdLJPqGGJyPCbsjPkfhTd6BEdIQraUcOjRfSxAroG5B9nslpJZA63tGk2R93MKzS48w8pEUJKeCNc9lq7Q91gnOgYXePvVHH49kJkJCf5DnRUSgdBqJS0Dh6nG2R7OcW67l22CzkV09rMSoVJlTLhktX5d3Ximn/zbkXSgGUos1pjcQR73ncJ+50rXoCD05SAA=') center/cover no-repeat"></span>
    <img
      class="phone-frame__screen"
      style="left: 4.889%; top: 2.326%; width: 90.222%; height: 95.349%"
      src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/android-after-v1_hu_a5ee68e09a427bed.webp"
      width="600" height="1333"
      alt="The Android app showing the headline delivered over the air"
      loading="lazy" decoding="async"
      data-zoom-src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/android-after-v1_hu_a5ee68e09a427bed.webp">
    <img class="phone-frame__bezel nozoom" src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/pixel-8-frame_hu_52e6b4e761a590c9.webp" width="900" height="1892" alt="" aria-hidden="true" decoding="async">
  </div>
  <figcaption>Android, back on v1 after its own rollback.</figcaption>
</figure>


<h2 class="relative group">Past the happy path
    <div id="past-the-happy-path" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#past-the-happy-path" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Updates arriving and rolling back is the core of it, but a team lives in the other features, so I went through them one at a time.</p>
<p>Staged rollouts are deterministic, which I liked. A device is in if the first eight hex digits of <code>md5(deviceId + &quot;-&quot; + releaseLabel)</code>, modulo 100, are below the rollout percentage, so the same phone stays in or out for a given release. I worked out that my simulator sat in bucket 91 for the next release, published it at 25%, and the simulator correctly got nothing. Raised to 95% with <code>cmpatch release patch</code>, which took under a second, it updated on the next launch.</p>
<figure>
  <div class="browser-frame">
    <div class="browser-frame__bar" aria-hidden="true">
      <span class="browser-frame__dots"><i></i><i></i><i></i></span>
      <span class="browser-frame__url">localhost:8080</span>
    </div><video
      class="browser-frame__page"
      autoplay loop muted playsinline preload="metadata"
      poster="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/dashboard-rollout-poster.jpg"
      style="background:url('data:image/webp;base64,UklGRnIAAABXRUJQVlA4IGYAAAAQBACdASogABQAPw1qqEemIyIYBABjEMT0gGH0Es2nvxX9G/4/1g7tAAD+1iXJGzIunVcHqQBmnStoD1oAHJUjpBT6bKy8GQx+Yo2Ka5cGJlghQl6jWcyOWHRQDYW9x5JJDLafQAA=') center/cover no-repeat"
      width="1280"
      height="800"
      aria-label="Raising a release&#39;s rollout from 25% to 95% in the dashboard">
      <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/dashboard-rollout.mp4" type="video/mp4">
    </video></div>
  <figcaption>Raising a partial rollout from 25% to 95%, without republishing.</figcaption>
</figure>

<p>Then my next release failed with a 409: &ldquo;deployment has an active rollout below 100 percent&rdquo;. Only one partial rollout per deployment is allowed, so you finish, disable or roll back a canary before shipping anything else. That&rsquo;s reasonable, and documented, but a pipeline that publishes on every merge will run into it in the middle of a canary. Since I reported it, the CLI explains itself here: if an active partial rollout is blocking you, it says waiting won&rsquo;t help and how to complete or disable the rollout, and if another release job is still running it tells you to wait with <code>release inspect --wait</code>. The docs now have a section on sequential release changes.</p>
<p>Mandatory releases use the SDK&rsquo;s <code>mandatoryInstallMode</code>. With mine set to apply on the next resume, the app downloaded the update and showed its prompt, and when I ignored the prompt, sent the app to the background and brought it back, the new version was simply there.</p>
<p>Disabling a release does more than stop offering it. The moment I disabled the latest one, the manifests pointed at the newest release still enabled, and devices on the disabled one were offered a patch back to it. Disable everything for a binary version and the manifest&rsquo;s target becomes null, and the SDK reverts the app to the bundle it shipped with. My update hook didn&rsquo;t prompt for that case at first, so now it does.</p>
<p>Promoting from Staging to Production took under a second and reused the exact package that was tested, same hash and notes, rather than rebuilding it. It also accepts a rollout percentage, so &ldquo;promote to 10% of Production&rdquo; is one command.</p>
<p>Building and publishing can also be separate steps. <code>cmpatch bundle</code> produces a <code>.cmpatch</code> artifact, and the dashboard&rsquo;s &ldquo;Bundle upload&rdquo; option reads it before uploading: platform, target version, fingerprint, signing status, size and bundler. That suits a setup where CI builds the artifact and someone else decides when to publish it.</p>
<figure>
  <div class="browser-frame">
    <div class="browser-frame__bar" aria-hidden="true">
      <span class="browser-frame__dots"><i></i><i></i><i></i></span>
      <span class="browser-frame__url">localhost:8080</span>
    </div><video
      class="browser-frame__page"
      autoplay loop muted playsinline preload="metadata"
      poster="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/dashboard-upload-poster.jpg"
      style="background:url('data:image/webp;base64,UklGRnwAAABXRUJQVlA4IHAAAAAwBACdASogABQAPw14sE+mI6IhKAgAxiGJ6QAAM7aVPPd3tO2d2B9IEAAA/tYlyRsyLp1nLc5Hh5nniWZ+UIxN4AAKrWhTSPPLnDPJV90MvTw1QAmDXcvY3C3ghY+Uo+Wdxkjji3HNEgzIPqpIwAAA') center/cover no-repeat"
      width="1280"
      height="800"
      aria-label="Uploading a .cmpatch artifact in the dashboard: it reads the platform, version, fingerprint and size, then warns that the fingerprint differs">
      <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/dashboard-upload.mp4" type="video/mp4">
    </video></div>
  <figcaption>Bundle upload: the dashboard reads the artifact, then the fingerprint guard steps in.</figcaption>
</figure>

<p>That&rsquo;s also where I ran into the fingerprint guard in earnest. After I fixed my stale widget plist, the server refused my next release with a 409, because the native project&rsquo;s fingerprint no longer matched the one it had recorded for 2.5.1. On Android, editing a comment in <code>app.config.js</code> was enough, since Expo includes the app config in the fingerprint. The dashboard shows the same check as a warning with both fingerprints and an &ldquo;Upload anyway&rdquo; button. In both cases nothing native had changed on the installed binary, so overriding was right. In real use, though, the honest answer is nearly always a version bump and a store build, and my publish script now says exactly that when it happens.</p>
<p>Code signing is RS256: the CLI signs the package hash with an RSA private key, and the SDK checks it against a public key compiled into the binary. The key goes in as a single base64 line, which fit my build-setting approach, and I tested it on both platforms. With the key in the app, an unsigned release was refused before it downloaded. With &ldquo;require code signing&rdquo; turned on for the app, the server rejected an unsigned publish with an error that named the fix and linked the guide. A signed release installed, and the SDK recorded the signature as verified. It also refused an older unsigned release the server fell back to when I disabled the signed one. The catch is that the public key has to be in the first binary you ship, because an update can&rsquo;t add it.</p>
<figure>
  <div class="browser-frame">
    <div class="browser-frame__bar" aria-hidden="true">
      <span class="browser-frame__dots"><i></i><i></i><i></i></span>
      <span class="browser-frame__url">localhost:8080</span>
    </div><span class="browser-frame__shot" style="background:url('data:image/webp;base64,UklGRnAAAABXRUJQVlA4IGQAAABwBACdASogAB0APw14sE+mI6IhKAgAxiGJ6QAAM+3OuAEp3oUrP1GNW2QgAAD+1hmAf4eqLtdnP/9v1g2ZTHRXrrujcZyW6apQhqigB3MdqokDYA7HESmkf+QYJtIlWU+VYAAA') center/cover no-repeat"><img
      class="browser-frame__page"
      src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/signed-release-detail_hu_23c3bd38e0daa226.webp"
      srcset="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/signed-release-detail_hu_23c3bd38e0daa226.webp 800w, https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/signed-release-detail_hu_2173e76e5a1b2cec.webp 1280w"
      sizes="(min-width: 768px) 50vw, 65vw"
      width="1400" height="1264"
      alt="Release detail showing the signature as Signed, sha256"
      loading="lazy" decoding="async"
      data-zoom-src="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/signed-release-detail_hu_f18ca5bb6112ee2a.webp"></span></div>
  <figcaption>A signed release.</figcaption>
</figure>

<p>Teams and CI are covered as well. Members get one of four team-wide roles (owner, admin, developer, viewer) and invitations wait until the person first signs in. Personal access tokens worked with an empty home directory, passed either as <code>--token</code> or through environment variables, and the token list shows when each was last used. I&rsquo;ve also written a manually triggered CI workflow that runs the same publish script on a Linux runner with the signing key from a secret, though I haven&rsquo;t run it yet, since it needs the hosted server.</p>
<p>One tool I&rsquo;d have skipped at the time is <code>cmpatch debug ios</code>. It streamed the system log filtered on &ldquo;OTA&rdquo; case-insensitively, which matches &ldquo;Rotation&rdquo;, so a twenty-second app launch produced a screenful of SpringBoard messages and nothing from the app. That&rsquo;s fixed: it now shows only lines carrying the SDK&rsquo;s markers. The SDK doesn&rsquo;t log much on its own, mostly errors and development-build warnings, so expect a quiet stream. The <code>getpwuid_r</code> warning you may see comes from <code>xcrun simctl</code>, not Patch.</p>

<h2 class="relative group">How hard is it, really
    <div id="how-hard-is-it-really" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#how-hard-is-it-really" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Codemagic asked for my opinion, so here it is, as plainly as I can put it.</p>
<p>Trying it out is easy. Two commands, a few minutes, and you have the real server, a dashboard with demo data, and a CLI you can point at your own app. I&rsquo;d rate it the best part of the first hour.</p>
<p>Integrating the SDK is moderate work, and most of the difficulty is in your own project rather than in Patch. On a fresh Expo app with generated native folders, it really is the plugin plus a few lines replacing <code>expo-updates</code> calls. On an app like maru, with committed native projects, a widget extension, a web build, R8 and build profiles, the work was in the edges. I had to apply the native changes by hand to avoid prebuild, make the configuration build-time so Staging and Production builds could differ, and keep the SDK away from web. I also had to make sure the JavaScript in an update was built with the same environment as the binary. None of it was hard once I understood it. When I did it most of that wasn&rsquo;t in the docs, though the committed-native-projects path and the bundle-time environment now are.</p>
<p>Day-to-day use is good. Publishing is one command and about half a minute. Rollouts, promotion, disabling and rollback are all under a second from the CLI or the dashboard, and the errors say what went wrong and what to do. The server&rsquo;s guards (the fingerprint check, one canary at a time, signing) are strict in ways that stopped me doing the wrong thing more than once.</p>
<p>Running it in production is the bigger commitment. It&rsquo;s a Docker Compose stack with Postgres and object storage that you have to host, back up and upgrade, and it needs two domains and an OAuth app. For a team already running servers that&rsquo;s a quiet afternoon. For a team on EAS precisely because they didn&rsquo;t want servers, it&rsquo;s the real cost of switching, more than the SDK work.</p>
<p>In wall-clock terms, I installed the CLI at 12:29 and had the first update applying on a simulator at 13:34, and half an hour of that was an Xcode build that stalled for reasons unrelated to Patch. Everything in this post, on both platforms, was done by mid-afternoon, not counting the hosted server.</p>
<p>The things that cost me the most time, in order: <code>expo prebuild --clean</code> wiping my committed native projects, and then working out how to wire everything by hand; the iOS version-detection bug, which would have sent updates to a version nobody runs; the double-counted installs, which were my own doing but easy for anyone to repeat, since <code>sync()</code> calls <code>notifyAppReady()</code> itself; and the undocumented three-launch crash budget, which surprised me halfway through a test. After those came things that are correct but need planning: the fingerprint guard firing after harmless native-adjacent edits, one canary at a time per deployment, and lifecycle jobs that can&rsquo;t overlap, which matters as soon as a script does several things in a row. The rest was small: a silent first-run setup, a noisy debug command, and a few docs examples that didn&rsquo;t match the code.</p>
<p>I wrote all of it up for Codemagic, with the details, and by 23 September most of it was fixed: the version detection, the overlapping confirmations, the prebuild warning, the crash budget, the silent setup, the debug command, the <code>InstallMode</code> examples, and the error you get when a release job or a canary is in the way. What&rsquo;s still open is smaller: the dashboard showing the API on <code>:8080</code> while everything else says <code>:3000</code>, the SDK throwing on import on web and in Jest, and a few docs gaps.</p>

<h2 class="relative group">Going to production
    <div id="going-to-production" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#going-to-production" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Everything above ran against the evaluation stack. Production is the same app and the same scripts pointed at a real server, and this is the plan for maru.</p>
<!-- EDITOR NOTE: this section is the procedure. Replace with what actually happened (host, timings, anything that broke) after the real cutover. -->
<p>The supported way to run the server is the Docker Compose install: a Linux machine with ports 80 and 443 open, two domains (one for the API and dashboard, one for downloads), and a GitHub OAuth app for sign-in, which the server won&rsquo;t start without. The installer does the rest, including TLS:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">scripts/selfhost/install.sh <span class="se">\
</span></span></span><span class="line"><span class="cl">  --api-domain updates.example.com <span class="se">\
</span></span></span><span class="line"><span class="cl">  --storage-domain storage.updates.example.com <span class="se">\
</span></span></span><span class="line"><span class="cl">  --email you<span>@</span>example.com <span class="se">\
</span></span></span><span class="line"><span class="cl">  --github-oauth-client-id &lt;id&gt; --github-oauth-client-secret &lt;secret&gt;</span></span></code></pre></div></div>
<p>It writes a <code>.env.selfhost</code> with the database and storage secrets, which belongs in your password manager.</p>
<p>You don&rsquo;t have to use the bundled database and storage, though, and that&rsquo;s what makes it fit a stack like mine. maru&rsquo;s API already runs on Fly.io and its files live on Tigris, and Patch works on both. Underneath the Compose file, the server is one container running in <code>MODE=all</code> (API and release worker together) that needs a Postgres database, S3-compatible storage and a public HTTPS URL for the files. That&rsquo;s a Fly app built from the repository&rsquo;s Dockerfile (there&rsquo;s no published image yet, so <code>fly deploy</code> builds it), a Fly Postgres database, and a Tigris bucket:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nv">MODE</span><span class="o">=</span>all
</span></span><span class="line"><span class="cl"><span class="nv">DATABASE_URL</span><span class="o">=</span>postgresql://…            <span class="c1"># Fly Postgres</span>
</span></span><span class="line"><span class="cl"><span class="nv">STORAGE_ADAPTER</span><span class="o">=</span>s3
</span></span><span class="line"><span class="cl"><span class="nv">S3_ENDPOINT</span><span class="o">=</span>https://fly.storage.tigris.dev
</span></span><span class="line"><span class="cl"><span class="nv">S3_REGION</span><span class="o">=</span>auto
</span></span><span class="line"><span class="cl"><span class="nv">S3_BUCKET</span><span class="o">=</span>myapp-patch
</span></span><span class="line"><span class="cl"><span class="nv">S3_FORCE_PATH_STYLE</span><span class="o">=</span><span class="nb">true</span>
</span></span><span class="line"><span class="cl"><span class="nv">PUBLIC_BASE_URL</span><span class="o">=</span>https://myapp-patch.fly.storage.tigris.dev/codemagic-patch</span></span></code></pre></div></div>
<p>Two caveats. Running it outside Compose is documented in the repository as reference material, not a supported path in this first open-source release, so on Fly you&rsquo;re on your own for upgrades and backups. I haven&rsquo;t deployed it that way yet either; this is the plan, not a report. And if you&rsquo;ve read my post on <a href="https://jared.lynskey.co.nz/en/posts/2026/2026-09-09-scale-to-zero-504s/" >Fly&rsquo;s scale-to-zero</a>, keep at least one machine running. Phones never wait on the API for an update check, since manifests come straight from storage, but every metrics upload and every release job would otherwise start with a cold boot.</p>
<p>Tigris is the part I&rsquo;m most keen on. It&rsquo;s where maru&rsquo;s files already are, and it puts a CDN in front of the URL every app launch hits. Mind the manifest caching if you do this: with the plain base-URL delivery adapter Patch serves manifests as <code>no-cache</code>, because it can&rsquo;t purge a CDN, and a manifest cached on its own TTL would keep serving a release you&rsquo;ve just rolled back. The configuration reference now documents this under <code>MANIFEST_CACHE_CONTROL</code>, and the docs site covers S3-compatible storage.</p>
<p>On the hosted server you create the apps again, put the new keys in the <code>preview</code> and <code>production</code> profiles in <code>eas.json</code> (Staging keys and Production keys), and create a token for publishing:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">cmpatch token create --name ci</span></span></code></pre></div></div>
<p>If you want code signing, decide now: generate the production key pair, keep the private key as a CI secret, put the public key in the build profiles, and turn on &ldquo;require code signing&rdquo; for both apps. The first Patch binary also needs a new version number, because the binaries already in the stores run <code>expo-updates</code>. Build it with the preview profile for TestFlight and Play internal testing first, and check the keys actually made it into the built <code>Info.plist</code> and Android resources before handing it to anyone. That&rsquo;s the one link my local tests didn&rsquo;t exercise, since I exported the environment by hand. Then publish to Staging, confirm one download and one success per tester, and only then build for the stores.</p>
<p>Production releases start small and grow:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">./scripts/publish-update.sh ios --production --rollout <span class="m">10</span>
</span></span><span class="line"><span class="cl">cmpatch release patch --app maru-ios --deployment Production --label v1 --rollout-percentage <span class="m">100</span></span></span></code></pre></div></div>
<p>The old server stays up in the meantime. Every copy of 2.5.1 that people haven&rsquo;t updated still checks it, and hotfixes for them still go through the old script. Once the logs show those requests have stopped, the old server, its publish script and its secret can all go.</p>

<h2 class="relative group">The first native upgrade
    <div id="the-first-native-upgrade" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-first-native-upgrade" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p><em>Added 16 October 2026.</em></p>
<p>Patch has been carrying maru&rsquo;s production updates since early October. The first native release since then was the move to Expo SDK 58: React Native 0.88, and on Android a new major version of the Gradle plugin. A native change can&rsquo;t go over the air, so it&rsquo;s a new binary, 2.6.0, and my publish script refuses to send 2.6.0 updates until that binary exists. Both platforms built cleanly the first time.</p>
<p>The production section above says to check the keys really made it into the built <code>Info.plist</code> and Android resources before handing a build to anyone. This time I did, and that check is the reason this section exists. The iOS build had its four Patch settings. The Android build had none:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">bundletool dump resources --bundle<span class="o">=</span>build.aab --values <span class="p">|</span> grep -A1 <span class="s2">&#34;string/Codemagic&#34;</span></span></span></code></pre></div></div>
<p>That command printed four keys for the 2.5.11 build and nothing for 2.6.0. The environment wasn&rsquo;t the problem: Gradle&rsquo;s <code>generateReleaseResValues</code> writes all four. They&rsquo;re removed later by the release resource shrinker, which in Android Gradle Plugin 9 is much more aggressive. The same app went from 9,240 resources to 7,116. The SDK reads its configuration by name with <code>getIdentifier</code>, which the shrinker can&rsquo;t see, so it removed the four strings as unused. A missing string reads as empty, and empty means &ldquo;no updates&rdquo;. Nothing would have failed. Android 2.6.0 would have installed, run normally and never received an update, and the only sign would have been no Android 2.6.0 devices on the dashboard.</p>
<p>The fix is one resource file that tells the shrinker to keep the four strings:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="line"><span class="cl"><span class="c">&lt;!-- android/app/src/main/res/raw/codemagic_patch_keep.xml --&gt;</span>
</span></span><span class="line"><span class="cl"><span class="nt">&lt;resources</span> <span class="na">xmlns:tools=</span><span class="s">&#34;http://schemas.android.com/tools&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="na">tools:keep=</span><span class="s">&#34;@string/CodemagicPatch*&#34;</span> <span class="nt">/&gt;</span></span></span></code></pre></div></div>
<p>Don&rsquo;t call it <code>keep.xml</code>: React Native&rsquo;s bundle task already generates a <code>raw/keep.xml</code> for your JavaScript assets (which is why images and fonts survived), and the two would collide. The better place for this rule is the SDK itself, since a library&rsquo;s keep file is merged into the app automatically, and a warning when a release build starts with no deployment key would turn the silent case into a visible one. This is the same kind of failure as the iOS version-detection bug earlier: nothing errors, and the updates just never arrive.</p>
<p>The same check turned up a second problem that has nothing to do with Patch, and it&rsquo;s worth knowing for a different reason. The Android release build crashed on launch, twice, for two separate reasons inside Expo&rsquo;s own modules. First, Expo&rsquo;s widgets module failed to register its native classes, so the app died before any JavaScript ran. With that fixed, the app got as far as starting its JavaScript and then stopped, because three modules that had moved to Expo&rsquo;s new module system were never registered. Patch&rsquo;s crash rollback can&rsquo;t help with either, because there is no update to roll back. It protects you from a bad update, not from a bad binary. A native upgrade still has to be installed and opened on a real device or emulator before it goes to the store, Patch or no Patch.</p>
<p>One smaller thing came out of the same testing. When <code>sync()</code> fails, it returns <code>&quot;error&quot;</code> and keeps the reason to itself unless the app is running in development, so a release build can only log that something went wrong. My hook now calls <code>checkForUpdate()</code> once after a failed sync and logs what that throws, which is how I learned that a local simulator build had empty Patch URLs (<code>unsupported URL</code>) rather than a broken server. It would help if the last error were readable in release builds too.</p>
<p>My checklist for a native release now has three lines it didn&rsquo;t have before: dump the Patch settings from the built <code>.ipa</code> and <code>.aab</code>, compare the deployment keys with the build profile, and launch the release build itself, not a debug build, before submitting.</p>

<h2 class="relative group">What I&rsquo;d tell someone with an Expo bill
    <div id="what-id-tell-someone-with-an-expo-bill" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-id-tell-someone-with-an-expo-bill" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>If you&rsquo;re paying for EAS Update because building a server looked like too much work, Patch is a real answer: you run a server, but it&rsquo;s a Compose stack and an installer, not code you maintain. Compared with what I built, you get staged rollouts, per-release install and failure numbers, binary patches, a fingerprint guard, code signing, crash rollback on the device, and a rollback button. I had built none of those.</p>
<p>What it costs: a new binary before anyone gets a Patch update, since the SDK has to be in the app; a server to keep upgraded and backed up; three crashed launches per user by default when a release is bad enough; and some hand work if your native projects are committed. It&rsquo;s also young. This was version 0.3.0, and I hit a version-detection bug, a noisy debug command and a few gaps in the docs, and made a bug of my own that the SDK could have prevented. The version detection and the debug command have since been fixed, most of the docs gaps filled, and the SDK now guards against the mistake I made. None of it stopped the migration, and all of it was visible, in the CLI, in the dashboard, or in the SDK&rsquo;s own files on the device, which is more than I can say for my old setup.</p>
]]></content:encoded>
      <media:content url="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/featured.jpg" medium="image" type="image/jpeg" />
    </item>
    <item>
      <title>Zustand vs React Query (TanStack Query) vs AsyncStorage: What Goes Where</title>
      <link>https://jared.lynskey.co.nz/en/posts/2026/2026-05-05-zustand-vs-react-query/</link>
      <guid isPermaLink="true">https://jared.lynskey.co.nz/en/posts/2026/2026-05-05-zustand-vs-react-query/</guid>
      <pubDate>Tue, 05 May 2026 00:00:00 +0000</pubDate>
      <dc:creator>Jared Lynskey</dc:creator>
      <category>React</category>
      <category>React Native</category>
      <category>Zustand</category>
      <category>React Query</category>
      <category>TanStack Query</category>
      <category>AsyncStorage</category>
      <category>State Management</category>
      <category>Mobile Development</category>
      <category>Web Development</category>
      <description>Zustand vs React Query isn&#39;t either/or: React Query (TanStack Query) caches server state, Zustand holds client state, and AsyncStorage keeps what has to survive a restart. How I split state between them in React and React Native, how to use Zustand and React Query together, and how the three combine to make offline mode work.</description>
      <content:encoded><![CDATA[<p>Zustand and React Query don&rsquo;t compete, so the real answer to &ldquo;Zustand vs React Query&rdquo; is usually both. React Query, now published as TanStack Query, is for server state: data the server owns, which it fetches, caches, deduplicates and refetches when it goes stale. Zustand is for client state: things only your app knows, like which tab is open or what&rsquo;s in a half-finished form. Most apps use the two together, and in React Native, AsyncStorage is the third piece, for whatever has to survive a restart. The rest of this post is where I draw those lines, with code, and how the three add up to an app that works offline.</p>
<p>The estimating app I&rsquo;m building has one hard requirement: it has to keep working with no signal. Quotes get written up on site visits, and site visits happen in new builds and basements where reception is a rumour. That constraint forced me to get honest about a question most React projects fudge: which kind of state lives where?</p>
<p>The usual failure mode is one store for everything. API caching, user preferences, form state, auth tokens, all shoved into the same Redux blob. But those are different kinds of state with different lifecycles, and they want different tools. Zustand, React Query and AsyncStorage each solve exactly one of these problems well. Draw the boundaries between them and the architecture mostly sorts itself out.</p>

<h2 class="relative group">Three kinds of state
    <div id="three-kinds-of-state" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#three-kinds-of-state" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Before arguing about libraries, it helps to name what you&rsquo;re actually managing.</p>
<p>Client state exists only in your app&rsquo;s runtime: UI toggles, the selected tab, form inputs, whether a modal is open. Nothing upstream owns it, and it dies with the process.</p>
<p>Server state is different. The server owns it; your app just holds a local copy. User profiles, product listings, notifications, feed data. Your copy goes stale, needs refetching, and other clients may be looking at a different version of it right now.</p>
<p>Persistent state is whatever has to survive a restart: auth tokens, the onboarding-complete flag, cached preferences, offline data. It lives on the device itself.</p>
<p>Most apps have all three. Most messes come from handling all three with one tool.</p>

<h2 class="relative group">Zustand: client state
    <div id="zustand-client-state" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#zustand-client-state" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Zustand is a small state library for React with none of the ceremony. No providers, no boilerplate, no context wrappers stacked five deep. You create a store, you use it in components, and that&rsquo;s the whole lesson.</p>
<p>It&rsquo;s the right tool when several components need the same UI state (sidebar open or closed, active filters, selected items), when app-level state doesn&rsquo;t come from an API (theme, language, feature flags read at startup), or when there&rsquo;s real client-side logic to manage, like cart calculations or a multi-step wizard. Anything that should update synchronously and predictably.</p>
<p>A basic store:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">create</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;zustand&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">interface</span> <span class="nx">AppState</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nx">theme</span><span class="o">:</span> <span class="s1">&#39;light&#39;</span> <span class="o">|</span> <span class="s1">&#39;dark&#39;</span>
</span></span><span class="line"><span class="cl">  <span class="nx">sidebarOpen</span>: <span class="kt">boolean</span>
</span></span><span class="line"><span class="cl">  <span class="nx">selectedFilters</span>: <span class="kt">string</span><span class="p">[]</span>
</span></span><span class="line"><span class="cl">  <span class="nx">setTheme</span><span class="o">:</span> <span class="p">(</span><span class="nx">theme</span><span class="o">:</span> <span class="s1">&#39;light&#39;</span> <span class="o">|</span> <span class="s1">&#39;dark&#39;</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="k">void</span>
</span></span><span class="line"><span class="cl">  <span class="nx">toggleSidebar</span><span class="o">:</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="k">void</span>
</span></span><span class="line"><span class="cl">  <span class="nx">setFilters</span><span class="o">:</span> <span class="p">(</span><span class="nx">filters</span>: <span class="kt">string</span><span class="p">[])</span> <span class="o">=&gt;</span> <span class="k">void</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">useAppStore</span> <span class="o">=</span> <span class="nx">create</span><span class="p">&lt;</span><span class="nt">AppState</span><span class="p">&gt;((</span><span class="kr">set</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">({</span>
</span></span><span class="line"><span class="cl">  <span class="nx">theme</span><span class="o">:</span> <span class="s1">&#39;light&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">sidebarOpen</span>: <span class="kt">false</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">selectedFilters</span><span class="o">:</span> <span class="p">[],</span>
</span></span><span class="line"><span class="cl">  <span class="nx">setTheme</span><span class="o">:</span> <span class="p">(</span><span class="nx">theme</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="kr">set</span><span class="p">({</span> <span class="nx">theme</span> <span class="p">}),</span>
</span></span><span class="line"><span class="cl">  <span class="nx">toggleSidebar</span><span class="o">:</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="kr">set</span><span class="p">((</span><span class="nx">state</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">({</span> <span class="nx">sidebarOpen</span><span class="o">:</span> <span class="o">!</span><span class="nx">state</span><span class="p">.</span><span class="nx">sidebarOpen</span> <span class="p">})),</span>
</span></span><span class="line"><span class="cl">  <span class="nx">setFilters</span><span class="o">:</span> <span class="p">(</span><span class="nx">filters</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="kr">set</span><span class="p">({</span> <span class="nx">selectedFilters</span>: <span class="kt">filters</span> <span class="p">}),</span>
</span></span><span class="line"><span class="cl"><span class="p">}))</span></span></span></code></pre></div></div>
<p>And in a component:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-tsx" data-lang="tsx"><span class="line"><span class="cl"><span class="kd">function</span> <span class="nx">Sidebar() {</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="p">{</span> <span class="nx">sidebarOpen</span><span class="p">,</span> <span class="nx">toggleSidebar</span> <span class="p">}</span> <span class="o">=</span> <span class="nx">useAppStore</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">sidebarOpen</span><span class="p">)</span> <span class="k">return</span> <span class="kc">null</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="p">&lt;</span><span class="nt">div</span> <span class="na">className</span><span class="o">=</span><span class="s">&#34;sidebar&#34;</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="p">&lt;</span><span class="nt">button</span> <span class="na">onClick</span><span class="o">=</span><span class="p">{</span><span class="nx">toggleSidebar</span><span class="p">}&gt;</span><span class="nx">Close</span><span class="p">&lt;/</span><span class="nt">button</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="p">{</span><span class="cm">/* sidebar content */</span><span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">&lt;/</span><span class="nt">div</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>

<h3 class="relative group">What I don&rsquo;t put in Zustand
    <div id="what-i-dont-put-in-zustand" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-i-dont-put-in-zustand" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>API responses, mainly. I&rsquo;ve seen projects where every API call writes into a Zustand store and components read from the store instead of querying. You end up reimplementing cache invalidation, loading states, error handling, refetching and pagination by hand, which is exactly the work React Query exists to do for you.</p>
<p>The other thing is anything that must survive a restart. Zustand state lives in memory; when the app closes, it&rsquo;s gone. The persist middleware can bridge into AsyncStorage (more on that later), but that should be a deliberate decision rather than a habit.</p>

<h2 class="relative group">React Query: server state
    <div id="react-query-server-state" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#react-query-server-state" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>React Query (TanStack Query these days) manages the whole lifecycle of remote data: fetching, caching, synchronising, updating, garbage collecting. The mental shift is that it treats server data as a cache you keep fresh, not as state you own. The server owns it. You&rsquo;re holding a copy.</p>
<p>I use it for anything that comes from an API. That covers data multiple components need from the same endpoint (requests get deduplicated automatically), paginated and infinite-scroll lists, data that should refetch in the background when someone returns to the app, and optimistic updates where the UI changes immediately and rolls back if the server says no.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">useQuery</span><span class="p">,</span> <span class="nx">useMutation</span><span class="p">,</span> <span class="nx">useQueryClient</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;@tanstack/react-query&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">function</span> <span class="nx">useUser</span><span class="p">(</span><span class="nx">userId</span>: <span class="kt">string</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="nx">useQuery</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">    <span class="nx">queryKey</span><span class="o">:</span> <span class="p">[</span><span class="s1">&#39;user&#39;</span><span class="p">,</span> <span class="nx">userId</span><span class="p">],</span>
</span></span><span class="line"><span class="cl">    <span class="nx">queryFn</span><span class="o">:</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="nx">fetch</span><span class="p">(</span><span class="sb">`/api/users/</span><span class="si">${</span><span class="nx">userId</span><span class="si">}</span><span class="sb">`</span><span class="p">).</span><span class="nx">then</span><span class="p">(</span><span class="nx">res</span> <span class="o">=&gt;</span> <span class="nx">res</span><span class="p">.</span><span class="nx">json</span><span class="p">()),</span>
</span></span><span class="line"><span class="cl">    <span class="nx">staleTime</span>: <span class="kt">5</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">,</span> <span class="c1">// Consider fresh for 5 minutes
</span></span></span><span class="line"><span class="cl">  <span class="p">})</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">function</span> <span class="nx">useUpdateUser() {</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="nx">queryClient</span> <span class="o">=</span> <span class="nx">useQueryClient</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="nx">useMutation</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">    <span class="nx">mutationFn</span><span class="o">:</span> <span class="p">(</span><span class="nx">data</span><span class="o">:</span> <span class="p">{</span> <span class="nx">id</span>: <span class="kt">string</span><span class="p">;</span> <span class="nx">name</span>: <span class="kt">string</span> <span class="p">})</span> <span class="o">=&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="nx">fetch</span><span class="p">(</span><span class="sb">`/api/users/</span><span class="si">${</span><span class="nx">data</span><span class="p">.</span><span class="nx">id</span><span class="si">}</span><span class="sb">`</span><span class="p">,</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nx">method</span><span class="o">:</span> <span class="s1">&#39;PATCH&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="nx">body</span>: <span class="kt">JSON.stringify</span><span class="p">(</span><span class="nx">data</span><span class="p">),</span>
</span></span><span class="line"><span class="cl">      <span class="p">}),</span>
</span></span><span class="line"><span class="cl">    <span class="nx">onSuccess</span><span class="o">:</span> <span class="p">(</span><span class="nx">_</span><span class="p">,</span> <span class="nx">variables</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nx">queryClient</span><span class="p">.</span><span class="nx">invalidateQueries</span><span class="p">({</span> <span class="nx">queryKey</span><span class="o">:</span> <span class="p">[</span><span class="s1">&#39;user&#39;</span><span class="p">,</span> <span class="nx">variables</span><span class="p">.</span><span class="nx">id</span><span class="p">]</span> <span class="p">})</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">  <span class="p">})</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>In a component:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-tsx" data-lang="tsx"><span class="line"><span class="cl"><span class="kd">function</span> <span class="nx">UserProfile</span><span class="p">({</span> <span class="nx">userId</span> <span class="p">}</span><span class="o">:</span> <span class="p">{</span> <span class="nx">userId</span>: <span class="kt">string</span> <span class="p">})</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="p">{</span> <span class="nx">data</span>: <span class="kt">user</span><span class="p">,</span> <span class="nx">isLoading</span><span class="p">,</span> <span class="nx">error</span> <span class="p">}</span> <span class="o">=</span> <span class="nx">useUser</span><span class="p">(</span><span class="nx">userId</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="nx">updateUser</span> <span class="o">=</span> <span class="nx">useUpdateUser</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">if</span> <span class="p">(</span><span class="nx">isLoading</span><span class="p">)</span> <span class="k">return</span> <span class="p">&lt;</span><span class="nt">Spinner</span> <span class="p">/&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="k">if</span> <span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="k">return</span> <span class="p">&lt;</span><span class="nt">ErrorMessage</span> <span class="na">error</span><span class="o">=</span><span class="p">{</span><span class="nx">error</span><span class="p">}</span> <span class="p">/&gt;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="p">&lt;</span><span class="nt">div</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;{</span><span class="nx">user</span><span class="p">.</span><span class="nx">name</span><span class="p">}&lt;/</span><span class="nt">h1</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="p">&lt;</span><span class="nt">button</span>
</span></span><span class="line"><span class="cl">        <span class="na">onClick</span><span class="o">=</span><span class="p">{()</span> <span class="o">=&gt;</span> <span class="nx">updateUser</span><span class="p">.</span><span class="nx">mutate</span><span class="p">({</span> <span class="nx">id</span>: <span class="kt">userId</span><span class="p">,</span> <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;New Name&#39;</span> <span class="p">})}</span>
</span></span><span class="line"><span class="cl">        <span class="na">disabled</span><span class="o">=</span><span class="p">{</span><span class="nx">updateUser</span><span class="p">.</span><span class="nx">isPending</span><span class="p">}</span>
</span></span><span class="line"><span class="cl">      <span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">        <span class="nx">Update</span> <span class="nx">Name</span>
</span></span><span class="line"><span class="cl">      <span class="p">&lt;/</span><span class="nt">button</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="p">&lt;/</span><span class="nt">div</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>

<h3 class="relative group">What you get without writing it
    <div id="what-you-get-without-writing-it" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-you-get-without-writing-it" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>The reason I&rsquo;m firm about putting server data here is the sheer amount of machinery that comes free. Five components requesting the same user produces one network request. Data refetches when the window regains focus or the network reconnects. Old cache entries get garbage collected on their own. Every query hands you <code>isLoading</code>, <code>isError</code>, <code>data</code> and friends, so loading and error UI stops being bespoke work. Failed requests retry with exponential backoff. And optimistic updates with rollback are a built-in pattern rather than an afternoon of custom plumbing.</p>

<h3 class="relative group">What it&rsquo;s not for
    <div id="what-its-not-for" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-its-not-for" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Client-only state. If the data never touches a server, React Query just adds ceremony; a modal&rsquo;s open state doesn&rsquo;t need cache invalidation or a refetch interval.</p>
<p>It&rsquo;s also not a persistence layer. The cache lives in memory, so a restart means an empty cache and a round of refetching. You can persist the cache (and on React Native you should, see the offline section below), but the source of truth is always the server.</p>

<h2 class="relative group">AsyncStorage: what survives a restart
    <div id="asyncstorage-what-survives-a-restart" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#asyncstorage-what-survives-a-restart" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>AsyncStorage is React Native&rsquo;s key-value storage. On the web the equivalent is <code>localStorage</code> (synchronous) or <code>IndexedDB</code> (async, more capable). Same idea either way: data that outlives the process because it&rsquo;s written to the device.</p>

<h3 class="relative group">What it actually is on each platform
    <div id="what-it-actually-is-on-each-platform" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-it-actually-is-on-each-platform" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>One API, three quite different backends, assuming you&rsquo;re using <code>@react-native-async-storage/async-storage</code>.</p>
<p>On Android it&rsquo;s SQLite under the hood, via <code>RKStorage</code>, in a database inside the app&rsquo;s internal storage directory. Fast, reliable, and sandboxed so other apps can&rsquo;t touch it. Mind the default size cap in the table below.</p>
<p>On iOS it&rsquo;s <code>NSUserDefaults</code> for small values and serialised files for larger ones, again sandboxed inside the app container. Apple doesn&rsquo;t set a hard limit on <code>NSUserDefaults</code>, but the sensible convention is to keep individual values under a few hundred KB. If your values are bigger than that, you probably want a proper database like WatermelonDB or Realm anyway.</p>
<p>On web (React Native Web or Expo Web) it falls back to <code>localStorage</code>, which caps out around 5-10 MB depending on the browser. Web-only React apps can use <code>localStorage</code> directly, or <code>IndexedDB</code> through a wrapper like <code>idb-keyval</code> for larger datasets.</p>
<table>
	<thead>
			<tr>
					<th>Platform</th>
					<th>Backend</th>
					<th>Size Limit</th>
					<th>Location</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Android</td>
					<td>SQLite (RKStorage)</td>
					<td>~6 MB default (configurable)</td>
					<td>App internal storage</td>
			</tr>
			<tr>
					<td>iOS</td>
					<td>NSUserDefaults / files</td>
					<td>No hard limit (keep values small)</td>
					<td>App sandbox container</td>
			</tr>
			<tr>
					<td>Web</td>
					<td>localStorage</td>
					<td>~5-10 MB (browser-dependent)</td>
					<td>Browser origin storage</td>
			</tr>
	</tbody>
</table>

<h3 class="relative group">What I keep in it
    <div id="what-i-keep-in-it" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-i-keep-in-it" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Auth tokens and session data, preferences that should stick around (language, theme, notification settings), the onboarding-completed flag, cached data for offline use. Small key-value things that need to survive a restart; that&rsquo;s the whole category.</p>
<p>The API is about as plain as storage gets:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="nx">AsyncStorage</span> <span class="kr">from</span> <span class="s1">&#39;@react-native-async-storage/async-storage&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Store a value
</span></span></span><span class="line"><span class="cl"><span class="k">await</span> <span class="nx">AsyncStorage</span><span class="p">.</span><span class="nx">setItem</span><span class="p">(</span><span class="s1">&#39;auth_token&#39;</span><span class="p">,</span> <span class="nx">token</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Read a value
</span></span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">token</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">AsyncStorage</span><span class="p">.</span><span class="nx">getItem</span><span class="p">(</span><span class="s1">&#39;auth_token&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Store an object (must serialize)
</span></span></span><span class="line"><span class="cl"><span class="k">await</span> <span class="nx">AsyncStorage</span><span class="p">.</span><span class="nx">setItem</span><span class="p">(</span><span class="s1">&#39;user_preferences&#39;</span><span class="p">,</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">  <span class="nx">theme</span><span class="o">:</span> <span class="s1">&#39;dark&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">language</span><span class="o">:</span> <span class="s1">&#39;en&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">notifications</span>: <span class="kt">true</span><span class="p">,</span>
</span></span><span class="line"><span class="cl"><span class="p">}))</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Read an object
</span></span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">prefs</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="k">await</span> <span class="nx">AsyncStorage</span><span class="p">.</span><span class="nx">getItem</span><span class="p">(</span><span class="s1">&#39;user_preferences&#39;</span><span class="p">)</span> <span class="o">??</span> <span class="s1">&#39;{}&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Remove a value
</span></span></span><span class="line"><span class="cl"><span class="k">await</span> <span class="nx">AsyncStorage</span><span class="p">.</span><span class="nx">removeItem</span><span class="p">(</span><span class="s1">&#39;auth_token&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Clear everything (careful with this)
</span></span></span><span class="line"><span class="cl"><span class="k">await</span> <span class="nx">AsyncStorage</span><span class="p">.</span><span class="nx">clear</span><span class="p">()</span></span></span></code></pre></div></div>

<h3 class="relative group">The web versions
    <div id="the-web-versions" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-web-versions" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Web-only React apps don&rsquo;t need AsyncStorage at all. <code>localStorage</code> covers the simple cases:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="c1">// Synchronous  - blocks the main thread, but fine for small data
</span></span></span><span class="line"><span class="cl"><span class="nx">localStorage</span><span class="p">.</span><span class="nx">setItem</span><span class="p">(</span><span class="s1">&#39;theme&#39;</span><span class="p">,</span> <span class="s1">&#39;dark&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">theme</span> <span class="o">=</span> <span class="nx">localStorage</span><span class="p">.</span><span class="nx">getItem</span><span class="p">(</span><span class="s1">&#39;theme&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// For structured data
</span></span></span><span class="line"><span class="cl"><span class="nx">localStorage</span><span class="p">.</span><span class="nx">setItem</span><span class="p">(</span><span class="s1">&#39;user&#39;</span><span class="p">,</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">({</span> <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;Jared&#39;</span><span class="p">,</span> <span class="nx">role</span><span class="o">:</span> <span class="s1">&#39;admin&#39;</span> <span class="p">}))</span>
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">user</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">localStorage</span><span class="p">.</span><span class="nx">getItem</span><span class="p">(</span><span class="s1">&#39;user&#39;</span><span class="p">)</span> <span class="o">??</span> <span class="s1">&#39;{}&#39;</span><span class="p">)</span></span></span></code></pre></div></div>
<p>And <code>IndexedDB</code> covers the bigger ones:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="kr">get</span><span class="p">,</span> <span class="kr">set</span><span class="p">,</span> <span class="nx">del</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;idb-keyval&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">await</span> <span class="kr">set</span><span class="p">(</span><span class="s1">&#39;large-dataset&#39;</span><span class="p">,</span> <span class="nx">hugeArray</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">data</span> <span class="o">=</span> <span class="k">await</span> <span class="kr">get</span><span class="p">(</span><span class="s1">&#39;large-dataset&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">await</span> <span class="nx">del</span><span class="p">(</span><span class="s1">&#39;large-dataset&#39;</span><span class="p">)</span></span></span></code></pre></div></div>

<h3 class="relative group">What it&rsquo;s not for
    <div id="what-its-not-for-1" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-its-not-for-1" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>It&rsquo;s a key-value store, not a database. Relational data, arrays with thousands of items, anything that needs indexing or querying: that&rsquo;s SQLite (via <code>expo-sqlite</code>), WatermelonDB or Realm territory.</p>
<p>It&rsquo;s also not secure storage. On a rooted or jailbroken device, AsyncStorage contents are readable. Sensitive tokens belong in <code>expo-secure-store</code> or <code>react-native-keychain</code> instead.</p>

<h2 class="relative group">How the three fit together
    <div id="how-the-three-fit-together" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#how-the-three-fit-together" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Real apps use all three at once. A few patterns I lean on constantly.</p>

<h3 class="relative group">The auth flow
    <div id="the-auth-flow" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-auth-flow" aria-label="Anchor">#</a>
    </span>
    
</h3>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="c1">// 1. AsyncStorage: persist the auth token
</span></span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="nx">AsyncStorage</span> <span class="kr">from</span> <span class="s1">&#39;@react-native-async-storage/async-storage&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">async</span> <span class="kd">function</span> <span class="nx">saveToken</span><span class="p">(</span><span class="nx">token</span>: <span class="kt">string</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">await</span> <span class="nx">AsyncStorage</span><span class="p">.</span><span class="nx">setItem</span><span class="p">(</span><span class="s1">&#39;auth_token&#39;</span><span class="p">,</span> <span class="nx">token</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">async</span> <span class="kd">function</span> <span class="nx">getToken</span><span class="p">()</span><span class="o">:</span> <span class="nx">Promise</span><span class="p">&lt;</span><span class="nt">string</span> <span class="err">|</span> <span class="na">null</span><span class="p">&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="nx">AsyncStorage</span><span class="p">.</span><span class="nx">getItem</span><span class="p">(</span><span class="s1">&#39;auth_token&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// 2. Zustand: track auth state in memory
</span></span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">create</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;zustand&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">interface</span> <span class="nx">AuthState</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nx">isAuthenticated</span>: <span class="kt">boolean</span>
</span></span><span class="line"><span class="cl">  <span class="nx">token</span>: <span class="kt">string</span> <span class="o">|</span> <span class="kc">null</span>
</span></span><span class="line"><span class="cl">  <span class="nx">setAuth</span><span class="o">:</span> <span class="p">(</span><span class="nx">token</span>: <span class="kt">string</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="k">void</span>
</span></span><span class="line"><span class="cl">  <span class="nx">clearAuth</span><span class="o">:</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="k">void</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">useAuthStore</span> <span class="o">=</span> <span class="nx">create</span><span class="p">&lt;</span><span class="nt">AuthState</span><span class="p">&gt;((</span><span class="kr">set</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">({</span>
</span></span><span class="line"><span class="cl">  <span class="nx">isAuthenticated</span>: <span class="kt">false</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">token</span>: <span class="kt">null</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">setAuth</span><span class="o">:</span> <span class="p">(</span><span class="nx">token</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="kr">set</span><span class="p">({</span> <span class="nx">isAuthenticated</span>: <span class="kt">true</span><span class="p">,</span> <span class="nx">token</span> <span class="p">}),</span>
</span></span><span class="line"><span class="cl">  <span class="nx">clearAuth</span><span class="o">:</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="kr">set</span><span class="p">({</span> <span class="nx">isAuthenticated</span>: <span class="kt">false</span><span class="p">,</span> <span class="nx">token</span>: <span class="kt">null</span> <span class="p">}),</span>
</span></span><span class="line"><span class="cl"><span class="p">}))</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// 3. React Query: fetch user profile using the token
</span></span></span><span class="line"><span class="cl"><span class="kd">function</span> <span class="nx">useCurrentUser() {</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="nx">token</span> <span class="o">=</span> <span class="nx">useAuthStore</span><span class="p">((</span><span class="nx">s</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="nx">s</span><span class="p">.</span><span class="nx">token</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="nx">useQuery</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">    <span class="nx">queryKey</span><span class="o">:</span> <span class="p">[</span><span class="s1">&#39;currentUser&#39;</span><span class="p">],</span>
</span></span><span class="line"><span class="cl">    <span class="nx">queryFn</span><span class="o">:</span> <span class="p">()</span> <span class="o">=&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="nx">fetch</span><span class="p">(</span><span class="s1">&#39;/api/me&#39;</span><span class="p">,</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nx">headers</span><span class="o">:</span> <span class="p">{</span> <span class="nx">Authorization</span><span class="o">:</span> <span class="sb">`Bearer </span><span class="si">${</span><span class="nx">token</span><span class="si">}</span><span class="sb">`</span> <span class="p">},</span>
</span></span><span class="line"><span class="cl">      <span class="p">}).</span><span class="nx">then</span><span class="p">(</span><span class="nx">res</span> <span class="o">=&gt;</span> <span class="nx">res</span><span class="p">.</span><span class="nx">json</span><span class="p">()),</span>
</span></span><span class="line"><span class="cl">    <span class="nx">enabled</span><span class="o">:</span> <span class="o">!!</span><span class="nx">token</span><span class="p">,</span> <span class="c1">// Only fetch when we have a token
</span></span></span><span class="line"><span class="cl">  <span class="p">})</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>And on startup:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="c1">// App initialization
</span></span></span><span class="line"><span class="cl"><span class="kr">async</span> <span class="kd">function</span> <span class="nx">initializeApp() {</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="nx">token</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">getToken</span><span class="p">()</span> <span class="c1">// Read from AsyncStorage
</span></span></span><span class="line"><span class="cl">  <span class="k">if</span> <span class="p">(</span><span class="nx">token</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nx">useAuthStore</span><span class="p">.</span><span class="nx">getState</span><span class="p">().</span><span class="nx">setAuth</span><span class="p">(</span><span class="nx">token</span><span class="p">)</span> <span class="c1">// Put in Zustand for quick access
</span></span></span><span class="line"><span class="cl">    <span class="c1">// React Query will automatically fetch the user profile
</span></span></span><span class="line"><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>AsyncStorage keeps the token across restarts, Zustand makes it cheap to read from anywhere, and React Query fetches the profile the moment a token exists. Each tool does the one thing it&rsquo;s good at.</p>

<h3 class="relative group">A theme that survives restarts
    <div id="a-theme-that-survives-restarts" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#a-theme-that-survives-restarts" aria-label="Anchor">#</a>
    </span>
    
</h3>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">create</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;zustand&#39;</span>
</span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">persist</span><span class="p">,</span> <span class="nx">createJSONStorage</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;zustand/middleware&#39;</span>
</span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="nx">AsyncStorage</span> <span class="kr">from</span> <span class="s1">&#39;@react-native-async-storage/async-storage&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Zustand with persistence middleware bridges the gap
</span></span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">useThemeStore</span> <span class="o">=</span> <span class="nx">create</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">  <span class="nx">persist</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="p">(</span><span class="kr">set</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">({</span>
</span></span><span class="line"><span class="cl">      <span class="nx">theme</span><span class="o">:</span> <span class="s1">&#39;light&#39;</span> <span class="kr">as</span> <span class="s1">&#39;light&#39;</span> <span class="o">|</span> <span class="s1">&#39;dark&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nx">toggleTheme</span><span class="o">:</span> <span class="p">()</span> <span class="o">=&gt;</span>
</span></span><span class="line"><span class="cl">        <span class="kr">set</span><span class="p">((</span><span class="nx">state</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">({</span>
</span></span><span class="line"><span class="cl">          <span class="nx">theme</span>: <span class="kt">state.theme</span> <span class="o">===</span> <span class="s1">&#39;light&#39;</span> <span class="o">?</span> <span class="s1">&#39;dark&#39;</span> <span class="o">:</span> <span class="s1">&#39;light&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">})),</span>
</span></span><span class="line"><span class="cl">    <span class="p">}),</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;theme-storage&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nx">storage</span>: <span class="kt">createJSONStorage</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="nx">AsyncStorage</span><span class="p">),</span> <span class="c1">// React Native
</span></span></span><span class="line"><span class="cl">      <span class="c1">// storage: createJSONStorage(() =&gt; localStorage), // Web
</span></span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span></span></span></code></pre></div></div>
<p>Zustand manages the runtime state and the persist middleware syncs it to AsyncStorage (or localStorage on web) behind the scenes. Your components neither know nor care that a persistence layer exists.</p>

<h3 class="relative group">Offline-first reads
    <div id="offline-first-reads" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#offline-first-reads" aria-label="Anchor">#</a>
    </span>
    
</h3>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">useQuery</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;@tanstack/react-query&#39;</span>
</span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="nx">AsyncStorage</span> <span class="kr">from</span> <span class="s1">&#39;@react-native-async-storage/async-storage&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">function</span> <span class="nx">useProducts() {</span>
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="nx">useQuery</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">    <span class="nx">queryKey</span><span class="o">:</span> <span class="p">[</span><span class="s1">&#39;products&#39;</span><span class="p">],</span>
</span></span><span class="line"><span class="cl">    <span class="nx">queryFn</span>: <span class="kt">async</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="kr">const</span> <span class="nx">res</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">fetch</span><span class="p">(</span><span class="s1">&#39;/api/products&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="kr">const</span> <span class="nx">data</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">res</span><span class="p">.</span><span class="nx">json</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="c1">// Cache in AsyncStorage for offline use
</span></span></span><span class="line"><span class="cl">        <span class="k">await</span> <span class="nx">AsyncStorage</span><span class="p">.</span><span class="nx">setItem</span><span class="p">(</span><span class="s1">&#39;cached_products&#39;</span><span class="p">,</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">data</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="nx">data</span>
</span></span><span class="line"><span class="cl">      <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="c1">// Network failed  - try cached data
</span></span></span><span class="line"><span class="cl">        <span class="kr">const</span> <span class="nx">cached</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">AsyncStorage</span><span class="p">.</span><span class="nx">getItem</span><span class="p">(</span><span class="s1">&#39;cached_products&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="nx">cached</span><span class="p">)</span> <span class="k">return</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">cached</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="k">throw</span> <span class="nx">error</span>
</span></span><span class="line"><span class="cl">      <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="nx">staleTime</span>: <span class="kt">10</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="p">})</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>React Query does the fetching and in-memory caching; AsyncStorage is the fallback when the network isn&rsquo;t there.</p>

<h2 class="relative group">Offline mode, step by step
    <div id="offline-mode-step-by-step" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#offline-mode-step-by-step" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>This is the part I actually care about. The general wisdom is that people open apps on the subway, in lifts, on planes, and that&rsquo;s true. In my case the requirement is blunter: quotes get written up on site, and I can&rsquo;t assume the site has reception. A spinner in a basement is a lost quote.</p>
<p>The nice surprise is that these three libraries get you a genuinely solid offline setup without reaching for a heavy framework.</p>

<h3 class="relative group">Step 1: know when you&rsquo;re offline
    <div id="step-1-know-when-youre-offline" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#step-1-know-when-youre-offline" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>The device needs to tell the app about the network, and the app needs somewhere to keep that answer. <code>@react-native-community/netinfo</code> provides the events; a tiny Zustand store makes the state readable everywhere.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">create</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;zustand&#39;</span>
</span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="nx">NetInfo</span> <span class="kr">from</span> <span class="s1">&#39;@react-native-community/netinfo&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">interface</span> <span class="nx">NetworkState</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nx">isOnline</span>: <span class="kt">boolean</span>
</span></span><span class="line"><span class="cl">  <span class="nx">setOnline</span><span class="o">:</span> <span class="p">(</span><span class="nx">online</span>: <span class="kt">boolean</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="k">void</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">useNetworkStore</span> <span class="o">=</span> <span class="nx">create</span><span class="p">&lt;</span><span class="nt">NetworkState</span><span class="p">&gt;((</span><span class="kr">set</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">({</span>
</span></span><span class="line"><span class="cl">  <span class="nx">isOnline</span>: <span class="kt">true</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">setOnline</span><span class="o">:</span> <span class="p">(</span><span class="nx">online</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="kr">set</span><span class="p">({</span> <span class="nx">isOnline</span>: <span class="kt">online</span> <span class="p">}),</span>
</span></span><span class="line"><span class="cl"><span class="p">}))</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Subscribe once at app startup
</span></span></span><span class="line"><span class="cl"><span class="nx">NetInfo</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">((</span><span class="nx">state</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nx">useNetworkStore</span><span class="p">.</span><span class="nx">getState</span><span class="p">().</span><span class="nx">setOnline</span><span class="p">(</span><span class="nx">state</span><span class="p">.</span><span class="nx">isConnected</span> <span class="o">??</span> <span class="kc">false</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">})</span></span></span></code></pre></div></div>
<p>Now any component can check <code>useNetworkStore((s) =&gt; s.isOnline)</code> to show an offline banner, disable a submit button, or explain that changes will sync later.</p>

<h3 class="relative group">Step 2: tell React Query about offline
    <div id="step-2-tell-react-query-about-offline" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#step-2-tell-react-query-about-offline" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>React Query has offline behaviour built in through <code>networkMode</code>, which controls what queries and mutations do when the network is out.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">QueryClient</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;@tanstack/react-query&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">queryClient</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">QueryClient</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">  <span class="nx">defaultOptions</span><span class="o">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nx">queries</span><span class="o">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nx">networkMode</span><span class="o">:</span> <span class="s1">&#39;offlineFirst&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="c1">// Return cached data immediately, then refetch in background when online
</span></span></span><span class="line"><span class="cl">      <span class="nx">staleTime</span>: <span class="kt">5</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nx">gcTime</span>: <span class="kt">24</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">,</span> <span class="c1">// Keep cache for 24 hours
</span></span></span><span class="line"><span class="cl">      <span class="nx">retry</span><span class="o">:</span> <span class="p">(</span><span class="nx">failureCount</span><span class="p">,</span> <span class="nx">error</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="c1">// Don&#39;t retry if we&#39;re offline  - it&#39;ll just fail again
</span></span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">useNetworkStore</span><span class="p">.</span><span class="nx">getState</span><span class="p">().</span><span class="nx">isOnline</span><span class="p">)</span> <span class="k">return</span> <span class="kc">false</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="nx">failureCount</span> <span class="o">&lt;</span> <span class="mi">3</span>
</span></span><span class="line"><span class="cl">      <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="nx">mutations</span><span class="o">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nx">networkMode</span><span class="o">:</span> <span class="s1">&#39;offlineFirst&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">  <span class="p">},</span>
</span></span><span class="line"><span class="cl"><span class="p">})</span></span></span></code></pre></div></div>
<p>The three modes:</p>
<table>
	<thead>
			<tr>
					<th>Mode</th>
					<th>Behaviour</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><code>online</code> (default)</td>
					<td>Queries only fire when online. Pauses when offline.</td>
			</tr>
			<tr>
					<td><code>always</code></td>
					<td>Queries fire regardless of network. Your <code>queryFn</code> handles failures.</td>
			</tr>
			<tr>
					<td><code>offlineFirst</code></td>
					<td>Queries fire once (for cached data), then pause until online to refetch.</td>
			</tr>
	</tbody>
</table>
<p>For most mobile apps <code>offlineFirst</code> is the one you want: cached data appears immediately, and fresh data arrives when the network allows.</p>

<h3 class="relative group">Step 3: persist the query cache
    <div id="step-3-persist-the-query-cache" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#step-3-persist-the-query-cache" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Out of the box the cache is memory-only, so a restart means spinners everywhere. For offline mode you persist it to AsyncStorage:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">QueryClient</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;@tanstack/react-query&#39;</span>
</span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">PersistQueryClientProvider</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;@tanstack/react-query-persist-client&#39;</span>
</span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">createAsyncStoragePersister</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;@tanstack/query-async-storage-persister&#39;</span>
</span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="nx">AsyncStorage</span> <span class="kr">from</span> <span class="s1">&#39;@react-native-async-storage/async-storage&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">queryClient</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">QueryClient</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">  <span class="nx">defaultOptions</span><span class="o">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nx">queries</span><span class="o">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nx">gcTime</span>: <span class="kt">24</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">,</span> <span class="c1">// 24 hours  - must be &gt;= maxAge
</span></span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">  <span class="p">},</span>
</span></span><span class="line"><span class="cl"><span class="p">})</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">asyncStoragePersister</span> <span class="o">=</span> <span class="nx">createAsyncStoragePersister</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">  <span class="nx">storage</span>: <span class="kt">AsyncStorage</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">key</span><span class="o">:</span> <span class="s1">&#39;react-query-cache&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl"><span class="p">})</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// In your App component
</span></span></span><span class="line"><span class="cl"><span class="kd">function</span> <span class="nx">App() {</span>
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="p">&lt;</span><span class="nt">PersistQueryClientProvider</span>
</span></span><span class="line"><span class="cl">      <span class="na">client</span><span class="o">=</span><span class="p">{</span><span class="nx">queryClient</span><span class="p">}</span>
</span></span><span class="line"><span class="cl">      <span class="na">persistOptions</span><span class="o">=</span><span class="p">{{</span>
</span></span><span class="line"><span class="cl">        <span class="nx">persister</span>: <span class="kt">asyncStoragePersister</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="nx">maxAge</span>: <span class="kt">24</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">*</span> <span class="mi">60</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">,</span> <span class="c1">// Don&#39;t restore data older than 24 hours
</span></span></span><span class="line"><span class="cl">        <span class="nx">dehydrateOptions</span><span class="o">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">          <span class="nx">shouldDehydrateQuery</span><span class="o">:</span> <span class="p">(</span><span class="nx">query</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="c1">// Only persist successful queries
</span></span></span><span class="line"><span class="cl">            <span class="k">return</span> <span class="nx">query</span><span class="p">.</span><span class="nx">state</span><span class="p">.</span><span class="nx">status</span> <span class="o">===</span> <span class="s1">&#39;success&#39;</span>
</span></span><span class="line"><span class="cl">          <span class="p">},</span>
</span></span><span class="line"><span class="cl">        <span class="p">},</span>
</span></span><span class="line"><span class="cl">      <span class="p">}}</span>
</span></span><span class="line"><span class="cl">    <span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="p">&lt;</span><span class="nt">YourApp</span> <span class="p">/&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="p">&lt;/</span><span class="nt">PersistQueryClientProvider</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>Now someone opening the app in a dead zone sees the last-fetched data straight away instead of a blank screen, and React Query quietly refetches once the network returns.</p>

<h3 class="relative group">Step 4: queue writes while offline
    <div id="step-4-queue-writes-while-offline" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#step-4-queue-writes-while-offline" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Reads are the easy half. Writes are where offline gets interesting: someone adds a comment, submits an order or edits their profile with no network, and that change has to be queued and replayed later.</p>
<p>React Query&rsquo;s answer is <code>useMutation</code> with an optimistic update in <code>onMutate</code>:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">useMutation</span><span class="p">,</span> <span class="nx">useQueryClient</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;@tanstack/react-query&#39;</span>
</span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="nx">AsyncStorage</span> <span class="kr">from</span> <span class="s1">&#39;@react-native-async-storage/async-storage&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">interface</span> <span class="nx">Comment</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nx">id</span>: <span class="kt">string</span>
</span></span><span class="line"><span class="cl">  <span class="nx">text</span>: <span class="kt">string</span>
</span></span><span class="line"><span class="cl">  <span class="nx">postId</span>: <span class="kt">string</span>
</span></span><span class="line"><span class="cl">  <span class="nx">createdAt</span>: <span class="kt">string</span>
</span></span><span class="line"><span class="cl">  <span class="nx">pending?</span>: <span class="kt">boolean</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">function</span> <span class="nx">useAddComment</span><span class="p">(</span><span class="nx">postId</span>: <span class="kt">string</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="nx">queryClient</span> <span class="o">=</span> <span class="nx">useQueryClient</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="nx">useMutation</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">    <span class="nx">mutationFn</span>: <span class="kt">async</span> <span class="p">(</span><span class="nx">text</span>: <span class="kt">string</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="kr">const</span> <span class="nx">res</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">fetch</span><span class="p">(</span><span class="sb">`/api/posts/</span><span class="si">${</span><span class="nx">postId</span><span class="si">}</span><span class="sb">/comments`</span><span class="p">,</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nx">method</span><span class="o">:</span> <span class="s1">&#39;POST&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="nx">headers</span><span class="o">:</span> <span class="p">{</span> <span class="s1">&#39;Content-Type&#39;</span><span class="o">:</span> <span class="s1">&#39;application/json&#39;</span> <span class="p">},</span>
</span></span><span class="line"><span class="cl">        <span class="nx">body</span>: <span class="kt">JSON.stringify</span><span class="p">({</span> <span class="nx">text</span> <span class="p">}),</span>
</span></span><span class="line"><span class="cl">      <span class="p">})</span>
</span></span><span class="line"><span class="cl">      <span class="k">return</span> <span class="nx">res</span><span class="p">.</span><span class="nx">json</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1">// Optimistic update  - show the comment immediately
</span></span></span><span class="line"><span class="cl">    <span class="nx">onMutate</span>: <span class="kt">async</span> <span class="p">(</span><span class="nx">text</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">await</span> <span class="nx">queryClient</span><span class="p">.</span><span class="nx">cancelQueries</span><span class="p">({</span> <span class="nx">queryKey</span><span class="o">:</span> <span class="p">[</span><span class="s1">&#39;comments&#39;</span><span class="p">,</span> <span class="nx">postId</span><span class="p">]</span> <span class="p">})</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="kr">const</span> <span class="nx">previous</span> <span class="o">=</span> <span class="nx">queryClient</span><span class="p">.</span><span class="nx">getQueryData</span><span class="p">&lt;</span><span class="nt">Comment</span><span class="err">[]</span><span class="p">&gt;([</span><span class="s1">&#39;comments&#39;</span><span class="p">,</span> <span class="nx">postId</span><span class="p">])</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="kr">const</span> <span class="nx">optimisticComment</span>: <span class="kt">Comment</span> <span class="o">=</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nx">id</span><span class="o">:</span> <span class="sb">`temp-</span><span class="si">${</span><span class="nb">Date</span><span class="p">.</span><span class="nx">now</span><span class="p">()</span><span class="si">}</span><span class="sb">`</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="nx">text</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="nx">postId</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="nx">createdAt</span>: <span class="kt">new</span> <span class="nb">Date</span><span class="p">().</span><span class="nx">toISOString</span><span class="p">(),</span>
</span></span><span class="line"><span class="cl">        <span class="nx">pending</span>: <span class="kt">true</span><span class="p">,</span> <span class="c1">// Show a &#34;sending...&#34; indicator in the UI
</span></span></span><span class="line"><span class="cl">      <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="nx">queryClient</span><span class="p">.</span><span class="nx">setQueryData</span><span class="p">&lt;</span><span class="nt">Comment</span><span class="err">[]</span><span class="p">&gt;(</span>
</span></span><span class="line"><span class="cl">        <span class="p">[</span><span class="s1">&#39;comments&#39;</span><span class="p">,</span> <span class="nx">postId</span><span class="p">],</span>
</span></span><span class="line"><span class="cl">        <span class="p">(</span><span class="nx">old</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">[...(</span><span class="nx">old</span> <span class="o">??</span> <span class="p">[]),</span> <span class="nx">optimisticComment</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">      <span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="k">return</span> <span class="p">{</span> <span class="nx">previous</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1">// Roll back on failure
</span></span></span><span class="line"><span class="cl">    <span class="nx">onError</span><span class="o">:</span> <span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">text</span><span class="p">,</span> <span class="nx">context</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">if</span> <span class="p">(</span><span class="nx">context</span><span class="o">?</span><span class="p">.</span><span class="nx">previous</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="nx">queryClient</span><span class="p">.</span><span class="nx">setQueryData</span><span class="p">([</span><span class="s1">&#39;comments&#39;</span><span class="p">,</span> <span class="nx">postId</span><span class="p">],</span> <span class="nx">context</span><span class="p">.</span><span class="nx">previous</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">      <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1">// Refetch to get the real data from the server
</span></span></span><span class="line"><span class="cl">    <span class="nx">onSettled</span><span class="o">:</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nx">queryClient</span><span class="p">.</span><span class="nx">invalidateQueries</span><span class="p">({</span> <span class="nx">queryKey</span><span class="o">:</span> <span class="p">[</span><span class="s1">&#39;comments&#39;</span><span class="p">,</span> <span class="nx">postId</span><span class="p">]</span> <span class="p">})</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl">  <span class="p">})</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>With <code>networkMode: 'offlineFirst'</code> on mutations, the <code>mutationFn</code> pauses until the network is back. The optimistic update puts the comment on screen immediately, and the real API call fires on reconnect.</p>
<p>If you need a more serious queue, say dozens of pending changes that have to replay in order, you can persist the mutation queue as well:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">MutationCache</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;@tanstack/react-query&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Save pending mutations to AsyncStorage
</span></span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">mutationCache</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">MutationCache</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">  <span class="nx">onError</span>: <span class="kt">async</span> <span class="p">(</span><span class="nx">error</span><span class="p">,</span> <span class="nx">variables</span><span class="p">,</span> <span class="nx">context</span><span class="p">,</span> <span class="nx">mutation</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// Log failed mutations for debugging
</span></span></span><span class="line"><span class="cl">    <span class="kr">const</span> <span class="nx">pending</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">      <span class="k">await</span> <span class="nx">AsyncStorage</span><span class="p">.</span><span class="nx">getItem</span><span class="p">(</span><span class="s1">&#39;pending_mutations&#39;</span><span class="p">)</span> <span class="o">??</span> <span class="s1">&#39;[]&#39;</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nx">pending</span><span class="p">.</span><span class="nx">push</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">      <span class="nx">key</span>: <span class="kt">mutation.options.mutationKey</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nx">variables</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">      <span class="nx">timestamp</span>: <span class="kt">Date.now</span><span class="p">(),</span>
</span></span><span class="line"><span class="cl">    <span class="p">})</span>
</span></span><span class="line"><span class="cl">    <span class="k">await</span> <span class="nx">AsyncStorage</span><span class="p">.</span><span class="nx">setItem</span><span class="p">(</span><span class="s1">&#39;pending_mutations&#39;</span><span class="p">,</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">pending</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">  <span class="p">},</span>
</span></span><span class="line"><span class="cl"><span class="p">})</span></span></span></code></pre></div></div>

<h3 class="relative group">Step 5: reconcile when the network returns
    <div id="step-5-reconcile-when-the-network-returns" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#step-5-reconcile-when-the-network-returns" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>React Query does most of the reconnection work itself: paused mutations resume, stale queries refetch. You just have to wire its managers up to React Native&rsquo;s events.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="nx">NetInfo</span> <span class="kr">from</span> <span class="s1">&#39;@react-native-community/netinfo&#39;</span>
</span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">onlineManager</span><span class="p">,</span> <span class="nx">focusManager</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;@tanstack/react-query&#39;</span>
</span></span><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">AppState</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;react-native&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Tell React Query about network state changes
</span></span></span><span class="line"><span class="cl"><span class="nx">onlineManager</span><span class="p">.</span><span class="nx">setEventListener</span><span class="p">((</span><span class="nx">setOnline</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="nx">NetInfo</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">((</span><span class="nx">state</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nx">setOnline</span><span class="p">(</span><span class="o">!!</span><span class="nx">state</span><span class="p">.</span><span class="nx">isConnected</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">  <span class="p">})</span>
</span></span><span class="line"><span class="cl"><span class="p">})</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Refetch when the app comes back to foreground
</span></span></span><span class="line"><span class="cl"><span class="nx">focusManager</span><span class="p">.</span><span class="nx">setEventListener</span><span class="p">((</span><span class="nx">setFocused</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="nx">subscription</span> <span class="o">=</span> <span class="nx">AppState</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;change&#39;</span><span class="p">,</span> <span class="p">(</span><span class="nx">status</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nx">setFocused</span><span class="p">(</span><span class="nx">status</span> <span class="o">===</span> <span class="s1">&#39;active&#39;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">  <span class="p">})</span>
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="nx">subscription</span><span class="p">.</span><span class="nx">remove</span><span class="p">()</span>
</span></span><span class="line"><span class="cl"><span class="p">})</span></span></span></code></pre></div></div>
<p>When someone backgrounds the app for an hour and comes back, <code>focusManager</code> triggers refetches so they see fresh data. When they walk out of a tunnel and regain signal, <code>onlineManager</code> resumes whatever was paused.</p>

<h3 class="relative group">Step 6: say so in the UI
    <div id="step-6-say-so-in-the-ui" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#step-6-say-so-in-the-ui" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Whatever else you do, don&rsquo;t swallow network errors silently. Tell people they&rsquo;re offline and show which changes are still pending.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-tsx" data-lang="tsx"><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">useNetworkStore</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;./stores/network&#39;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">function</span> <span class="nx">OfflineBanner() {</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="nx">isOnline</span> <span class="o">=</span> <span class="nx">useNetworkStore</span><span class="p">((</span><span class="nx">s</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="nx">s</span><span class="p">.</span><span class="nx">isOnline</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">if</span> <span class="p">(</span><span class="nx">isOnline</span><span class="p">)</span> <span class="k">return</span> <span class="kc">null</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="p">&lt;</span><span class="nt">View</span> <span class="na">style</span><span class="o">=</span><span class="p">{</span><span class="nx">styles</span><span class="p">.</span><span class="nx">banner</span><span class="p">}&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="p">&lt;</span><span class="nt">Text</span><span class="p">&gt;</span><span class="nx">You</span><span class="err">&#39;</span><span class="nx">re</span> <span class="nx">offline</span><span class="p">.</span> <span class="nx">Changes</span> <span class="nx">will</span> <span class="nx">sync</span> <span class="nx">when</span> <span class="nx">you</span> <span class="nx">reconnect</span><span class="p">.&lt;/</span><span class="nt">Text</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="p">&lt;/</span><span class="nt">View</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">function</span> <span class="nx">CommentItem</span><span class="p">({</span> <span class="nx">comment</span> <span class="p">}</span><span class="o">:</span> <span class="p">{</span> <span class="nx">comment</span>: <span class="kt">Comment</span> <span class="p">})</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="p">&lt;</span><span class="nt">View</span> <span class="na">style</span><span class="o">=</span><span class="p">{[</span><span class="nx">styles</span><span class="p">.</span><span class="nx">comment</span><span class="p">,</span> <span class="nx">comment</span><span class="p">.</span><span class="nx">pending</span> <span class="o">&amp;&amp;</span> <span class="nx">styles</span><span class="p">.</span><span class="nx">pending</span><span class="p">]}&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="p">&lt;</span><span class="nt">Text</span><span class="p">&gt;{</span><span class="nx">comment</span><span class="p">.</span><span class="nx">text</span><span class="p">}&lt;/</span><span class="nt">Text</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="p">{</span><span class="nx">comment</span><span class="p">.</span><span class="nx">pending</span> <span class="o">&amp;&amp;</span> <span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="p">&lt;</span><span class="nt">Text</span> <span class="na">style</span><span class="o">=</span><span class="p">{</span><span class="nx">styles</span><span class="p">.</span><span class="nx">pendingLabel</span><span class="p">}&gt;</span><span class="nx">Sending</span><span class="p">...&lt;/</span><span class="nt">Text</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">      <span class="p">)}</span>
</span></span><span class="line"><span class="cl">    <span class="p">&lt;/</span><span class="nt">View</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>

<h3 class="relative group">The whole picture
    <div id="the-whole-picture" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-whole-picture" aria-label="Anchor">#</a>
    </span>
    
</h3>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">┌─────────────────────────────────────────────────┐
</span></span><span class="line"><span class="cl">│                   Components                     │
</span></span><span class="line"><span class="cl">│  useQuery() for reads    useMutation() for writes│
</span></span><span class="line"><span class="cl">└──────────┬──────────────────────┬────────────────┘
</span></span><span class="line"><span class="cl">           │                      │
</span></span><span class="line"><span class="cl">     ┌─────▼──────┐        ┌─────▼──────┐
</span></span><span class="line"><span class="cl">     │ React Query │        │ React Query │
</span></span><span class="line"><span class="cl">     │   Cache     │        │  Mutation   │
</span></span><span class="line"><span class="cl">     │ (in-memory) │        │   Queue     │
</span></span><span class="line"><span class="cl">     └─────┬──────┘        └─────┬──────┘
</span></span><span class="line"><span class="cl">           │                      │
</span></span><span class="line"><span class="cl">     ┌─────▼──────────────────────▼──────┐
</span></span><span class="line"><span class="cl">     │     AsyncStorage Persister         │
</span></span><span class="line"><span class="cl">     │  (survives app restart)            │
</span></span><span class="line"><span class="cl">     └─────┬──────────────────────┬──────┘
</span></span><span class="line"><span class="cl">           │                      │
</span></span><span class="line"><span class="cl">     ┌─────▼──────┐        ┌─────▼──────┐
</span></span><span class="line"><span class="cl">     │   Zustand   │        │   Network  │
</span></span><span class="line"><span class="cl">     │ (isOnline,  │◄───────│   NetInfo  │
</span></span><span class="line"><span class="cl">     │  UI state)  │        │            │
</span></span><span class="line"><span class="cl">     └────────────┘        └────────────┘</span></span></code></pre></div></div>
<table>
	<thead>
			<tr>
					<th>Layer</th>
					<th>Tool</th>
					<th>Role</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Network detection</td>
					<td>Zustand + NetInfo</td>
					<td>Track online/offline, drive UI banners</td>
			</tr>
			<tr>
					<td>Data fetching</td>
					<td>React Query</td>
					<td>Fetch when online, serve cache when offline</td>
			</tr>
			<tr>
					<td>Cache persistence</td>
					<td>React Query + AsyncStorage</td>
					<td>Restore cache on app restart</td>
			</tr>
			<tr>
					<td>Offline writes</td>
					<td>React Query mutations</td>
					<td>Queue mutations, replay on reconnect</td>
			</tr>
			<tr>
					<td>Optimistic UI</td>
					<td>React Query <code>onMutate</code></td>
					<td>Show changes immediately, roll back on failure</td>
			</tr>
			<tr>
					<td>App focus sync</td>
					<td>React Query <code>focusManager</code></td>
					<td>Refetch stale data when app returns to foreground</td>
			</tr>
	</tbody>
</table>

<h3 class="relative group">When you need a real sync engine
    <div id="when-you-need-a-real-sync-engine" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#when-you-need-a-real-sync-engine" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>All of the above assumes the server is the source of truth and offline is temporary. If you need true offline-first with conflict resolution (think a notes app where two devices edit the same document offline), this stack won&rsquo;t cut it and you want a proper sync engine. WatermelonDB is built for React Native, runs on SQLite and ships a sync protocol for resolving conflicts. Realm with Atlas Device Sync is a full offline-first database with automatic conflict resolution through MongoDB Atlas. PowerSync is a SQLite-based sync layer that works with your existing Postgres backend. And if you need total control, Expo SQLite plus your own sync logic is always an option.</p>
<p>Zustand + React Query + AsyncStorage covers about 80% of mobile apps. The other 20%, the collaborative editors and multi-device offline-heavy workflows, need a dedicated sync database.</p>

<h2 class="relative group">Deciding where a piece of state goes
    <div id="deciding-where-a-piece-of-state-goes" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#deciding-where-a-piece-of-state-goes" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>When I&rsquo;m not sure where something belongs, I run it through these questions:</p>
<table>
	<thead>
			<tr>
					<th>Question</th>
					<th>Yes → Use</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Does it come from a server/API?</td>
					<td>React Query</td>
			</tr>
			<tr>
					<td>Is it client-only UI state shared across components?</td>
					<td>Zustand</td>
			</tr>
			<tr>
					<td>Does it need to survive an app restart?</td>
					<td>AsyncStorage (+ optionally Zustand persist)</td>
			</tr>
			<tr>
					<td>Is it sensitive (tokens, passwords)?</td>
					<td>expo-secure-store / react-native-keychain</td>
			</tr>
			<tr>
					<td>Is it large structured data that needs querying?</td>
					<td>SQLite / WatermelonDB / Realm</td>
			</tr>
			<tr>
					<td>Is it a simple form input used by one component?</td>
					<td>useState</td>
			</tr>
	</tbody>
</table>

<h3 class="relative group">Common cases
    <div id="common-cases" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#common-cases" aria-label="Anchor">#</a>
    </span>
    
</h3>
<table>
	<thead>
			<tr>
					<th>State</th>
					<th>Tool</th>
					<th>Why</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>API response data</td>
					<td>React Query</td>
					<td>Caching, dedup, refetch, loading states</td>
			</tr>
			<tr>
					<td>Selected tab / active filter</td>
					<td>Zustand</td>
					<td>Client-only, multiple components care</td>
			</tr>
			<tr>
					<td>Auth token</td>
					<td>AsyncStorage + Zustand</td>
					<td>Persists across restarts, fast in-memory access</td>
			</tr>
			<tr>
					<td>Theme preference</td>
					<td>Zustand with persist middleware</td>
					<td>Client state that should survive restarts</td>
			</tr>
			<tr>
					<td>Shopping cart</td>
					<td>Zustand with persist middleware</td>
					<td>Complex client logic, should survive restarts</td>
			</tr>
			<tr>
					<td>Form input</td>
					<td>useState</td>
					<td>Single component, no need to share</td>
			</tr>
			<tr>
					<td>User profile from API</td>
					<td>React Query</td>
					<td>Server state, might be stale</td>
			</tr>
			<tr>
					<td>Onboarding completed flag</td>
					<td>AsyncStorage</td>
					<td>Just a boolean that persists</td>
			</tr>
			<tr>
					<td>Offline cached feed</td>
					<td>React Query + AsyncStorage</td>
					<td>Fetch from server, fall back to cache</td>
			</tr>
	</tbody>
</table>

<h2 class="relative group">Setup by platform
    <div id="setup-by-platform" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#setup-by-platform" aria-label="Anchor">#</a>
    </span>
    
</h2>

<h3 class="relative group">React Native (Android + iOS)
    <div id="react-native-android--ios" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#react-native-android--ios" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>All three at once:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">npm install zustand @tanstack/react-query @react-native-async-storage/async-storage</span></span></code></pre></div></div>
<p>Plus secure storage for anything sensitive:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">npx expo install expo-secure-store
</span></span><span class="line"><span class="cl"><span class="c1"># or</span>
</span></span><span class="line"><span class="cl">npm install react-native-keychain</span></span></code></pre></div></div>

<h3 class="relative group">Expo
    <div id="expo" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#expo" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>AsyncStorage works out of the box with Expo, no native linking required.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">npx expo install @react-native-async-storage/async-storage</span></span></code></pre></div></div>

<h3 class="relative group">Web-only React
    <div id="web-only-react" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#web-only-react" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Skip AsyncStorage entirely and use <code>localStorage</code> or <code>IndexedDB</code> directly.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">npm install zustand @tanstack/react-query
</span></span><span class="line"><span class="cl"><span class="c1"># Optional for IndexedDB</span>
</span></span><span class="line"><span class="cl">npm install idb-keyval</span></span></code></pre></div></div>
<p>Zustand&rsquo;s persist middleware already defaults to <code>localStorage</code> on web:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="nx">persist</span><span class="p">(</span><span class="nx">storeConfig</span><span class="p">,</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;my-store&#39;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="c1">// localStorage is the default on web  - no extra config needed
</span></span></span><span class="line"><span class="cl"><span class="p">})</span></span></span></code></pre></div></div>

<h2 class="relative group">Mistakes I keep seeing
    <div id="mistakes-i-keep-seeing" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#mistakes-i-keep-seeing" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Putting API data in Zustand. If there&rsquo;s a <code>setUsers(apiResponse.users)</code> in one of your actions, stop. That&rsquo;s React Query&rsquo;s job, and you&rsquo;re one sprint away from reinventing cache invalidation badly.</p>
<p>Using React Query for client state. If the <code>queryFn</code> doesn&rsquo;t make a network request, wrong tool.</p>
<p>Treating AsyncStorage like a database. Serialising an array of 10,000 items into a key-value store ends in tears. Use SQLite or a real database.</p>
<p>Leaving tokens unencrypted. AsyncStorage is not secure storage. Auth tokens, API keys and credentials go in <code>expo-secure-store</code> or the platform keychain.</p>
<p>Hand-rolling persistence. If you&rsquo;re reading AsyncStorage on mount and writing on every state change, Zustand&rsquo;s persist middleware already does that, plus hydration and serialisation, with less code and fewer bugs.</p>
<hr>
<p>Server data goes through React Query. Client state lives in Zustand. Anything that must survive a restart goes to AsyncStorage, and anything sensitive goes to secure storage.</p>
<p>The worst architectures I&rsquo;ve worked on all had one giant store that everything flowed through. The best ones had clear lines between server state, client state and what needs to persist. Draw those lines early and everything after gets easier.</p>
]]></content:encoded>
      <media:content url="https://jared.lynskey.co.nz/en/posts/2026/2026-05-05-zustand-vs-react-query/featured.jpg" medium="image" type="image/jpeg" />
    </item>
    <item>
      <title>How to Debug an iOS App in Xcode: Breakpoints, LLDB, Instruments and the Simulator</title>
      <link>https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/</link>
      <guid isPermaLink="true">https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/</guid>
      <pubDate>Thu, 26 Feb 2026 00:00:00 +0000</pubDate>
      <dc:creator>Jared Lynskey</dc:creator>
      <category>iOS</category>
      <category>Xcode</category>
      <category>Debugging</category>
      <category>Swift</category>
      <category>iOS Simulator</category>
      <category>Mobile Development</category>
      <description>How to debug an iOS app in Xcode: conditional and symbolic breakpoints, the LLDB commands worth knowing, the view and memory debuggers, Instruments, the sanitizers, crash logs, and what the simulator misses that a real iPhone catches.</description>
      <content:encoded><![CDATA[<p>To debug an iOS app in Xcode, add an exception breakpoint so a crash stops on the line that threw, reproduce the bug, and inspect state in the LLDB console with <code>po</code>. Then match the tool to the symptom: the view debugger for layout problems, the memory graph and Instruments for leaks and slowness, and the Address and Thread Sanitizers for crashes that only happen sometimes. Finish on a real iPhone, because the simulator hides a whole class of bugs.</p>
<p>I spend way too much time debugging. Everyone does. These days most of mine happens in Xcode and the simulator, chasing bugs in my own app, and the thing that keeps striking me is how much debugging machinery Xcode ships with that hardly anyone touches. This is the workflow I&rsquo;ve settled into over the years, the parts that actually save time when something breaks.</p>
<figure><div class="film-pair">
  <div class="mc-film film-dark">
  <video
    class="my-0 rounded-md"
    controls playsinline preload="none"
    poster="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film-poster.jpg" style="background:url('data:image/webp;base64,UklGRnYAAABXRUJQVlA4IGoAAACwBACdASogABIAPw10q0omI6GYDAQAYxDE9IABUYPdK9J7LAix1DOefbDeaFAAAP7ouyyQ8gmq2n0OJFwS2ozDV21keVe7mp4YMAaMcC2c0TvhxpeeVUutiNnRDQ7cGAAF5HvCUh6TAAAA') center/cover no-repeat"
    width="1280"
    height="720"
    aria-label="A short narrated film of this post">
    <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film.webm" type="video/webm">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film_en.vtt" srclang="en" label="English">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film_ja.vtt" srclang="ja" label="日本語">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film_ko.vtt" srclang="ko" label="한국어">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film_vi.vtt" srclang="vi" label="Tiếng Việt">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film_zh-cn.vtt" srclang="zh-cn" label="简体中文">
  </video>
  </div>
  <div class="mc-film film-light">
  <video
    class="my-0 rounded-md"
    controls playsinline preload="none"
    poster="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film-light-poster.jpg" style="background:url('data:image/webp;base64,UklGRpAAAABXRUJQVlA4IIQAAAAQBQCdASogABIAPw1yq0omI6GYDAQAYxDE9IAHPf226S4YClYzU9XAx5Z9snqv0mMAAP7zbrWGjWitB9IDF4k4ejBh2+lk/1wDWp0UmPbOye0BWqKsZ+tOCwLAfdMUc6whhMbqZ7T4TZFYHYuacvt5/h28z91+Bsx0AAIOdoDWMB6QAAA=') center/cover no-repeat"
    width="1280"
    height="720"
    aria-label="A short narrated film of this post">
    <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film-light.webm" type="video/webm">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film_en.vtt" srclang="en" label="English">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film_ja.vtt" srclang="ja" label="日本語">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film_ko.vtt" srclang="ko" label="한국어">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film_vi.vtt" srclang="vi" label="Tiếng Việt">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/ios-debugging-film_zh-cn.vtt" srclang="zh-cn" label="简体中文">
  </video>
  </div>
  <script>window.mcFilm && window.mcFilm()</script></div><figcaption>This post as a ten-minute film, if you&rsquo;d rather watch than read.</figcaption>
</figure>


<h2 class="relative group">Breakpoints Are More Powerful Than You Think
    <div id="breakpoints-are-more-powerful-than-you-think" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#breakpoints-are-more-powerful-than-you-think" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Most people click the gutter to set a breakpoint and leave it at that. Right-click one, though, and there&rsquo;s a whole menu of options that changes how you debug.</p>

<h3 class="relative group">Conditional Breakpoints
    <div id="conditional-breakpoints" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#conditional-breakpoints" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Say you&rsquo;ve got a loop processing 1000 items and only item 347 misbehaves. Hitting the breakpoint 346 times first is a waste of an afternoon.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-swift" data-lang="swift"><span class="line"><span class="cl"><span class="k">for</span> <span class="n">i</span> <span class="k">in</span> <span class="mf">0.</span><span class="p">.&lt;</span><span class="n">users</span><span class="p">.</span><span class="bp">count</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">processUser</span><span class="p">(</span><span class="n">users</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>  <span class="c1">// Set breakpoint here with condition: i == 347</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>Right-click the breakpoint, add the condition <code>i == 347</code>, and Xcode only stops when it&rsquo;s true. Works just as well with things like <code>userId == &quot;abc123&quot;</code> or <code>error != nil</code>.</p>

<h3 class="relative group">Symbolic Breakpoints
    <div id="symbolic-breakpoints" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#symbolic-breakpoints" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>These are for when you don&rsquo;t know where a method is being called from. Open the breakpoint navigator (Cmd+8), click the + button, and choose &ldquo;Symbolic Breakpoint&rdquo;.</p>
<p>Want to see every time any view controller loads? Set the symbol to <code>viewDidLoad</code> and Xcode pauses on every single one. Too noisy? Narrow it down: <code>MyViewController.viewDidLoad</code>.</p>
<p>The ones I keep around permanently:</p>
<ul>
<li><code>UIViewAlertForUnsatisfiableConstraints</code> catches Auto Layout conflicts the moment they happen</li>
<li><code>objc_exception_throw</code> breaks on any Objective-C exception before the crash</li>
<li><code>malloc_error_break</code> finds memory allocation problems</li>
</ul>

<h3 class="relative group">Exception Breakpoints
    <div id="exception-breakpoints" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#exception-breakpoints" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>This should be the first thing you set up in any new project. Add one (breakpoint navigator, + → Exception Breakpoint) and Xcode pauses the moment something throws, instead of after the app has already died.</p>
<p>It&rsquo;s caught more nil-unwrapping bugs for me than I&rsquo;d like to admit, the kind that otherwise just show up as mysterious crashes in the console.</p>

<h3 class="relative group">Breakpoint Actions
    <div id="breakpoint-actions" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#breakpoint-actions" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Breakpoints don&rsquo;t have to stop execution at all. Edit one, click &ldquo;Add Action&rdquo;, and it can:</p>
<ul>
<li>Print variables without stopping: <code>&quot;User count: @(users.count)@&quot;</code></li>
<li>Run LLDB commands automatically</li>
<li>Execute shell scripts</li>
<li>Play a sound (I use this for rare code paths I want to know about)</li>
</ul>
<p>Tick &ldquo;Automatically continue after evaluating actions&rdquo; and the breakpoint becomes a logger that never interrupts you.</p>

<h2 class="relative group">LLDB: The Console Commands You&rsquo;ll Actually Use
    <div id="lldb-the-console-commands-youll-actually-use" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#lldb-the-console-commands-youll-actually-use" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>When you hit a breakpoint, the console at the bottom isn&rsquo;t just for reading crash logs. It&rsquo;s LLDB, and it&rsquo;s genuinely useful.</p>

<h3 class="relative group">The Basics
    <div id="the-basics" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-basics" aria-label="Anchor">#</a>
    </span>
    
</h3>
<div class="highlight-wrapper"><pre tabindex="0"><code class="language-lldb" data-lang="lldb">(lldb) po user
▿ User
  - id: &#34;123&#34;
  - name: &#34;John Doe&#34;
  - email: &#34;john<span>@</span>example.com&#34;</code></pre></div>
<p><code>po</code> prints objects in a readable format. That&rsquo;s 90% of my LLDB usage right there.</p>
<p>Need more detail? Try <code>p</code> instead:</p>
<div class="highlight-wrapper"><pre tabindex="0"><code class="language-lldb" data-lang="lldb">(lldb) p user.name
(String) $R0 = &#34;John Doe&#34;</code></pre></div>
<p>And to see every local variable at once:</p>
<div class="highlight-wrapper"><pre tabindex="0"><code class="language-lldb" data-lang="lldb">(lldb) frame variable</code></pre></div>

<h3 class="relative group">Changing Things at Runtime
    <div id="changing-things-at-runtime" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#changing-things-at-runtime" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>This is where LLDB earns its keep: you can modify variables without recompiling.</p>
<div class="highlight-wrapper"><pre tabindex="0"><code class="language-lldb" data-lang="lldb">(lldb) expr user.name = &#34;Jane Doe&#34;
(lldb) expr index = 0</code></pre></div>
<p>Found a bug and want to try a fix without rebuilding? Change the variable and continue. I use this constantly when narrowing down edge cases.</p>
<p>You can call methods too:</p>
<div class="highlight-wrapper"><pre tabindex="0"><code class="language-lldb" data-lang="lldb">(lldb) po self.refreshUI()
(lldb) expr navigationController?.popViewController(animated: true)</code></pre></div>

<h3 class="relative group">Navigation
    <div id="navigation" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#navigation" aria-label="Anchor">#</a>
    </span>
    
</h3>
<div class="highlight-wrapper"><pre tabindex="0"><code class="language-lldb" data-lang="lldb">(lldb) bt              # Show the call stack
(lldb) frame select 3  # Jump to a different stack frame
(lldb) continue        # Keep running (or just &#39;c&#39;)
(lldb) n               # Step over (next line)
(lldb) s               # Step into function</code></pre></div>

<h3 class="relative group">Watchpoints
    <div id="watchpoints" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#watchpoints" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Want to know when a variable changes? Set a watchpoint:</p>
<div class="highlight-wrapper"><pre tabindex="0"><code class="language-lldb" data-lang="lldb">(lldb) watchpoint set variable user.isLoggedIn</code></pre></div>
<p>Execution now pauses whenever that value changes, no matter where in your code it happens. Gold for tracking down unexpected state mutations.</p>

<h2 class="relative group">Console.app: The Hidden Debugging Tool
    <div id="consoleapp-the-hidden-debugging-tool" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#consoleapp-the-hidden-debugging-tool" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Xcode&rsquo;s console is fine until you need to see everything: system logs, crash reports, the lot. That&rsquo;s when I open Console.app.</p>
<p>If you&rsquo;re using OSLog (you should be), Console.app makes those logs searchable and filterable:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-swift" data-lang="swift"><span class="line"><span class="cl"><span class="kd">import</span> <span class="nc">os</span><span class="p">.</span><span class="nc">log</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">let</span> <span class="nv">logger</span> <span class="p">=</span> <span class="n">Logger</span><span class="p">(</span><span class="n">subsystem</span><span class="p">:</span> <span class="s">&#34;com.example.app&#34;</span><span class="p">,</span> <span class="n">category</span><span class="p">:</span> <span class="s">&#34;networking&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">logger</span><span class="p">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#34;Starting API request&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">logger</span><span class="p">.</span><span class="n">debug</span><span class="p">(</span><span class="s">&#34;Request URL: </span><span class="si">\(</span><span class="n">url</span><span class="p">.</span><span class="n">absoluteString</span><span class="si">)</span><span class="s">&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">logger</span><span class="p">.</span><span class="n">error</span><span class="p">(</span><span class="s">&#34;Failed to decode: </span><span class="si">\(</span><span class="n">error</span><span class="p">.</span><span class="n">localizedDescription</span><span class="si">)</span><span class="s">&#34;</span><span class="p">)</span></span></span></code></pre></div></div>
<p>Then in Console.app:</p>
<ol>
<li>Select your simulator or connected device</li>
<li>Filter by your subsystem: <code>subsystem:com.example.app</code></li>
<li>Filter by level: <code>subsystem:com.example.app AND level:error</code></li>
</ol>
<p>You can save filter predicates for the sessions you run often. I&rsquo;ve got one for network requests, one for database operations, and one that shows nothing but errors and warnings.</p>

<h3 class="relative group">Why OSLog Over print()?
    <div id="why-oslog-over-print" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#why-oslog-over-print" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>OSLog beats scattering <code>print()</code> statements everywhere. It&rsquo;s structured, so you can filter by level and category. It&rsquo;s fast enough that logging won&rsquo;t slow the app down. It redacts sensitive data in production automatically, and the logs survive your app crashing.</p>
<p><code>print()</code> is still fine for quick throwaway checks. Anything you might want to look at later belongs in OSLog.</p>

<h3 class="relative group">Advanced Console.app Filtering
    <div id="advanced-consoleapp-filtering" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#advanced-consoleapp-filtering" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Console.app supports proper predicate queries. The ones I use regularly:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl"># All errors and faults in your app
</span></span><span class="line"><span class="cl">subsystem:com.example.app AND (level:error OR level:fault)
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"># Network requests that failed
</span></span><span class="line"><span class="cl">subsystem:com.example.app AND category:networking AND eventMessage CONTAINS &#34;failed&#34;
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"># Everything from the last 5 minutes
</span></span><span class="line"><span class="cl">subsystem:com.example.app AND timestamp &gt;= now(-5m)</span></span></code></pre></div></div>
<p>You can also export logs to attach to bug reports, which beats copy-pasting out of Xcode&rsquo;s console.</p>

<h2 class="relative group">View Debugging
    <div id="view-debugging" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#view-debugging" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>When the UI is broken and you can&rsquo;t see why, the view debugger is the fastest way out.</p>
<p>Run the app, navigate to the broken screen, and click the &ldquo;Debug View Hierarchy&rdquo; button in Xcode&rsquo;s debug bar (or press Cmd+Shift+D). You get a 3D exploded view of the whole hierarchy.</p>
<p>Rotate it around and things jump out:</p>
<ul>
<li>Views rendering behind other views</li>
<li>Views sitting way off-screen</li>
<li>Views with zero size</li>
<li>The full constraint chain for whatever you select</li>
</ul>
<p>I&rsquo;ve used it to find invisible buttons swallowing tap events, labels rendering at 0x0, and an image that was accidentally 10,000 pixels wide.</p>

<h3 class="relative group">Auto Layout Debugging
    <div id="auto-layout-debugging" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#auto-layout-debugging" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Purple warning icons in the view hierarchy mean constraint conflicts. Click one and Xcode shows exactly which constraints are fighting.</p>
<p>Give your constraints identifiers:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-swift" data-lang="swift"><span class="line"><span class="cl"><span class="n">heightConstraint</span><span class="p">.</span><span class="n">identifier</span> <span class="p">=</span> <span class="s">&#34;ProfileImageHeight&#34;</span></span></span></code></pre></div></div>
<p>When a constraint breaks, you&rsquo;ll see <code>&quot;ProfileImageHeight&quot;</code> in the error instead of a memory address, which makes the log actually readable.</p>
<p>From LLDB you can also print the constraint tree:</p>
<div class="highlight-wrapper"><pre tabindex="0"><code class="language-lldb" data-lang="lldb">(lldb) po view.hasAmbiguousLayout
(lldb) po view._autolayoutTrace()</code></pre></div>

<h2 class="relative group">Simulator Features That Save Time
    <div id="simulator-features-that-save-time" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#simulator-features-that-save-time" aria-label="Anchor">#</a>
    </span>
    
</h2>

<h3 class="relative group">Slow Animations
    <div id="slow-animations" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#slow-animations" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Debug → Slow Animations runs everything at 1/10 speed. Perfect for seeing what&rsquo;s actually happening during a transition, or why an animation looks off.</p>

<h3 class="relative group">Simulate Memory Warnings
    <div id="simulate-memory-warnings" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#simulate-memory-warnings" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Debug → Simulate Memory Warning tests how your app copes with low memory. I&rsquo;ve found plenty of image caching bugs this way: everything works fine until the warning fires and suddenly all your images vanish.</p>

<h3 class="relative group">Network Link Conditioner
    <div id="network-link-conditioner" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#network-link-conditioner" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Xcode → Open Developer Tools → Network Link Conditioner</p>
<p>Simulate 3G, LTE, high packet loss, or complete offline mode. If an API request has ever worked fine on WiFi and timed out on cellular, this is how you reproduce it.</p>
<p>I keep a &ldquo;Bad Network&rdquo; profile with 500ms latency and 10% packet loss. It surfaces timeout bugs and loading-state problems you&rsquo;d never see on fast office WiFi.</p>

<h3 class="relative group">Status Bar Overrides
    <div id="status-bar-overrides" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#status-bar-overrides" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Right-click the status bar in the simulator and you can override the time, battery level, signal strength, and carrier. Handy for consistent screenshots, or for checking how the UI looks at different battery levels.</p>

<h3 class="relative group">Location Simulation
    <div id="location-simulation" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#location-simulation" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Debug → Location simulates different locations without leaving your desk: custom coordinates, city walks, freeway drives. Very useful for location-based features, or bugs that only show up in certain regions.</p>

<h2 class="relative group">Memory Debugging
    <div id="memory-debugging" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#memory-debugging" aria-label="Anchor">#</a>
    </span>
    
</h2>

<h3 class="relative group">Debug Memory Graph
    <div id="debug-memory-graph" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#debug-memory-graph" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Click the Debug Memory Graph button (Cmd+Shift+M) and Xcode shows every object in memory, their relationships, and the part you actually care about: which ones are leaking.</p>
<p>Purple exclamation marks mean leaks. Click one and you can see the retain cycle.</p>
<p>The most common leak I see:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-swift" data-lang="swift"><span class="line"><span class="cl"><span class="kd">class</span> <span class="nc">ViewController</span><span class="p">:</span> <span class="n">UIViewController</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="kd">var</span> <span class="nv">onComplete</span><span class="p">:</span> <span class="p">(()</span> <span class="p">-&gt;</span> <span class="nb">Void</span><span class="p">)?</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="kd">func</span> <span class="nf">setupHandler</span><span class="p">()</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">onComplete</span> <span class="p">=</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="kc">self</span><span class="p">.</span><span class="n">dismiss</span><span class="p">(</span><span class="n">animated</span><span class="p">:</span> <span class="kc">true</span><span class="p">)</span>  <span class="c1">// ❌ Captures self strongly</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>Fix it with weak self:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-swift" data-lang="swift"><span class="line"><span class="cl"><span class="n">onComplete</span> <span class="p">=</span> <span class="p">{</span> <span class="p">[</span><span class="kr">weak</span> <span class="kc">self</span><span class="p">]</span> <span class="k">in</span>
</span></span><span class="line"><span class="cl">    <span class="kc">self</span><span class="p">?.</span><span class="n">dismiss</span><span class="p">(</span><span class="n">animated</span><span class="p">:</span> <span class="kc">true</span><span class="p">)</span>  <span class="c1">// ✓ No retain cycle</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>Delegates need to be weak too:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-swift" data-lang="swift"><span class="line"><span class="cl"><span class="kr">weak</span> <span class="kd">var</span> <span class="nv">delegate</span><span class="p">:</span> <span class="n">ManagerDelegate</span><span class="p">?</span>  <span class="c1">// Not just &#39;var&#39;</span></span></span></code></pre></div></div>

<h3 class="relative group">Instruments
    <div id="instruments" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#instruments" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>For serious memory investigation, use Instruments (Product → Profile, or Cmd+I).</p>
<p>The Allocations instrument shows every object allocation, memory growth over time, which classes are using the most memory, and stack traces for where each allocation happened.</p>
<p>What I&rsquo;m usually looking for: memory that grows linearly over time (probably a leak), unexpectedly large allocations (did I just load all 1000 images at once?), and objects that should have been deallocated but weren&rsquo;t.</p>
<p>Mark generations (the little flag button) before and after an action to see what&rsquo;s persisting when it shouldn&rsquo;t.</p>

<h2 class="relative group">Performance Profiling
    <div id="performance-profiling" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#performance-profiling" aria-label="Anchor">#</a>
    </span>
    
</h2>

<h3 class="relative group">Time Profiler
    <div id="time-profiler" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#time-profiler" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Product → Profile → Time Profiler. Record while doing the slow thing in your app, then read the call tree.</p>
<p>Sort by &ldquo;Self Weight&rdquo; to find the bottlenecks. If a function shows 40% self weight, that&rsquo;s where your time is going.</p>
<p>I once found a JSON parsing function being called 1000 times a second. Moved it to a background queue and the UI stopped stuttering.</p>

<h3 class="relative group">Main Thread Checker
    <div id="main-thread-checker" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#main-thread-checker" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Xcode automatically catches UI updates on background threads. If you see this:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">Main Thread Checker: UI API called on a background thread: -[UILabel setText:]</span></span></code></pre></div></div>
<p>you did something like this:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-swift" data-lang="swift"><span class="line"><span class="cl"><span class="n">URLSession</span><span class="p">.</span><span class="n">shared</span><span class="p">.</span><span class="n">dataTask</span><span class="p">(</span><span class="n">with</span><span class="p">:</span> <span class="n">url</span><span class="p">)</span> <span class="p">{</span> <span class="n">data</span><span class="p">,</span> <span class="n">response</span><span class="p">,</span> <span class="n">error</span> <span class="k">in</span>
</span></span><span class="line"><span class="cl">    <span class="kc">self</span><span class="p">.</span><span class="n">label</span><span class="p">.</span><span class="n">text</span> <span class="p">=</span> <span class="s">&#34;Loaded&#34;</span>  <span class="c1">// ❌ Crash!</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>Fix it:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-swift" data-lang="swift"><span class="line"><span class="cl"><span class="n">URLSession</span><span class="p">.</span><span class="n">shared</span><span class="p">.</span><span class="n">dataTask</span><span class="p">(</span><span class="n">with</span><span class="p">:</span> <span class="n">url</span><span class="p">)</span> <span class="p">{</span> <span class="n">data</span><span class="p">,</span> <span class="n">response</span><span class="p">,</span> <span class="n">error</span> <span class="k">in</span>
</span></span><span class="line"><span class="cl">    <span class="n">DispatchQueue</span><span class="p">.</span><span class="n">main</span><span class="p">.</span><span class="n">async</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="kc">self</span><span class="p">.</span><span class="n">label</span><span class="p">.</span><span class="n">text</span> <span class="p">=</span> <span class="s">&#34;Loaded&#34;</span>  <span class="c1">// ✓</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>

<h2 class="relative group">Runtime Diagnostics
    <div id="runtime-diagnostics" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#runtime-diagnostics" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Edit Scheme → Run → Diagnostics. There&rsquo;s a row of checkboxes in here that catch bugs you&rsquo;d never find by hand.</p>

<h3 class="relative group">Address Sanitizer
    <div id="address-sanitizer" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#address-sanitizer" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Finds memory corruption: use-after-free errors, buffer overflows, memory leaks. It makes the app 2-3x slower, but it catches bugs that are near impossible to track down any other way. I turn it on when chasing crashes that only happen sometimes.</p>

<h3 class="relative group">Thread Sanitizer
    <div id="thread-sanitizer" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#thread-sanitizer" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Catches data races and threading bugs. Enable it, run the app, and use it normally; if there&rsquo;s a race condition in there, Thread Sanitizer will find it.</p>
<p>You can&rsquo;t run Address Sanitizer and Thread Sanitizer at the same time, so I alternate between them when a crash is being weird.</p>

<h3 class="relative group">Zombie Objects
    <div id="zombie-objects" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#zombie-objects" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Catches messages sent to deallocated objects. With it enabled, Xcode tells you exactly when you&rsquo;re touching freed memory:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">*** -[MyViewController viewDidLoad]: message sent to deallocated instance 0x600001234000</span></span></code></pre></div></div>
<p>Don&rsquo;t leave it on permanently. It stops objects from being deallocated, so memory climbs forever. But for pinning down a specific use-after-free bug, it&rsquo;s great.</p>

<h2 class="relative group">Common Debugging Scenarios
    <div id="common-debugging-scenarios" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#common-debugging-scenarios" aria-label="Anchor">#</a>
    </span>
    
</h2>

<h3 class="relative group">App Crashes on Launch
    <div id="app-crashes-on-launch" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#app-crashes-on-launch" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Add an exception breakpoint first; that usually catches it.</p>
<p>If not, the usual suspects are missing keys in Info.plist, force-unwrapped optionals in initialisation code, or dependency injection failing.</p>

<h3 class="relative group">UI Not Updating
    <div id="ui-not-updating" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#ui-not-updating" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Every. Single. Time. It&rsquo;s one of:</p>
<ol>
<li>The update isn&rsquo;t on the main thread</li>
<li>The outlet isn&rsquo;t connected</li>
<li>The view isn&rsquo;t actually visible (check with <code>po view.window</code> in LLDB; if it returns nil, the view isn&rsquo;t in the hierarchy)</li>
</ol>
<p>And for table or collection views: you forgot to call <code>reloadData()</code>.</p>

<h3 class="relative group">Memory Warnings Crashing the App
    <div id="memory-warnings-crashing-the-app" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#memory-warnings-crashing-the-app" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Use Instruments Allocations to see what&rsquo;s holding memory. It&rsquo;s usually images never released from a cache, view controllers that won&rsquo;t deallocate (retain cycle), or some array or dictionary growing forever.</p>
<p>Simulate memory warnings in the simulator to test your cleanup code.</p>

<h3 class="relative group">Mysterious Crashes
    <div id="mysterious-crashes" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#mysterious-crashes" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Turn on the sanitizers. Intermittent usually means threading, so run with Thread Sanitizer. Crashing inside system frameworks usually means memory corruption, so run with Address Sanitizer.</p>

<h3 class="relative group">Crashes You Can&rsquo;t Reproduce
    <div id="crashes-you-cant-reproduce" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#crashes-you-cant-reproduce" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>When the crash happened on someone else&rsquo;s phone, the report usually still exists. For TestFlight and App Store builds, Xcode&rsquo;s Organizer (Window → Organizer → Crashes) collects crash reports from users who share analytics, symbolicated if the dSYMs went up with the build. For a tester&rsquo;s phone, the reports are on the device itself under Settings → Privacy &amp; Security → Analytics &amp; Improvements → Analytics Data, as <code>.ips</code> files starting with the app&rsquo;s name, and they can AirDrop one over. Start from the crashed thread&rsquo;s stack trace, then work through the scenarios above.</p>

<h3 class="relative group">Debugging OTA Updates in the Simulator
    <div id="debugging-ota-updates-in-the-simulator" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#debugging-ota-updates-in-the-simulator" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>My app ships over-the-air updates, and the simulator is the easiest place to debug that whole flow.</p>
<p>I start by watching the network traffic. Console.app filtered to the app&rsquo;s subsystem shows the manifest requests and responses in real time, so you can see exactly which headers go out and what the server sends back.</p>
<p>Then I make the network bad on purpose. Network Link Conditioner shows you how the update flow copes with slow connections and packet loss. Does the app hang? Show a loading indicator? Fall back gracefully?</p>
<p>Around the update check itself, I log everything: when the check starts, when an update is available, when the download begins, and when the new bundle loads.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-swift" data-lang="swift"><span class="line"><span class="cl"><span class="kd">import</span> <span class="nc">os</span><span class="p">.</span><span class="nc">log</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kd">let</span> <span class="nv">logger</span> <span class="p">=</span> <span class="n">Logger</span><span class="p">(</span><span class="n">subsystem</span><span class="p">:</span> <span class="s">&#34;com.example.app&#34;</span><span class="p">,</span> <span class="n">category</span><span class="p">:</span> <span class="s">&#34;updates&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">logger</span><span class="p">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#34;Checking for updates...&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="kd">let</span> <span class="nv">update</span> <span class="p">=</span> <span class="k">try</span> <span class="n">await</span> <span class="n">Updates</span><span class="p">.</span><span class="n">checkForUpdateAsync</span><span class="p">()</span>
</span></span><span class="line"><span class="cl"><span class="n">logger</span><span class="p">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#34;Update available: </span><span class="si">\(</span><span class="n">update</span><span class="p">.</span><span class="n">isAvailable</span><span class="si">)</span><span class="s">&#34;</span><span class="p">)</span></span></span></code></pre></div></div>
<p>Finally, it&rsquo;s worth testing the manifest endpoint on its own. You can curl it with the same headers the app sends:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">curl -H <span class="s2">&#34;expo-protocol-version: 1&#34;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">     -H <span class="s2">&#34;expo-platform: ios&#34;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">     -H <span class="s2">&#34;expo-runtime-version: 1.0.0&#34;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">     https://updates.example.com/manifest</span></span></code></pre></div></div>
<p>That confirms the server is returning the right data before you go digging into the client.</p>

<h2 class="relative group">Third-Party Tools
    <div id="third-party-tools" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#third-party-tools" aria-label="Anchor">#</a>
    </span>
    
</h2>

<h3 class="relative group">Charles Proxy / Proxyman
    <div id="charles-proxy--proxyman" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#charles-proxy--proxyman" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>See all your network traffic, modify requests and responses, test error conditions. Essential for API debugging.</p>
<p>Proxyman has a nicer UI than Charles and feels more at home on macOS. I switched last year and haven&rsquo;t looked back.</p>

<h3 class="relative group">Reveal
    <div id="reveal" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#reveal" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Like Xcode&rsquo;s view debugger, but more capable. It works on physical devices without being attached to Xcode, which makes it great for chasing layout issues on testers&rsquo; devices.</p>

<h2 class="relative group">Simulator vs Real Device
    <div id="simulator-vs-real-device" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#simulator-vs-real-device" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Most of my debugging happens in the simulator because it&rsquo;s quick: no cable, no signing, no waiting for an install. But the simulator is an iOS build running on your Mac&rsquo;s processor, with your Mac&rsquo;s memory and your Mac&rsquo;s network connection, and some bugs only exist on a phone.</p>
<table>
	<thead>
			<tr>
					<th></th>
					<th>Simulator</th>
					<th>Real iPhone</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Speed</td>
					<td>Your Mac&rsquo;s CPU, usually faster than a phone</td>
					<td>Real numbers; profile performance here</td>
			</tr>
			<tr>
					<td>Memory</td>
					<td>No real limit, so you simulate memory warnings</td>
					<td>The system kills apps that use too much</td>
			</tr>
			<tr>
					<td>Network</td>
					<td>Your Mac&rsquo;s connection</td>
					<td>Cellular, weak signal, switching between Wi-Fi and mobile data</td>
			</tr>
			<tr>
					<td>Camera, Bluetooth, NFC</td>
					<td>Not available</td>
					<td>Available</td>
			</tr>
			<tr>
					<td>Push notifications</td>
					<td>Can be faked with <code>xcrun simctl push</code></td>
					<td>Real delivery, the way users get them</td>
			</tr>
			<tr>
					<td>Iteration</td>
					<td>Seconds</td>
					<td>Slower: signing, install, cable or Wi-Fi</td>
			</tr>
	</tbody>
</table>
<p>So I build and debug logic in the simulator, and before a release I run the app on the oldest iPhone I still support. Performance, memory pressure and anything that touches hardware haven&rsquo;t really been tested until they&rsquo;ve run on a device.</p>

<h3 class="relative group">Running on a Device
    <div id="running-on-a-device" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#running-on-a-device" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Plug the iPhone in, pick it as the run destination, and set a team under Signing &amp; Capabilities (a free Apple ID is enough for your own phone). Since iOS 16 the phone also needs Developer Mode turned on under Settings → Privacy &amp; Security, which restarts it the first time. Once it&rsquo;s on, the phone&rsquo;s own Settings → Developer menu has a Network Link Conditioner with the same bad-network profiles as the Mac&rsquo;s.</p>

<h3 class="relative group">Wireless Debugging
    <div id="wireless-debugging" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#wireless-debugging" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Plug the device in over USB once, go to Window → Devices and Simulators, tick &ldquo;Connect via network&rdquo;, then unplug. The device stays available in Xcode as long as you&rsquo;re on the same WiFi.</p>

<h3 class="relative group">Device Console
    <div id="device-console" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#device-console" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Window → Devices and Simulators → Open Console. This shows everything: system logs, app logs, crash reports. Far more detail than Xcode&rsquo;s own console.</p>
<p>When a tester tells me &ldquo;the app crashed&rdquo;, I always ask them to plug their device in so I can grab the console logs. There&rsquo;s often a system-level error sitting right there that explains the whole thing.</p>

<h2 class="relative group">What I Actually Do When Debugging
    <div id="what-i-actually-do-when-debugging" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-i-actually-do-when-debugging" aria-label="Anchor">#</a>
    </span>
    
</h2>
<ol>
<li>Add an exception breakpoint if there isn&rsquo;t one already</li>
<li>Reproduce the bug</li>
<li>Set a breakpoint near where I think it&rsquo;s going wrong</li>
<li>Check values with <code>po</code> in LLDB</li>
<li>Modify variables to test fixes without recompiling</li>
<li>Check the view hierarchy if it&rsquo;s UI-related</li>
<li>Profile with Instruments if it&rsquo;s performance-related</li>
<li>Turn on the sanitizers if it&rsquo;s memory or threading</li>
</ol>
<p>The trick is working backwards from the symptom. Crash? Exception breakpoint. Slow? Time Profiler. Memory? Instruments. Weird UI? View debugger.</p>

<h2 class="relative group">Tips I Wish I&rsquo;d Known Earlier
    <div id="tips-i-wish-id-known-earlier" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#tips-i-wish-id-known-earlier" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Use assertions. They catch logic errors before they turn into bugs:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-swift" data-lang="swift"><span class="line"><span class="cl"><span class="bp">assert</span><span class="p">(</span><span class="n">users</span><span class="p">.</span><span class="bp">count</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">,</span> <span class="s">&#34;Users array should never be empty here&#34;</span><span class="p">)</span></span></span></code></pre></div></div>
<p>Commit before you start debugging. Once you&rsquo;re changing things to test theories, you&rsquo;ll want a clean point to revert to.</p>
<p>Delete your print statements when you&rsquo;re done, or at least wrap them in <code>#if DEBUG</code>. Old debug logs make the next bug harder to see.</p>
<p>Learn LLDB properly. It&rsquo;s faster than rebuilding your app twenty times.</p>
<p>And remember the simulator is not a real phone. Bugs that only appear on device are almost always threading or memory. Or performance, because the simulator runs on your Mac&rsquo;s CPU rather than an actual iPhone chip.</p>

<h2 class="relative group">Tools I Keep Open
    <div id="tools-i-keep-open" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#tools-i-keep-open" aria-label="Anchor">#</a>
    </span>
    
</h2>
<ul>
<li>Xcode, obviously</li>
<li>Console.app filtered to my app&rsquo;s subsystem</li>
<li>Proxyman for network debugging</li>
<li>Instruments when things get serious</li>
</ul>
<hr>
<p>No single tool covers everything. The view debugger won&rsquo;t find a memory leak, and Instruments won&rsquo;t untangle an Auto Layout conflict, so most of the skill is matching the tool to the symptom. That part just comes with repetition: after enough retain cycles you start to smell them from the stack trace alone. Debugging never becomes fun exactly, but it does stop being miserable.</p>
]]></content:encoded>
      <media:content url="https://jared.lynskey.co.nz/en/posts/2026/2026-02-26-debugging-ios-mobile-apps/featured.jpg" medium="image" type="image/jpeg" />
    </item>
    <item>
      <title>Self-Hosted Expo OTA Updates Without EAS: An Update Server With Django and Tigris</title>
      <link>https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/</link>
      <guid isPermaLink="true">https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/</guid>
      <pubDate>Sun, 22 Feb 2026 00:00:00 +0000</pubDate>
      <dc:creator>Jared Lynskey</dc:creator>
      <category>React Native</category>
      <category>Expo</category>
      <category>OTA Updates</category>
      <category>Django</category>
      <category>Mobile Development</category>
      <category>CI/CD</category>
      <category>Self-Hosted</category>
      <category>Tigris</category>
      <category>S3</category>
      <description>How Expo OTA updates work, and how I self-host them without EAS Update: a Django REST server that speaks the Expo Updates protocol, bundles on Tigris S3, and about a dollar a month to run.</description>
      <content:encoded><![CDATA[<blockquote><p><strong>Update, 13 September 2026.</strong> Since this went up, Codemagic have released <a href="https://patch.codemagic.io/"  target="_blank" rel="noreferrer sponsored">Patch</a>, an <a href="https://github.com/codemagic-ci-cd/codemagic-patch"  target="_blank" rel="noreferrer sponsored">open-source</a>, self-hostable OTA server in the CodePush mould. If you got here because you&rsquo;d rather not build the server yourself, it&rsquo;s now a real option: I&rsquo;ve since <a href="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/" >moved an app from the setup below to Patch</a> and written up how that went, and there&rsquo;s a short note on it under <a href="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/#wrapping-up" >Wrapping up</a>. Disclosure: Codemagic paid me to do that migration and write about it, and asked for a mention here. The code in the rest of this post has since been trimmed to short examples.</p>
</blockquote><p>My estimating app gets its bug fixes pushed over the air: JavaScript changes land on users&rsquo; phones without going anywhere near App Store review. Expo&rsquo;s hosted service, EAS Update, will happily do this for you. I built my own version anyway, with Django REST Framework and Tigris S3, and it has served every iOS and Android update since.</p>
<p>Expo OTA updates work like this: the app&rsquo;s <code>expo-updates</code> library asks an update server for a manifest, sending its platform and runtime version in headers. The server answers with the newest compatible update and the URLs of its JavaScript bundle and assets, and the app downloads them and runs the new bundle on its next launch. EAS Update is Expo&rsquo;s hosted server for that protocol, but any server that speaks it will do, and that&rsquo;s what I built.</p>
<p>This post walks through the whole thing: the models, the manifest endpoint, the publishing pipeline, and the gotchas that only show up once you&rsquo;re running it yourself.</p>
<figure><div class="film-pair">
  <div class="mc-film film-dark">
  <video
    class="my-0 rounded-md"
    controls playsinline preload="none"
    poster="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film-poster.jpg" style="background:url('data:image/webp;base64,UklGRm4AAABXRUJQVlA4IGIAAAAQBQCdASogABIAPw1sqEemIyIYBABjEMT0gAHv/19hLgpVytr9aI4tbGYN60LlTyNgAP7ixnoxnS14Lf/jWFfD1Ayx7Fvv7xZAlaZJ6juRdHEk24X2J2/+A6wYlCvALkAAAA==') center/cover no-repeat"
    width="1280"
    height="720"
    aria-label="A short narrated film of this post">
    <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film.webm" type="video/webm">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film_en.vtt" srclang="en" label="English">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film_ja.vtt" srclang="ja" label="日本語">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film_ko.vtt" srclang="ko" label="한국어">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film_vi.vtt" srclang="vi" label="Tiếng Việt">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film_zh-cn.vtt" srclang="zh-cn" label="简体中文">
  </video>
  </div>
  <div class="mc-film film-light">
  <video
    class="my-0 rounded-md"
    controls playsinline preload="none"
    poster="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film-light-poster.jpg" style="background:url('data:image/webp;base64,UklGRoAAAABXRUJQVlA4IHQAAACQBACdASogABIAPw1qqEemIyIYBABjEMT0gAFRZYz2GsagLYYqubW7XVZz++AA/u+6YQNy59OpOVcSrgpPjcRqp3rs9rBcw35QGsQ974BdqiBwqzvG68GlC5Ck9kFFL9rbx7a7jNe7Qym3Zj2uivALkAAAAA==') center/cover no-repeat"
    width="1280"
    height="720"
    aria-label="A short narrated film of this post">
    <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film-light.webm" type="video/webm">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film_en.vtt" srclang="en" label="English">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film_ja.vtt" srclang="ja" label="日本語">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film_ko.vtt" srclang="ko" label="한국어">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film_vi.vtt" srclang="vi" label="Tiếng Việt">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/ota-film_zh-cn.vtt" srclang="zh-cn" label="简体中文">
  </video>
  </div>
  <script>window.mcFilm && window.mcFilm()</script></div><figcaption>This post as a nine-minute film, if you&rsquo;d rather watch than read.</figcaption>
</figure>


<h2 class="relative group">Why self-host at all?
    <div id="why-self-host-at-all" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#why-self-host-at-all" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Mostly cost, in my case. EAS Update pricing scales with usage, so pushing frequent updates to a growing user base adds up, while S3-compatible storage like Tigris stays nearly free. There are other reasons that might weigh more for you: some industries have to keep every application asset inside their own infrastructure, and owning the server means owning the update flow, so you can roll out to specific user segments or A/B test bundles if your product calls for it. It also means nothing about your update pipeline depends on Expo&rsquo;s availability or their next pricing change.</p>

<h2 class="relative group">How the pieces fit
    <div id="how-the-pieces-fit" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#how-the-pieces-fit" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Four components: a Django backend that serves update manifests and stores metadata, Tigris holding the actual bundle and asset files, a publishing script that exports, uploads and registers updates, and the mobile app itself pointed at my server instead of Expo&rsquo;s.</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">┌─────────────────┐
</span></span><span class="line"><span class="cl">│   Mobile App    │
</span></span><span class="line"><span class="cl">│  (expo-updates) │
</span></span><span class="line"><span class="cl">└────────┬────────┘
</span></span><span class="line"><span class="cl">         │ 1. Request manifest
</span></span><span class="line"><span class="cl">         │    (with headers: platform, runtime-version)
</span></span><span class="line"><span class="cl">         ↓
</span></span><span class="line"><span class="cl">┌─────────────────┐
</span></span><span class="line"><span class="cl">│  Django Server  │
</span></span><span class="line"><span class="cl">│  /api/expo-     │◄─── 2. Query DB for latest update
</span></span><span class="line"><span class="cl">│   updates/      │
</span></span><span class="line"><span class="cl">│   manifest/     │
</span></span><span class="line"><span class="cl">└────────┬────────┘
</span></span><span class="line"><span class="cl">         │ 3. Generate presigned URLs
</span></span><span class="line"><span class="cl">         │
</span></span><span class="line"><span class="cl">         ↓
</span></span><span class="line"><span class="cl">┌─────────────────┐
</span></span><span class="line"><span class="cl">│   Tigris S3     │
</span></span><span class="line"><span class="cl">│  (Asset Files)  │◄─── 4. App downloads bundles directly
</span></span><span class="line"><span class="cl">└─────────────────┘</span></span></code></pre></div></div>

<h2 class="relative group">Building it
    <div id="building-it" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#building-it" aria-label="Anchor">#</a>
    </span>
    
</h2>

<h3 class="relative group">The two models
    <div id="the-two-models" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-two-models" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Everything hangs off <code>ExpoUpdate</code> and <code>ExpoUpdateAsset</code>. The first stores metadata for each update:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">ExpoUpdate</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="nb">id</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">UUIDField</span><span class="p">(</span><span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid4</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">runtime_version</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">,</span> <span class="n">db_index</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">platform</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="n">max_length</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="n">choices</span><span class="o">=</span><span class="p">[(</span><span class="s2">&#34;ios&#34;</span><span class="p">,</span> <span class="s2">&#34;iOS&#34;</span><span class="p">),</span> <span class="p">(</span><span class="s2">&#34;android&#34;</span><span class="p">,</span> <span class="s2">&#34;Android&#34;</span><span class="p">)],</span>
</span></span><span class="line"><span class="cl">        <span class="n">db_index</span><span class="o">=</span><span class="kc">True</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">is_active</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">BooleanField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">db_index</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">manifest_data</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">JSONField</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="n">description</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">(</span><span class="n">blank</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">created_at</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="n">auto_now_add</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">indexes</span> <span class="o">=</span> <span class="p">[</span>
</span></span><span class="line"><span class="cl">            <span class="n">models</span><span class="o">.</span><span class="n">Index</span><span class="p">(</span><span class="n">fields</span><span class="o">=</span><span class="p">[</span><span class="s2">&#34;runtime_version&#34;</span><span class="p">,</span> <span class="s2">&#34;platform&#34;</span><span class="p">,</span> <span class="s2">&#34;is_active&#34;</span><span class="p">,</span> <span class="s2">&#34;-created_at&#34;</span><span class="p">])</span>
</span></span><span class="line"><span class="cl">        <span class="p">]</span></span></span></code></pre></div></div>
<p>A few deliberate choices in there. <code>runtime_version</code> mirrors the <code>runtimeVersion</code> in <code>app.json</code>, and it does a lot of work: clients only ever download updates matching their own runtime version. iOS and Android get separate rows because the bundles differ. <code>is_active</code> is the rollback mechanism; deactivate a bad update and clients fall back to the previous one. And <code>manifest_data</code> holds the complete Expo Updates v1 protocol manifest as JSON, so serving it later is just a lookup.</p>
<p><code>ExpoUpdateAsset</code> tracks the individual files:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">ExpoUpdateAsset</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="nb">id</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">UUIDField</span><span class="p">(</span><span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid4</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">update</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">ExpoUpdate</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s2">&#34;assets&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nb">hash</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">255</span><span class="p">,</span> <span class="n">db_index</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">key</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">255</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">content_type</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">file_extension</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">file_path</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">500</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">file_size</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span></span></span></code></pre></div></div>
<p>Assets are keyed by SHA-256 hash, which makes them immutable and cacheable. The same asset can be shared across any number of updates.</p>

<h3 class="relative group">The manifest endpoint
    <div id="the-manifest-endpoint" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-manifest-endpoint" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p><code>/api/expo-updates/manifest/</code> is where app and server actually talk. It implements the <a href="https://docs.expo.dev/technical-specs/expo-updates-1/"  target="_blank" rel="noreferrer">Expo Updates v1 protocol</a>:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="nd">@action</span><span class="p">(</span><span class="n">detail</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">methods</span><span class="o">=</span><span class="p">[</span><span class="s2">&#34;get&#34;</span><span class="p">],</span> <span class="n">url_path</span><span class="o">=</span><span class="s2">&#34;manifest&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">manifest</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Extract required headers</span>
</span></span><span class="line"><span class="cl">    <span class="n">protocol_version</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">META</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&#34;HTTP_EXPO_PROTOCOL_VERSION&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">platform</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">META</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&#34;HTTP_EXPO_PLATFORM&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">runtime_version</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">META</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&#34;HTTP_EXPO_RUNTIME_VERSION&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Validate protocol version</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">protocol_version</span> <span class="o">!=</span> <span class="s2">&#34;1&#34;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">Response</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">            <span class="p">{</span><span class="s2">&#34;error&#34;</span><span class="p">:</span> <span class="sa">f</span><span class="s2">&#34;Unsupported protocol version: </span><span class="si">{</span><span class="n">protocol_version</span><span class="si">}</span><span class="s2">&#34;</span><span class="p">},</span>
</span></span><span class="line"><span class="cl">            <span class="n">status</span><span class="o">=</span><span class="mi">400</span>
</span></span><span class="line"><span class="cl">        <span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Find latest active update for this runtime + platform</span>
</span></span><span class="line"><span class="cl">    <span class="n">update</span> <span class="o">=</span> <span class="n">ExpoUpdate</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="n">runtime_version</span><span class="o">=</span><span class="n">runtime_version</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="n">platform</span><span class="o">=</span><span class="n">platform</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="n">is_active</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s2">&#34;-created_at&#34;</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># No update available - client uses embedded bundle</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="ow">not</span> <span class="n">update</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">response</span> <span class="o">=</span> <span class="n">Response</span><span class="p">(</span><span class="n">status</span><span class="o">=</span><span class="mi">204</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">response</span><span class="p">[</span><span class="s2">&#34;expo-protocol-version&#34;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&#34;1&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">response</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Generate presigned URLs for all assets</span>
</span></span><span class="line"><span class="cl">    <span class="n">manifest_data</span> <span class="o">=</span> <span class="n">build_manifest</span><span class="p">(</span><span class="n">update</span><span class="p">)</span>  <span class="c1"># fills in presigned asset URLs</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">Response</span><span class="p">(</span><span class="n">manifest_data</span><span class="p">,</span> <span class="n">status</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span></span></span></code></pre></div></div>
<p>Three details matter here. A 204 response means &ldquo;no update&rdquo;, and the app carries on with its embedded bundle. The asset URLs in the manifest are presigned, so the app downloads straight from Tigris&rsquo;s CDN rather than streaming everything through Django. And the <code>expo-protocol-version</code> response header isn&rsquo;t optional; the client checks for it.</p>

<h3 class="relative group">Publishing updates
    <div id="publishing-updates" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#publishing-updates" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Publishing is a Django management command with a shell script wrapped around it. The command reads the output of <code>expo export</code>, hashes every asset with SHA-256, uploads bundles and assets to Tigris in parallel, writes the database records, and optionally drops an import JSON into the bucket for production sync. Cut down to the part that matters:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">concurrent.futures</span> <span class="kn">import</span> <span class="n">ThreadPoolExecutor</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">transaction</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">publish</span><span class="p">(</span><span class="n">platform</span><span class="p">,</span> <span class="n">runtime_version</span><span class="p">,</span> <span class="n">manifest</span><span class="p">,</span> <span class="n">files</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Upload the bundle and assets in parallel (keys are content hashes)</span>
</span></span><span class="line"><span class="cl">    <span class="k">with</span> <span class="n">ThreadPoolExecutor</span><span class="p">(</span><span class="n">max_workers</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span> <span class="k">as</span> <span class="n">executor</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="nb">list</span><span class="p">(</span><span class="n">executor</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">upload_asset</span><span class="p">,</span> <span class="n">files</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Swap the active update in one transaction</span>
</span></span><span class="line"><span class="cl">    <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">        <span class="n">ExpoUpdate</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">            <span class="n">runtime_version</span><span class="o">=</span><span class="n">runtime_version</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="n">platform</span><span class="o">=</span><span class="n">platform</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="n">is_active</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">is_active</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">ExpoUpdate</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">            <span class="n">runtime_version</span><span class="o">=</span><span class="n">runtime_version</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="n">platform</span><span class="o">=</span><span class="n">platform</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="n">manifest_data</span><span class="o">=</span><span class="n">manifest</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="p">)</span></span></span></code></pre></div></div>
<p>The wrapper script is what I actually type:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># Publish to local environment</span>
</span></span><span class="line"><span class="cl">./publish.sh ios
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Publish to production</span>
</span></span><span class="line"><span class="cl">./publish.sh ios --production
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Dry run to validate</span>
</span></span><span class="line"><span class="cl">./publish.sh --dry-run</span></span></code></pre></div></div>
<p>It loads production environment variables before exporting, handles one platform or both, and takes care of the production sync described next.</p>

<h3 class="relative group">Syncing to production
    <div id="syncing-to-production" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#syncing-to-production" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>I didn&rsquo;t want production credentials sitting on my laptop, so production deploys happen in two steps: publish locally (assets go to Tigris, along with a JSON snapshot of the metadata), then call a production API endpoint with the S3 path so the server imports the metadata itself:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="nd">@action</span><span class="p">(</span><span class="n">detail</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">methods</span><span class="o">=</span><span class="p">[</span><span class="s2">&#34;post&#34;</span><span class="p">],</span> <span class="n">url_path</span><span class="o">=</span><span class="s2">&#34;import-update&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">import_update</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Authenticate via Bearer token</span>
</span></span><span class="line"><span class="cl">    <span class="n">token</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">META</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&#34;HTTP_AUTHORIZATION&#34;</span><span class="p">,</span> <span class="s2">&#34;&#34;</span><span class="p">)</span><span class="o">.</span><span class="n">removeprefix</span><span class="p">(</span><span class="s2">&#34;Bearer &#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="ow">not</span> <span class="n">hmac</span><span class="o">.</span><span class="n">compare_digest</span><span class="p">(</span><span class="n">token</span><span class="p">,</span> <span class="n">settings</span><span class="o">.</span><span class="n">IMPORT_TOKEN</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">Response</span><span class="p">({</span><span class="s2">&#34;error&#34;</span><span class="p">:</span> <span class="s2">&#34;Invalid token&#34;</span><span class="p">},</span> <span class="n">status</span><span class="o">=</span><span class="mi">401</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Download the import JSON from the bucket</span>
</span></span><span class="line"><span class="cl">    <span class="n">s3_key</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&#34;s3_key&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">obj</span> <span class="o">=</span> <span class="n">s3_client</span><span class="o">.</span><span class="n">get_object</span><span class="p">(</span><span class="n">Bucket</span><span class="o">=</span><span class="n">bucket_name</span><span class="p">,</span> <span class="n">Key</span><span class="o">=</span><span class="n">s3_key</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">data</span> <span class="o">=</span> <span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">obj</span><span class="p">[</span><span class="s2">&#34;Body&#34;</span><span class="p">]</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Import into the production database</span>
</span></span><span class="line"><span class="cl">    <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">        <span class="n">update</span><span class="p">,</span> <span class="n">_</span> <span class="o">=</span> <span class="n">ExpoUpdate</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">update_or_create</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="n">data</span><span class="p">[</span><span class="s2">&#34;id&#34;</span><span class="p">],</span> <span class="n">defaults</span><span class="o">=</span><span class="p">{</span><span class="o">...</span><span class="p">})</span>
</span></span><span class="line"><span class="cl">        <span class="k">for</span> <span class="n">asset_data</span> <span class="ow">in</span> <span class="n">data</span><span class="p">[</span><span class="s2">&#34;assets&#34;</span><span class="p">]:</span>
</span></span><span class="line"><span class="cl">            <span class="n">ExpoUpdateAsset</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">update_or_create</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># Clean up the import JSON</span>
</span></span><span class="line"><span class="cl">    <span class="n">s3_client</span><span class="o">.</span><span class="n">delete_object</span><span class="p">(</span><span class="n">Bucket</span><span class="o">=</span><span class="n">bucket_name</span><span class="p">,</span> <span class="n">Key</span><span class="o">=</span><span class="n">s3_key</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">Response</span><span class="p">({</span><span class="s2">&#34;update_id&#34;</span><span class="p">:</span> <span class="nb">str</span><span class="p">(</span><span class="n">update</span><span class="o">.</span><span class="n">id</span><span class="p">)})</span></span></span></code></pre></div></div>

<h3 class="relative group">Pointing the app at your server
    <div id="pointing-the-app-at-your-server" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#pointing-the-app-at-your-server" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>In <code>app.json</code>, set the update URL and runtime version:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nt">&#34;expo&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;runtimeVersion&#34;</span><span class="p">:</span> <span class="s2">&#34;1.0.0&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;updates&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;url&#34;</span><span class="p">:</span> <span class="s2">&#34;https://api.example.com/api/expo-updates/manifest/&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>Be strict about keeping <code>runtimeVersion</code> matched between app and server. When you change native code or upgrade the Expo SDK, bump the runtime version and publish fresh updates for it.</p>

<h2 class="relative group">Storage on Tigris
    <div id="storage-on-tigris" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#storage-on-tigris" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Tigris is S3-compatible object storage, considerably cheaper than actual AWS S3, and it includes global edge caching, which matters when users are pulling down multi-megabyte bundles. The Django configuration:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="c1"># settings.py</span>
</span></span><span class="line"><span class="cl"><span class="n">BUCKET_NAME</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s2">&#34;BUCKET_NAME&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">AWS_ENDPOINT_URL_S3</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s2">&#34;AWS_ENDPOINT_URL_S3&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">AWS_ACCESS_KEY_ID</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s2">&#34;AWS_ACCESS_KEY_ID&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">AWS_SECRET_ACCESS_KEY</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s2">&#34;AWS_SECRET_ACCESS_KEY&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">AWS_REGION</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s2">&#34;AWS_REGION&#34;</span><span class="p">,</span> <span class="s2">&#34;auto&#34;</span><span class="p">)</span></span></span></code></pre></div></div>
<p>Creating the client is standard boto3:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">boto3</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">create_s3_client</span><span class="p">(</span><span class="n">endpoint_url</span><span class="p">,</span> <span class="n">region</span><span class="p">,</span> <span class="n">access_key</span><span class="p">,</span> <span class="n">secret_key</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">boto3</span><span class="o">.</span><span class="n">client</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;s3&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="n">endpoint_url</span><span class="o">=</span><span class="n">endpoint_url</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="n">region_name</span><span class="o">=</span><span class="n">region</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="n">aws_access_key_id</span><span class="o">=</span><span class="n">access_key</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="n">aws_secret_access_key</span><span class="o">=</span><span class="n">secret_key</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="p">)</span></span></span></code></pre></div></div>
<p>Downloads go through presigned URLs, so the app fetches straight from the CDN:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">presigned_url</span> <span class="o">=</span> <span class="n">s3_client</span><span class="o">.</span><span class="n">generate_presigned_url</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;get_object&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">Params</span><span class="o">=</span><span class="p">{</span><span class="s2">&#34;Bucket&#34;</span><span class="p">:</span> <span class="n">bucket_name</span><span class="p">,</span> <span class="s2">&#34;Key&#34;</span><span class="p">:</span> <span class="n">asset</span><span class="o">.</span><span class="n">file_path</span><span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="n">ExpiresIn</span><span class="o">=</span><span class="mi">3600</span><span class="p">,</span>  <span class="c1"># 1 hour</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span></span></span></code></pre></div></div>

<h2 class="relative group">Security
    <div id="security" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#security" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The manifest endpoint is unauthenticated on purpose, because apps need updates before anyone has logged in. The import endpoint is a different story. It can write to the production database, so it wants a shared secret, compared in constant time to rule out timing attacks:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">IMPORT_TOKEN</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s2">&#34;IMPORT_TOKEN&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Constant-time comparison prevents timing attacks</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="ow">not</span> <span class="n">hmac</span><span class="o">.</span><span class="n">compare_digest</span><span class="p">(</span><span class="n">token</span><span class="p">,</span> <span class="n">IMPORT_TOKEN</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">Response</span><span class="p">({</span><span class="s2">&#34;error&#34;</span><span class="p">:</span> <span class="s2">&#34;Invalid token&#34;</span><span class="p">},</span> <span class="n">status</span><span class="o">=</span><span class="mi">401</span><span class="p">)</span></span></span></code></pre></div></div>
<p>Asset integrity comes free with the design: everything is verified against its SHA-256 hash, so a tampered asset simply fails. And presigned URLs expire after an hour, which keeps bundles from being hotlinked indefinitely.</p>

<h2 class="relative group">Keeping it fast
    <div id="keeping-it-fast" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#keeping-it-fast" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The composite index on <code>(runtime_version, platform, is_active, -created_at)</code> keeps the manifest query quick no matter how many updates accumulate:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="n">indexes</span> <span class="o">=</span> <span class="p">[</span>
</span></span><span class="line"><span class="cl">        <span class="n">models</span><span class="o">.</span><span class="n">Index</span><span class="p">(</span><span class="n">fields</span><span class="o">=</span><span class="p">[</span><span class="s2">&#34;runtime_version&#34;</span><span class="p">,</span> <span class="s2">&#34;platform&#34;</span><span class="p">,</span> <span class="s2">&#34;is_active&#34;</span><span class="p">,</span> <span class="s2">&#34;-created_at&#34;</span><span class="p">])</span>
</span></span><span class="line"><span class="cl">    <span class="p">]</span></span></span></code></pre></div></div>
<p>The publishing script uploads assets concurrently:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">with</span> <span class="n">ThreadPoolExecutor</span><span class="p">(</span><span class="n">max_workers</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span> <span class="k">as</span> <span class="n">executor</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="n">futures</span> <span class="o">=</span> <span class="p">{</span><span class="n">executor</span><span class="o">.</span><span class="n">submit</span><span class="p">(</span><span class="n">upload_asset</span><span class="p">,</span> <span class="n">asset</span><span class="p">):</span> <span class="n">asset</span> <span class="k">for</span> <span class="n">asset</span> <span class="ow">in</span> <span class="n">assets</span><span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">future</span> <span class="ow">in</span> <span class="n">as_completed</span><span class="p">(</span><span class="n">futures</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># Track progress</span></span></span></code></pre></div></div>
<p>For a typical update with 50 or so assets, that took publishing from about 2 minutes down to 15 seconds. Distribution needs no work at all: Tigris caches assets at edge locations near your users on its own.</p>

<h2 class="relative group">Day-to-day workflow
    <div id="day-to-day-workflow" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#day-to-day-workflow" aria-label="Anchor">#</a>
    </span>
    
</h2>

<h3 class="relative group">During development
    <div id="during-development" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#during-development" aria-label="Anchor">#</a>
    </span>
    
</h3>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># 1. Make code changes in the app</span>
</span></span><span class="line"><span class="cl">git commit -am <span class="s2">&#34;Fix bug&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># 2. Publish OTA update to local environment</span>
</span></span><span class="line"><span class="cl">./publish.sh ios
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># 3. Test on device</span>
</span></span><span class="line"><span class="cl"><span class="c1"># App automatically downloads and applies update</span></span></span></code></pre></div></div>

<h3 class="relative group">Shipping to production
    <div id="shipping-to-production" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#shipping-to-production" aria-label="Anchor">#</a>
    </span>
    
</h3>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># 1. Publish to production</span>
</span></span><span class="line"><span class="cl">./publish.sh ios --production
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># 2. Monitor</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Check Django admin for update records</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Verify assets in Tigris dashboard</span></span></span></code></pre></div></div>

<h3 class="relative group">Rolling back
    <div id="rolling-back" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#rolling-back" aria-label="Anchor">#</a>
    </span>
    
</h3>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># Mark problematic update as inactive in Django admin</span>
</span></span><span class="line"><span class="cl"><span class="c1"># or via management shell:</span>
</span></span><span class="line"><span class="cl">python manage.py shell
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">&gt;&gt;&gt; from updates.models import ExpoUpdate
</span></span><span class="line"><span class="cl">&gt;&gt;&gt; <span class="nv">bad_update</span> <span class="o">=</span> ExpoUpdate.objects.get<span class="o">(</span><span class="nv">id</span><span class="o">=</span><span class="s2">&#34;uuid-here&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">&gt;&gt;&gt; bad_update.is_active <span class="o">=</span> False
</span></span><span class="line"><span class="cl">&gt;&gt;&gt; bad_update.save<span class="o">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Clients will now receive the previous active update</span></span></span></code></pre></div></div>

<h2 class="relative group">What it costs
    <div id="what-it-costs" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-it-costs" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The app has around 500 active users. On Tigris, the ~200 MB of historical updates costs about $0.02/month, and the ~50 GB of monthly egress from update downloads about $1.00. The Django side rides along on the server my API already runs on, so its incremental cost is zero. Call it a dollar a month, all in. EAS Update at similar usage would land somewhere around $300–500/year, so this paid for itself more or less immediately.</p>

<h2 class="relative group">Monitoring and debugging
    <div id="monitoring-and-debugging" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#monitoring-and-debugging" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Nothing fancy here. The viewset logs every manifest request:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="sa">f</span><span class="s2">&#34;Manifest request: platform=</span><span class="si">{</span><span class="n">platform</span><span class="si">}</span><span class="s2">, runtime=</span><span class="si">{</span><span class="n">runtime_version</span><span class="si">}</span><span class="s2">&#34;</span><span class="p">)</span></span></span></code></pre></div></div>
<p>The Django admin is the de facto dashboard. Register the models and you can inspect and filter everything:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="nd"><span>@</span>admin.register</span><span class="p">(</span><span class="n">ExpoUpdate</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">ExpoUpdateAdmin</span><span class="p">(</span><span class="n">admin</span><span class="o">.</span><span class="n">ModelAdmin</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">list_display</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&#34;platform&#34;</span><span class="p">,</span> <span class="s2">&#34;runtime_version&#34;</span><span class="p">,</span> <span class="s2">&#34;is_active&#34;</span><span class="p">,</span> <span class="s2">&#34;created_at&#34;</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">    <span class="n">list_filter</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&#34;platform&#34;</span><span class="p">,</span> <span class="s2">&#34;is_active&#34;</span><span class="p">,</span> <span class="s2">&#34;runtime_version&#34;</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">    <span class="n">search_fields</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&#34;description&#34;</span><span class="p">]</span></span></span></code></pre></div></div>
<p>And on the client, <code>expo-updates</code> will tell you what it sees:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="o">*</span> <span class="kr">as</span> <span class="nx">Updates</span> <span class="kr">from</span> <span class="s1">&#39;expo-updates&#39;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nx">Updates</span><span class="p">.</span><span class="nx">checkForUpdateAsync</span><span class="p">().</span><span class="nx">then</span><span class="p">(</span><span class="nx">update</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;Update available:&#39;</span><span class="p">,</span> <span class="nx">update</span><span class="p">.</span><span class="nx">isAvailable</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;Manifest:&#39;</span><span class="p">,</span> <span class="nx">update</span><span class="p">.</span><span class="nx">manifest</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="p">});</span></span></span></code></pre></div></div>

<h2 class="relative group">Gotchas
    <div id="gotchas" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#gotchas" aria-label="Anchor">#</a>
    </span>
    
</h2>

<h3 class="relative group">Runtime version mismatches
    <div id="runtime-version-mismatches" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#runtime-version-mismatches" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>The most common failure is also the quietest: clients only download updates matching their runtime version. If the installed app is on runtime <code>1.0.0</code> and you publish for <code>1.0.1</code>, nothing arrives and nothing errors. Keep the runtime version in sync with your builds, and only bump it when native code changes.</p>

<h3 class="relative group">The createdAt timestamp
    <div id="the-createdat-timestamp" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#the-createdat-timestamp" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>The <code>expo-updates</code> client compares the manifest&rsquo;s <code>createdAt</code> against the embedded bundle&rsquo;s <code>commitTime</code>, and only applies an update whose <code>createdAt</code> is newer. The viewset overrides it with the database timestamp:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">manifest_data</span><span class="p">[</span><span class="s2">&#34;createdAt&#34;</span><span class="p">]</span> <span class="o">=</span> <span class="n">update</span><span class="o">.</span><span class="n">created_at</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s2">&#34;%Y-%m-</span><span class="si">%d</span><span class="s2">T%H:%M:%S.</span><span class="si">%f</span><span class="s2">Z&#34;</span><span class="p">)</span></span></span></code></pre></div></div>
<p>For local development, if you build a binary <em>after</em> publishing an OTA, republish the OTA so its timestamp wins.</p>

<h3 class="relative group">Manifest asset <code>key</code> values
    <div id="manifest-asset-key-values" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#manifest-asset-key-values" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>The <code>key</code> field on each manifest asset is what <code>expo-updates</code> uses for caching, and it must be a deterministic hash (the MD5 of the filename works), not a random UUID or arbitrary string. Get this wrong and the client may fail to cache or retrieve assets correctly, and updates silently break after the first successful load. Thanks to reader Raphael Mutschler for flagging this one; he had updates working exactly once before discovering the issue.</p>

<h3 class="relative group">App config in <code>expoClient</code>
    <div id="app-config-in-expoclient" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#app-config-in-expoclient" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>If your app uses <code>Linking</code>, <code>Constants</code>, or anything else that reads the app config at runtime, the manifest&rsquo;s <code>extra.expoClient</code> field needs to include your app config. Without it the app may launch fine at first, then crash or refuse to reopen after being closed. That&rsquo;s because <code>expo-updates</code> replaces the embedded manifest with the OTA one, and if <code>expoClient</code> is missing, those APIs lose the config they depend on. Raphael Mutschler caught this one too.</p>

<h3 class="relative group">Asset cleanup
    <div id="asset-cleanup" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#asset-cleanup" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Old updates pile up in Tigris. For now, cleanup at my end is manual:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="c1"># Delete updates older than 30 days</span>
</span></span><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">timedelta</span>
</span></span><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">cutoff</span> <span class="o">=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">()</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">old_updates</span> <span class="o">=</span> <span class="n">ExpoUpdate</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">created_at__lt</span><span class="o">=</span><span class="n">cutoff</span><span class="p">,</span> <span class="n">is_active</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">for</span> <span class="n">update</span> <span class="ow">in</span> <span class="n">old_updates</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Delete assets from S3</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">asset</span> <span class="ow">in</span> <span class="n">update</span><span class="o">.</span><span class="n">assets</span><span class="o">.</span><span class="n">all</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">        <span class="n">s3_client</span><span class="o">.</span><span class="n">delete_object</span><span class="p">(</span><span class="n">Bucket</span><span class="o">=</span><span class="n">bucket_name</span><span class="p">,</span> <span class="n">Key</span><span class="o">=</span><span class="n">asset</span><span class="o">.</span><span class="n">file_path</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Delete DB records</span>
</span></span><span class="line"><span class="cl">    <span class="n">update</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span></span></span></code></pre></div></div>
<p>A scheduled task is the obvious home for this. I haven&rsquo;t got round to it.</p>

<h2 class="relative group">Things I&rsquo;d add next
    <div id="things-id-add-next" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#things-id-add-next" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p><em>(September 2026: Patch now does all three of these and more; see <a href="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/" >the migration write-up</a>.)</em></p>

<h3 class="relative group">Gradual rollouts
    <div id="gradual-rollouts" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#gradual-rollouts" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>A <code>rollout_percentage</code> field would let an update go out to a slice of users first:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">rollout_percentage</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># In the manifest view:</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="n">update</span><span class="o">.</span><span class="n">rollout_percentage</span> <span class="o">&lt;</span> <span class="mi">100</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Hash user ID and check if they&#39;re in rollout group</span>
</span></span><span class="line"><span class="cl">    <span class="n">user_hash</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">hashlib</span><span class="o">.</span><span class="n">sha256</span><span class="p">(</span><span class="n">user_id</span><span class="o">.</span><span class="n">encode</span><span class="p">())</span><span class="o">.</span><span class="n">hexdigest</span><span class="p">(),</span> <span class="mi">16</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="n">user_hash</span> <span class="o">%</span> <span class="mi">100</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="n">update</span><span class="o">.</span><span class="n">rollout_percentage</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">Response</span><span class="p">(</span><span class="n">status</span><span class="o">=</span><span class="mi">204</span><span class="p">)</span>  <span class="c1"># No update</span></span></span></code></pre></div></div>

<h3 class="relative group">Separate staging updates
    <div id="separate-staging-updates" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#separate-staging-updates" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>An <code>environment</code> field would let staging builds receive different updates from production:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">environment</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">20</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s2">&#34;production&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Client sends environment in custom header</span>
</span></span><span class="line"><span class="cl"><span class="n">environment</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">META</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&#34;HTTP_X_UPDATE_ENVIRONMENT&#34;</span><span class="p">,</span> <span class="s2">&#34;production&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">update</span> <span class="o">=</span> <span class="n">ExpoUpdate</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">environment</span><span class="o">=</span><span class="n">environment</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span></span></span></code></pre></div></div>

<h3 class="relative group">Download analytics
    <div id="download-analytics" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#download-analytics" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>And a small model would answer the &ldquo;did anyone actually get this?&rdquo; question properly:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">ExpoUpdateDownload</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">update</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">ExpoUpdate</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">user_id</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">255</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">platform</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">downloaded_at</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="n">auto_now_add</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span></span></span></code></pre></div></div>

<h2 class="relative group">Wrapping up
    <div id="wrapping-up" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#wrapping-up" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The whole system is two Django models, a couple of views, a publishing script and a dollar a month in infrastructure. That&rsquo;s less than I expected going in, and it has quietly done its job for the app on both platforms since.</p>
<p>The snippets above are simplified examples of what runs in that production app, so adapt them to whatever you&rsquo;re building. Reader Raphael Mutschler also published a standalone implementation at <a href="https://github.com/mutschler/expo-ota-server"  target="_blank" rel="noreferrer">expo-ota-server</a> if you&rsquo;d rather start from something that already runs.</p>

<h3 class="relative group">If you&rsquo;d rather not write the server
    <div id="if-youd-rather-not-write-the-server" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#if-youd-rather-not-write-the-server" aria-label="Anchor">#</a>
    </span>
    
</h3>
<p>Two things have appeared since I wrote this that cover the same ground without the Django. The first is Raphael&rsquo;s <code>expo-ota-server</code> above. The second is <a href="https://patch.codemagic.io/"  target="_blank" rel="noreferrer sponsored">Codemagic Patch</a>: <a href="https://github.com/codemagic-ci-cd/codemagic-patch"  target="_blank" rel="noreferrer sponsored">open source</a>, runs on your own box from a Docker Compose install, and speaks CodePush rather than the Expo Updates protocol, so you swap <code>expo-updates</code> for its SDK and <code>eas update</code> for <code>cmpatch release-react</code>. It can use S3-compatible storage, so a Tigris bucket like the one in this post works too.</p>
<p>Out of the box it has the things I listed under &ldquo;Things I&rsquo;d add next&rdquo; and never built: staging and production deployments, percentage rollouts, per-release download and install numbers, mandatory updates, binary patches, code signing, and a rollback on the device when a new bundle crashes before the app reports ready. The trade is a new native binary before anyone gets a Patch update, since the SDK has to be in the app, and a server to run instead of a management command.</p>
<p>I moved one of my own apps, with its committed native projects and real release pipeline, from the setup in this post to Patch. <a href="https://jared.lynskey.co.nz/en/posts/2026/2026-09-13-moving-to-codemagic-patch/" >The write-up</a> covers what worked, what didn&rsquo;t, and how hard it really is. Codemagic sponsored that work and had a factual review pass on it, not an editorial one.</p>
<hr>
<p><em>For the full spec, see the <a href="https://docs.expo.dev/technical-specs/expo-updates-1/"  target="_blank" rel="noreferrer">Expo Updates Protocol Specification</a>.</em></p>
]]></content:encoded>
      <media:content url="https://jared.lynskey.co.nz/en/posts/2026/2026-02-22-self-hosted-ota-updates/featured.jpg" medium="image" type="image/jpeg" />
    </item>
    <item>
      <title>On-Device LLM in React Native: Running Qwen Offline With llama.rn and llama.cpp</title>
      <link>https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/</link>
      <guid isPermaLink="true">https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/</guid>
      <pubDate>Fri, 30 Jan 2026 00:00:00 +0000</pubDate>
      <dc:creator>Jared Lynskey</dc:creator>
      <category>React Native</category>
      <category>AI</category>
      <category>LLM</category>
      <category>llama.cpp</category>
      <category>Qwen</category>
      <category>On-Device AI</category>
      <category>Privacy</category>
      <category>Mobile Development</category>
      <description>How I run a small LLM entirely on the phone in a React Native and Expo app: llama.rn, a Qwen GGUF model at Q4_K_M, streaming, tool calling a small model can manage, and real numbers from an iPhone and a Galaxy S23.</description>
      <content:encoded><![CDATA[<p>The AI assistant in an estimating app I build runs entirely on the phone. Nothing leaves the device. Users can create jobs, search customers, and manage projects by typing plain English, and it all keeps working in airplane mode.</p>
<p>This post walks through how I built it with <strong>llama.rn</strong> (React Native bindings for llama.cpp) and <strong>Qwen 1.7B</strong>, a small model that turned out to be more capable than I expected.</p>
<p>The short version: install llama.rn, download a 4-bit GGUF model (about 1 GB) the first time the app opens, load it with <code>initLlama</code>, and stream completions from it. On an iPhone 14 Pro that runs at about 15 tokens a second with no network at all. The rest of this post is what it took to make that useful: picking the model, getting tool calls out of it reliably, and keeping memory in check.</p>
<blockquote><p><strong>📝 Update:</strong> This implementation now uses <a href="https://huggingface.co/unsloth/Qwen3.5-2B-GGUF"  target="_blank" rel="noreferrer">Qwen3.5-2B-GGUF</a> instead of the original Qwen3-1.7B. I&rsquo;ve also stopped using the <code>/no_think</code> message hack and now disable thinking mode properly via the <code>chat_template_kwargs</code> parameter:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">chat_response</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">chat</span><span class="o">.</span><span class="n">completions</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">model</span><span class="o">=</span><span class="s2">&#34;Qwen/Qwen3.5-27B&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">messages</span><span class="o">=</span><span class="n">messages</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">max_tokens</span><span class="o">=</span><span class="mi">32768</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">temperature</span><span class="o">=</span><span class="mf">0.7</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">top_p</span><span class="o">=</span><span class="mf">0.8</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">presence_penalty</span><span class="o">=</span><span class="mf">1.5</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">extra_body</span><span class="o">=</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;top_k&#34;</span><span class="p">:</span> <span class="mi">20</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">        <span class="s2">&#34;chat_template_kwargs&#34;</span><span class="p">:</span> <span class="p">{</span><span class="s2">&#34;enable_thinking&#34;</span><span class="p">:</span> <span class="kc">False</span><span class="p">},</span>
</span></span><span class="line"><span class="cl">    <span class="p">},</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span></span></span></code></pre></div></div>
<p>Much cleaner than smuggling control flags into the prompt.</p>
</blockquote><figure><div class="film-pair">
  <div class="mc-film film-dark">
  <video
    class="my-0 rounded-md"
    controls playsinline preload="none"
    poster="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film-poster.jpg" style="background:url('data:image/webp;base64,UklGRnAAAABXRUJQVlA4IGQAAACwBACdASogABIAPw1uqUemIyIYBABjEMT0gAFRZzp3IyiSND5CxppNutGcCYkAAP7ixmKvS+0H/fAThx4cbifiH8PzygNYbl6sJuQFubAi+gzkxN3eXPGHfroT5K82AG+x8AAA') center/cover no-repeat"
    width="1280"
    height="720"
    aria-label="A short narrated film of this post">
    <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film.webm" type="video/webm">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film_en.vtt" srclang="en" label="English">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film_ja.vtt" srclang="ja" label="日本語">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film_ko.vtt" srclang="ko" label="한국어">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film_vi.vtt" srclang="vi" label="Tiếng Việt">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film_zh-cn.vtt" srclang="zh-cn" label="简体中文">
  </video>
  </div>
  <div class="mc-film film-light">
  <video
    class="my-0 rounded-md"
    controls playsinline preload="none"
    poster="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film-light-poster.jpg" style="background:url('data:image/webp;base64,UklGRoIAAABXRUJQVlA4IHYAAACwBACdASogABIAPw1uqUemIyIYBABjEMT0gAFRZY2mogaLUpH79C93CfzUrxKAAP7vul6EGA0ytD4npxsGq682/6nTvmGx0/XY0S/eONnq1STOt/i7tLHFRM4DTibTbGueLxPoaxVrlM6FoYdfCU8gCNqwAAAA') center/cover no-repeat"
    width="1280"
    height="720"
    aria-label="A short narrated film of this post">
    <source src="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film-light.webm" type="video/webm">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film_en.vtt" srclang="en" label="English">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film_ja.vtt" srclang="ja" label="日本語">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film_ko.vtt" srclang="ko" label="한국어">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film_vi.vtt" srclang="vi" label="Tiếng Việt">
    <track kind="subtitles" src="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/on-device-ai-film_zh-cn.vtt" srclang="zh-cn" label="简体中文">
  </video>
  </div>
  <script>window.mcFilm && window.mcFilm()</script></div><figcaption>This post as a nine-minute film, if you&rsquo;d rather watch than read.</figcaption>
</figure>


<h2 class="relative group">Why I didn&rsquo;t want cloud AI for this
    <div id="why-i-didnt-want-cloud-ai-for-this" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#why-i-didnt-want-cloud-ai-for-this" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The standard recipe for an AI feature in a mobile app is: user types a message, app sends it to a cloud model provider, response comes back, bill ticks up.</p>
<p>For an app that tradespeople use to run their business, that recipe has problems. Customer names, addresses, and phone numbers go to a third party. Project details, pricing, and notes sit on someone else&rsquo;s servers. There are GDPR and data-residency questions I&rsquo;d rather not spend time on. And the API bill grows with every user.</p>
<p>The alternative is to run the model on the user&rsquo;s phone, so that&rsquo;s what I did.</p>

<h2 class="relative group">Why this is finally practical
    <div id="why-this-is-finally-practical" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#why-this-is-finally-practical" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>A year earlier I wouldn&rsquo;t have bothered, but three things changed roughly at once. Quantised models got small — Qwen 1.7B at Q4_K_M is 1.1 GB, smaller than most games, and it downloads once and lives in app storage. Mobile GPUs got fast — llama.cpp uses Metal on iOS and OpenCL on recent Qualcomm Android GPUs, and on an iPhone 14 Pro I see about 15 tokens a second, plenty for real-time streaming. And small models got genuinely useful: Qwen 1.7B follows structured instructions, parses JSON, and chains multi-step reasoning. That&rsquo;s exactly the profile business logic needs. Nobody&rsquo;s asking it to write poetry.</p>

<h2 class="relative group">Picking a model
    <div id="picking-a-model" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#picking-a-model" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>I tested four small models before settling on Qwen3-1.7B.</p>
<p><strong>TinyLlama 1.1B</strong> (637 MB) was the fastest, but it kept hallucinating customer IDs and dropping required fields — structured output just wasn&rsquo;t reliable. <strong>Phi-3-mini</strong> (1.8 GB) reasons well but wouldn&rsquo;t shut up; simple queries came back as 200-word essays when I needed 20. <strong>Gemma-2B</strong> (1.2 GB) was quick and accurate at classification but weak at function calling — it couldn&rsquo;t consistently produce the <code>&lt;action&gt;</code> tags my tool system needs. <strong>Qwen3-1.7B</strong> (1.1 GB) hit the sweet spot: reliable structured output, precise instruction following, and chain-of-thought support via <code>&lt;think&gt;</code> tags.</p>
<p>Q4_K_M is one of llama.cpp&rsquo;s &ldquo;k-quant&rdquo; formats: weights are stored as 4-bit values in blocks that each carry their own scale, and the M mix keeps a few sensitive tensors at 6-bit. That makes the file about 70% smaller than 16-bit weights for a small quality loss.</p>

<h2 class="relative group">Setting up llama.rn
    <div id="setting-up-llamarn" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#setting-up-llamarn" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>llama.rn wraps llama.cpp for React Native, and installation is the easy part:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">npm install llama.rn
</span></span><span class="line"><span class="cl"><span class="nb">cd</span> ios <span class="o">&amp;&amp;</span> pod install</span></span></code></pre></div></div>
<p>On Expo, llama.rn is a native module, so it won&rsquo;t run in Expo Go. Add its config plugin and use a development build:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-js" data-lang="js"><span class="line"><span class="cl"><span class="c1">// app.config.js
</span></span></span><span class="line"><span class="cl"><span class="kr">export</span> <span class="k">default</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nx">expo</span><span class="o">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nx">plugins</span><span class="o">:</span> <span class="p">[</span><span class="s2">&#34;llama.rn&#34;</span><span class="p">],</span>
</span></span><span class="line"><span class="cl">  <span class="p">},</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span></span></span></code></pre></div></div>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">npx expo install llama.rn
</span></span><span class="line"><span class="cl">npx expo run:ios</span></span></code></pre></div></div>
<p>For production builds, the plugin also adds the two iOS entitlements llama.rn recommends for big models (extended virtual addressing and the increased memory limit).</p>
<p>The model itself downloads on first use:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">MODEL_URL</span> <span class="o">=</span> <span class="s2">&#34;https://huggingface.co/unsloth/Qwen3-1.7B-GGUF/resolve/main/Qwen3-1.7B-Q4_K_M.gguf&#34;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">MODEL_PATH</span> <span class="o">=</span> <span class="nx">FileSystem</span><span class="p">.</span><span class="nx">documentDirectory</span> <span class="o">+</span> <span class="s2">&#34;llama-models/Qwen3-1.7B-Q4_K_M.gguf&#34;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">downloadModel</span> <span class="o">=</span> <span class="kr">async</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="nx">downloadResumable</span> <span class="o">=</span> <span class="nx">FileSystem</span><span class="p">.</span><span class="nx">createDownloadResumable</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="nx">MODEL_URL</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nx">MODEL_PATH</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="p">{},</span>
</span></span><span class="line"><span class="cl">    <span class="p">(</span><span class="nx">progress</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="kr">const</span> <span class="nx">pct</span> <span class="o">=</span> <span class="nx">progress</span><span class="p">.</span><span class="nx">totalBytesWritten</span> <span class="o">/</span> <span class="nx">progress</span><span class="p">.</span><span class="nx">totalBytesExpectedToWrite</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">      <span class="nx">setDownloadProgress</span><span class="p">(</span><span class="nx">pct</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">await</span> <span class="nx">downloadResumable</span><span class="p">.</span><span class="nx">downloadAsync</span><span class="p">();</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span></span></span></code></pre></div></div>
<p>On WiFi that&rsquo;s 2-3 minutes; on LTE more like 5-8. Once it&rsquo;s on disk, load it with GPU acceleration:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">ctx</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">initLlama</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">  <span class="nx">model</span>: <span class="kt">MODEL_PATH</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">n_ctx</span>: <span class="kt">8192</span><span class="p">,</span>      <span class="c1">// 8K context window
</span></span></span><span class="line"><span class="cl">  <span class="nx">n_gpu_layers</span>: <span class="kt">99</span><span class="p">,</span> <span class="c1">// Use GPU for all layers
</span></span></span><span class="line"><span class="cl"><span class="p">});</span></span></span></code></pre></div></div>
<p>Don&rsquo;t skip <code>n_gpu_layers: 99</code>. Offloading everything to Metal or OpenCL instead of the CPU is worth about a 5x speedup.</p>

<h2 class="relative group">Streaming inference
    <div id="streaming-inference" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#streaming-inference" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Nobody wants to stare at a spinner for ten seconds, so responses stream token by token:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kd">let</span> <span class="nx">fullResponse</span> <span class="o">=</span> <span class="s2">&#34;&#34;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">await</span> <span class="nx">llamaContext</span><span class="p">.</span><span class="nx">completion</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">  <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nx">messages</span><span class="o">:</span> <span class="p">[</span>
</span></span><span class="line"><span class="cl">      <span class="p">{</span> <span class="nx">role</span><span class="o">:</span> <span class="s2">&#34;system&#34;</span><span class="p">,</span> <span class="nx">content</span>: <span class="kt">systemPrompt</span> <span class="p">},</span>
</span></span><span class="line"><span class="cl">      <span class="p">{</span> <span class="nx">role</span><span class="o">:</span> <span class="s2">&#34;user&#34;</span><span class="p">,</span> <span class="nx">content</span><span class="o">:</span> <span class="s2">&#34;Create a job for John Smith&#34;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="p">],</span>
</span></span><span class="line"><span class="cl">    <span class="nx">n_predict</span>: <span class="kt">512</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nx">temperature</span>: <span class="kt">0.7</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nx">top_p</span>: <span class="kt">0.8</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="p">},</span>
</span></span><span class="line"><span class="cl">  <span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// Called for each token
</span></span></span><span class="line"><span class="cl">    <span class="nx">fullResponse</span> <span class="o">+=</span> <span class="nx">data</span><span class="p">.</span><span class="nx">token</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="nx">setStreamingText</span><span class="p">(</span><span class="nx">fullResponse</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">);</span></span></span></code></pre></div></div>
<p>On modern phones the first token lands in about 200ms (that&rsquo;s prompt processing) and each token after that takes 50-80ms. Compared to anything network-bound, it feels instant.</p>

<h2 class="relative group">Function calling that small models can actually do
    <div id="function-calling-that-small-models-can-actually-do" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#function-calling-that-small-models-can-actually-do" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The function calling that big cloud models offer leans on JSON schemas, and small models fall over on it — malformed JSON, missing fields, the lot. So I use a simpler XML-based protocol:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">systemPrompt</span> <span class="o">=</span> <span class="sb">`You are an AI assistant. When you need to take an action, output:
</span></span></span><span class="line"><span class="cl"><span class="sb">&lt;action&gt;{&#34;type&#34;:&#34;search_customers&#34;,&#34;query&#34;:&#34;Smith&#34;}&lt;/action&gt;
</span></span></span><span class="line"><span class="cl"><span class="sb">
</span></span></span><span class="line"><span class="cl"><span class="sb">Available actions:
</span></span></span><span class="line"><span class="cl"><span class="sb">- search_customers: {&#34;type&#34;:&#34;search_customers&#34;,&#34;query&#34;:&#34;John&#34;}
</span></span></span><span class="line"><span class="cl"><span class="sb">- create_job: {&#34;type&#34;:&#34;create_job&#34;,&#34;customer_id&#34;:5,&#34;alias&#34;:&#34;Living Room&#34;}
</span></span></span><span class="line"><span class="cl"><span class="sb">- update_job: {&#34;type&#34;:&#34;update_job&#34;,&#34;job_id&#34;:&#34;J-0042&#34;,&#34;status&#34;:&#34;quoting&#34;}
</span></span></span><span class="line"><span class="cl"><span class="sb">
</span></span></span><span class="line"><span class="cl"><span class="sb">Rules:
</span></span></span><span class="line"><span class="cl"><span class="sb">1. ONE action tag per response, at the very end
</span></span></span><span class="line"><span class="cl"><span class="sb">2. When searching/creating → end with &lt;action&gt;
</span></span></span><span class="line"><span class="cl"><span class="sb">3. When just chatting → no action tag
</span></span></span><span class="line"><span class="cl"><span class="sb">`</span><span class="p">;</span></span></span></code></pre></div></div>
<p>XML tags won for boring reasons: <code>&lt;action&gt;</code> and <code>&lt;/action&gt;</code> are unambiguous delimiters, a regex is all the parsing you need, the examples in the prompt double as documentation, and it still works when the model wraps the tag in extra chatter.</p>
<p>Parsing is exactly as dumb as it looks:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kd">function</span> <span class="nx">parseAction</span><span class="p">(</span><span class="nx">text</span>: <span class="kt">string</span><span class="p">)</span><span class="o">:</span> <span class="nx">Action</span> <span class="o">|</span> <span class="kc">null</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="nx">match</span> <span class="o">=</span> <span class="nx">text</span><span class="p">.</span><span class="nx">match</span><span class="p">(</span><span class="sr">/&lt;action&gt;([\s\S]*?)&lt;\/action&gt;/</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">match</span><span class="p">)</span> <span class="k">return</span> <span class="kc">null</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">try</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">match</span><span class="p">[</span><span class="mi">1</span><span class="p">].</span><span class="nx">trim</span><span class="p">());</span>
</span></span><span class="line"><span class="cl">  <span class="p">}</span> <span class="k">catch</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">null</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>When an action comes out, I execute it and feed the result back into the conversation:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">action</span> <span class="o">=</span> <span class="nx">parseAction</span><span class="p">(</span><span class="nx">modelResponse</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="nx">action</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="nx">result</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">executeAction</span><span class="p">(</span><span class="nx">action</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="c1">// Inject result as a system message
</span></span></span><span class="line"><span class="cl">  <span class="nx">conversationHistory</span><span class="p">.</span><span class="nx">push</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">    <span class="nx">role</span><span class="o">:</span> <span class="s2">&#34;user&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nx">content</span><span class="o">:</span> <span class="sb">`[TOOL_RESULT] </span><span class="si">${</span><span class="nx">result</span><span class="p">.</span><span class="nx">message</span><span class="si">}</span><span class="err">\</span><span class="sb">n</span><span class="err">\</span><span class="sb">n→ NEXT: Tell the user what happened.`</span>
</span></span><span class="line"><span class="cl">  <span class="p">});</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="c1">// Continue generation
</span></span></span><span class="line"><span class="cl">  <span class="k">await</span> <span class="nx">generateNextResponse</span><span class="p">();</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span></span></span></code></pre></div></div>
<p>That&rsquo;s enough for proper multi-step workflows:</p>
<p><strong>User</strong>: &ldquo;Create a job for Smith&rdquo;</p>
<ol>
<li><strong>Model</strong>: <code>&lt;action&gt;{&quot;type&quot;:&quot;search_customers&quot;,&quot;query&quot;:&quot;Smith&quot;}&lt;/action&gt;</code></li>
<li><strong>System</strong>: <code>[TOOL_RESULT] Found: Jane Smith (id:42), Bob Smith (id:89)</code></li>
<li><strong>Model</strong>: &ldquo;I found two Smiths—Jane and Bob. Which one?&rdquo;</li>
<li><strong>User</strong>: &ldquo;Jane&rdquo;</li>
<li><strong>Model</strong>: <code>&lt;action&gt;{&quot;type&quot;:&quot;create_job&quot;,&quot;customer_id&quot;:42}&lt;/action&gt;</code></li>
<li><strong>System</strong>: <code>[TOOL_RESULT] Job J-0073 created</code></li>
<li><strong>Model</strong>: &ldquo;Done! Created job J-0073 for Jane Smith.&rdquo;</li>
</ol>

<h2 class="relative group">Chain-of-thought with &lt;think&gt; tags
    <div id="chain-of-thought-with-think-tags" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#chain-of-thought-with-think-tags" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>Small models do noticeably better when you make them reason out loud. Qwen has a thinking mode built in:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">systemPrompt</span> <span class="o">=</span> <span class="sb">`Before each response, wrap your reasoning in &lt;think&gt; tags:
</span></span></span><span class="line"><span class="cl"><span class="sb">
</span></span></span><span class="line"><span class="cl"><span class="sb">&lt;think&gt;
</span></span></span><span class="line"><span class="cl"><span class="sb">INTENT: what does the user want?
</span></span></span><span class="line"><span class="cl"><span class="sb">HAVE: what data do I already have?
</span></span></span><span class="line"><span class="cl"><span class="sb">NEED: what&#39;s still missing?
</span></span></span><span class="line"><span class="cl"><span class="sb">DECISION: call tool | ask user | just respond
</span></span></span><span class="line"><span class="cl"><span class="sb">&lt;/think&gt;
</span></span></span><span class="line"><span class="cl"><span class="sb">
</span></span></span><span class="line"><span class="cl"><span class="sb">Then output your actual response.`</span><span class="p">;</span></span></span></code></pre></div></div>
<p>What the model produces internally looks like this:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">&lt;think&gt;
</span></span><span class="line"><span class="cl">INTENT: create a job
</span></span><span class="line"><span class="cl">HAVE: customer query &#34;Smith&#34;
</span></span><span class="line"><span class="cl">NEED: exact customer_id
</span></span><span class="line"><span class="cl">DECISION: search first
</span></span><span class="line"><span class="cl">&lt;/think&gt;
</span></span><span class="line"><span class="cl">&lt;action&gt;{&#34;type&#34;:&#34;search_customers&#34;,&#34;query&#34;:&#34;Smith&#34;}&lt;/action&gt;</span></span></code></pre></div></div>
<p>I strip the <code>&lt;think&gt;</code> tags before anything hits the UI, but leave them visible during development. The reliability difference is dramatic — the model talks itself through the logic before committing to an action.</p>

<h2 class="relative group">Keeping long conversations inside 8K
    <div id="keeping-long-conversations-inside-8k" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#keeping-long-conversations-inside-8k" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The 8K context window fills up faster than you&rsquo;d think once tool results start piling in. Around 30 turns, I hit the wall.</p>
<p>My fix is conversation compaction — I ask the model to summarise itself:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">compactPrompt</span> <span class="o">=</span> <span class="sb">`Summarize this conversation in under 200 words.
</span></span></span><span class="line"><span class="cl"><span class="sb">Include: user&#39;s goal, customers/jobs created (with IDs), and any unfinished tasks.
</span></span></span><span class="line"><span class="cl"><span class="sb">
</span></span></span><span class="line"><span class="cl"><span class="si">${</span><span class="nx">conversationHistory</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">m</span> <span class="o">=&gt;</span> <span class="sb">`</span><span class="si">${</span><span class="nx">m</span><span class="p">.</span><span class="nx">role</span><span class="si">}</span><span class="sb">: </span><span class="si">${</span><span class="nx">m</span><span class="p">.</span><span class="nx">content</span><span class="si">}</span><span class="sb">`</span><span class="p">).</span><span class="nx">join</span><span class="p">(</span><span class="s1">&#39;\n\n&#39;</span><span class="p">)</span><span class="si">}</span><span class="sb">`</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">summary</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">chat</span><span class="p">([{</span> <span class="nx">role</span><span class="o">:</span> <span class="s2">&#34;user&#34;</span><span class="p">,</span> <span class="nx">content</span>: <span class="kt">compactPrompt</span> <span class="p">}]);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// Replace history with summary
</span></span></span><span class="line"><span class="cl"><span class="nx">conversationHistory</span> <span class="o">=</span> <span class="p">[</span>
</span></span><span class="line"><span class="cl">  <span class="p">{</span> <span class="nx">role</span><span class="o">:</span> <span class="s2">&#34;user&#34;</span><span class="p">,</span> <span class="nx">content</span><span class="o">:</span> <span class="sb">`[CONTEXT SUMMARY]</span><span class="err">\</span><span class="sb">n</span><span class="si">${</span><span class="nx">summary</span><span class="si">}</span><span class="err">\</span><span class="sb">n[END SUMMARY]`</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">];</span></span></span></code></pre></div></div>
<p>A 50-message conversation squeezes down to about 150 tokens, and the model carries on without losing track of which jobs and customer IDs it created.</p>

<h2 class="relative group">Saving sessions
    <div id="saving-sessions" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#saving-sessions" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>I also save chat sessions to the app&rsquo;s backend. The one idea worth copying is to store every assistant message twice: once cleaned up for display, and once raw, with the <code>&lt;think&gt;</code> and <code>&lt;action&gt;</code> tags left in. History then replays cleanly in the UI, while a resumed session gets the full context back, actions and all. Users switch between past conversations from a history dropdown, the way most chat apps work.</p>

<h2 class="relative group">Benchmarks from production
    <div id="benchmarks-from-production" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#benchmarks-from-production" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p><strong>iPhone 14 Pro</strong> (A16 Bionic, 6GB RAM):</p>
<ul>
<li>Model load: ~3 seconds</li>
<li>First token: 180-220ms</li>
<li>Streaming: 14-16 tokens/sec</li>
<li>Memory: ~1.8 GB</li>
</ul>
<p><strong>Samsung Galaxy S23</strong> (Snapdragon 8 Gen 2, 8GB RAM):</p>
<ul>
<li>Model load: ~4 seconds</li>
<li>First token: 250-300ms</li>
<li>Streaming: 10-12 tokens/sec</li>
<li>Memory: ~2.1 GB</li>
</ul>
<p><strong>iPhone 11</strong> (A13, 4GB RAM):</p>
<ul>
<li>Model load: ~6 seconds</li>
<li>First token: 400-500ms</li>
<li>Streaming: 6-8 tokens/sec</li>
<li>Memory: ~2.2 GB (occasionally crashes on low memory)</li>
</ul>
<p>My rule of thumb: 6GB+ RAM for a smooth experience. It runs on 4GB, but you&rsquo;ll probably need to unload the model when the app backgrounds.</p>

<h2 class="relative group">Memory management
    <div id="memory-management" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#memory-management" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>iOS will happily kill your app for hoarding memory, so I release the model whenever the app leaves the foreground:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="nx">useEffect</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="kr">const</span> <span class="nx">subscription</span> <span class="o">=</span> <span class="nx">AppState</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s2">&#34;change&#34;</span><span class="p">,</span> <span class="p">(</span><span class="nx">nextAppState</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="nx">nextAppState</span> <span class="o">===</span> <span class="s2">&#34;background&#34;</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nx">llamaContext</span><span class="o">?</span><span class="p">.</span><span class="nx">release</span><span class="p">();</span> <span class="c1">// Free ~2 GB
</span></span></span><span class="line"><span class="cl">    <span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">nextAppState</span> <span class="o">===</span> <span class="s2">&#34;active&#34;</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nx">loadModel</span><span class="p">();</span> <span class="c1">// Reload when foregrounded
</span></span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">});</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="k">return</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="nx">subscription</span><span class="p">.</span><span class="nx">remove</span><span class="p">();</span>
</span></span><span class="line"><span class="cl"><span class="p">},</span> <span class="p">[]);</span></span></span></code></pre></div></div>

<h2 class="relative group">Battery impact
    <div id="battery-impact" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#battery-impact" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>On-device inference isn&rsquo;t free, power-wise. From real-world testing:</p>
<table>
	<thead>
			<tr>
					<th>Usage Pattern</th>
					<th>Extra Battery Drain</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Light (5-10 queries/day)</td>
					<td>&lt;1% per day</td>
			</tr>
			<tr>
					<td>Medium (20-30 queries/day)</td>
					<td>~3-4% per day</td>
			</tr>
			<tr>
					<td>Heavy (50+ queries/day)</td>
					<td>~6-8% per day</td>
			</tr>
	</tbody>
</table>
<p>GPU inference draws more power than CPU but finishes much sooner, and users clearly prefer the instant response, so I&rsquo;ve kept it.</p>

<h2 class="relative group">Two months in, with ~200 beta users
    <div id="two-months-in-with-200-beta-users" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#two-months-in-with-200-beta-users" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>The query breakdown surprised me a little:</p>
<ol>
<li>&ldquo;Create a job for [customer name]&rdquo; - 68% of queries</li>
<li>&ldquo;Find jobs for [customer]&rdquo; - 15%</li>
<li>&ldquo;Update job [ID] to [status]&rdquo; - 9%</li>
<li>General questions about the app - 8%</li>
</ol>
<p>91% of queries succeed on the first try. The failures split into customer not found because the user misspelled the name (4%), context overflow in very long conversations (3%), and the model inventing customer IDs (2%).</p>
<p>That last one used to be much worse. Hallucinated IDs mostly disappeared once I made tool results explicit — returning <code>customer_id=42</code> rather than prose. Small models need that scaffolding spelled out.</p>

<h2 class="relative group">What it costs
    <div id="what-it-costs" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#what-it-costs" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>On-device: $0/month infrastructure, $0 per user beyond the one-time 1.1 GB download, and it scales to as many users as care to install the app.</p>
<p>The cloud version, roughly estimated: an average conversation is ~2,000 tokens, and 200 users at 30 conversations a month is 6,000 conversations — 12M tokens/month. That&rsquo;s about $18/month on a budget cloud model, and $180-360/month on the top-tier ones. Not ruinous at this scale, but the on-device approach paid for itself on day one, and at 10,000 users it would still cost nothing.</p>

<h2 class="relative group">Limitations worth knowing
    <div id="limitations-worth-knowing" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#limitations-worth-knowing" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p><strong>Model capabilities.</strong> Qwen 1.7B is great at structured tasks and terrible at complex multi-hop reasoning, factual recall (it&rsquo;s not a search engine), creative writing, and nuance. Design features around what small models do well and you&rsquo;ll be fine.</p>
<p><strong>Device requirements.</strong> Minimum is 3 GB RAM and 2 GB free storage; realistically you want 6 GB RAM, a 64-bit processor, and GPU support. Older devices like the iPhone 8 or Galaxy S9 struggle — do feature detection and fall back gracefully.</p>
<p><strong>Model updates.</strong> Shipping a new model means users re-download 1.1 GB. I version the model in the storage path:</p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">MODEL_PATH</span> <span class="o">=</span> <span class="sb">`</span><span class="si">${</span><span class="nx">FileSystem</span><span class="p">.</span><span class="nx">documentDirectory</span><span class="si">}</span><span class="sb">llama-models/v2/Qwen3-1.7B-Q4_K_M.gguf`</span><span class="p">;</span></span></span></code></pre></div></div>
<p>Bump the path for each new model version. Old models clean themselves up on uninstall.</p>

<h2 class="relative group">iOS vs Android
    <div id="ios-vs-android" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#ios-vs-android" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>iOS on Metal is around 20% faster than Android, manages memory better, and backs the model up to iCloud by default (disable that with <code>NSURLIsExcludedFromBackupKey</code> unless you want to eat users&rsquo; backup quota). Android varies a lot more across devices — llama.rn&rsquo;s GPU path is OpenCL on Qualcomm Adreno 700-series GPUs, and phones without one run on the CPU — and storage isn&rsquo;t backed up automatically. Test on both; the gap between a good and bad Android device is bigger than the gap between platforms.</p>

<h2 class="relative group">Debugging tips
    <div id="debugging-tips" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#debugging-tips" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p><strong>1. Enable verbose logging</strong></p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">ctx</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">initLlama</span><span class="p">({</span>
</span></span><span class="line"><span class="cl">  <span class="nx">model</span>: <span class="kt">MODEL_PATH</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">n_ctx</span>: <span class="kt">8192</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">n_gpu_layers</span>: <span class="kt">99</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">  <span class="nx">verbose</span>: <span class="kt">true</span><span class="p">,</span> <span class="c1">// Logs every token + timings
</span></span></span><span class="line"><span class="cl"><span class="p">});</span></span></span></code></pre></div></div>
<p><strong>2. Track token counts</strong></p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">tokens</span> <span class="o">=</span> <span class="nx">fullResponse</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="sr">/\s+/</span><span class="p">).</span><span class="nx">length</span> <span class="o">*</span> <span class="mf">1.3</span><span class="p">;</span> <span class="c1">// Rough estimate
</span></span></span><span class="line"><span class="cl"><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="sb">`Generated </span><span class="si">${</span><span class="nx">tokens</span><span class="si">}</span><span class="sb"> tokens in </span><span class="si">${</span><span class="nx">duration</span><span class="si">}</span><span class="sb">ms`</span><span class="p">);</span></span></span></code></pre></div></div>
<p><strong>3. Monitor memory</strong></p>
<div class="highlight-wrapper"><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-typescript" data-lang="typescript"><span class="line"><span class="cl"><span class="kr">import</span> <span class="p">{</span> <span class="nx">MemoryInfo</span> <span class="p">}</span> <span class="kr">from</span> <span class="s1">&#39;react-native-device-info&#39;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">memoryUsage</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">MemoryInfo</span><span class="p">.</span><span class="nx">getUsedMemory</span><span class="p">();</span>
</span></span><span class="line"><span class="cl"><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="sb">`Memory: </span><span class="si">${</span><span class="p">(</span><span class="nx">memoryUsage</span> <span class="o">/</span> <span class="mi">1024</span> <span class="o">/</span> <span class="mi">1024</span><span class="p">).</span><span class="nx">toFixed</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span><span class="si">}</span><span class="sb"> MB`</span><span class="p">);</span></span></span></code></pre></div></div>
<p><strong>4. Test offline</strong></p>
<p>Flip on airplane mode and use the app properly. The model should load from cache, inference should complete, and only the backend persistence should fail — gracefully.</p>

<h2 class="relative group">Where I want to take it
    <div id="where-i-want-to-take-it" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#where-i-want-to-take-it" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>llama.cpp already supports vision models, and &ldquo;here&rsquo;s a photo from the site, add it to the job&rdquo; is an obvious fit for this app. I&rsquo;d also like to try fine-tuning a LoRA adapter on past job descriptions — my guess is 20-30% better accuracy on domain queries. Further out: an on-device speech-to-text model for a fully offline voice interface, and maybe federated learning so the model improves across users without any raw data leaving their phones.</p>

<h2 class="relative group">Should you build this?
    <div id="should-you-build-this" class="anchor"></div>
    
    <span
        class="absolute top-0 w-6 transition-opacity opacity-0 -start-6 not-prose group-hover:opacity-100 select-none">
        <a class="text-primary-300 dark:text-neutral-700 !no-underline" href="#should-you-build-this" aria-label="Anchor">#</a>
    </span>
    
</h2>
<p>If you&rsquo;re building a business app with sensitive data, offline-first workflows, or structured tasks like classification and data entry — and especially if API costs at scale worry you — yes, this works today.</p>
<p>If you need open-ended chat, use one of the big cloud models. Same if the task is knowledge-heavy (small models simply don&rsquo;t know much), if you must support low-end devices, or if your domain knowledge changes faster than you can ship model updates.</p>
<p>The whole thing took me about 12 hours to build. It costs $0 a month to run, works on a plane, and the customer data never leaves the customer&rsquo;s hand. Hard to argue with.</p>
<hr>
<p><em>Questions? Feedback? I&rsquo;m <a href="https://twitter.com/jaredlynskey"  target="_blank" rel="noreferrer">@jaredlynskey</a>. The llama.rn library is at <a href="https://github.com/mybigday/llama.rn"  target="_blank" rel="noreferrer">github.com/mybigday/llama.rn</a>.</em></p>
]]></content:encoded>
      <media:content url="https://jared.lynskey.co.nz/en/posts/2026/2026-01-30-on-device-ai/featured.jpg" medium="image" type="image/jpeg" />
    </item>
  </channel>
</rss>
