This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-background-sync-lifecycle-invariant

Capacitor 7 Background Sync Native-Bridge Lifecycle Invariant

Standardizes native bridge lifecycle handling in Capacitor 7 to eliminate OS-enforced background process termination (SIGKILL) on iOS and Android. Mandates defensive bridge timeouts, deterministic background task registration (`App.addListener('appStateChange')` and native BGTaskScheduler / WorkManager coordination), and idempotent queue synchronization with transactional state persistence.

Prohibited Anti-Pattern: Unbounded JavaScript promises spanning OS background transitions causing silent process termination and non-idempotent duplicate writes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Sync Native-Bridge Lifecycle Invariant - Standardizes native bridge lifecycle handling in Capacitor 7 to eliminate OS-enforced background process termination (SIGKILL) on iOS and Android. Mandates defensive bridge timeouts, deterministic background task registration (`App.addListener('appStateChange')` and native BGTaskScheduler / WorkManager coordination), and idempotent queue synchronization with transactional state persistence.
globs: src/**/*.{ts,tsx}, src/services/**/*.{ts,js}, src/sync/**/*.{ts,js}, src/plugins/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-sync-lifecycle-invariant"
---

# Capacitor 7 Background Sync Native-Bridge Lifecycle Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded JavaScript promises spanning OS background transitions causing silent process termination and non-idempotent duplicate writes

## System Constraints
You are a Principal Mobile Architect enforcing the Capacitor 7 Background Sync Native-Bridge Lifecycle Invariant. Your objective is to ensure that all background synchronization logic adheres to strict native execution budgets, transactional checkpoints, and idempotent bridge communication protocols. In Capacitor applications, the WebView thread is throttled or suspended almost immediately upon entering the background unless an active background task is registered through the native runtime. Failure to bound JavaScript promises to the native watchdog timer leads to termination by the OS (watchdog/OOM) and state corruption.

## Strict Guidelines
- Engineers MUST ALWAYS bound all network and bridge sync operations with an AbortController constrained to a safe watchdog timeout (maximum 25 seconds for iOS BackgroundTasks to stay well below the 30-second OS limit).
- Engineers MUST NOT execute raw, unmonitored Promise.all() sequences across native bridge calls during background sync transitions without persisting transactional checkpoints.
- Sync jobs MUST enforce idempotency via cryptographic deduplication keys (UUIDv5/SHA-256 of payload + timestamp bucket) persisted in native-backed storage (such as Capacitor Preferences or SQLite) before dispatching the bridge call.
- Services MUST cleanly release native background tokens (e.g., BackgroundTask.finish(taskId)) inside a finally block regardless of whether the JavaScript sync promise resolves, rejects, or aborts.
- Engineers MUST register native App.addListener('appStateChange') handlers to immediately trigger graceful degradation or pause synchronization queues when isActive flips to false.

## Bad vs Good Implementations
### Unbounded Sync Queue vs. Lifecycle-Aware Idempotent Sync Manager

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The task registers a background execution block but performs sequential unbounded network requests. If any fetch stalls or the batch exceeds the OS watchdog budget (typically 30s on iOS), the app is terminated by SIGKILL, the Preferences queue is never cleared (causing duplicate re-submissions on next launch), and taskId is leaked if an error occurs.
```typescript
import { BackgroundTask } from '@capawesome/capacitor-background-task';
import { Preferences } from '@capacitor/preferences';

export async function runSyncQueue() {
  // Anti-Pattern: No timeout bounds, no idempotency checks, token leak on uncaught errors
  const taskId = await BackgroundTask.beforeExit(async () => {
    const pending = JSON.parse((await Preferences.get({ key: 'queue' })).value || '[]');
    for (const item of pending) {
      // OS will SIGKILL WebView if network hangs past 30s
      await fetch('https://api.example.com/sync', {
        method: 'POST',
        body: JSON.stringify(item),
      });
    }
    await Preferences.remove({ key: 'queue' });
    BackgroundTask.finish({ taskId });
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements defensive 24-second hard timeouts using AbortController, ensuring execution finishes prior to iOS/Android watchdog SIGKILL. State is transactional; successful items are popped, and unprocessed or failed items remain persisted for future runs. Background execution tokens are guaranteed to finish in the finally block.
```typescript
import { BackgroundTask } from '@capawesome/capacitor-background-task';
import { Preferences } from '@capacitor/preferences';

interface SyncItem {
  id: string;
  idempotencyKey: string;
  payload: Record<string, unknown>;
}

const NATIVE_BG_TIMEOUT_MS = 24_000;

export async function runLifecycleAwareSyncQueue(): Promise<void> {
  let taskId: string | null = null;
  const abortController = new AbortController();
  const timeoutHandle = setTimeout(() => abortController.abort(), NATIVE_BG_TIMEOUT_MS);

  try {
    taskId = await BackgroundTask.beforeExit(async () => {
      const rawQueue = (await Preferences.get({ key: 'sync_queue_v1' })).value;
      if (!rawQueue) return;
      
      const queue: SyncItem[] = JSON.parse(rawQueue);
      const remaining: SyncItem[] = [];

      for (const item of queue) {
        if (abortController.signal.aborted) {
          remaining.push(item);
          continue;
        }

        try {
          const response = await fetch('https://api.example.com/v1/sync', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-Idempotency-Key': item.idempotencyKey,
            },
            body: JSON.stringify(item.payload),
            signal: abortController.signal,
          });

          if (!response.ok && response.status < 500) {
            console.error(`Client error for sync item ${item.id}, discarding`);
            continue;
          }
          if (!response.ok) {
            remaining.push(item);
          }
        } catch (err: unknown) {
          remaining.push(item);
        }
      }

      await Preferences.set({
        key: 'sync_queue_v1',
        value: JSON.stringify(remaining),
      });
    });
  } finally {
    clearTimeout(timeoutHandle);
    if (taskId) {
      BackgroundTask.finish({ taskId });
    }
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Background Sync Native-Bridge Lifecycle Invariant

Capacitor 7 Background Sync Native-Bridge Lifecycle Invariant defines an industrial-grade behavioral standard for mobile engineering. Standardizes native bridge lifecycle handling in Capacitor 7 to eliminate OS-enforced background process termination (SIGKILL) on iOS and Android. Mandates defensive bridge timeouts, deterministic background task registration (`App.addListener('appStateChange')` and native BGTaskScheduler / WorkManager coordination), and idempotent queue synchronization with transactional state persistence. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unbounded JavaScript promises spanning OS background transitions causing silent process termination and non-idempotent duplicate writes Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnbounded JavaScript promises spanning OS background transitions causing silent process termination and non-idempotent duplicate writesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS bound all network and bridge sync operations with an AbortController constrained to a safe watchdog timeout (maximum 25 seconds for iOS BackgroundTasks to stay well below the 30-second OS limit).

Engineers MUST ALWAYS bound all network and bridge sync operations with an AbortController constrained to a safe watchdog timeout (maximum 25 seconds for iOS BackgroundTasks to stay well below the 30-second OS limit).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT execute raw, unmonitored Promise.all() sequences across native bridge calls during background sync transitions without persisting transactional checkpoints.

Engineers MUST NOT execute raw, unmonitored Promise.all() sequences across native bridge calls during background sync transitions without persisting transactional checkpoints.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Sync jobs MUST enforce idempotency via cryptographic deduplication keys (UUIDv5/SHA-256 of payload + timestamp bucket) persisted in native-backed storage (such as Capacitor Preferences or SQLite) before dispatching the bridge call.

Sync jobs MUST enforce idempotency via cryptographic deduplication keys (UUIDv5/SHA-256 of payload + timestamp bucket) persisted in native-backed storage (such as Capacitor Preferences or SQLite) before dispatching the bridge call.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST cleanly release native background tokens (e.g., BackgroundTask.finish(taskId)) inside a finally block regardless of whether the JavaScript sync promise resolves, rejects, or aborts.

Services MUST cleanly release native background tokens (e.g., BackgroundTask.finish(taskId)) inside a finally block regardless of whether the JavaScript sync promise resolves, rejects, or aborts.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Engineers MUST register native App.addListener('appStateChange') handlers to immediately trigger graceful degradation or pause synchronization queues when isActive flips to false.

Engineers MUST register native App.addListener('appStateChange') handlers to immediately trigger graceful degradation or pause synchronization queues when isActive flips to false.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Capacitor 7 Background Sync Native-Bridge Lifecycle Invariant critical for AI coding assistants?

Standardizes native bridge lifecycle handling in Capacitor 7 to eliminate OS-enforced background process termination (SIGKILL) on iOS and Android. Mandates defensive bridge timeouts, deterministic background task registration (`App.addListener('appStateChange')` and native BGTaskScheduler / WorkManager coordination), and idempotent queue synchronization with transactional state persistence. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unbounded JavaScript promises spanning OS background transitions causing silent process termination and non-idempotent duplicate writes) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor