A utility company has 6,000 field technicians who inspect equipment in basements, rural sites and tunnels where connectivity is absent or unreliable for hours. Today they use paper forms that are typed in later. You are asked to design an offline-first progressive web app that runs on company-managed Android tablets and some iPads.
Technicians must be able to:
Dispatchers in the office edit the same work orders (reassigning, adding notes, changing priority) while technicians are offline. Some forms are edited by two technicians on the same site.
Design the client architecture, storage, sync protocol and conflict-resolution strategy, the service-worker and update strategy, and how you would roll this out and support it as a platform used by several teams that build different form types.
"Offline support" is often designed as a cache in front of an online app. Offline-first inverts that: the local database is the app's source of truth for the UI, and the network is a background replication channel. Every user action writes locally and succeeds immediately; sync happens later, possibly hours later, possibly in pieces.
That inversion moves the hard problems from rendering to data: what to download, how to store it durably in a browser, how to send changes reliably exactly once, and what to do when the office and the field change the same record. A lead-level answer spends most of its time there, and is honest about where the web platform is weaker than native (iOS background execution, storage eviction).
Layers:
Every syncable record carries sync metadata:
interface SyncedRecord<T> {
id: string; // client-generated UUID v7 (sortable), so offline creates need no server round trip
type: 'workOrder' | 'submission' | 'defect' | 'note';
data: T;
serverVersion: number | null; // last version acknowledged by server
fieldVersions: Record<string, { v: number; by: string; at: string }>; // per-field for merge
localState: 'synced' | 'pending' | 'conflict' | 'error';
deleted?: boolean; // tombstone
}
interface OutboxOp {
opId: string; // UUID; the server's idempotency key
recordId: string;
recordType: SyncedRecord<unknown>['type'];
kind: 'create' | 'patch' | 'delete';
baseVersion: number | null; // server version the edit was based on
patch: Record<string, unknown>; // only changed fields
createdAt: string;
deviceId: string;
attempts: number;
}
Patches, not whole records: sending only changed fields shrinks payloads and makes field-level merges possible.
{
"cursor": "c_000184223",
"hasMore": false,
"changes": [
{ "id": "wo_81", "type": "workOrder", "version": 14, "changedFields": { "priority": "high" },
"by": "dispatcher:jlee", "at": "2025-06-02T09:12:00Z" },
{ "id": "wo_77", "type": "workOrder", "deleted": true, "reason": "reassigned" }
]
}
"Reassigned away" is delivered as a scoped delete so the device evicts data it is no longer allowed to hold.
Forms are JSON schemas plus UI hints, versioned and downloaded with the shift. A submission records the
formVersion it was completed against, so the server can validate and migrate older submissions after a form change.
POST /sync/push
{ "deviceId": "d_19", "ops": [ OutboxOp, ... ] } // batches of up to 100 ops
200 { "results": [ { "opId": "...", "status": "applied", "version": 15 },
{ "opId": "...", "status": "conflict", "server": { ...record, "version": 16 } },
{ "opId": "...", "status": "rejected", "error": "VALIDATION", "details": {...} } ] }
GET /sync/pull?cursor=c_000184100&scope=technician:t_42
200 { "cursor": "...", "hasMore": true, "changes": [...] }
Push is idempotent by opId: the server stores applied op IDs, so a retry after a lost response is harmless.
Media: POST /media creates an upload session, chunks are PUT with byte ranges, and a final call commits. A tus-style
protocol works well here. The record references media by client-generated ID, so records can sync before photos do.
interface OfflineStore {
query<T>(type: string, where?: Partial<T>): LiveQuery<T[]>; // reactive, local only
get<T>(type: string, id: string): LiveQuery<SyncedRecord<T> | undefined>;
create<T>(type: string, data: T): Promise<string>; // writes record + outbox op atomically
patch<T>(type: string, id: string, changes: Partial<T>): Promise<void>;
remove(type: string, id: string): Promise<void>;
attachMedia(recordId: string, file: Blob, meta: { kind: 'photo' | 'signature' }): Promise<string>;
}
interface SyncStatus {
online: boolean;
pendingOps: number;
pendingMediaBytes: number;
lastSuccessfulSync: string | null;
conflicts: number;
}
declare function useSyncStatus(): SyncStatus;
declare function requestSync(reason: 'user' | 'online' | 'interval' | 'visibility'): void;
Form teams write UI against OfflineStore. They never call fetch, never manage the outbox, and get offline behaviour
for free.
navigator.storage.persist() on first run; on managed Android with an installed PWA this is normally granted,
which protects data from best-effort eviction. Show storage usage via navigator.storage.estimate() and warn before
quota is reached.Triggers: app start, online event, visibilitychange to visible, a periodic timer while open, and user "Sync now".
On Android Chrome, register a Background Sync (sync event) so the service worker can flush the outbox after the app
is closed. Periodic Background Sync exists in Chromium for installed apps but is opportunistic; do not depend on it.
On iOS, there is no background sync; the UI must make pending state visible and nudge users to open the app on
connectivity.
navigator.onLine is unreliable (true on captive portals and dead Wi-Fi), so treat it as a hint and judge
connectivity by actual request success, with exponential backoff and jitter.
Ops are pushed in creation order per record. If op N for a record is rejected, later ops for the same record are held (they may depend on it), but other records continue. A poison op (validation failure that will never succeed) is moved to an error state and surfaced to the user rather than blocking the queue forever.
Conflicts are inevitable: a dispatcher edits priority while a technician edits notes on the same work order. Options, from simplest to most powerful:
| Strategy | How it works | Good for | Risk |
|---|---|---|---|
| Last-writer-wins (record) | Whole record overwritten by the latest timestamp | Nothing important | Silent data loss; device clocks drift |
| Field-level merge with versions | Server compares baseVersion and changed fields; non-overlapping fields merge automatically | Most form and work-order edits | Overlapping edits still need a rule |
| Domain rules | Per field policy: "server wins" for assignment, "max" for severity, "append" for notes, "client wins" for measurements taken on site | Business-meaningful fields | Must be designed with the business |
| Manual resolution | Conflict surfaced to a human with both values | Safety-critical overlapping edits | UX burden; must be rare |
| CRDTs (Yjs, Automerge) | Data types that merge automatically and deterministically | Collaborative free text, checklists edited by two technicians | More storage, harder server-side validation and querying |
Recommendation: field-level merge plus per-field domain rules, declared in the form or entity schema
("mergePolicy": "server-wins" | "client-wins" | "max" | "append" | "manual"). Use a CRDT only for the shared
on-site notes field where two technicians type concurrently. Never rely on device clocks for ordering; the server
assigns versions, and per-field metadata records author and server sequence.
Example: technician sets hazardPresent = true offline; dispatcher meanwhile closes the work order. Policy says hazard
reports are never discarded: the server applies the hazard flag, re-opens the order, and alerts the dispatcher. That
is a product decision, which is why the platform makes policies declarative and visible to form owners.
Use tombstones so a delete syncs like any other change. When a work order is reassigned, the original device receives a scoped delete; if it holds unsynced edits, those are pushed first and then attributed to the original technician, and the local copy is evicted only after acknowledgement.
skipWaiting when the user accepts
or at next cold start.Photos are the bulk of the data. Compress on device (resize to a max dimension, re-encode as JPEG or WebP with
OffscreenCanvas in a worker), compute a content hash for deduplication, upload in 1–5 MB chunks with resume, and
upload records before media so dispatchers see text immediately. Allow technicians to keep working while uploads
continue in the background.
Devices can be lost. Use short-lived access tokens with refresh tokens bound to the device, MDM remote wipe, and an app-level PIN after inactivity. Encrypting IndexedDB contents with a key from WebCrypto helps only if the key is not stored next to the data; on managed devices, rely on OS-level disk encryption and MDM, and say so honestly.
For this brief: Dexie plus a custom sync protocol on top of a server change log, keeping the option of PowerSync if the back end is Postgres. The decisive factor is how much the existing back end can change.
OfflineStore API; form teams own form schemas, merge policies for their fields and UI. Merge policies are reviewed
with the business owner of each form.Why not just cache API responses in the service worker? A response cache gives offline reads but not offline writes, merges, or queries across records. You would still need an outbox and a local model, so the cache becomes an awkward partial database.
How do you handle clock skew? Never use device time for ordering or conflict resolution. Device timestamps are recorded for audit only; the server assigns versions and sequence numbers.
What if a form schema changes while a technician has an old draft? The draft records its form version. The server validates against that version and runs a migration. Breaking form changes publish as a new form version while the old one remains accepted for a grace period.
How would you test this? Unit tests for merge policies with property-based tests; integration tests of the sync engine against a fake server that drops, duplicates and reorders responses; end-to-end tests with Playwright toggling offline mode; and a fleet of test devices running soak tests across app updates.
Two tabs open on the same device? Use the Web Locks API so only one context runs sync, and BroadcastChannel (or IndexedDB observers in the data layer) to keep live queries in both tabs up to date.
Spotted a mistake or a rights concern? Report an issue