The background-work layer

Background layers adapt your app to the OS scheduler. They turn many triggers (app open, network back, push, timers, user actions) into a f…

Part 1 of 5

Basics

What this part of the system is, what it is responsible for, and the vocabulary you need before the mechanics.

1.1Definition

The one-paragraph summary, then where its responsibility starts and stops.

Background layers adapt your app to the OS scheduler. They turn many triggers (app open, network back, push, timers, user actions) into a few jobs, give each a time budget, and report results so the OS keeps trusting your app.

Its job
  • Collect triggers and coalesce them into one job
  • Map jobs to WorkManager on Android and BGTaskScheduler on iOS
  • Pass a time budget and a cancellation signal to the engines
  • Translate engine results into success, retry or reschedule
  • Record which triggers actually ran, per OS and manufacturer
Not its job
  • Contain sync or transfer logic
  • Keep anything alive with wake locks or endless services
  • Poll the server on a timer while the app is closed

1.2Key concepts

Ideas this deep dive relies on, in one sentence each.

01Outbox

Table of pending local writes, committed in the same transaction as the data, drained by the sync engine.

02WorkManager

Android library for deferrable, guaranteed background work.

03BGTaskScheduler

iOS framework that runs background tasks at times the system chooses.

04Background URLSession

iOS transfer session performed by a system daemon and surviving app termination.

05Turbo Module

React Native native module using JSI with a typed spec.

06KMP

Kotlin Multiplatform: share Kotlin logic between Android and iOS.

1.3Real-life run

A concrete example first, so the mechanics have something to attach to.

In one minute, Meera’s phone produces five reasons to sync: she edits a booking, the app goes to the background, Wi-Fi reconnects, a push arrives saying her clinic changed a time, and the periodic job comes due. A naive app would start five syncs.

The trigger hub coalesces them. On Android, each trigger enqueues unique work named sync with a KEEP policy, so only one job exists. On iOS, the edit starts a short background task to finish the write, and the rest schedule one app refresh request.

WorkManager runs the job when the network constraint is met. The worker calls the sync engine with an eight-minute budget. The engine returns Success with more pending, so the worker returns success and enqueues one follow-up job.

Over a week, telemetry shows that on one manufacturer’s phones, periodic jobs ran 70% less often. The team adds a one-time battery-settings guide for affected users and shifts weight to sync-on-open, without touching the sync engine.

Part 2 of 5

Question

Know what you are reading for. These are the questions this deep dive prepares you to answer, and the rounds where they come up.

2.1Target questions

Keep them in mind while you read the detail.

  1. Why put an adapter between engines and the OS?
  2. What do you do in the FCM callback?
  3. How do you know background sync works in the field?

Model answers are in part 4, after the detail that supports them.

2.2Interview rounds

System design rounds where this component is part of a strong answer.

Part 3 of 5

Detailed answer

How it actually works: the components, the states it moves through, a full run, and the code.

3.1Anatomy

The parts and how they connect.

TRIGGERSBACKGROUND-WORK LAYERENGINESApp lifecycleopen · backgroundNetwork + pushconnectivity · FCM· APNsUser actionedit · uploadTrigger hubdedupe · priorityAndroid adapterWorkManager · UIDTiOS adapterBGTaskSchedulerJob runnerbudget · cancelResult mappersuccess · retryRun telemetryby OS · OEMSync enginerecordsTransfer managerfilesRemote configrules · kill switchenqueuerun(budget)Result
ClientService
Boxes are components; arrows show calls and data flow.
Trigger hub
Accepts trigger(reason, priority). It collapses duplicates within a short window and decides the job type: an immediate expedited job after a user edit, a constrained job for background catch-up, or a user-initiated transfer job.
Android adapter
Enqueues unique work with WorkManager, sets constraints and backoff, uses expedited work with a fallback when quota runs out, and schedules user-initiated data transfer jobs for big uploads on Android 14+.
iOS adapter
Registers BGTask identifiers at launch, schedules BGAppRefreshTask and BGProcessingTask requests, wraps the expiration handler, and starts a short background task when the app is backgrounded mid-write.
Job runner
Creates a deadline from the OS budget, passes a cancellation token to the engines, and guarantees the OS is told the job finished.
Result mapper
Turns engine results into Result.success(), Result.retry() or setTaskCompleted(success:), and schedules the next run with the delay the engine suggested.
Run telemetry
Logs every run: trigger, scheduled time, actual start, duration, outcome, OS version and manufacturer. This is how you discover OEM restrictions.

3.2States

StateMeaning
Not scheduledNo pending reason to run.
ScheduledA job exists with constraints; waiting for the OS.
RunningEngine executing within its budget.
Retry pendingEngine asked for a retry; OS backoff applies.
BlockedUser or OS has stopped background work (Force Stop, background restrictions); runs only when the app opens.

3.3Run loop

One run, step by step.

TriggerTrigger hubWorkManagerWorkerSync engineedit savednetwork backpush receivedenqueueUniqueWork(sync, KEEP)Constraint met: network connecteddoWork()run(reason, budget 8 min)Success(morePending)Result.success()enqueue follow-up
Solid arrows are calls; dashed arrows are responses.
  1. Three triggers become one job because the work name is unique and the policy is KEEP.
  2. Network work never happens inside the push callback; the callback only enqueues.
  3. The worker always returns a result, so the OS keeps scheduling the app normally.

3.4Code

Working code for the core of it.

Android: trigger hub and worker

android-trigger-hub.ktKotlinCopy
1object SyncTriggers {2  fun request(ctx: Context, reason: Reason, urgent: Boolean = false) {3    val req = OneTimeWorkRequestBuilder<SyncWorker>()4      .setInputData(workDataOf("reason" to reason.name))5      .setConstraints(Constraints(requiredNetworkType = NetworkType.CONNECTED))6      .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)7      .apply { if (urgent) setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) }8      .build()9    WorkManager.getInstance(ctx).enqueueUniqueWork("sync", ExistingWorkPolicy.KEEP, req)10  }11}12 13class SyncWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) {14  override suspend fun doWork(): Result {15    val reason = Reason.valueOf(inputData.getString("reason") ?: "PERIODIC")16    return when (val r = engine.run(reason, budget = 8.minutes)) {17      is RunResult.Success -> { if (r.morePending) SyncTriggers.request(applicationContext, Reason.FOLLOW_UP); Result.success() }18      is RunResult.Retry -> Result.retry()19      RunResult.NeedsLogin, RunResult.Disabled, RunResult.AlreadyRunning -> Result.success()20    }21  }22}23 24class PushService : FirebaseMessagingService() {25  override fun onMessageReceived(msg: RemoteMessage) {26    if (msg.data["type"] == "changes") SyncTriggers.request(this, Reason.PUSH, urgent = true)   // enqueue only27  }28}
28 linesUTF-8Kotlin

Android: periodic safety net and the leave-app trigger

android-periodic-safety.ktKotlinCopy
1// Periodic safety net: Android may batch or delay it, so it is never the only trigger.2fun schedulePeriodicSync(ctx: Context) {3  val req = PeriodicWorkRequestBuilder<SyncWorker>(15, TimeUnit.MINUTES)4    .setInputData(workDataOf("reason" to Reason.PERIODIC.name))5    .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).setRequiresBatteryNotLow(true).build())6    .build()7  WorkManager.getInstance(ctx).enqueueUniquePeriodicWork("sync-periodic", ExistingPeriodicWorkPolicy.KEEP, req)8}9 10// The user just left the app with unsynced edits: ask for expedited work, not a background service.11class LeaveAppTrigger(private val ctx: Context, private val outbox: OutboxDao) : DefaultLifecycleObserver {12  override fun onStop(owner: LifecycleOwner) {13    owner.lifecycleScope.launch {14      if (outbox.readyCount() > 0) SyncTriggers.request(ctx, Reason.BACKGROUNDED, urgent = true)15    }16  }17}18 19class App : Application() {20  override fun onCreate() {21    super.onCreate()22    schedulePeriodicSync(this)23    ProcessLifecycleOwner.get().lifecycle.addObserver(LeaveAppTrigger(this, db.outbox()))   // whole app, not one Activity24  }25}
25 linesUTF-8Kotlin

React Native: Turbo Module spec

react-native-turbo.tsTypeScriptCopy
1// NativeSyncModule.ts — codegen generates the native interfaces from this spec2import type { TurboModule } from 'react-native';3import { TurboModuleRegistry } from 'react-native';4 5export interface Spec extends TurboModule {6  requestSync(reason: string): void;7  enqueueUpload(fileUri: string, ownerId: string, priority: string): Promise<string>;8  cancelUpload(transferId: string): void;9}10export default TurboModuleRegistry.getEnforcing<Spec>('SyncModule');
10 linesUTF-8TypeScript

3.5Tested code, explained

A working implementation, then what each part does and why.

Every trigger becomes one job

Edits, pushes, timers and reconnects all want a sync. Without this funnel, a busy minute would start five of them.

SyncTriggers.ktKotlinCopy
1/** The part of WorkManager this code needs. Returns false when a job with this name already waits. */2fun interface JobScheduler {3  fun enqueueUnique(name: String, requiresNetwork: Boolean): Boolean4}5 6/** Every reason to sync comes through here, and they all become the same one job. */7class TriggerHub(private val scheduler: JobScheduler) {8  var lastTrigger: Trigger? = null9    private set10 11  fun fire(trigger: Trigger): Boolean {12    lastTrigger = trigger13    return scheduler.enqueueUnique("sync", requiresNetwork = true)14  }15}
15 linesUTF-8Kotlin
fun interface JobScheduler
The one WorkManager feature this code needs. Hiding it behind an interface lets a plain test run this code.
enqueueUnique("sync", ...)
On Android this is enqueueUniqueWork with KEEP: if a job named sync already waits, nothing new is added.
requiresNetwork = true
The condition the OS waits for. Your code doesn't watch the network at all.

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.ktKotlinCopy
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.

3.6Platforms

Android

  • WorkManager for deferrable and expedited work; unique names stop duplicates.
  • User-initiated data transfer jobs for long uploads the user started (Android 14+).
  • Foreground services only with a declared type, and not as a long-term home for sync (Android 15 limits dataSync).
  • Test Doze with adb shell dumpsys deviceidle force-idle and standby buckets with am set-standby-bucket.

iOS

  • BGTaskSchedulerPermittedIdentifiers and UIBackgroundModes in Info.plist.
  • BGAppRefreshTask for short catch-up; BGProcessingTask for heavy work while charging.
  • Silent push only triggers a refresh; the OS throttles it and guarantees nothing.
  • Simulate launches from the Xcode debugger with _simulateLaunchForTaskWithIdentifier.

React Native

  • A Turbo Module whose native side calls the same Android and iOS adapters.
  • expo-background-task or react-native-background-fetch for early versions, replaced by native adapters at scale.
  • JavaScript only requests work and observes results.
Part 4 of 5

Q&A

The questions from part 2, now with model answers. Try each one out loud before opening it.

4.1Interview questions

Why put an adapter between engines and the OS?
The engines become platform-agnostic and testable, and all OS quirks, quotas and telemetry live in one small place per platform.
What do you do in the FCM callback?
Only enqueue work. The callback has a short time window, and the network call belongs in a worker with constraints and retries.
How do you know background sync works in the field?
Run telemetry by trigger, OS version and manufacturer, plus freshness percentiles. Without it, you are guessing.
Part 5 of 5

Extra depth

Practical context for real projects: which technology to pick, what successful teams do, what to measure and the edge cases to plan for.

5.1Technology choices

Show detailsHide details
NeedOptionsWhen to pick
Android schedulingWorkManager · JobScheduler · AlarmManager · foreground serviceWorkManager for almost everything; UIDT jobs for long user transfers; avoid exact alarms for sync.
iOS schedulingBGTaskScheduler · background URLSession · silent push · beginBackgroundTaskRefresh tasks for catch-up, URLSession for bytes, short tasks to finish writes.
PushFCM data messages · APNs background notificationsUse as a hint with collapse keys; never as the only path.
Cross-platform glueTurbo Modules · Expo Modules API · KMP expect/actualTurbo Modules for bare RN, Expo Modules in Expo apps, KMP for shared Kotlin.

5.2Metrics to emit

Show detailsHide details
MetricWhy it matters
runs per device per day by triggerShows which triggers actually execute.
scheduled → started delayReveals Doze, standby buckets and OEM throttling.
expirations and cancellationsiOS schedules apps that overrun less often.
share of syncs on app openIf most syncs happen on open, background scheduling is not working for that segment.

5.3Edge cases

Show detailsHide details
CaseHow it is handled
Force Stop on AndroidAll jobs cancelled until the user opens the app; sync on open covers it.
User rarely opens the iOS appFew background runs; push hints and on-open sync carry freshness.
Expedited quota exhaustedFalls back to normal work automatically with the out-of-quota policy.
Push stormCollapse keys plus KEEP policy mean one job, not hundreds.