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

Capacitor 7 Native Bridge Buffer Isolation & High-Frequency Streaming Guardrail

Enforces strict buffer isolation, off-thread queuing, and Web Worker routing for high-throughput peripheral and sensor streams over the Capacitor 7 native-web bridge. Eliminates V8 heap exhaustion and main-thread UI frame dropping caused by unthrottled serialization across WKWebView and Android WebView bridge boundaries.

Prohibited Anti-Pattern: Unthrottled Bridge Event Dispatching Directly into Main-Thread React/Vue State

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Buffer Isolation & High-Frequency Streaming Guardrail - Enforces strict buffer isolation, off-thread queuing, and Web Worker routing for high-throughput peripheral and sensor streams over the Capacitor 7 native-web bridge. Eliminates V8 heap exhaustion and main-thread UI frame dropping caused by unthrottled serialization across WKWebView and Android WebView bridge boundaries.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, android/app/src/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-native-bridge-buffer-isolation"
---

# Capacitor 7 Native Bridge Buffer Isolation & High-Frequency Streaming Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unthrottled Bridge Event Dispatching Directly into Main-Thread React/Vue State

## System Constraints
You are a Principal Mobile Architect specializing in Capacitor 7 core internals, WKScriptMessageHandler, and Android WebView JSI/IPC bridges. You enforce strict buffer isolation, transferable typed arrays, and backpressure management. Never permit continuous (>30Hz) stringified JSON payloads across Capacitor plugins directly to main-thread UI state. Mandate batched RingBuffers, Web Worker offloading, and requestAnimationFrame-coupled rendering states to safeguard 60fps/120fps UI threads and prevent V8 Garbage Collection stalls.

## Strict Guidelines
- Engineers MUST ALWAYS route streaming telemetry (>30Hz, e.g., BLE, IMU, audio, LiDAR) to a dedicated Web Worker via transferable ArrayBuffers or batched chunk structures instead of firing continuous native plugin listener events.
- Engineers MUST NOT mutate reactive UI framework state (React useState/useReducer, Vue ref) directly inside Capacitor plugin event listener callbacks for streaming peripherals.
- Native plugins MUST implement backpressure handling and windowed batching (e.g., accumulating 16ms-33ms buckets of byte buffers) before dispatching native-to-web events via notifyListeners.
- Web clients MUST process high-frequency bridge messages through a pre-allocated Float64Array or Uint8Array circular ring buffer, avoiding repeated object allocation and V8 micro-heap fragmentation.
- UI components NEVER render raw sensor ticks directly; they MUST sample the latest consolidated frame state decoupled from ingestion using requestAnimationFrame (rAF).

## Bad vs Good Implementations
### High-Frequency Native Stream Ingestion: Direct UI Listener vs Isolated Buffer Worker

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Connecting native high-frequency events directly to React state updates over the Capacitor bridge floods the JavaScript main thread. Parsing individual DataView frames and scheduling continuous React reconciliation runs at 100Hz causes severe dropped frames, GC pauses, and bridge starvation.
```typescript
import React, { useEffect, useState } from 'react';
import { PluginListenerHandle } from '@capacitor/core';
import { BleClient } from '@capacitor-community/bluetooth-le';

interface SensorReading {
  x: number;
  y: number;
  z: number;
  timestamp: number;
}

export const SensorTelemetryDisplay: React.FC = () => {
  // ANTI-PATTERN: Direct state update on 100Hz native event stream
  // Triggers 100 React re-renders/sec, mass string serialization over bridge,
  // and massive V8 minor GC spikes stalling WKWebView/Android UI thread.
  const [reading, setReading] = useState<SensorReading | null>(null);

  useEffect(() => {
    let handle: PluginListenerHandle;
    const startStream = async () => {
      await BleClient.startNotifications(
        'DEVICE_ID',
        'SERVICE_UUID',
        'CHAR_UUID',
        (value: DataView) => {
          // Inefficient base64/JSON bridging and main thread state push
          const parsed: SensorReading = {
            x: value.getFloat32(0, true),
            y: value.getFloat32(4, true),
            z: value.getFloat32(8, true),
            timestamp: performance.now(),
          };
          setReading(parsed);
        }
      );
    };
    startStream();
    return () => {
      BleClient.stopNotifications('DEVICE_ID', 'SERVICE_UUID', 'CHAR_UUID');
    };
  }, []);

  return <div>X: {reading?.x} Y: {reading?.y} Z: {reading?.z}</div>;
};
```

#### Production Standard (Correct)
> **Standard**: Incoming native notifications bypass the UI framework reconciliation layer by writing directly to a pre-allocated Float64Array ring buffer. UI state is sampled on demand using requestAnimationFrame, capping rendering workload to the device refresh rate (60/120Hz) and eliminating object allocation churn.
```typescript
import React, { useEffect, useRef, useState } from 'react';
import { BleClient } from '@capacitor-community/bluetooth-le';

// Pre-allocated ring buffer holding latest snapshot (X, Y, Z, Timestamp)
class IsolatedMetricsBuffer {
  private buffer: Float64Array = new Float64Array(4);
  
  public update(view: DataView): void {
    // Direct typed write without heap allocation
    this.buffer[0] = view.getFloat32(0, true);
    this.buffer[1] = view.getFloat32(4, true);
    this.buffer[2] = view.getFloat32(8, true);
    this.buffer[3] = performance.now();
  }

  public readLatest(target: Float64Array): void {
    target.set(this.buffer);
  }
}

export const SensorTelemetryDisplay: React.FC = () => {
  const metricsRef = useRef(new IsolatedMetricsBuffer());
  const [displayCoords, setDisplayCoords] = useState<{ x: number; y: number; z: number }>({ x: 0, y: 0, z: 0 });

  useEffect(() => {
    let rafId: number;
    const readSnapshot = new Float64Array(4);

    // Render Loop: Decoupled from bridge throughput (locked to display refresh rate)
    const tick = () => {
      metricsRef.current.readLatest(readSnapshot);
      setDisplayCoords({
        x: readSnapshot[0],
        y: readSnapshot[1],
        z: readSnapshot[2],
      });
      rafId = requestAnimationFrame(tick);
    };
    rafId = requestAnimationFrame(tick);

    const startStream = async () => {
      await BleClient.startNotifications(
        'DEVICE_ID',
        'SERVICE_UUID',
        'CHAR_UUID',
        (value: DataView) => {
          // Ingest frame into zero-alloc ring buffer off the React lifecycle
          metricsRef.current.update(value);
        }
      );
    };
    startStream();

    return () => {
      cancelAnimationFrame(rafId);
      BleClient.stopNotifications('DEVICE_ID', 'SERVICE_UUID', 'CHAR_UUID').catch(() => {});
    };
  }, []);

  return <div>X: {displayCoords.x.toFixed(2)} Y: {displayCoords.y.toFixed(2)} Z: {displayCoords.z.toFixed(2)}</div>;
};
```

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 Buffer Isolation & High-Frequency Streaming Guardrail

Capacitor 7 Native Bridge Buffer Isolation & High-Frequency Streaming Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict buffer isolation, off-thread queuing, and Web Worker routing for high-throughput peripheral and sensor streams over the Capacitor 7 native-web bridge. Eliminates V8 heap exhaustion and main-thread UI frame dropping caused by unthrottled serialization across WKWebView and Android WebView bridge boundaries. 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: Unthrottled Bridge Event Dispatching Directly into Main-Thread React/Vue State 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 DriftUnthrottled Bridge Event Dispatching Directly into Main-Thread React/Vue StateCritical
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 route streaming telemetry (>30Hz, e.g., BLE, IMU, audio, LiDAR) to a dedicated Web Worker via transferable ArrayBuffers or batched chunk structures instead of firing continuous native plugin listener events.

Engineers MUST ALWAYS route streaming telemetry (>30Hz, e.g., BLE, IMU, audio, LiDAR) to a dedicated Web Worker via transferable ArrayBuffers or batched chunk structures instead of firing continuous native plugin listener events.

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 mutate reactive UI framework state (React useState/useReducer, Vue ref) directly inside Capacitor plugin event listener callbacks for streaming peripherals.

Engineers MUST NOT mutate reactive UI framework state (React useState/useReducer, Vue ref) directly inside Capacitor plugin event listener callbacks for streaming peripherals.

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 plugins MUST implement backpressure handling and windowed batching (e.g., accumulating 16ms-33ms buckets of byte buffers) before dispatching native-to-web events via notifyListeners.

Native plugins MUST implement backpressure handling and windowed batching (e.g., accumulating 16ms-33ms buckets of byte buffers) before dispatching native-to-web events via notifyListeners.

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

Web clients MUST process high-frequency bridge messages through a pre-allocated Float64Array or Uint8Array circular ring buffer, avoiding repeated object allocation and V8 micro-heap fragmentation.

Web clients MUST process high-frequency bridge messages through a pre-allocated Float64Array or Uint8Array circular ring buffer, avoiding repeated object allocation and V8 micro-heap fragmentation.

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

UI components NEVER render raw sensor ticks directly

UI components NEVER render raw sensor ticks directly; they MUST sample the latest consolidated frame state decoupled from ingestion using requestAnimationFrame (rAF).

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 Buffer Isolation & High-Frequency Streaming Guardrail critical for AI coding assistants?

Enforces strict buffer isolation, off-thread queuing, and Web Worker routing for high-throughput peripheral and sensor streams over the Capacitor 7 native-web bridge. Eliminates V8 heap exhaustion and main-thread UI frame dropping caused by unthrottled serialization across WKWebView and Android WebView bridge boundaries. 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 (Unthrottled Bridge Event Dispatching Directly into Main-Thread React/Vue State) 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