Offline Sync in React Native: What to Persist and Where

A queue held in memory loses unsent changes when the OS kills the app. Persist the mutations, and keep them atomic with the local write.

Part 1 of 5

Basics

The whole idea first, then the terms the rest of this page uses.

1.1Whole idea

The user's change must reach the disk before anything else happens, in the same transaction as the queue entry that will send it. Persist only the small mutation, and not a large copy of app state. A drain loop sends entries in order, keeps conflicts and failures visible, retries server trouble with backoff, and survives a crash because every send carries a key.

Why it matters

A queue held in memory loses unsent changes when the OS kills the app. Persist the mutations, and keep them atomic with the local write.

1.2Key concepts

One idea per card, in plain words.

01Mutation

One recorded change: the method, the endpoint, a small payload, and a status.

02Optimistic update

The screen shows the result straight away, before the server has agreed.

03Atomic enqueue

The local row and the queue row commit together, or neither does.

04Idempotency key

A stable id sent with each attempt, so a resend after a crash doesn't apply the change twice.

05Status machine

PENDING, IN_FLIGHT, then removed on success. CONFLICT and FAILED stay on disk until someone resolves them.

06Headless task

JavaScript run by the OS with no screen. Android can start one, and may stop it early, so long syncs belong in native workers.

07Optimistic write

The UI and the local database change at once, before the server answers. If the server rejects the change, you roll it back.

08Chunked transfer

A large file is sliced into parts, and the app records which parts the server holds. After a drop, the upload resumes from the first missing part.

09OS background work

WorkManager on Android and background tasks on iOS can run when your JavaScript runtime has been killed. React Native code cannot be relied on to run then.

10Local-first reads

The UI reads only from local storage. The network updates the database, and the database updates the screen, so the screen never waits on the network.

11Conflict check

The server compares a version number, hash or clock sent with the change. If they differ, it returns the authoritative state and the app rolls back its optimistic write.

Part 2 of 5

Question

What exactly you must answer, and what to settle before you start.

2.1Question

Interviewer

Field staff edit jobs in basements. Their changes must survive the OS killing the app, and reach the server in order once there is signal. Design the queue in React Native.

2.2Clarify first

Each answer removes a guess.

You askAnswer
Can one change depend on another?Yes. A status update must not overtake the edit it follows.
What happens when the server has a newer version?The user should see both and choose.
How large are the changes?Small fields and notes. Photos use a separate resumable upload.
Part 3 of 5

Detailed answer

How it works, and how to build or explain it.

3.1Architecture

The components and how they connect.

Screenreads the local rowOne transactionlocal row + queue rowQueuePENDING · CONFLICT · FAILEDDrain loopordered · single runServeridempotency keysaveoldest firstsendconflict · done
ClientServiceData storeQueue / streamExternal
Boxes are components; arrows show calls and data flow.

3.2Step by step

The mechanism, in the order you would explain it.

  1. Write the data and the queue entry together

    One transaction updates the local row and inserts the pending mutation. If either fails, neither is saved.

  2. Show the local row

    The screen reads the database, directly or through a cache seeded from it. The change appears at once.

  3. Drain in order, one run at a time

    Take the oldest pending entry, mark it in flight, send it with its id as the key. Two triggers must not start two runs.

  4. Stop when the network fails

    Put the entry back to pending and stop. Later changes must never overtake it.

  5. Keep conflicts and rejections

    A 409 becomes CONFLICT for the user to resolve. Another 4xx becomes FAILED with the reason. Deleting either loses the user's work.

  6. Back off on server trouble

    For 429 and 5xx, wait longer each time and stop after a limit. Don't hammer a struggling server.

  7. Recover after a crash

    At startup, return IN_FLIGHT entries to pending. The key makes a resend safe.

3.3What to persist

KindTypical toolPersist?Why
Server cacheTanStack Query, RTK QueryOptionalIt can be fetched again
UI and session stateZustand, ContextNoCheap to rebuild
Unsent mutationsSQLite, WatermelonDBYes, alwaysThe only copy of the user's work
Form draftsA form libraryNoLost on unmount, by design

3.4Code

Working code for the core of it.

A mutation queue that survives the OS

An offline queue with the rules that a quick version gets wrong: atomic enqueue, order, visible conflicts, backoff and crash recovery.

mutation-queue.tsTypeScriptCopy
1/* An offline mutation queue, written to fix what a quick version gets wrong. The database here is in memory, and the2   transaction rule is the same one SQLite gives you: the local row and the queue row commit together, or neither does. */3export type Status = "PENDING" | "IN_FLIGHT" | "CONFLICT" | "FAILED";4export interface Mutation {5  id: string;6  method: "POST" | "PUT" | "PATCH" | "DELETE";7  endpoint: string;8  body: string;9  status: Status;10  attempts: number;11  createdAt: number;12  /** not before this time, set by backoff */13  nextAt: number;14  lastError?: string;15}16export type Sender = (req: { method: string; endpoint: string; body: string; idempotencyKey: string }) => Promise<{ status: number }>;17 18export class MemoryDb {19  rows = new Map<string, unknown>();20  queue: Mutation[] = [];21  transaction<T>(fn: (rows: Map<string, unknown>, queue: Mutation[]) => T): T {22    const rows = new Map(this.rows);23    const queue = this.queue.map((m) => ({ ...m }));24    const result = fn(rows, queue);25    this.rows = rows;26    this.queue = queue;27    return result;28  }29}30 31export interface Options {32  now: () => number;33  baseDelayMs: number;34  maxAttempts: number;35}36 37export class MutationQueue {38  private running?: Promise<void>;39  private db: MemoryDb;40  private send: Sender;41  private opts: Options;42  constructor(db: MemoryDb, send: Sender, opts: Options) {43    this.db = db;44    this.send = send;45    this.opts = opts;46  }47 48  /** The screen reads the local row, so it updates at once. The queue row records what the server still has to hear. */49  enqueue(m: Pick<Mutation, "id" | "method" | "endpoint" | "body">, writeLocal: (rows: Map<string, unknown>) => void): void {50    this.db.transaction((rows, queue) => {51      writeLocal(rows);52      queue.push({ ...m, status: "PENDING", attempts: 0, createdAt: this.opts.now(), nextAt: 0 });53    });54  }55 56  /** After a crash, anything marked IN_FLIGHT may or may not have reached the server. Sending it again is safe, because of the key. */57  recover(): void {58    this.db.transaction((_rows, queue) => queue.forEach((m) => m.status === "IN_FLIGHT" && (m.status = "PENDING")));59  }60 61  drain(): Promise<void> {62    this.running ??= this.run().finally(() => (this.running = undefined));63    return this.running;64  }65 66  private async run(): Promise<void> {67    for (;;) {68      const next = this.db.queue.filter((m) => m.status === "PENDING").sort((a, b) => a.createdAt - b.createdAt)[0];69      if (!next || next.nextAt > this.opts.now()) return;70      this.mark(next.id, { status: "IN_FLIGHT" });71      let status: number;72      try {73        status = (await this.send({ method: next.method, endpoint: next.endpoint, body: next.body, idempotencyKey: next.id })).status;74      } catch {75        // No network. Stop here, so later changes never overtake this one.76        this.mark(next.id, { status: "PENDING" });77        return;78      }79      if (status >= 200 && status < 300) this.db.queue = this.db.queue.filter((m) => m.id !== next.id);80      else if (status === 409) this.mark(next.id, { status: "CONFLICT", lastError: "server has a newer version" });81      else if (status === 429 || status >= 500) {82        const attempts = next.attempts + 1;83        if (attempts >= this.opts.maxAttempts) this.mark(next.id, { status: "FAILED", attempts, lastError: `gave up after HTTP ${status}` });84        else {85          this.mark(next.id, { status: "PENDING", attempts, nextAt: this.opts.now() + this.opts.baseDelayMs * 2 ** (attempts - 1), lastError: `HTTP ${status}` });86          return; // the server is unwell, so wait before trying anything87        }88      } else this.mark(next.id, { status: "FAILED", lastError: `HTTP ${status}` });89    }90  }91 92  private mark(id: string, patch: Partial<Mutation>) {93    this.db.queue = this.db.queue.map((m) => (m.id === id ? { ...m, ...patch } : m));94  }95}
95 linesUTF-8TypeScript
this.db.transaction((rows, queue) => {
The local row and the queue row commit together. If the local write throws, the queue row isn't saved either.
this.running ??= this.run()
Single flight. Two triggers that fire at once share one drain, so no change is sent twice.
No network. Stop here
A failed send puts the entry back and stops, so a later change can't overtake it.
status === 409
A conflict stays on disk for the user to resolve. Deleting it would lose their work silently.
2 ** (attempts - 1)
The wait doubles after each failure, and the entry is marked FAILED after the last attempt.
idempotencyKey: next.id
The same key on every attempt lets the server ignore a repeat.
recover()
After a crash, an IN_FLIGHT entry may or may not have arrived. Back to pending, and the key makes the resend safe.

Tested by npm run test:modules.

3.5Slides

From the source decks this page draws on. Swipe, use the arrows, or press the left and right keys. Notes flag where a slide's numbers or flow differ from this page.

A global in-memory store losing uncommitted data when the OS terminates the app‹›
1 / 14
Full sizeFull screen

Why in-memory state loses unsent changes.The crash-rate figure on this slide has no source we could check.

  1. Why in-memory state loses unsent changes.
  2. The four parts of an offline design.
  3. Persist the small mutation, and not the whole state.
  4. The queue table, indexed for oldest-first reads.
  5. A worker wakes, reads pending rows and sends them.
  6. The lifecycle of one queued change.
  7. The UI reads only local data, and every action also queues a mutation.
  8. A worker pops the oldest change, the server merges or refuses, and the queue clears or rolls back.
  9. What each OS lets you run in the background, and the rule that follows.
  10. Chunk the file, stream it through binary buffers, and save which chunk is next.
  11. The offline-first path: write locally, queue, check the network, sync, then confirm.
  12. Large files go up in resumable chunks, and background work belongs to the operating system.
  13. One change, from tap to server acknowledgement.
  14. Small JSON through the query layer, large files through native transfer code.
Part 4 of 5

Q&A

What interviewers ask next. Answer out loud, then open.

4.1Interview questions

Why not persist the whole app state?
A large blob slows the first render and startup, and it copies data the server already has. The small mutation is the only thing that can't be refetched.
The queue write happens after the cache update. What's wrong?
A crash between them loses the change, or leaves it shown and never sent. Commit both in one transaction.
Why do 409 and other 4xx stay on disk?
The user's change was not applied. Removing the row would delete work silently, so keep it visible and ask.
Why stop at the first network error?
Sending later changes first would reorder them, and a status update could reach the server before the edit it follows.
Should the sync run in headless JavaScript?
For a short drain, it works. The OS can stop it early, so for long or critical syncs run the engine in a native worker that calls the same endpoints.
Why does offline-first change the app's state model?
It adds a queue, conflict handling and local schema migrations, so the device holds data the server has not seen. These are architecture decisions, and a feature you add late costs far more.
Why not upload a large video in one request?
One dropped connection throws away the whole transfer. Chunks let you resume from the last one the server confirmed, and a native transfer layer can keep going after the app closes.
What changes on iOS and Android for background sync?
iOS lets the system decide when background tasks run, and suspends the JS runtime aggressively. Android's WorkManager defers deferrable work and long tasks may need a foreground service. Neither guarantees continuous JavaScript, so move heavy sync to native code.
How does a transfer manager survive a crash?
It saves the file's current chunk index to local storage after each acknowledged chunk. After a crash or OS termination, it reads the index and continues from there.
Part 5 of 5

Extra depth

Edge cases, counterpoints and what to read next.

5.1Edge cases and counterpoints

Includes the strongest argument against this approach.

Show detailsHide details
Compared with the deep dives
The sync engine and transfer manager pages cover the whole system: server versions, field merge, and resumable uploads. This module covers the React Native side. The background sync article has a 15-slide overview of the whole system.
Debugging from the field
Store each entry's attempts and last error. Support teams then see why a change is stuck.
Counterpoint
A read-mostly app with rare edits may need only a retry on a failed request, and a queue adds more than it saves.
From tap to confirmation
The path is a local write, a queued mutation, a network check, a sync to the server's version service, and then a confirmation that updates the local cache. Each arrow in that path is a place a change can wait, so decide what the user sees at each.
Streaming and memory
Reading a 500 MB video into a JavaScript string can run the app out of memory. Stream it from disk through binary buffers in native code, one chunk at a time.