Building an Offline Outbox in React Native That Doesn't Lose Writes
A practical guide to building an offline-safe write queue in React Native with persistence, smart retries, and idempotency keys.
We spend most of our time building mobile apps for businesses, and offline support comes up in almost every project. Users open apps in warehouses, basements, parking garages, and on trains, and they expect their work to be saved anyway.
Most React Native applications handle offline mode the same way at first. Wrap fetch in a try/catch, show a toast that says "No connection," and hope the user tries again.
That works until your users are field staff, delivery drivers, or anyone who spends half their day without a stable signal. Then "try again" turns into lost orders, duplicate records, and support tickets nobody can reproduce.
The pattern our team reaches for is an outbox: every write goes into a persistent local queue first, and a background process drains that queue to the server when it can. It sounds simple. The details are where it gets interesting.
The Naive Version and Why It Breaks
The first version usually looks something like this:
async function saveOrder(order: Order) {
try {
await api.post('/orders', order);
} catch {
pendingOrders.push(order); // retry later
}
}
There are at least three problems here.
First, pendingOrders lives in memory. If the OS kills the app, which both iOS and Android do aggressively in the background, the pending writes are gone.
Second, a failed request is not the same as a request that never reached the server. If the connection drops after the server commits the order but before the response arrives, the retry creates a duplicate.
Third, nothing decides when to retry. Either you retry in a tight loop and drain the battery, or you wait for the user to do something.
A real outbox has to solve all three: persistence, idempotency, and scheduling.
The Data Model
Each queued write is a small, serializable record:
type Mutation = {
id: string; // also used as the idempotency key
endpoint: string;
method: 'POST' | 'PUT' | 'PATCH' | 'DELETE';
body?: unknown;
attempts: number;
nextAttemptAt: number; // epoch ms
createdAt: number;
};
The id is generated on the device when the user takes the action, not when the request is sent. That's the key decision. The same logical action keeps the same ID no matter how many times it's retried.
On React Native, you'll need a polyfill for crypto.getRandomValues before using uuid:
import 'react-native-get-random-values';
import { v4 as uuid } from 'uuid';
Persisting the Queue Safely
We're using AsyncStorage here to keep the example short. For high write volumes, SQLite or MMKV is a better fit, but the structure stays the same.
The trap with AsyncStorage is concurrent read-modify-write. If the user saves something while the sync loop is halfway through draining the queue, one of the writes silently overwrites the other. So every queue change goes through a single serialized chain:
import AsyncStorage from '@react-native-async-storage/async-storage';
const QUEUE_KEY = 'outbox:v1';
let lock: Promise<unknown> = Promise.resolve();
function withQueue<T>(
fn: (queue: Mutation[]) => [Mutation[], T]
): Promise<T> {
const run = lock.then(async () => {
const raw = await AsyncStorage.getItem(QUEUE_KEY);
const queue: Mutation[] = raw ? JSON.parse(raw) : [];
const [next, result] = fn(queue);
await AsyncStorage.setItem(QUEUE_KEY, JSON.stringify(next));
return result;
});
lock = run.catch(() => undefined);
return run;
}
export function enqueue(
m: Omit<Mutation, 'id' | 'attempts' | 'nextAttemptAt' | 'createdAt'>
) {
const item: Mutation = {
...m,
id: uuid(),
attempts: 0,
nextAttemptAt: Date.now(),
createdAt: Date.now(),
};
return withQueue(q => [[...q, item], item.id]).then(id => {
flush();
return id;
});
}
The outbox:v1 key is versioned on purpose. When the Mutation shape changes in a future release, you'll want to migrate old queues instead of crashing on them.
Sending a Mutation
Each send returns one of three outcomes. Treating every failure the same is one of the most common mistakes we see in retry logic.
type SendResult = 'done' | 'retry' | 'drop';
async function send(m: Mutation): Promise<SendResult> {
let res: Response;
try {
res = await fetch(`${API_URL}${m.endpoint}`, {
method: m.method,
headers: {
'Content-Type': 'application/json',
'Idempotency-Key': m.id,
},
body: m.body === undefined ? undefined : JSON.stringify(m.body),
});
} catch {
return 'retry'; // network error, the server may or may not have it
}
if (res.ok) return 'done';
if (res.status === 408 || res.status === 429 || res.status >= 500) {
return 'retry';
}
return 'drop'; // 4xx: retrying the same payload won't help
}
A 400 or 422 means the payload itself is wrong. Retrying it forever just blocks everything behind it. Those mutations should leave the queue and be shown to the user, or logged, so someone can fix the data.
Draining the Queue
The sync loop processes the queue in order, one item at a time:
const MAX_ATTEMPTS = 10; let flushing = false;const MAX_ATTEMPTS = 10;
let flushing = false;
export async function flush(): Promise<void> {
if (flushing) return;
flushing = true;
try {
while (true) {
const head = await withQueue(q => [q, q[0]]);
if (!head || head.nextAttemptAt > Date.now()) break;
const result = await send(head);
if (result === 'retry' && head.attempts + 1 < MAX_ATTEMPTS) {
await withQueue(q => [
q.map(x =>
x.id === head.id
? {
...x,
attempts: x.attempts + 1,
nextAttemptAt: Date.now() + backoff(x.attempts + 1),
}
: x
),
null,
]);
break;
}
if (result !== 'done') reportFailed(head, result);
await withQueue(q => [q.filter(x => x.id !== head.id), null]);
}
} finally {
flushing = false;
}
}
Notice that items are removed by id, not by position. New writes can land at the end of the queue while a request is in flight, and this keeps them intact.
Backoff uses full jitter. Without it, every device that lost connection at the same moment retries at the same moment too, and your API gets a thundering herd the second a cell tower comes back:
function backoff(attempt: number): number { const base = 1_000; const cap = 5 * 60 * 1_000; return Math.random() * Math.min(cap, base * 2 ** attempt); }
When to Flush
The queue should drain without the user doing anything. Three triggers cover most cases:
import NetInfo from '@react-native-community/netinfo'; import { AppState } from 'react-native';
NetInfo.addEventListener(state => { if (state.isConnected && state.isInternetReachable !== false) flush(); });
AppState.addEventListener('change', s => { if (s === 'active') flush(); });
The third trigger is a timer set for the head item's nextAttemptAt, so a retry fires even if the network state never changes. We've left it out here for brevity.
Don't trust isConnected alone. A phone on hotel Wi-Fi behind a captive portal reports as connected. That's why the check also looks at isInternetReachable, and why send still has to handle network errors gracefully.
The Server Half: Idempotency Keys
None of this prevents duplicates unless the server cooperates. The API must remember which keys it has already processed:
CREATE TABLE idempotency_keys (
key TEXT PRIMARY KEY,
status_code INT NOT NULL,
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
When a request arrives, the server checks the key inside the same transaction as the business write. If the key already exists, it returns the stored response instead of running the operation again. Old keys can be cleaned up after a day or two, as long as that window is longer than your client's maximum retry period.
Trade-Offs Worth Knowing
Strict ordering causes head-of-line blocking. One slow mutation delays everything behind it. We accept that because ordering matters for most business data: you can't update an order that hasn't been created yet. If your writes are truly independent, you can process them in parallel per entity instead.
Optimistic UI needs a rollback path. If you show the change immediately, a dropped mutation has to reverse it on screen. Otherwise the user sees data that never reached the server.
Conflicts are a separate problem. An outbox guarantees delivery, not correctness. If two devices edit the same record offline, you still need a version field and a policy for 409 Conflict, whether that's last-write-wins, a merge, or asking the user.
Wrapping Up
An outbox turns flaky connectivity from a user-facing error into a background detail. The core ideas are small: persist every write before sending it, give each action a stable ID, classify failures instead of retrying blindly, and make the server idempotent.
This is the baseline we start from whenever a mobile app has to work offline. Start with the simplest storage that works, measure how big your queues get in the real world, and only then reach for something heavier.
Opinions expressed by DZone contributors are their own.