If you only read this
- The JS runtime is not reliably available in the background. Do not run sync or transfers in it.
- Put the sync engine and transfer manager in native code or a shared Kotlin Multiplatform or Rust core. Expose a thin Turbo Module.
- JS observes SQLite and sends intents. It never carries file bytes or holds the only copy of state.
01What actually happens when the OS wakes you
On Android, WorkManager starts your Worker in the application process. The React instance may not exist, and booting it just to sync costs hundreds of milliseconds and memory the system may not give you. On iOS, a background URLSession relaunch or a BGTask starts the process without any UI and gives you seconds, not minutes.
Headless JS on Android and background-fetch libraries can run JavaScript in this situation, and they are fine for prototypes and small jobs. They share the same constraints: strict time limits, no guarantees, and a startup cost. For a sync engine that must be dependable, native is the answer.
02Split of responsibilities
| Layer | Technology | Owns |
|---|---|---|
| Screens and state | React Native, TypeScript | Rendering, navigation, forms, calling intents |
| Bridge | Turbo Module (JSI) with a Codegen spec | Typed calls to native, events back to JS |
| Sync engine, transfer manager, scheduling | Kotlin and Swift, or one shared KMP / Rust core | Outbox, cursors, retries, uploads, OS scheduling |
| Storage | SQLite via a native module or op-sqlite | The single source of truth for both sides |
The database is the important line. Native code writes to it from the background. JS reads from it and subscribes to changes. Because both sides see the same rows, it does not matter whether the JS runtime was alive when the sync happened.
03A Turbo Module that only sends intent
Define a typed spec in TypeScript. Codegen produces the native interfaces. The module exposes small, asynchronous calls and an event emitter for coarse updates. Large data never crosses the bridge: you pass IDs and file paths, not payloads.
The JS side
1// NativeSyncEngine.ts2import type { TurboModule } from 'react-native';3import { TurboModuleRegistry } from 'react-native';4 5export interface Spec extends TurboModule {6 requestSync(reason: string): Promise<void>; // fire an intent7 enqueueUpload(localPath: string, entityId: string): Promise<string>; // returns upload id8 cancelUpload(uploadId: string): Promise<void>;9 addListener(eventName: string): void; // required by NativeEventEmitter10 removeListeners(count: number): void;11}12export default TurboModuleRegistry.getEnforcing<Spec>('NativeSyncEngine');The native side delegates to the same engine the background job uses. That is the point: one engine, two entry points.
The Android side
1class NativeSyncEngineModule(ctx: ReactApplicationContext) : NativeSyncEngineSpec(ctx) {2 private val engine = SyncEngine.get(ctx) // same singleton the Worker uses3 override fun getName() = "NativeSyncEngine"4 override fun requestSync(reason: String, p: Promise) { engine.requestSync(reason); p.resolve(null) }5 override fun enqueueUpload(path: String, entityId: String, p: Promise) =6 p.resolve(engine.transfers.enqueue(path, entityId))7 // engine.events -> emit coarse 'syncStateChanged' to JS. Data itself is read from SQLite.8}9 10class SyncWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) {11 override suspend fun doWork(): Result =12 if (SyncEngine.get(applicationContext).runOnce()) Result.success() else Result.retry()13}04Observing the database from JS
The screens need to update when native code writes. Two patterns work. A native table-change observer emits a lightweight event (table name, maybe an ID range) and the JS side re-runs its query. Or use a library with observation built in, such as WatermelonDB, or op-sqlite's reactive queries.
Keep lists on FlashList with stable keys and fixed item types, and select only the columns a row needs. If a screen opens slowly, the cause is almost always data shape and list configuration, not React Native itself.
05Shared core: KMP or Rust
Writing the sync engine twice invites divergence: the same bug in two languages with two fixes. Teams solve this with one shared core. Kotlin Multiplatform shares business logic across Android and iOS and is a natural fit if the Android team writes Kotlin. A Rust core with UniFFI bindings gives a small, dependency-free library for both platforms and also runs on a server, which helps when the sync protocol has a server half.
Share the sync protocol, merge rules, outbox and state machines. Keep platform scheduling (WorkManager, BGTaskScheduler) and platform networking (background URLSession) as thin adapters, because those are exactly the parts that differ.
| Option | Good | Watch for |
|---|---|---|
| Native twice | Simple tooling, platform-idiomatic | Two implementations drift; double the tests |
| KMP | Kotlin team productivity, mature Android story | iOS integration and build times need care |
| Rust + UniFFI | One tiny core, also usable server-side | Team needs Rust skills; async bridging takes effort |
06Expo and the new architecture
If you use Expo, config plugins and development builds let you add the native modules and background capabilities without ejecting. Expo's background task APIs are fine for light periodic work. The new architecture (Fabric and Turbo Modules, running on JSI) removes the old asynchronous JSON bridge, which makes the thin-module pattern faster, but it does not change the rule about where background work lives.
07Tested code, explained
A screen as one mapping
The whole list is a transformation of one database query. That's why the screen needs no sync logic.
1data class JobRow(val id: String, val ui: RowUi)2data class ListSummary(val rows: List<JobRow>, val ticks: Int, val needsReview: Int)3 4/** The whole screen is one mapping over the database query. It never mentions the network. */5fun jobList(db: LocalDb): Flow<ListSummary> = db.jobs6 .map { jobs ->7 val rows = jobs.values.sortedBy { it.id }.map { JobRow(it.id, rowUi(it)) }8 ListSummary(rows, rows.count { it.ui is RowUi.Synced }, rows.count { it.ui is RowUi.Conflict })9 }10 .distinctUntilChanged()db.jobs.map { ... }- Each commit produces one new screen state, whoever made the change.
distinctUntilChanged()- If a sync changed nothing visible, nothing redraws.
val ticks: Int- The eleven green ticks and one amber badge are simply counts of this list.
Compiled and tested by npm run test:mobile.
The worker, and its time budget
The OS gives you a few minutes. This code spends them, and leaves things tidy if it runs out.
1sealed interface WorkResult {2 /** Done. The worker enqueues a follow-up job when [morePending] is true. */3 data class Success(val morePending: Boolean) : WorkResult4 data object Retry : WorkResult5}6 7/** What the Android worker does, with no Android types, so a plain test can run it. */8class SyncWork(9 private val engine: SyncEngine,10 private val hub: TriggerHub,11 private val clockMs: () -> Long,12 private val budgetMs: Long = 8 * 60_000,13) {14 suspend fun doWork(): WorkResult {15 val deadline = clockMs() + budgetMs16 return when (val out = engine.run(hasTime = { clockMs() < deadline })) {17 is RunOutcome.Finished -> {18 if (out.morePending) hub.fire(Trigger.PERIODIC)19 WorkResult.Success(out.morePending)20 }21 is RunOutcome.RetryLater -> WorkResult.Retry // the OS applies its own backoff22 RunOutcome.AlreadyRunning -> WorkResult.Success(morePending = false)23 is RunOutcome.RebuildNeeded -> WorkResult.Success(morePending = false)24 }25 }26}deadline = clockMs() + budgetMs- Eight minutes, a little under what Android allows, so the code stops itself before the OS stops it.
hasTime = { ... }- The engine checks this between batches, so it always stops at a safe point.
if (out.morePending) hub.fire(...)- Leftover work gets a follow-up job, so nothing depends on one run finishing.
RetryLater -> WorkResult.Retry- Tells the OS to apply its own backoff. The ops are still in the outbox.
Compiled and tested by npm run test:mobile.
08Interview questions
Why not run the sync loop in JavaScript and keep one codebase?
How does a screen update after a background sync with no JS running?
What crosses the Turbo Module boundary?
KMP or Rust for the shared core?
How do you test the bridge?
Practise it: