← Back to Angular, page 10

angular-0195 · Hard senior

Design an offline-first feature (for example, a teacher marking attendance in a classroom with bad internet). How do you store changes, sync them later and handle conflicts in Angular?

Save every change locally first (IndexedDB), show it in the UI at once, and put it in an outbox queue. A sync service sends queued changes when the network is back, with idempotency keys so retries are safe, and resolves conflicts with a clear rule. The service worker caches the app shell and read data, and the UI shows sync status.

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:

  1. App shell and assets: the Angular service worker (@angular/service-worker) caches the app files, so the app starts offline. Use dataGroups for read-only API data (class lists) with a freshness or performance strategy and a sensible age.
  2. Local data: store data in IndexedDB (use a small wrapper such as Dexie or idb), not localStorage (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.
  3. 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.
  4. Sync service: when navigator.onLine is true and the app is online (the online event 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).
  5. Idempotency: the client sends the command id as an idempotency key, and the server stores processed ids, so a retry after a timeout does not create duplicates.
  6. 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.
  7. Pull: after pushing, fetch changes since the last sync token (delta sync), and merge into IndexedDB.
  8. 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.
  9. 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.
  10. 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.