Full answer
Clarify the requirement: which actions must work offline (read lists, mark attendance), how long a device can be offline, whether several people edit the same data, and what is acceptable when two edits clash.
Design:
- App shell and assets: the Angular service worker (
@angular/service-worker) caches the app files, so the app starts offline. UsedataGroupsfor read-only API data (class lists) with a freshness or performance strategy and a sensible age. - Local data: store data in IndexedDB (use a small wrapper such as Dexie or
idb), notlocalStorage(too small and synchronous). The UI reads from the local store through a service that exposes signals. This is the "local first" idea: the screen never waits for the network. - Writing: every user action becomes a command in an outbox table:
{ id (uuid), type, payload, createdAt, status }. The UI updates the local data at once (optimistic), and shows a small "pending" mark for items that are not synced. - Sync service: when
navigator.onLineis true and the app is online (theonlineevent is a hint, a failed request is the truth), it sends outbox items in order, one by one or in batches. Success removes the item. A network error keeps it and retries with backoff. A validation error (4xx) marks it as failed and shows it to the user. Use the Background Sync API where supported to sync after the tab closes, but do not depend on it (Safari has no support). - Idempotency: the client sends the command
idas an idempotency key, and the server stores processed ids, so a retry after a timeout does not create duplicates. - Conflicts: choose a rule. Last write wins (simple, may lose data), per field merge, version numbers (the server rejects an update if the base version is old, and the client shows a merge dialog), or CRDTs for collaborative text. For attendance, "per student per date, latest timestamp wins" is usually enough, and the audit log keeps the history.
- Pull: after pushing, fetch changes since the last sync token (delta sync), and merge into IndexedDB.
- UX: show an offline banner, a count of unsynced items, a retry button, and the time of the last sync. Tell users clearly when the data may be old.
- Security and cleanup: the local database holds personal data, so clear it on logout, and avoid storing more than needed. Encrypt only if the threat model needs it, since keys in the browser are hard to protect.
- Testing: simulate offline with the browser's network throttle, run Playwright tests with
context.setOffline(true), and test the sync service with a fake clock and fake API.
State the trade-off: offline-first adds a lot of complexity (storage, sync, conflicts, migrations), so build it only for features where users really lack connectivity.
typescript
export interface Command {
id: string;
type: 'mark-attendance';
payload: { studentId: number; date: string; present: boolean };
}
export class Outbox {
private readonly queue: Command[] = [];
add(command: Command): void {
this.queue.push(command);
}
get pending(): number {
return this.queue.length;
}
// Sends commands in order. Stops at the first network failure and keeps the rest.
async flush(send: (command: Command) => Promise<'ok' | 'rejected'>): Promise<{ sent: number; rejected: Command[] }> {
let sent = 0;
const rejected: Command[] = [];
while (this.queue.length > 0) {
const next = this.queue[0];
try {
const result = await send(next); // the command id is the idempotency key
this.queue.shift();
if (result === 'ok') sent++;
else rejected.push(next);
} catch {
break; // offline: try again later
}
}
return { sent, rejected };
}
}
// Demo: the first send fails (offline), the second attempt works.
const outbox = new Outbox();
outbox.add({ id: 'c1', type: 'mark-attendance', payload: { studentId: 1, date: '2026-12-04', present: true } });
outbox.add({ id: 'c2', type: 'mark-attendance', payload: { studentId: 2, date: '2026-12-04', present: false } });
let online = false;
const send = async (): Promise<'ok' | 'rejected'> => {
if (!online) throw new Error('offline');
return 'ok';
};
const first = await outbox.flush(send);
console.log('offline flush:', first.sent, 'sent,', outbox.pending, 'pending');
online = true;
const second = await outbox.flush(send);
console.log('online flush:', second.sent, 'sent,', outbox.pending, 'pending');Angular 20.3, type-checked. The outbox logic was run in Node 24 twice with identical output, using an in-memory queue and a fake send function that fails while offline and succeeds when online. IndexedDB, the service worker and Background Sync were not run here.
Key points
- Local first: write to IndexedDB, update the UI at once, queue commands in an outbox.
- A sync service retries with backoff and uses idempotency keys. It handles 4xx failures separately.
- Pick a conflict rule (last write wins, versions with a merge, CRDT) that fits the data.
- The service worker caches the shell and read data. The UI shows pending and sync status.
Common mistakes
- Using `localStorage` for offline data.
- Retrying without idempotency, creating duplicates.
- Trusting `navigator.onLine` as proof of a working connection.
Follow-ups
- How do you handle a schema change in the local database?
- What conflict rule would you use for attendance?
- When is Background Sync not available?
Tips
- Ask which actions need offline support.
- Describe the outbox pattern in two sentences.
- Mention the extra complexity honestly.
Evaluation rubric
- Designs storage, queue and sync correctly.
- Handles idempotency and conflicts.
- Covers UX, security and testing.