This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-native-bridge-serialization-quarantine

Capacitor 7 Native Bridge Serialization Quarantine and Thread Isolation

High-frequency bi-directional bridge traffic between the WebView and native runtime in Capacitor 7 can monopolize the UI thread and trigger Out-Of-Memory (OOM) faults via unmetered JSON serialization. This rule enforces an off-main-thread serialization quarantine via dedicated Web Workers on the web layer and explicit background dispatch queues/coroutines with bounded chunk buffers on native platforms.

Prohibited Anti-Pattern: Synchronous Main-Thread JSON Bridge Flooding with Unbounded Large Payloads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Serialization Quarantine and Thread Isolation - High-frequency bi-directional bridge traffic between the WebView and native runtime in Capacitor 7 can monopolize the UI thread and trigger Out-Of-Memory (OOM) faults via unmetered JSON serialization. This rule enforces an off-main-thread serialization quarantine via dedicated Web Workers on the web layer and explicit background dispatch queues/coroutines with bounded chunk buffers on native platforms.
globs: src/**/*.{ts,tsx}, android/app/src/main/java/**/*.java, android/app/src/main/kotlin/**/*.kt, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-native-bridge-serialization-quarantine"
---

# Capacitor 7 Native Bridge Serialization Quarantine and Thread Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Synchronous Main-Thread JSON Bridge Flooding with Unbounded Large Payloads

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Bi-Directional Native Bridge Serialization Quarantine. You must strictly mandate that all high-frequency (>30Hz) or large-payload (>64KB) bridge communications are isolated from the main/UI thread on both the WebView and native layers. You must prohibit direct JSON.stringify/parse calls on the DOM main thread for bridge traffic, mandate off-thread worker processing or binary transfer via ArrayBuffers/File handles, and reject any native plugin implementation that executes heavy deserialization directly inside the main UI dispatch queue.

## Strict Guidelines
- Engineers MUST ALWAYS process bridge payloads exceeding 64KB or running at higher frequencies than 30Hz inside a Web Worker before sending them to Capacitor plugins.
- Engineers MUST NOT dispatch plugin callbacks containing large payloads directly onto the Android UI Thread or iOS Main Dispatch Queue.
- Native Android plugins MUST consume payloads on Dispatchers.Default or an isolated ExecutorService, and iOS plugins MUST execute deserialization on an isolated DispatchQueue with QoS .utility or .userInitiated.
- Services MUST chunk high-throughput sensor or streaming data into pre-allocated TypedArray buffers, avoiding raw JSON string serialization across the bridge.
- Components NEVER attach high-frequency event listeners directly to Capacitor plugin interfaces without applying client-side backpressure (e.g., throttling, batching, or windowing).

## Bad vs Good Implementations
### High-Frequency Native Bridge Dispatch with Worker Quarantine

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing JSON.stringify on multi-megabyte payloads directly on the browser main thread causes severe frame drops (UI starvation). Furthermore, passing huge JSON strings over the native bridge forces synchronous string marshaling on the UI thread.
```typescript
import { registerPlugin } from '@capacitor/core';

interface StreamPlugin {
  pushBatch(options: { data: string }): Promise<void>;
}
const NativeStream = registerPlugin<StreamPlugin>('StreamPlugin');

// ANTI-PATTERN: Serializing 5MB payload on UI thread and blocking the WebView event loop
export async function sendTelemetryData(largeDataset: Record<string, unknown>[]): Promise<void> {
  const serialized = JSON.stringify(largeDataset);
  await NativeStream.pushBatch({ data: serialized });
}
```

#### Production Standard (Correct)
> **Standard**: The CPU-intensive serialization is quarantined to an isolated Web Worker. Instead of flooding the bridge string-marshalling pipe, data is persisted to a scratchpad file or handled as chunked memory, passing only a pointer descriptor across the native bridge.
```typescript
import { registerPlugin } from '@capacitor/core';

interface StreamPlugin {
  pushBatchChunked(options: { chunkPath: string; byteCount: number }): Promise<{ success: boolean }>;
}
const NativeStream = registerPlugin<StreamPlugin>('StreamPlugin');

// PRODUCTION FIX: Quarantine serialization to Web Worker and stream via file reference/chunking
export async function sendTelemetryData(largeDataset: Record<string, unknown>[]): Promise<void> {
  const worker = new Worker(new URL('./serialization.worker.ts', import.meta.url), { type: 'module' });
  
  const chunkFileRef = await new Promise<string>((resolve, reject) => {
    worker.onmessage = (event: MessageEvent<{ filePath: string }>) => resolve(event.data.filePath);
    worker.onerror = (err) => reject(err);
    worker.postMessage({ payload: largeDataset });
  });

  try {
    await NativeStream.pushBatchChunked({ chunkPath: chunkFileRef, byteCount: largeDataset.length });
  } finally {
    worker.terminate();
  }
}
```

### Native iOS Plugin Off-Thread Bridge Handling (Swift)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The plugin method runs on the default bridge thread context without offloading JSON deserialization. Doing heavy parsing in ingestBatch directly blocks Capacitor's internal message processing loop, stalling the WebView.
```swift
import Foundation
import Capacitor

@objc(SensorStreamPlugin)
public class SensorStreamPlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "SensorStreamPlugin"
    public let jsName = "SensorStream"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "ingestBatch", returnType: CAPPluginReturnPromise)
    ]

    // ANTI-PATTERN: Deserializing large raw JSON directly on the UI dispatch thread
    @objc func ingestBatch(_ call: CAPPluginCall) {
        guard let rawPayload = call.getString("data") else {
            call.reject("Missing data")
            return
        }
        let data = Data(rawPayload.utf8)
        let json = try! JSONSerialization.jsonObject(with: data, options: [])
        // Mutating models or doing intensive parsing on the caller thread
        call.resolve(["status": "processed", "items": (json as? [Any])?.count ?? 0])
    }
}
```

#### Production Standard (Correct)
> **Standard**: The computationally expensive JSON deserialization is quarantined to a dedicated utility DispatchQueue, preventing the Capacitor bridge loop and the Main UI Thread from dropping frames.
```swift
import Foundation
import Capacitor

@objc(SensorStreamPlugin)
public class SensorStreamPlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "SensorStreamPlugin"
    public let jsName = "SensorStream"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "ingestBatch", returnType: CAPPluginReturnPromise)
    ]
    
    // Dedicated QoS quarantine queue with concurrency bounding
    private let processingQueue = DispatchQueue(label: "io.capacitor.bridge.quarantine", qos: .utility)

    @objc func ingestBatch(_ call: CAPPluginCall) {
        guard let rawPayload = call.getString("data") else {
            call.reject("Missing data payload")
            return
        }
        
        // PRODUCTION FIX: Offload deserialization and processing off the main/bridge queue
        processingQueue.async { [weak self] in
            guard let self = self else { return }
            do {
                let data = Data(rawPayload.utf8)
                guard let json = try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) as? [String: Any] else {
                    call.reject("Invalid payload structure")
                    return
                }
                let processedCount = json.keys.count
                call.resolve(["status": "processed", "keys": processedCount])
            } catch {
                call.reject("Deserialization failed: \(error.localizedDescription)")
            }
        }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Native Bridge Serialization Quarantine and Thread Isolation

Capacitor 7 Native Bridge Serialization Quarantine and Thread Isolation defines an industrial-grade behavioral standard for mobile engineering. High-frequency bi-directional bridge traffic between the WebView and native runtime in Capacitor 7 can monopolize the UI thread and trigger Out-Of-Memory (OOM) faults via unmetered JSON serialization. This rule enforces an off-main-thread serialization quarantine via dedicated Web Workers on the web layer and explicit background dispatch queues/coroutines with bounded chunk buffers on native platforms. 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: Synchronous Main-Thread JSON Bridge Flooding with Unbounded Large Payloads 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 DriftSynchronous Main-Thread JSON Bridge Flooding with Unbounded Large PayloadsCritical
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 process bridge payloads exceeding 64KB or running at higher frequencies than 30Hz inside a Web Worker before sending them to Capacitor plugins.

Engineers MUST ALWAYS process bridge payloads exceeding 64KB or running at higher frequencies than 30Hz inside a Web Worker before sending them to Capacitor plugins.

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 dispatch plugin callbacks containing large payloads directly onto the Android UI Thread or iOS Main Dispatch Queue.

Engineers MUST NOT dispatch plugin callbacks containing large payloads directly onto the Android UI Thread or iOS Main Dispatch Queue.

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

Native Android plugins MUST consume payloads on Dispatchers.Default or an isolated ExecutorService, and iOS plugins MUST execute deserialization on an isolated DispatchQueue with QoS .utility or .userInitiated.

Native Android plugins MUST consume payloads on Dispatchers.Default or an isolated ExecutorService, and iOS plugins MUST execute deserialization on an isolated DispatchQueue with QoS .utility or .userInitiated.

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 chunk high-throughput sensor or streaming data into pre-allocated TypedArray buffers, avoiding raw JSON string serialization across the bridge.

Services MUST chunk high-throughput sensor or streaming data into pre-allocated TypedArray buffers, avoiding raw JSON string serialization across the bridge.

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

Components NEVER attach high-frequency event listeners directly to Capacitor plugin interfaces without applying client-side backpressure (e.g., throttling, batching, or windowing).

Components NEVER attach high-frequency event listeners directly to Capacitor plugin interfaces without applying client-side backpressure (e.g., throttling, batching, or windowing).

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 Native Bridge Serialization Quarantine and Thread Isolation critical for AI coding assistants?

High-frequency bi-directional bridge traffic between the WebView and native runtime in Capacitor 7 can monopolize the UI thread and trigger Out-Of-Memory (OOM) faults via unmetered JSON serialization. This rule enforces an off-main-thread serialization quarantine via dedicated Web Workers on the web layer and explicit background dispatch queues/coroutines with bounded chunk buffers on native platforms. 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 (Synchronous Main-Thread JSON Bridge Flooding with Unbounded Large Payloads) 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