# Mobile Background Work That Survives OS Limits

Background sync is not a forever daemon. Mobile platforms grant scarce execution windows—charging, unmetered network, idle, or a short push wakeup—so durable work must be queued locally with constraints, idempotency, and honest UI. Staff engineers design for completion users can see, not processes that only finish in the debugger.

Published: 2026-09-06

## The OS owns the clock, not your process

Modern iOS and Android aggressively suspend apps to protect battery, memory, and privacy. A design that assumes a long-lived background thread will finish uploads, sync CRM notes, or drain an AI job queue works on a tethered device and fails when users lock the screen on a commute.

The durable unit of work is a persisted job with metadata—retry count, last error, constraint set—not hope that JavaScript keeps running in Expo or that a native service survives OEM task killers. Treat every background entry point as a loan: you borrow milliseconds or seconds, then the OS reclaims the process.

Product features that require certainty—payment confirmation, regulated message delivery, safety alerts—need a path that does not depend on opportunistic sync alone. Foreground affordances, server-side reconciliation, or push with user-visible acknowledgment belong in the same story as WorkManager and BGTaskScheduler.

Staff mobile architecture documents what happens when the loan is never granted: queue growth, stale UI copy, and escalation to the user or support. Silence is not resilience; it is a deferred one-star review.

For Expo and React Native MVPs shipping against Supabase or custom APIs, the gap between works in dev client and works after force-quit is where background design is won or lost. Test cold start, kill, and airplane mode as first-class scenarios—not edge cases filed after launch.

Battery and thermal throttling change scheduler behavior mid-drain. Code that assumes full CPU during background windows should degrade payload size and split work across multiple wakeups instead of failing opaque.

## Model durable jobs, not background daemons

Replace mental models of our sync service with tables or files that survive process death: outbox rows, SQLite queues, or encrypted blobs keyed by idempotency tokens. Each job records intended mutation, constraints, and correlation ids for analytics.

When the OS wakes the app—foreground transition, background fetch, push handler—drain eligible jobs until the budget expires, then persist cursor state and exit cleanly. Never spin on tight loops waiting for network; bounded work per wakeup keeps you inside platform guidelines and reduces watchdog kills.

| Anti-pattern | Durable alternative |
| --- | --- |
| setInterval sync | Platform scheduler + one-shot drain |
| Fire-and-forget fetch | Outbox with retry metadata |
| Global syncing flag | Per-job state in storage |
| Assuming JS thread alive | Native module or headless task where required |

Daemons hidden from product and support become incident magnets. If only one engineer knows which module keeps sync alive, ownership failed before the first battery complaint.

Link background design to API idempotency on the server—retries from mobile are guaranteed, not exceptional. Duplicate uploads without server dedupe teach users not to trust your offline badge.

## Queue locally, reconcile with declared constraints

Persist intended mutations before the network round-trip. Attach constraints the platform understands: unmetered network, charging, device idle, or require network any. Map product language like Wi-Fi only uploads to APIs users can configure in system settings, not hidden toggles only engineers know.

Separate user-initiated urgent work from deferrable maintenance. A photo the user just captured may deserve an immediate attempt with visible progress. Nightly embedding refresh for on-device search can wait for charging and Wi-Fi. Mixing priorities in one queue burns battery and obscures which failures matter.

Conflicts belong in product design, not accidental last-write-wins. Document merge rules per entity and surface conflict UI when user outcomes depend on server truth. Background drain should never silently discard edits the user believes were saved.

```typescript
type BackgroundJob = {
  id: string;
  idempotencyKey: string;
  payload: unknown;
  constraints: ("network" | "unmetered" | "charging" | "idle")[];
  attempts: number;
  nextRunAt: string;
};

export async function enqueueMutation(job: Omit<BackgroundJob, "attempts" | "nextRunAt">) {
  await outbox.insert({
    ...job,
    attempts: 0,
    nextRunAt: new Date().toISOString(),
  });
  await schedulePlatformDrain(job.constraints);
}
```

Exponential backoff with jitter prevents thundering herds when connectivity returns across a fleet of devices. Cap attempts and route hard failures to user-visible error states or support tooling—not infinite silent retries.

## Use WorkManager and BGTaskScheduler, not custom loops

On Android, WorkManager is the supported path for deferrable, guaranteed work with constraint expressions and chaining. On iOS, BGTaskScheduler registers processing and refresh tasks with identifiers the system can coalesce across apps. Both platforms punish abuse—frequent wakeups, large transfers on cellular, work that ignores expiration handlers.

Register tasks during app launch, handle expiration by persisting partial progress, and never assume the next run time you requested is the time you receive. OS scheduling is probabilistic; product copy must reflect will sync when possible.

For React Native, prefer well-maintained bridges or config plugins that wrap these APIs over ad hoc native modules unless you own the maintenance burden. Background entry points must be idempotent: the same job id may run twice after a crash mid-drain.

Test on release builds, not only debug. Throttling, battery saver, and low-power mode differ materially from emulator defaults. Include at least one OEM device in field validation—vendor-specific killers are still common in budget Android segments.

Document minimum OS versions where background APIs you rely on exist, and degrade gracefully on older versions with foreground prompts rather than silent data loss.

## Split urgent paths from deferrable maintenance

Urgent work ties to user action: send message, confirm payment, upload evidence for a support ticket. Give it foreground network access when the app is open, a clear progress indicator, and a fallback message when background budget is insufficient.

Deferrable work includes analytics batching, cache warming, non-critical catalog sync, and expensive model downloads. Schedule it with stricter constraints and lower priority tags in your queue schema so drain logic never starves urgent jobs.

Staff teams publish a priority matrix with product: which features may show pending sync for hours versus which must block or escalate within minutes. Without that matrix, engineers default to sync everything always, which collides with OS policy and user trust.

When Supabase Realtime or push hints arrive, treat them as triggers to drain eligible jobs—not proof that all queued mutations succeeded. Realtime updates can race with offline outbox replay; ordering rules belong in server merge logic documented beside mobile queues.

Align with sibling posts on offline-first conflicts: background drain replays payloads that must match server idempotency and conflict classes. Background without conflict policy is eventual inconsistency users experience as data loss.

## Push and short wakeups accelerate; they do not replace design

Silent or data pushes can open a brief execution window for high-value sync. Platforms rate-limit abuse; users revoke notification permission; FCM and APNs delivery is best-effort. Design the happy path to complete without push, then use push as acceleration when token and permission exist.

Document behavior when wakeup never arrives: stale badges, manual pull-to-refresh, or email fallback for critical workflows. Mobile teams that treat push as guaranteed inherit web socket assumptions that do not survive iOS background rules.

For AI-assisted features—transcription, summarization, cloud retrieval—prefer on-device incremental work with explicit user initiation for expensive calls. Background LLM jobs that surprise battery meters become store reviews faster than missing cache. If cloud AI must run backgrounded, show opt-in, cost estimate, and cancellation.

Push handlers must finish quickly: deserialize, enqueue durable work, schedule drain, return. Heavy inference or large downloads inside the push callback risk termination before persistence completes.

Pair push strategy with versioning and feature flags so server can disable wakeups for builds with known drain bugs without forcing emergency store submissions.

## Expo and React Native background patterns

Expo projects often combine JavaScript application logic with native background hooks via expo-task-manager and related modules. Define tasks with stable names, register them once, and ensure task bodies rehydrate app context from cold start—no reliance on in-memory singletons from a previous session.

Use expo-background-fetch or platform-specific plugins where appropriate, understanding Expo Go limitations: development clients differ from production builds for background behavior. CI should exercise EAS production-like binaries for at least smoke background registration, not only Metro dev loops.

Keep JavaScript drain paths short; delegate large file IO and crypto to native modules when profiling shows JS thread pressure during wakeups. Background time is too small for just one more React render tree.

Secure queued payloads at rest when they contain tokens or PII—encrypted storage, exclude secrets from logs, and scrub analytics events. Background incidents are privacy incidents when crash logs include job payloads.

Freelance MVPs should hand off a background runbook: registered task ids, constraint mapping, expected queue depth metrics, and how to test drain after force-quit. Clients discover missing runbooks during the first holiday traffic spike, not during handoff week.

## Measure completion, not just enqueue

Instrument job age percentiles, success rate by constraint set, retry exhaustion counts, and user-visible staleness—last synced timestamps users actually see. A queue that grows while the app is backgrounded warns that constraints are too strict, payloads too large, or server errors too frequent.

Segment metrics by OS version and app build after releases. Background regressions often appear only on one platform when scheduler APIs change or a new animation library blocks the JS thread during drain.

Surface sync health in product when outcomes depend on it: failed uploads, pending forms, offline edits not yet merged. Hidden queues create support tickets that reproduce only on real devices in pockets.

Staff-level mobile architecture accepts OS limits as requirements, not bugs to hack around. Winning systems complete work users care about within those limits, fail loudly when they cannot, and never pretend a suspended process is still serving the customer.

Run quarterly drills: force-quit after enqueue, deny network for an hour, revoke push permission—verify UI and server state match documented promises. Drills cheaply expose gaps that unit tests miss.

Link metrics to release gates: if median job age crosses SLO after a release, treat it as a rollback candidate alongside crash rate. Background debt is production debt.

## Operational checklist for background work

Before shipping background sync: enumerate job types, constraints, idempotency keys, and user-visible states for each failure mode. Before store submission: test drain on release builds for cold start, kill mid-drain, and low battery mode.

Maintain a living diagram of entry points—foreground, push, scheduler, deep link—and which queue each may touch. On-call runbooks should name how to disable drain via remote config without shipping a store update when possible.

After incidents involving stuck queues, update retry policy, payload size limits, or product copy—not only hotfix a single bug. Postmortems that stop at network flaky without queue metrics repeat.

Coordinate with API versioning posts: background clients replay old payload shapes long after server deploys. Epoch headers and build ids on every request let you shadow, block, or migrate safely.

Healthy background layers feel invisible when working and honest when not. Users forgive syncing when on Wi-Fi more than silent data loss. Engineers forgive platforms when designs respect their contracts instead of fighting them.

When scoping Expo MVPs for remote clients, budget background behavior in the same sprint as offline outbox—not as a post-launch polish item. Store reviewers and real users punish works on my desk sync first.

Publish a one-page background contract for QA: which flows must complete in foreground, which may lag, and how long pending is acceptable before UI must warn. QA scripts that only pass on plugged-in Wi-Fi miss the OS stories users live daily.
