/Learn
Mobile systems at scale · Part 5 of 7

React Native after the JS runtime is gone

JavaScript may not be running when the OS wakes your app to sync. Build those parts in native code, and let React Native do what it does well.

05
React NativeTurbo ModulesKMP

Mobile engineeringReact Native in one place8 of 22Next: The sync engine →

Run Priya's app in React Native, and the 4:12 pm wake-up may have no JavaScript at all. This post splits the work accordingly. Start from the basics in Day 9 →

Study with AI

If you only read this

  1. The JS runtime is not reliably available in the background. Do not run sync or transfers in it.
  2. Put the sync engine and transfer manager in native code or a shared Kotlin Multiplatform or Rust core. Expose a thin Turbo Module.
  3. JS observes SQLite and sends intents. It never carries file bytes or holds the only copy of state.
The one ruleJavaScript renders and requests. Native code schedules, transfers and syncs. The database is the contract between them.

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

LayerTechnologyOwns
Screens and stateReact Native, TypeScriptRendering, navigation, forms, calling intents
BridgeTurbo Module (JSI) with a Codegen specTyped calls to native, events back to JS
Sync engine, transfer manager, schedulingKotlin and Swift, or one shared KMP / Rust coreOutbox, cursors, retries, uploads, OS scheduling
StorageSQLite via a native module or op-sqliteThe 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

js-side.tsTypeScript
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');
12 linesUTF-8TypeScript

The native side delegates to the same engine the background job uses. That is the point: one engine, two entry points.

The Android side

android-side.ktKotlin
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}
13 linesUTF-8Kotlin

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.

Do notSend large JSON arrays or base64 images over the bridge, run SQLite queries on the JS thread for big lists, or keep upload state only in a Redux store. A process death erases all three.

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.

OptionGoodWatch for
Native twiceSimple tooling, platform-idiomaticTwo implementations drift; double the tests
KMPKotlin team productivity, mature Android storyiOS integration and build times need care
Rust + UniFFIOne tiny core, also usable server-sideTeam 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.

RowUi.ktKotlin
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()
10 linesUTF-8Kotlin
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.

SyncTriggers.ktKotlin
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}
26 linesUTF-8Kotlin
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?
The runtime may not exist when the OS wakes the app, startup costs time and memory, and background limits are strict. Native code starts instantly and is allowed to run.
How does a screen update after a background sync with no JS running?
Native writes to SQLite. When the app opens, the screen queries the database. If JS is alive, a change event triggers a re-query.
What crosses the Turbo Module boundary?
Small typed calls: intents, IDs, file paths and coarse state events. Never files or large payloads.
KMP or Rust for the shared core?
KMP if the team is Kotlin-first and the core is mostly business logic. Rust if you also want the core on the server or need a very small, strictly controlled library.
How do you test the bridge?
Unit-test the core with fakes, contract-test the module spec against both platforms, and run an end-to-end test that kills the app mid-sync and asserts it resumes.

Practise it:

React NativeTurbo ModulesKMP
Written by

Rizvan

Builds mobile and AI systems at scale and writes the series he wished existed before his own principal loop: one rule, one analogy, something to break, and the interview kit.

All 7 parts
AI Engineer · written by Rizvan · part 5 of 7