react-native-sync-vault
A durable, native outbox for React Native. Mutations you hand to Sync Vault are committed to SQLite on the device and delivered to your server at least once, applied exactly once: they survive offline periods, app kills, crashes, and reboots, and they keep syncing in the background without a JavaScript runtime.
v2 is a rewrite. The delivery engine now lives entirely in native code (Kotlin on Android, Swift on iOS) behind a single Turbo Module, and both platforms implement the same state machine, retry policy, and SQL schema. JavaScript only configures the engine, enqueues requests, and listens to events.
πΉ Demo Video: Watch on YouTube
Contents
Guarantees
| Guarantee |
How |
A request is never lost once enqueue() resolves |
It resolves only after the row is committed to SQLite (WAL mode) on the native DB queue. |
| Applied exactly once on the server |
Every request carries an Idempotency-Key (UUIDv7) that stays the same across all retries; the server replays the stored response for duplicates. |
| Ordered per entity |
Requests sharing a queueKey are delivered strictly one after another, in enqueue order. |
| Newest change wins |
A newer request with the same dedupeKey replaces a pending older one, and an older body can never overwrite a newer one. |
| Crash-safe in-flight work |
In-flight rows hold a lease. After a crash the lease expires and the row is retried with the same idempotency key, or dead-lettered if that was its last attempt. |
| Delivery without JS |
WorkManager (Android) and BGTaskScheduler plus a background URLSession (iOS) drain the queue while the app is suspended or killed. |
| Token refresh doesn't burn retries |
A 401 parks the request, asks JS for fresh headers, and refunds the attempt. |
| Conflicts are surfaced, not overwritten |
409/412 move the request to conflict with the server's body and version, for your resolver or UI. |
These guarantees are verified by one shared contract suite. It runs in Jest against the in-memory engine, and on device against the real Kotlin and Swift engines (see Testing).
How it works
flowchart LR
subgraph JS["JavaScript"]
App["Your app<br/>SyncVault.enqueue()"]
Hooks["Hooks / UI<br/>useSyncStatus, useRequests"]
end
subgraph Native["Native engine (Kotlin / Swift)"]
TM["Turbo Module<br/>NativeSyncVault"]
DB[("SQLite outbox<br/>WAL, single writer")]
Drain["Drain loop<br/>lease β send β classify"]
BG["Background<br/>WorkManager / BGTaskScheduler"]
Net["Connectivity<br/>ConnectivityManager / NWPathMonitor"]
end
Server["Your API<br/>(backend contract)"]
App -->|enqueue| TM --> DB
DB --> Drain -->|HTTP + Idempotency-Key| Server
Server -->|status, Retry-After, ETag| Drain --> DB
Net --> Drain
BG --> Drain
TM -->|typed events| Hooks
SyncVault.enqueue() serializes the request and hands it to the Turbo Module, which inserts it into the outbox in one transaction and returns its id.
- The drain loop claims eligible rows. A row is eligible when it is
pending, its retry time has passed, it isn't blocked on auth, and no older unfinished row shares its queueKey or dedupeKey. Claiming takes a lease and moves the row to inflight.
- The response is classified with the same table on every platform, and the row moves to its next state in a single transaction.
- Events (
enqueued, attempt, succeeded, retry_scheduled, β¦) are emitted to JS when a JS runtime is attached; hooks update from them without polling.
- When the app is in the background or killed, the platform scheduler wakes the engine at the next retry time and when connectivity returns.
Request lifecycle
stateDiagram-v2
[*] --> pending: enqueue
pending --> inflight: claimed (lease)
inflight --> succeeded: 2xx
inflight --> pending: 408 / 425 / 429 / 5xx / network error (backoff)
inflight --> pending: 401 (auth_blocked, attempt refunded)
inflight --> conflict: 409 / 412
inflight --> dead_letter: other 4xx, or attempts exhausted
inflight --> pending: lease expired (crash)
conflict --> pending: resolveConflict (keep_local / merge)
conflict --> succeeded: resolveConflict (keep_server)
dead_letter --> pending: retry()
succeeded --> [*]
dead_letter --> [*]: discard()
| Response |
Outcome |
What happens |
2xx |
success |
succeeded; kept for 7 days for inspection, then purged. |
401 |
auth |
Parked as authBlocked, JS is asked for new headers, the attempt is refunded. |
409, 412 |
conflict |
conflict with the server body and ETag; resolved by strategy, resolver, or UI. |
408, 425, 429, 5xx, network error |
retryable |
Back to pending at now + max(Retry-After, backoff). |
any other 4xx |
permanent |
dead_letter immediately; never retried automatically. |
Backoff is exponential with full jitter: random(0, min(retryMaxDelayMs, retryBaseDelayMs Γ 2^(attemptβ1))). Retry-After is honoured in both delta-seconds and HTTP-date form. After maxAttempts retryable failures the request is dead-lettered.
Platform features
|
Android |
iOS |
| Storage |
SQLite (WAL) in noBackupFilesDir |
SQLite (WAL), file protection completeUntilFirstUserAuthentication, excluded from backup |
| Connectivity |
ConnectivityManager network callbacks |
NWPathMonitor |
| Background drain |
WorkManager: expedited one-time work, delayed work at the next retry time, periodic work |
BGProcessingTask + BGAppRefreshTask, beginBackgroundTask to finish an in-progress drain |
| Large payloads |
Stored as files, uploaded by a dataSync foreground service |
Stored as files, uploaded by a background URLSession that continues after the app is killed |
| Encryption at rest (opt-in) |
AES-256-GCM, non-exportable Android Keystore key |
AES-256-GCM, Keychain key (AfterFirstUnlockThisDeviceOnly) |
| HTTP |
OkHttp |
URLSession |
Requirements
- React Native 0.76+ with the New Architecture enabled (the default in 0.76). The legacy bridge is not supported.
- React 18+.
- iOS 15.1+, Android API 24+.
Installation
npm install react-native-sync-vault
npx sync-vault-init # patches Info.plist and checks AndroidManifest.xml (--dry-run to preview)
cd ios && pod install
iOS
sync-vault-init adds these keys to your app's Info.plist; add them by hand if you don't use the CLI:
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>com.syncvault.drain</string>
<string>com.syncvault.refresh</string>
</array>
<key>UIBackgroundModes</key>
<array>
<string>processing</string>
<string>fetch</string>
</array>
Background task handlers are registered by the library at process start, so no extra code is needed for them. To record large uploads that finish while the app is suspended or killed, forward the background URLSession callback in AppDelegate.mm:
#import <react-native-sync-vault/SyncVaultAppDelegate.h>
- (void)application:(UIApplication *)application
handleEventsForBackgroundURLSession:(NSString *)identifier
completionHandler:(void (^)(void))completionHandler
{
[SyncVaultAppDelegate handleEventsForBackgroundURLSession:identifier completionHandler:completionHandler];
}
Xcode 26+ with React Native 0.76: the bundled fmt 11.0.2 pod doesn't compile as C++20 with newer clang. Add this to the post_install block of your Podfile:
installer.pods_project.targets.each do |target|
next unless target.name == 'fmt'
target.build_configurations.each { |c| c.build_settings['CLANG_CXX_LANGUAGE_STANDARD'] = 'c++17' }
end
Android
Nothing to add: autolinking registers the module, and the library manifest merges INTERNET, ACCESS_NETWORK_STATE, FOREGROUND_SERVICE, FOREGROUND_SERVICE_DATA_SYNC, and the WorkManager foreground service with foregroundServiceType="dataSync". sync-vault-init warns if your app manifest removes any of them with tools:node="remove".
Quick start
Configure the engine once, at app start, outside React (for example in index.js). Background launches on iOS and Android may start your JS without mounting any component.
// index.js
import { SyncVault } from 'react-native-sync-vault';
import { tokenStore } from './auth';
SyncVault.configure({
baseUrl: 'https://api.example.com',
// Called at configure time and on every 401; headers are stored natively and
// attached at send time, so a refreshed token applies to already-queued requests.
getAuthHeaders: async () => ({ Authorization: `Bearer ${await tokenStore.freshToken()}` }),
conflictResolver: (conflict) => ({ action: 'keep_server' }),
onEvent: (event) => logger.debug('sync', event),
});
Queue mutations with client-generated IDs, and update the UI optimistically:
import { SyncVault } from 'react-native-sync-vault';
async function addTodo(title: string) {
const todo = { id: SyncVault.generateId(), title, done: false }; // UUIDv7
setTodos((list) => [...list, todo]); // optimistic
await SyncVault.enqueue({
method: 'POST',
url: '/todos',
body: todo,
queueKey: `todo:${todo.id}`, // create β update β delete stay in order
});
}
async function toggleTodo(todo: Todo) {
await SyncVault.enqueue({
method: 'PATCH',
url: `/todos/${todo.id}`,
body: { done: !todo.done },
queueKey: `todo:${todo.id}`,
dedupeKey: `todo:${todo.id}:done`, // rapid taps collapse into one request
});
}
Show sync state anywhere:
import { useSyncStatus, useFailedRequests } from 'react-native-sync-vault';
function SyncBadge() {
const { isOnline, pendingCount, counts, isDraining } = useSyncStatus();
return <Text>{isOnline ? 'online' : 'offline'} Β· {pendingCount} pending Β· {counts.deadLetter} failed</Text>;
}
function FailedList() {
const { requests, retry, discard } = useFailedRequests();
return requests.map((r) => (
<Row key={r.id} title={`${r.method} ${r.url}`} subtitle={r.lastError} onRetry={() => retry(r.id)} onDiscard={() => discard(r.id)} />
));
}
Core concepts
Idempotency keys
Each request gets an Idempotency-Key header, defaulting to its UUIDv7 id. The key never changes across retries, so a request whose response was lost is replayed by the server instead of applied twice. Pass idempotencyKey to reuse a key you already have. The key is rotated only when the payload changes after it may already have been sent: on coalescing (see below) and on conflict resolution.
Ordering with queueKey
Requests with the same queueKey are delivered strictly in enqueue order; a later request waits until the earlier one reaches a terminal state or a conflict. Requests with different keys (or no key) are sent in parallel, up to maxConcurrency. Use one key per entity, such as todo:<id>.
Coalescing with dedupeKey
When a request with a dedupeKey is enqueued and the newest unfinished request with that key is still pending, its body is replaced instead of a second row being added. If the newest one is already in flight or in conflict, the new request is queued behind it, so an older body can never overwrite a newer one on the server.
Client-generated IDs
Create records offline with SyncVault.generateId() (RFC 9562 UUIDv7, time-ordered). Your server should accept the client ID as the primary key, which makes creates naturally idempotent and lets follow-up updates reference the record before it exists on the server.
Authentication
Provide getAuthHeaders instead of baking tokens into queued requests. Headers are stored natively and attached at send time. On a 401 the request is parked (authBlocked) without spending an attempt, JS is asked once for fresh headers (single-flight), and all parked requests resume. If JS isn't running, requests stay parked until the next configure() or setAuthHeaders().
Conflicts
A 409 or 412 moves the request to conflict and stores the server's body and ETag. What happens next depends on the request's conflictStrategy:
| Strategy |
Behaviour |
manual (default) |
Stays in conflict until conflictResolver or your UI calls resolveConflict(). |
client_wins |
Resent natively with the server's version as If-Match. |
server_wins |
The local change is dropped. |