Case-Study: How I Made an Entire Healthcare App Available Offline Without Changing the Backend Architecture
Table of contents
- Background
- The TanStack Query approach
- Changing course
- Architecture
- Trade-offs
- Collecting the API URLs
- Sorting them by page
- Replacing the IDs with variables
- Mapping the pages to a tree
- The sequence, step by step
- When the sequence runs
- Fetching
- Caching
- Reading from the cache
- What it looks like now
Background
The app was already in the middle of development when the request came in: make it work fully when the device goes offline. Not a cached dashboard, not a read-only mode. Everything a user does on a shift, with no network.
The system behind it is big. The app and its backend infrastructure are the result of 2+ years of work by a team of 10+ developers, and neither was designed with offline in mind. Restructuring the whole project was not an option, and neither was changing much in the backend. The mobile team was asked to work out what could be done with the backend left as it was, and I was asked to figure out the answer.
Offline splits into two problems: having the data on the device before the network disappears, and getting the user's actions back to the server once it returns. The first one gates everything else. A user cannot record a medication they cannot see, so before any offline action was possible, every piece of data the app might show had to already be on the device. That is why offline prefetch was the first requirement of the offline work, and it is what this case study covers.
The TanStack Query approach
The app already used TanStack Query for every read, so the first idea was the obvious one: use what was already there. TanStack Query can prefetch a query before any screen asks for it, and it can persist its cache to disk and rehydrate it on the next launch. If I could list every query the app might make, prefetch them all while the device was online, and persist the cache to MMKV or AsyncStorage, then every screen would show cached data.
I started building it with TanStack Query's prefetchQuery and each query's queryKey.
While building it I found a few problems with this approach:
- Dynamic query keys. Nested pages such as resident details and the medication pages are keyed by IDs that only exist once the list above them has been fetched, so at launch
prefetchQueryhad nothing to call them with. - MMKV crashed under a very large cache. MMKV is memory-mapped on purpose, built for small values that are read often, so once a few prefetch runs had grown the persisted cache to many megabytes it could not hold it.
- No guarantee of an immediate cache write. Not every API result was in the persisted cache straight away. Killing the app lost the latest data, and opening it on another day showed no persisted data at all.
Changing course
I debugged, modified the query client config, switched to AsyncStorage, and then, rather than keep spending time on it, took some decisions:
- API collection. I decided to collect every API the app calls, including the nested ones that only become reachable once a list has been fetched.
- Manual prefetch. I decided to run my own prefetch, one that iterates through the whole API collection on app startup and runs again after a set interval.
- Persistence. I decided to write my own cache persister, so that every response that lands gets cached, with no step in between that can skip one.
- Storage. I decided to create a SQLite database with a key-value table for the large blobs that were crashing MMKV.
Architecture
Before the pieces, the whole. Read it top to bottom: the API collection is recorded while the app is used in development and shipped inside the build; at runtime a background service walks a tree of pages, expands each page's URL templates with the IDs discovered above it, and fetches them one at a time; every successful response lands in one shared cache; and the screens read from that same cache, by the same key, before they ever touch the network.
Trade-offs
Offline here means the last copy that reached the cache, and some data stops being right while it waits on the device. These were the known limits when it shipped:
- Data tied to a date. Some URLs carry today's date, so a run fetches today's data. The next day the same screen asks for the next day's URL, and nothing in the cache answers it until a run has gone through online that day.
- Data that changes by the minute. Some lists move on their own. A medication due at 6:00 is listed as missed at 6:01, and a copy cached before then still shows it as due.
- Changes made on another phone. When one user administers a medication, another user does not see it until the change has synced to the server and travelled to the second phone. Here that was safe: each resident had only one nurse, so two people were never working from the same list.
So it was delivered as a temporary solution for one gap: a resident whose room is out of Wi-Fi range. The nurse can carry on with the administration inside the room, and stepping back out into range syncs it straight away.
Collecting the API URLs
Everything downstream depends on knowing what the app asks for, so that was the first thing to build. I did not trust a list written by hand to be complete after 2+ years and 10+ developers of screens, or to stay complete for long. So the app records it.
In a development build, the data layer's request adapter logs every GET it sends, keyed by the page the user is on at that moment:
const recordRequest = (fullUrl: string, method: string) => {
if (!__DEV__ || method.toLowerCase() !== "get") return;
const page = currentPage();
if (!collection.has(page)) collection.set(page, new Set());
collection.get(page)!.add(fullUrl);
flushSoon(); // batched, a moment after the last request lands
};
Nothing is decided at this point. Whatever the screens request while the app is used in development is written down, together with the page that was open when it happened. The recorder batches its entries and sends them to a small remote collection, so every development session contributes and the list grows without anybody maintaining it. A release build records nothing.
Sorting them by page
The collection keeps one document per page: the page's route, and the set of URLs that page has been seen to request. New recordings merge into the document, so a URL is listed once no matter how many sessions hit it. The page is the unit for everything that follows. It is where the IDs for the pages below it come from, it is what the walk visits in order, and it is what the user is told about as the run reaches it.
Page by page, the collection looks like this:
{
"/residents": [
"https://api-dev.example.org/v1/residents?siteId=42&page=1",
"https://api-dev.example.org/v1/residents?siteId=42&page=2"
],
"/residents/residentId": [
"https://api-dev.example.org/v1/residents/8f3a1c?siteId=42",
"https://api-dev.example.org/v1/medications?residentId=8f3a1c&siteId=42&page=1",
"https://api-dev.example.org/v1/medications?residentId=c07d9e&siteId=42&page=3"
],
"/residents/residentId/body-map": [
"https://api-dev.example.org/v1/medications/5d21/body-map?residentId=8f3a1c&siteId=42&date=2026-09-30"
]
}
Those are real requests: a real host, real IDs, the date that was on screen, whichever page of a list had been scrolled to. That is the point and it is also the problem. The collection is complete because it is real traffic, and it is useless as-is for the same reason. The user who installs the release build is on a different host, a different site, looks after different residents, and is working today.
Before a release I copy the collection into a map committed with the app. A release build reads only that map and never the remote collection.
Replacing the IDs with variables
So when the service loads the collection, it rewrites every URL into a template. The committed map already holds the rewritten form, and the rewrite leaves a template alone, so one code path serves both. Three rewrites:
- The host is swapped for the one this build talks to.
- Page numbers are reset to 1, so every list starts from the top. Pagination is followed at fetch time instead.
- IDs and dates become placeholders. A rule list maps each variable to the URL shapes it appears in. A resident ID shows up in a dozen shapes, as a path segment under several prefixes and as a query parameter, so that variable has a dozen patterns. A date becomes today, in whichever of the two formats the API uses in that URL, so a URL recorded last Tuesday asks for today's data when it runs.
const variablePatterns: Record<string, RegExp[]> = {
siteId: [/siteId=([\w-]+)/g],
residentId: [/\/residents\/([\w-]+)/g, /residentId=([\w-]+)/g],
medicationId: [/\/medications\/([\w-]+)\/body-map/g],
today: [/(\d{4}-\d{2}-\d{2})/g],
reversedToday: [/(\d{2}-\d{2}-\d{4})/g],
};
const toTemplate = (url: string) =>
Object.entries(variablePatterns).reduce(
(acc, [name, patterns]) =>
patterns.reduce((u, re) => u.replace(re, (m, id) => m.replace(id, `{{${name}}}`)), acc),
url.replace(/api-\w+\./, `api-${env}.`).replace(/page=\d+/g, "page=1"),
);
Duplicates collapse. The six recorded URLs become four templates:
https://api-prod.example.org/v1/residents?siteId={{siteId}}&page=1
https://api-prod.example.org/v1/residents/{{residentId}}?siteId={{siteId}}
https://api-prod.example.org/v1/medications?residentId={{residentId}}&siteId={{siteId}}&page=1
https://api-prod.example.org/v1/medications/{{medicationId}}/body-map?residentId={{residentId}}&siteId={{siteId}}&date={{today}}
A template is only useful once something fills the placeholders in. The site, the user and the date are known before a run starts. A resident ID is not. It exists only in the response of the residents list, which is the same wall prefetchQuery ran into. The difference is that this time the walk is mine to design.
Mapping the pages to a tree
Pages form a tree because the data does. The dashboard belongs to a site, the site has residents, a resident has medication pages, a medication has a body map. A child page's URLs need IDs that only exist in a parent page's responses, so the pages are arranged in a tree, written by hand, one node per page. A node names its route, which is also its key into the collection, the pages whose IDs it may use, and how to pull the IDs its own children need out of its responses:
const sequence: PageNode = {
href: "/",
children: [
{
href: "/residents",
dataMapping: { "/v1/residents?": { residentId: ["data[].id"] } },
children: [
{
href: "/residents/residentId",
contexts: ["/residents"],
dataMapping: {
"/v1/medications?residentId=": {
medicationId: ["data[].id"],
residentMedication: (res) => res.data.map((m) => `${m.residentId}|${m.id}`),
},
},
children: [
{ href: "/residents/residentId/body-map", contexts: ["/residents/residentId"] },
],
},
],
},
{
href: "/vitals",
dataMapping: { "/v1/vitals/residents": { residentId: ["data[].id"] } },
children: [{ href: "/vitals/residentId", contexts: ["/vitals"] }],
},
],
};
dataMapping is keyed by URL prefix, so a page with five URLs can say which one its children's IDs come from. The resident page above lists two URLs, the profile and the medication list, and the prefix picks out the second. An extractor is a path such as data[].id or, for the shapes a path cannot express, a function. The function above returns a resident and a medication joined into one value, which matters in a moment.
The IDs live in a context store. A run begins by seeding a global context with the site ID, the user ID and today's date in the two formats the API accepts, each resolved lazily the first time a template asks for it. Every page then has a bucket of its own, variable name to list of values. When a page is processed it reads the global context plus the buckets of the pages it names in contexts, with self standing for its own:
function contextFor(page: PageNode): Record<string, Set<string>> {
const keys = ["global", ...(page.contexts ?? [])].map((k) => (k === "self" ? page.href : k));
return merge(...keys.map((k) => store[k] ?? {}));
}
The declaration is explicit. A page reads what it names and nothing else, so an ID discovered on the residents list reaches the body map two levels down because the body map asks for its parent's bucket, and the two sibling lists above, which both extract a resident ID, never see each other's values.
The sequence, step by step
The engine walks the tree depth first. I wrote the walk as recursion first, and it overflowed the call stack. I tried breadth first, which fetched every list before any detail, and settled on depth first with an explicit stack: no recursion, and a list's details follow right behind it. The abort signal is checked before every fetch, so a run stops within one request of being told to:
const stack: PageNode[] = [sequence];
while (stack.length) {
const page = stack.pop()!;
await runPage(page, collection[page.href] ?? [], signal);
stack.push(...(page.children ?? []));
}
Everything interesting happens inside runPage. For each page it pops:
-
Split the page's URLs into independent and dependent. A page sometimes lists two URLs where the second needs an ID from the first, so there is a rule list, keyed by URL prefix, that says B depends on A when both are present on the page. Dependent URLs are parked. If a page is left with only dependent URLs, that is a cycle, and the page is skipped rather than looped on.
-
Read the contexts this page declares, the global context plus the buckets it names, into one map of variable name to values.
-
Expand each template into concrete URLs. By default every placeholder is replaced by every value it has, a cartesian product. For variables that only make sense together, a generator registered against that template splits the joined values a parent page wrote in its step 5 back into their parts instead. A resident ID and a medication ID are such a pair: the product would request every medication against every resident, which is a wall of 404s. A placeholder with no values yields no URLs at all, so a URL that would still hold a placeholder is dropped, because nothing above it provided that value.
function expand(template: string, ctx: Record<string, Set<string>>): string[] { const vars = [...template.matchAll(/\{\{(\w+)\}\}/g)].map((m) => m[1]); return product(vars.map((v) => [...(ctx[v] ?? [])])).map((values) => vars.reduce((url, v, i) => url.replaceAll(`{{${v}}}`, values[i]), template), ); } -
Fetch the URLs, one at a time. Not in parallel, by choice. The backend could not change, and I did not want every device opening a burst of parallel requests against it. Each URL is fetched once per run: the first time in network-only mode, later meetings in cache-only. A failed URL is skipped and the run moves on, with two exceptions that end the run instead: the network is gone, or the server has rejected the refresh token, and neither will get better by continuing. A paginated response is followed to its last page and the pages are merged, so the
page=1template still yields the full list. -
Extract IDs from the responses with the page's
dataMapping, matched by URL prefix, and write them into this page's bucket for its children. -
Release the parked URLs into the same steps, now with the richer context. When none are left, the page is done, and the next one comes off the stack.
That is the whole engine. The collection says what the app asks for, the page tree says in what order the answers become available, and the context store carries the IDs downward.
When the sequence runs
The scheduler is the part that decides when a run is a good idea. It wakes up whenever the current page or the connectivity changes, and reads the user session and the selected site each time. If there is no user or no network, it aborts whatever is running and stands down. If the site is unchanged, a run is already in progress or throttled, and the last run did not end in an error, it does nothing. Otherwise it aborts the run in progress, if any, and starts a fresh one. The engine itself only runs in release builds. A development build records and does not prefetch.
It does not start the moment the conditions hold. At launch the inputs change several times in a row, as the session is restored, the site is selected and the first screen renders, so the scheduler loads the collection and then waits for ten seconds of quiet before starting. Each run gets an abort controller that is passed down to every fetch, and the next run is throttled for five minutes after one finishes.
A site switch is the case that matters most. Stopping is not enough. The context store holds the old site's residents, so the run begins again from the seed.
The user sees two things. A small icon in the header shows the state at a glance: a clock while a run is in progress, a tick when it finished, a warning when it failed. A toast names each page as the run reaches it. On a shift the tick is the one that matters. It is the answer to "is it safe to walk out of Wi-Fi range yet".
Fetching
Every URL the engine produces goes through the same cache interceptor the screens' requests end up in. It decides whether a request is cacheable at all, GET or HEAD and not an auth endpoint, and if it is, it reads and writes the cache around the call. Which way it leans is a mode the caller passes in:
async function intercept(config: Request, mode: CacheMode, next: (c: Request) => Promise<Response>) {
if (!isCacheable(config)) return next(config);
const key = sha256(JSON.stringify({ url: config.url, method: config.method }));
const fetchAndStore = async () => {
const response = await next(config);
if (response.status === 200) saveToCache(key, response);
return response;
};
if (mode === "network-only") return fetchAndStore();
const cached = await getFromCache(key);
try {
if (cached && mode === "cache-only") return cached;
if (cached) {
if (!refreshing.has(key)) {
refreshing.add(key); // one background refresh per key per few seconds
setTimeout(() => refreshing.delete(key), 3000);
void fetchAndStore().then((fresh) => notifyScreens(config.url, fresh)).catch(() => {});
}
return cached;
}
return await fetchAndStore();
} catch (error) {
if (cached) return cached;
throw error;
}
}
The three modes map onto the two callers:
- network-only is what the prefetch uses the first time it meets a URL in a run. Always fetch, store on 200.
- cache-only is what the prefetch uses when it meets the same URL again in the same run. Return the cached copy, fetch only if there is none.
- cache-first is what the screens use. A hit is returned immediately and refreshed in the background, at most once every few seconds per key. A miss goes to the network. A network error falls back to the cached copy.
The key is a hash of the URL and the method, and nothing else. That is the only contract between the prefetch service and the screens. If both sides build the same URL, they share the cache row. There are no query keys to register, no mapping table to keep in sync, and a screen nobody told the service about still gets a hit as long as the URL it asks for has been fetched.
Underneath the interceptor sits the HTTP client the app already had. It adds the auth header, and when the server rejects the token it refreshes and retries the request once. One detail I had to get right here: a single refresh is in flight at a time, requests that fail meanwhile wait behind it and retry with the new token, and the result is reused for five minutes. Without that, a prefetch run that meets an expired token would start one refresh per URL.
Caching
MMKV is memory-mapped, which is exactly right for a few hundred small settings and exactly wrong for a cache that holds a whole site's worth of API responses. SQLite is built for large rows and for transactions, so the cache moved there. In front of it sits a layer that keeps the disk out of the hot path:
const memory = new Map<string, CachedResponse>();
async function getFromCache(key: string) {
const hit = memory.get(key);
if (hit) return hit;
const stored = await storage.getItem(key);
if (!stored) return null;
memory.set(key, stored); // warm memory on the way back
return stored;
}
function saveToCache(key: string, response: CachedResponse) {
if (isSameAsCached(key, response)) return; // unchanged payload, no write
memory.set(key, response);
debounce(key, () => storage.setItem(key, response), 3000);
}
Reads check memory first and only then the disk, warming memory as they return. Writes land in memory immediately, which is what a screen reads a moment later, and reach the disk three seconds after the last change to that key, so a URL refetched twice in a row costs one write. A response whose payload matches what is already cached is not written at all. The comparison skips the envelope, because a server nonce that changes on every call would otherwise make every response look new.
The schema underneath is as small as it can be, one table with two columns:
create table if not exists keyval (
key text not null primary key,
value text not null
);
Keys carry a namespace prefix, [apiCache] for the response cache, so the same table can serve other uses without the two colliding, and one like query clears a namespace without touching the rest. Writing is an upsert, so a refreshed response replaces the old row in place:
upsert(key: string, value: string) {
writer.mutate(
`insert into keyval (key, value) values (?, ?)
on conflict(key) do update set value = excluded.value;`,
[key, value],
);
}
writer is the part that made the difference. A prefetch run produces hundreds of writes in a short burst, and one round trip per write is the slowest way to use SQLite. So writes never go to the database directly. They wait in a buffer, and the buffer flushes as one batch after a second of quiet, or as soon as sixteen are waiting, whichever comes first:
class BatchedWriter {
private pending: Array<{ query: string; params: unknown[] }> = [];
private timer: ReturnType<typeof setTimeout> | null = null;
constructor(private db: Database, private delay = 1000, private batchSize = 16) {}
mutate(query: string, params: unknown[]) {
this.pending.push({ query, params });
if (this.timer) {
if (this.pending.length >= this.batchSize) return; // a flush is already due
clearTimeout(this.timer);
}
this.timer = setTimeout(() => this.flush(), this.delay);
}
private async flush() {
this.timer = null;
await this.db.executeBatchAsync(this.pending.splice(0)); // one batch, one round trip
}
}
The database runs in WAL mode with a busy timeout, so a read never blocks on a write in progress, and each JS runtime opens its own connection, because a reload or a background task would otherwise fight the foreground over one handle.
Reading from the cache
The screens did not change. The query layer did not change. Everything the offline work needed sits in the network layer under them, as three layers, two enhancers around the fetch at the bottom:
- Throttle. Identical requests within one second share one call.
- Cache, in cache-first mode. A hit is returned at once and refreshed behind it. A miss fetches. An error falls back to the cached copy.
- Fetch. If the device has no network, fail fast instead of waiting for a timeout, so the cache enhancer can answer. Otherwise add the auth header and the client ID and go. In a development build this is also where the recorder lives.
When a hit was served and the background refetch brings back something new, the enhancer emits the fresh response by URL, the query layer writes it into the query for that URL, and the screen re-renders. The cache key is the same hash the prefetch wrote. A screen's URL and the prefetch's expanded URL are the same string, so they land on the same row, and the first thing a screen does offline is read what the run put there.
What it looks like now
Open the app with the network off and every page the run has walked shows its data, through the same screens and the same queries as before. The backend did not change. No endpoint was added for the app, and no response shape was altered.
Adding a page to the offline set is three steps: use it in a development build so its requests are recorded, add it to the page tree with its contexts and extractors, and copy the collection into the committed map before the release.
Prefetch is half of offline. The other half, sending the user's offline actions back to the server once the network returns, has its own problems. I will share that one another day.
If you want to comment or ask about any of this, the discussion is on the Facebook post: