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

Capacitor 7 Concurrent Native Bridge Thread Invariants

Enforces strict offloading of high-frequency native telemetry and bi-directional hardware streaming away from the WebView main UI thread into dedicated native worker queues and Web Workers. Prevents main-thread micro-stutters and frame drops by establishing batched RingBuffers, asynchronous native dispatching, and zero-copy transfer protocols over Capacitor 7 bridge interfaces.

Prohibited Anti-Pattern: Saturating WebView UI thread with synchronous unbatched native bridge event notifications

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Concurrent Native Bridge Thread Invariants - Enforces strict offloading of high-frequency native telemetry and bi-directional hardware streaming away from the WebView main UI thread into dedicated native worker queues and Web Workers. Prevents main-thread micro-stutters and frame drops by establishing batched RingBuffers, asynchronous native dispatching, and zero-copy transfer protocols over Capacitor 7 bridge interfaces.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.swift, android/app/src/main/java/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-native-bridge-thread-invariants"
---

# Capacitor 7 Concurrent Native Bridge Thread Invariants

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Saturating WebView UI thread with synchronous unbatched native bridge event notifications

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Concurrent Native Bridge Thread Invariants. You must mandate that high-frequency hardware streams (IMU, BLE, GPS, audio telemetry) are never dispatched directly to the main thread or directly into unthrottled WebView bridge listeners. All bi-directional bridge calls exceeding 60Hz MUST be isolated in native background queues, buffered via lock-free ring buffers, and transferred across the bridge in coalesced chunks to a dedicated Web Worker via MessageChannel or transferable ArrayBuffers.

## Strict Guidelines
- Engineers MUST ALWAYS buffer high-frequency (>60Hz) native hardware events using a native RingBuffer or fixed-interval dispatch window (16ms-33ms) before posting events over the Capacitor bridge.
- Engineers MUST NOT invoke `notifyListeners` directly from iOS main dispatch queues (`DispatchQueue.main`) or Android UI threads (`Looper.getMainLooper()`) for streaming telemetry.
- Code SHOULD offload JS-side telemetry ingestion to dedicated Web Workers using transferable `ArrayBuffer` payloads via `MessagePort` instead of parsing high-overhead JSON on the UI thread.
- Services MUST implement native-side backpressure detection that drops or aggregates hardware frames if the bridge transfer channel is congested or JS processing falls behind.
- Components NEVER attach individual React/Vue/Angular state updates directly to raw Capacitor streaming plugin listeners without an intermediate throttling or batching layer.

## Bad vs Good Implementations
### Unthrottled Raw Telemetry Stream vs. Batched Web Worker Bridge Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Attaching a direct listener to an unthrottled 100Hz native telemetry event floods the Capacitor IPC bridge, forcing JSON serialization/deserialization on the main UI thread at every tick, causing immediate jank and severe dropped frames.
```typescript
import { PluginListenerHandle } from '@capacitor/core';
import { BleTelemetryPlugin } from './plugins/telemetry';

let listenerHandle: PluginListenerHandle | null = null;

// ANTI-PATTERN: Direct binding of 100Hz BLE telemetry to UI state causes bridge congestion and frame drops
export function startTelemetryStream(onData: (val: number) => void) {
  listenerHandle = BleTelemetryPlugin.addListener('telemetryData', (event: { value: number }) => {
    // Directly executing on WebView main thread for every 10ms frame
    onData(event.value);
  });
}

export function stopTelemetryStream() {
  if (listenerHandle) {
    listenerHandle.remove();
  }
}
```

#### Production Standard (Correct)
> **Standard**: Batches native hardware stream frames native-side within a 33ms window and transfers the continuous ArrayBuffer directly to a background Web Worker using zero-copy semantics, completely isolating the WebView main thread from data ingestion.
```typescript
import { BleTelemetryPlugin } from './plugins/telemetry';

interface TelemetryBufferPayload {
  buffer: ArrayBuffer;
  sampleCount: number;
}

// PRODUCTION FIX: Offload ingestion to Web Worker using batched binary packets
export class TelemetryBridgeManager {
  private worker: Worker;
  private channel: MessageChannel;

  constructor(workerScriptUrl: string) {
    this.worker = new Worker(workerScriptUrl, { type: 'module' });
    this.channel = new MessageChannel();
    this.worker.postMessage({ type: 'INIT_PORT' }, [this.channel.port2]);
  }

  public async startStream(): Promise<void> {
    // Native plugin configured with internal 30ms RingBuffer and binary transfer
    await BleTelemetryPlugin.setStreamingParameters({ batchIntervalMs: 33, format: 'binary' });

    await BleTelemetryPlugin.addListener('telemetryBatch', (payload: TelemetryBufferPayload) => {
      // Transfer ArrayBuffer directly to Web Worker with zero copy, bypassing UI execution
      this.channel.port1.postMessage(payload.buffer, [payload.buffer]);
    });

    await BleTelemetryPlugin.startHardwareStream();
  }

  public async stopStream(): Promise<void> {
    await BleTelemetryPlugin.stopHardwareStream();
    await BleTelemetryPlugin.removeAllListeners();
    this.worker.terminate();
  }
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Concurrent Native Bridge Thread Invariants

Capacitor 7 Concurrent Native Bridge Thread Invariants defines an industrial-grade behavioral standard for mobile engineering. Enforces strict offloading of high-frequency native telemetry and bi-directional hardware streaming away from the WebView main UI thread into dedicated native worker queues and Web Workers. Prevents main-thread micro-stutters and frame drops by establishing batched RingBuffers, asynchronous native dispatching, and zero-copy transfer protocols over Capacitor 7 bridge interfaces. 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: Saturating WebView UI thread with synchronous unbatched native bridge event notifications 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 DriftSaturating WebView UI thread with synchronous unbatched native bridge event notificationsCritical
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 buffer high-frequency (>60Hz) native hardware events using a native RingBuffer or fixed-interval dispatch window (16ms-33ms) before posting events over the Capacitor bridge.

Engineers MUST ALWAYS buffer high-frequency (>60Hz) native hardware events using a native RingBuffer or fixed-interval dispatch window (16ms-33ms) before posting events over the Capacitor 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.
2

Engineers MUST NOT invoke `notifyListeners` directly from iOS main dispatch queues (`DispatchQueue.main`) or Android UI threads (`Looper.getMainLooper()`) for streaming telemetry.

Engineers MUST NOT invoke `notifyListeners` directly from iOS main dispatch queues (`DispatchQueue.main`) or Android UI threads (`Looper.getMainLooper()`) for streaming telemetry.

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

Code SHOULD offload JS-side telemetry ingestion to dedicated Web Workers using transferable `ArrayBuffer` payloads via `MessagePort` instead of parsing high-overhead JSON on the UI thread.

Code SHOULD offload JS-side telemetry ingestion to dedicated Web Workers using transferable `ArrayBuffer` payloads via `MessagePort` instead of parsing high-overhead JSON on the UI thread.

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 implement native-side backpressure detection that drops or aggregates hardware frames if the bridge transfer channel is congested or JS processing falls behind.

Services MUST implement native-side backpressure detection that drops or aggregates hardware frames if the bridge transfer channel is congested or JS processing falls behind.

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 individual React/Vue/Angular state updates directly to raw Capacitor streaming plugin listeners without an intermediate throttling or batching layer.

Components NEVER attach individual React/Vue/Angular state updates directly to raw Capacitor streaming plugin listeners without an intermediate throttling or batching layer.

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 Concurrent Native Bridge Thread Invariants critical for AI coding assistants?

Enforces strict offloading of high-frequency native telemetry and bi-directional hardware streaming away from the WebView main UI thread into dedicated native worker queues and Web Workers. Prevents main-thread micro-stutters and frame drops by establishing batched RingBuffers, asynchronous native dispatching, and zero-copy transfer protocols over Capacitor 7 bridge interfaces. 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 (Saturating WebView UI thread with synchronous unbatched native bridge event notifications) 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