Offline-first: the app always answers from the phone, the network updates later
An offline-first app always reads and writes on the device and uses the network only to line up with the server. A student who opens a lesson on the subway finds it there; one who completes a quiz without coverage sees it recorded and the server receives it later. Getting there takes three pieces with distinct responsibilities: a Service Worker that decides where to answer requests from, a local database (IndexedDB) that keeps the data and the pending writes, and a merge rule for when the two worlds meet and disagree.
I am not quoting figures on how much offline-first apps "pay off": the engagement percentages that circulate have no primary source I could open. The argument that holds is simpler: if some of your students have an intermittent connection, a lesson that will not open without a network is a certain failure, while one that opens and syncs later is at worst slow. The listings were run with Node 24, Dexie 4.4.7 on fake-indexeddb 6.2.8 (an in-memory IndexedDB, not the browser) and Python 3.14. A real Service Worker needs a browser: its configuration is a schema to adapt, and I test the strategies with a simulation. The previous article, Real-Time Collaboration in EdTech, covers who edits the same document at the same time; here the conflicts are between a device and the server.
Three cache strategies: when the network is slow or absent
Workbox, Google's library for Service Workers, offers ready-made strategies. The choice changes what the student sees in three conditions: online, on a very slow network and with no network. The listing rewrites the documented logic of three strategies in a few lines, with a cache that already holds version
v1 while the server has v2, and shows what each one answers.
// The three cache strategies as Workbox reads them, on a simulated cache and network
const scenari = {
'online': () => Promise.resolve('v2'),
'slow (300 ms)': () => new Promise((r) => setTimeout(() => r('v2'), 300)),
'offline': () => Promise.reject(new Error('offline')),
};
const conTimeout = (p, ms) => Promise.race([p, new Promise((_, no) => setTimeout(() => no(new Error('timeout')), ms))]);
const cacheFirst = async (cache, rete) => {
if (cache.has('k')) return { risposta: cache.get('k'), da: 'cache' };
const r = await rete(); cache.set('k', r); return { risposta: r, da: 'network' };
};
const networkFirst = async (cache, rete, timeoutMs) => {
try { const r = await conTimeout(rete(), timeoutMs); cache.set('k', r); return { risposta: r, da: 'network' }; }
catch { return cache.has('k') ? { risposta: cache.get('k'), da: 'cache' } : { risposta: null, da: 'nothing' }; }
};
const staleWhileRevalidate = async (cache, rete) => {
const vecchia = cache.get('k');
const aggiornamento = rete().then((r) => { cache.set('k', r); return r; }).catch(() => null);
return vecchia !== undefined ? { risposta: vecchia, da: 'cache', aggiornamento } : { risposta: await aggiornamento, da: 'network', aggiornamento };
};
for (const [nome, rete] of Object.entries(scenari)) {
const cf = await cacheFirst(new Map([['k', 'v1']]), rete);
const nf = await networkFirst(new Map([['k', 'v1']]), rete, 100);
const cacheSwr = new Map([['k', 'v1']]);
const sw = await staleWhileRevalidate(cacheSwr, rete);
await sw.aggiornamento;
console.log(`${nome.padEnd(15)} cache-first: ${cf.risposta}/${cf.da} | network-first (100 ms): ${nf.risposta}/${nf.da} | SWR: ${sw.risposta}/${sw.da}, then in cache ${cacheSwr.get('k')}`);
}
const vuota = await staleWhileRevalidate(new Map(), scenari.offline);
const vuota2 = await networkFirst(new Map(), scenari.offline, 100);
console.log('empty cache + offline: SWR =>', vuota.risposta, '| network-first =>', vuota2.risposta);
# Output (executed):
# online cache-first: v1/cache | network-first (100 ms): v2/network | SWR: v1/cache, then in cache v2
# slow (300 ms) cache-first: v1/cache | network-first (100 ms): v1/cache | SWR: v1/cache, then in cache v2
# offline cache-first: v1/cache | network-first (100 ms): v1/cache | SWR: v1/cache, then in cache v1
# empty cache + offline: SWR => null | network-first => null
Read the rows as a table. Cache-first always answers v1: it never looks at the network if it has a copy, so it is very fast and never updates, which suits what does not change (images, fonts).
Network-first with a 100 ms timeout answers v2 if the network is ready, but slips to v1 on a slow network: it is what you need for data that must be fresh but must not block. Stale-while-revalidate answers v1 right away and updates in the background: the lesson opens immediately and, as the "then in cache" column shows, on the next visit v2 is already there (with a slow or absent network, the update arrives later or never).
Workbox specifies that this strategy always makes the revalidation request, whatever the age of the copy.
The last row shows the limit they share: with an empty cache and no network, all of them answer "nothing". A student who opens a lesson that was never downloaded, while offline, must see a clear message ("this lesson is not available offline"), not a blank page: it is a case to design, not to discover in production. Personal data such as the student's profile must not go into a shared Service Worker cache: it stays accessible to anyone who uses the device even after logout.
// Schema to adapt: requires a browser, a registered Service Worker and Workbox. NOT executed.
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { CacheFirst, StaleWhileRevalidate, NetworkOnly } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
import { BackgroundSyncPlugin } from 'workbox-background-sync';
precacheAndRoute(self.__WB_MANIFEST); // the "shell": HTML, JS and CSS of the current version
cleanupOutdatedCaches(); // removes the shells of previous versions
// Images and fonts: they rarely change, so cache-first
registerRoute(
({ request }) => request.destination === 'image' || request.destination === 'font',
new CacheFirst({
cacheName: 'static-v1',
plugins: [new ExpirationPlugin({ maxEntries: 200, maxAgeSeconds: 30 * 24 * 3600 })],
}),
);
// Course catalog and lesson texts: stale-while-revalidate
registerRoute(
({ url }) => url.pathname.startsWith('/api/courses/'),
new StaleWhileRevalidate({ cacheName: 'courses-v1' }),
);
// Student data: NEVER in a shared Service Worker cache
registerRoute(({ url }) => url.pathname.startsWith('/api/students/'), new NetworkOnly());
// Sending progress: if the network drops, Workbox puts it back in the queue (where the browser supports it)
registerRoute(
({ url }) => url.pathname === '/api/progress',
new NetworkOnly({ plugins: [new BackgroundSyncPlugin('progress-queue', { maxRetentionTime: 24 * 60 })] }),
'POST', // minutes: 24 * 60 = one day
);
// Video: no route. They are downloaded whole (200 response) when the student chooses "available offline".
The schema assigns a strategy to each type of request. The value precacheAndRoute(self.__WB_MANIFEST) caches the application shell (HTML, JS and CSS of the current version) and cleanupOutdatedCaches() removes those of earlier versions, which is what prevents serving an old app for weeks after a release.
For maxRetentionTime the value is in minutes: the Workbox documentation shows it with 24 * 60 for one day, and it is easy to put in a number while thinking in seconds. The BackgroundSyncPlugin plugin acts only when the request fails with a network exception, not on a 4xx or 5xx response. The Background Synchronization API, moreover, according to MDN is not Baseline: it does not work in some of the most widespread browsers, so it cannot be the only mechanism. The queue in the local database in the next section does not depend on it.
One choice the schema makes, and that many examples get wrong, concerns video: it has no route. How video reaches the student, in segments, is the subject of Video Streaming for Education. A video arrives in pieces, with Range requests and responses with status 206, and the Service Workers specification says that Cache.put rejects with a TypeError a response with status 206.
Code that tries to cache the first segment of a video with a Range header therefore fails by construction. For offline use, the student chooses "make available offline" and the app downloads the whole file (a 200 response), within a declared space budget.
The write queue: save first, send later, without duplicates
The heart of offline-first for people who study is the write: the student completes a lesson and the progress must survive an app being closed, a crash and a repeated send. The pattern is the outbox: every write goes first into a local table, every entry has an identifier chosen by the client, and a draining loop tries to send them. A frequent defect is marking the entry "failed" on the first error and never retrying it, because the loop only looks for "pending" entries: the entry stays stuck forever. The listing distinguishes three outcomes.
import 'fake-indexeddb/auto';
import Dexie from 'dexie';
const db = new Dexie('edtech');
db.version(1).stores({ outbox: '&opId, status, createdAt' }); // &opId: primary key, generated by the client
let n = 0;
const registra = (lessonId, progress) =>
db.outbox.put({ opId: `op-${++n}`, lessonId, progress, status: 'pending', attempts: 0, createdAt: n });
// Fake server: idempotent on opId, rejects operation op-3 with a 422
const server = { accettate: new Set(), chiamate: 0, giu: true };
const invia = async (op) => {
server.chiamate++;
if (server.giu) throw Object.assign(new Error('network down'), { rete: true });
if (op.opId === 'op-3') throw Object.assign(new Error('422'), { status: 422 });
server.accettate.add(op.opId); // a second send changes nothing
};
async function svuota(maxTentativi = 3) {
for (const op of await db.outbox.where('status').equals('pending').sortBy('createdAt')) {
try {
await invia(op);
await db.outbox.update(op.opId, { status: 'synced' });
} catch (e) {
const tentativi = op.attempts + 1;
const permanente = !e.rete || tentativi >= maxTentativi; // 4xx or too many attempts: do not retry
await db.outbox.update(op.opId, { attempts: tentativi, status: permanente ? 'rejected' : 'pending' });
}
}
}
const stato = async () => (await db.outbox.orderBy('createdAt').toArray()).map((o) => `${o.opId}:${o.status}(${o.attempts})`).join(' ');
await registra('lez-1', 30); await registra('lez-2', 100); await registra('lez-3', 55);
await svuota();
console.log('offline :', await stato());
server.giu = false;
await svuota();
console.log('online :', await stato(), '| accepted:', [...server.accettate].join(','));
// Crash after the server replied but before saving 'synced': the operation is resent
await db.outbox.update('op-1', { status: 'pending' });
await svuota();
console.log('resend op-1 :', await stato(), '| accepted:', server.accettate.size, '| server calls:', server.chiamate);
# Output (executed):
# offline : op-1:pending(1) op-2:pending(1) op-3:pending(1)
# online : op-1:synced(1) op-2:synced(1) op-3:rejected(2) | accepted: op-1,op-2
# resend op-1 : op-1:synced(1) op-2:synced(1) op-3:rejected(2) | accepted: 2 | server calls: 7
With the network down (server.giu = true) the three writes stay pending and the attempt counter rises to 1. When the network returns, op-1 and op-2 move to synced, while op-3 gets a 422 from the server: a permanent error, because repeating the same request would not fix it,
so the entry moves to rejected instead of burning attempts forever. An entry with a network error, by contrast, stays pending up to maxTentativi.
The last row is the guarantee that matters. If the app closes after the server has replied but before synced is written, the operation is resent on restart. The server recognizes the opId it has already seen and does not record the progress twice: the listing shows it with 7 calls in total but only 2 operations accepted.
The identifier is generated by the client at write time, not by the server on receipt, otherwise the resend would not be recognizable. This is the same principle as the idempotence of statements in the pipeline of
Learning Analytics with xAPI and Kafka. One limit of the listing: IndexedDB is simulated in memory, so it proves neither real persistence nor the browser's space limits.
Downloading ahead without eating the student's data
Fetching the next lesson in advance is useful only if it does not cost the student more than it is worth. Three constraints: respect the data-saving request, avoid very slow connections, and stay within a space the device can afford. For the first two the NetworkInformation interface exposes saveData and effectiveType; for the third
navigator.storage.estimate() returns an estimate of usage and quota. According to MDN the quota is a conservative approximation, and NetworkInformation is not Baseline: in some browsers it does not exist, so the code must work without it.
// Which next lessons to download, given connection and space. Pure function: testable without a browser.
export function scegliLezioni({ saveData, effectiveType, usatoMB, quotaMB, budgetMB, lezioni }) {
if (saveData) return []; // the user asked to save data
if (effectiveType === 'slow-2g' || effectiveType === '2g') return [];
const libero = Math.min(budgetMB, quotaMB * 0.8 - usatoMB); // never beyond 80% of the estimated quota
const scelte = [];
let speso = 0;
for (const l of lezioni) { // in curriculum order, stops at the first that does not fit
if (speso + l.mb > libero) break;
scelte.push(l.id); speso += l.mb;
}
return scelte;
}
const lezioni = [{ id: 'l4', mb: 12 }, { id: 'l5', mb: 30 }, { id: 'l6', mb: 25 }];
const base = { saveData: false, effectiveType: '4g', usatoMB: 40, quotaMB: 500, budgetMB: 60, lezioni };
console.log('4g, 60 MB budget :', scegliLezioni(base));
console.log('2g :', scegliLezioni({ ...base, effectiveType: '2g' }));
console.log('saveData :', scegliLezioni({ ...base, saveData: true }));
console.log('quota almost full :', scegliLezioni({ ...base, usatoMB: 380 }));
console.log('network not declared:', scegliLezioni({ ...base, effectiveType: undefined }));
# Output (executed):
# 4g, 60 MB budget : [ 'l4', 'l5' ]
# 2g : []
# saveData : []
# quota almost full : [ 'l4' ]
# network not declared: [ 'l4', 'l5' ]
The function is pure: it receives the state of the connection and of the space and returns the identifiers to download, so it can be tested without a browser. With 4g, 40 MB already used and a 60 MB budget it picks l4 (12 MB) and l5 (30 MB) and stops because l6 (25 MB) would bring the total to 67 MB.
With 2g or saveData it downloads nothing; with the quota almost full it downloads only l4, because it always leaves 20% free. The last row is the case of a browser that does not declare the network type: the listing downloads anyway, and if you prefer caution the default should be changed to a refusal.
The figures (60 MB budget, 80% of quota) are example choices, not recommended thresholds: they depend on your audience and should be read from settings, shown to the student and editable. The student must also be able to see how much space the offline material takes and delete it. Beware of a cleanup that removes lessons from the local database by age: if a lesson has progress not yet sent, deleting it loses that progress together with the lesson. Clean up the content copies, never the write queue.
When local and server disagree
A student completes three lessons offline while, on the server, the teacher resets the course path. On reconnection the two states diverge. The most common rule is "the highest progress wins", and for ordinary progress it is right: progress is monotonic, it only grows. But applied with nothing else, the same rule brings back the work the teacher had deliberately cancelled. You need two things: the common copy from which both sides started (the base) and an epoch counter that the teacher increments when resetting.
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Progress:
progress: float # 0.0 - 1.0
completed: bool
time_spent: int # seconds
epoch: int # +1 every time the teacher resets the path
def resolve(local, server, base):
"""Merges offline progress (local) with the server's, starting from the common copy (base)."""
if server.epoch > base.epoch:
# The teacher reset while the student was offline: the old work is not restored
return server, "server reset: offline progress is not reapplied"
# Same epoch: progress is monotonic, so the maximum wins
delta_local = max(0, local.time_spent - base.time_spent)
delta_server = max(0, server.time_spent - base.time_spent)
merged = Progress(
progress=max(local.progress, server.progress),
completed=local.completed or server.completed,
time_spent=base.time_spent + delta_local + delta_server, # sum the increments, not the totals
epoch=server.epoch,
)
return merged, "same epoch: maximum progress, times summed"
if __name__ == "__main__":
base = Progress(0.40, False, 600, epoch=0)
local = replace(base, progress=0.60, time_spent=900)
server = replace(base, progress=0.55, time_spent=800)
print("two advances :", *resolve(local, server, base))
azzerato = Progress(0.0, False, 0, epoch=1)
print("reset :", *resolve(local, azzerato, base))
print("time with max :", max(local.time_spent, server.time_spent), "s; with increments:",
resolve(local, server, base)[0].time_spent, "s")
completo = replace(local, progress=1.0, completed=True)
print("completed offline:", resolve(completo, server, base)[0].completed)
# Output (executed):
# two advances : Progress(progress=0.6, completed=False, time_spent=1100, epoch=0) same epoch: maximum progress, times summed
# reset : Progress(progress=0.0, completed=False, time_spent=0, epoch=1) server reset: offline progress is not reapplied
# time with max : 900 s; with increments: 1100 s
# completed offline: True
In the first row the two sides advanced in the same epoch: progress becomes the maximum (0.60) and the time is obtained by summing the increments over the base (300 s local and 200 s on the server, on top of the common 600 s) instead of the totals. The difference is visible in the output: taking the maximum of the two totals would give 900 seconds, the merge gives 1100.
One limit: if the student and the server recorded the same period of study, for example on two devices at once, the sum counts it twice; for times that feed assessments you need a session log, not a total. In the second row the server has epoch=1 against the base epoch=0: the reset wins and the offline work is not reapplied.
The student, however, must not find out in silence: the discarded work must be shown ("the path was reset by the teacher, your offline answers were not applied"), and kept for a period in case of disputes. The last row confirms that a course completed offline stays completed when there was no reset. The "maximum" rule is right for data that only grows; for a freely editable field, such as the profile name, you need a different rule (for example the most recent edit wins, declaring it).
Where it hurts
The mistakes you meet most often, with the part of the article that avoids them.
- Personal data in a Service Worker cache: it stays on the device after logout; for student data use
NetworkOnlyor an encrypted, erasable store. - Service Worker without versions: it serves an old app after a release; versioned cache names and
cleanupOutdatedCaches(). - Video in cache with Range requests:
Cache.putrejects 206 responses; download whole files on request. - A queue that never retries or retries forever: distinguish network errors (retry) from permanent errors (discard and show).
- Cache cleanup that deletes unsent data: separate regenerable content from pending writes.
- No offline testing: try with DevTools in offline mode and with a throttled connection, because the first launch without a network is the case that breaks.
The criterion that joins the entries is the separation between what can be regenerated (content, shell, cache) and what cannot be lost (the student's writes). You can throw the cache away at any moment; the queue, no. If in an existing project you must decide where to start, start from the queue with a client identifier: it removes data loss and duplication, the two defects students notice. Push notifications to remind people to study stay out of this article: they require permissions, server keys and per-platform rules that I did not try here.
Frequently asked questions
Does a PWA work on every phone?
Service Worker and IndexedDB are widely supported, but not everything is: Background Synchronization and NetworkInformation, according to MDN, are not Baseline. The code must work even when these APIs are missing.
Where do I store pending writes, in the cache or in IndexedDB?
In IndexedDB. The Service Worker cache is meant for HTTP responses that can be regenerated; the student's writes are data not to be lost, with a status and attempts, and IndexedDB lets you query them.
How do I avoid recording a resent progress twice?
Assign an identifier to every operation on the client and have the server recognize those it has already seen. Resending after a crash becomes harmless.
Can I cache videos?
Not with a route and partial responses: the Service Workers specification makes Cache.put reject 206 responses. Download the whole file after an explicit request from the student and declare the space it takes.
What you can do now
You can choose the cache strategy for each type of request and predict what the student sees online, on a slow network and offline, keep writes in a queue with client identifiers, tell apart errors to retry from errors to discard, decide what to download ahead while respecting data and space, and merge progress with a rule that does not restore a reset. The last article in the series is about the content this app downloads: how it is versioned and distributed to several customers, in Multi-Tenant Content Management: Versioning and SCORM.
Sources
- Workbox: Strategies - cache-first, network-first with timeout and stale-while-revalidate (revalidation always performed), accessed on 2026-11-12
- Workbox: Background Sync - maxRetentionTime in minutes and the fact that the plugin triggers only on network exceptions, accessed on 2026-11-12
- Service Workers (W3C), Cache.put algorithm - the rejection with TypeError of responses with status 206, accessed on 2026-11-12
- MDN: Background Synchronization API - limited availability, not Baseline, accessed on 2026-11-12
- MDN: NetworkInformation - saveData, effectiveType and limited availability, accessed on 2026-11-12
- MDN: StorageManager.estimate() - quota as a conservative approximation of the available space, accessed on 2026-11-12
The JavaScript listings were run with Node 24, Dexie 4.4.7 and fake-indexeddb 6.2.8 (in-memory IndexedDB, not a browser); the Python listing with Python 3.14. The strategy simulation is not Workbox. The Service Worker schema was not executed. Budget, quota and thresholds are example choices.
Commenti
Caricamento commenti...
Sign in to comment