This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor7-bridge-memory-buffer-pooling-guardrail

Capacitor 7 Bi-directional Bridge Memory Buffer Pooling & High-Frequency Streaming Guardrail

High-frequency native sensor and telemetry streams must never execute per-sample JSON serialization over the Capacitor 7 bridge or trigger unbounded JavaScript heap allocations. This guardrail mandates native-to-web ring-buffer chunking, typed array pooling, and zero-allocation deserialization patterns to eliminate bridge thread-hopping stalls and V8/JavaScriptCore garbage collection pauses.

Prohibited Anti-Pattern: Unbatched per-tick JSON IPC serialization over notifyListeners causing bridge thread congestion and V8 GC thrashing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Bi-directional Bridge Memory Buffer Pooling & High-Frequency Streaming Guardrail - High-frequency native sensor and telemetry streams must never execute per-sample JSON serialization over the Capacitor 7 bridge or trigger unbounded JavaScript heap allocations. This guardrail mandates native-to-web ring-buffer chunking, typed array pooling, and zero-allocation deserialization patterns to eliminate bridge thread-hopping stalls and V8/JavaScriptCore garbage collection pauses.
globs: src/**/*.{ts,tsx}, android/**/*.java, ios/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-bridge-memory-buffer-pooling-guardrail"
---

# Capacitor 7 Bi-directional Bridge Memory Buffer Pooling & High-Frequency Streaming Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbatched per-tick JSON IPC serialization over notifyListeners causing bridge thread congestion and V8 GC thrashing

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Bridge Memory Buffer Pooling invariants. Mandate that high-frequency data streams (e.g., IMU, BLE, GPS, audio, canvas telemetry exceeding 30Hz) use packed binary or flat typed buffers with pre-allocated pooling rather than per-event JSON objects across notifyListeners. Prevent bridge serialization bottlenecks, thread-hopping overhead, and WebKit/V8 garbage collection pressure.

## Strict Guidelines
- Engineers MUST ALWAYS batch high-frequency sensor readings (>30Hz) into packed flat arrays or base64 binary chunks before crossing the Capacitor bridge.
- Engineers MUST NOT invoke plugin `notifyListeners()` on individual sensor ticks or per-packet native telemetry callbacks.
- Code SHOULD maintain a pre-allocated object and `Float32Array`/`Uint8Array` pool in TypeScript to ingest bridge payloads without allocating new heap objects per sample.
- Services MUST throttle bridge dispatches to VSYNC cadence (16ms/33ms) using native ring buffers or fixed-interval flush timers.
- Components NEVER subscribe raw UI components directly to bridge event emitters; downstream state must be updated via pooled batch consumers outside the UI rendering path.

## Bad vs Good Implementations
### Native-to-Web Telemetry Streaming

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Emitting unbatched native events creates extreme thread-hopping overhead between native background threads, the Capacitor bridge dispatch thread, and the WebKit/V8 JS thread. Deserializing small JSON payloads 100+ times per second generates thousands of short-lived JS objects, triggering micro-stutters via garbage collection.
```typescript
import { PluginListenerHandle } from '@capacitor/core';
import { MotionPlugin } from './definitions';

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

// ANTI-PATTERN: Native plugin fires notifyListeners 100+ times/sec.
// Every tick creates a bridge IPC message, serializes JSON, and allocates a new JS object,
// triggering severe V8 GC pauses and frame drops on low-end devices.
let listener: PluginListenerHandle;
export async function startTracking(callback: (sample: AccelSample) => void) {
  listener = await MotionPlugin.addListener('accelTick', (data: AccelSample) => {
    // Allocates new object and forces GC churn in high-frequency loop
    callback({ x: data.x, y: data.y, z: data.z, timestamp: data.timestamp });
  });
}
```

#### Production Standard (Correct)
> **Standard**: Batches telemetry into a single binary payload per display tick (16-33ms). The TypeScript consumer decodes the payload into a reusable, pre-allocated typed buffer pool, entirely avoiding object allocations, JSON bridge overhead, and V8 garbage collector invocation.
```typescript
import { PluginListenerHandle } from '@capacitor/core';
import { MotionPlugin } from './definitions';

interface PackedBatchPayload {
  samplesCount: number;
  bufferBase64: string;
}

// PRODUCTION FIX: Pre-allocated buffer pool with flat typed array views.
// The native side batches 60 samples into a single binary buffer flushed at 60Hz.
const MAX_SAMPLES_PER_BATCH = 120;
const FLOATS_PER_SAMPLE = 4; // timestamp, x, y, z
const sharedBuffer = new ArrayBuffer(MAX_SAMPLES_PER_BATCH * FLOATS_PER_SAMPLE * Float32Array.BYTES_PER_ELEMENT);
const floatView = new Float32Array(sharedBuffer);
const byteView = new Uint8Array(sharedBuffer);

let listener: PluginListenerHandle | null = null;

export async function startPooledTracking(onBatchProcessed: (view: Float32Array, count: number) => void): Promise<void> {
  listener = await MotionPlugin.addListener('accelBatch', (batch: PackedBatchPayload) => {
    const binaryStr = atob(batch.bufferBase64);
    const len = binaryStr.length;
    
    // Zero-allocation byte copy into pre-allocated memory pool
    for (let i = 0; i < len; i++) {
      byteView[i] = binaryStr.charCodeAt(i);
    }

    // Expose typed array view directly to consumer without heap allocation
    onBatchProcessed(floatView, batch.samplesCount);
  });
}
```

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 Bi-directional Bridge Memory Buffer Pooling & High-Frequency Streaming Guardrail

Capacitor 7 Bi-directional Bridge Memory Buffer Pooling & High-Frequency Streaming Guardrail defines an industrial-grade behavioral standard for mobile engineering. High-frequency native sensor and telemetry streams must never execute per-sample JSON serialization over the Capacitor 7 bridge or trigger unbounded JavaScript heap allocations. This guardrail mandates native-to-web ring-buffer chunking, typed array pooling, and zero-allocation deserialization patterns to eliminate bridge thread-hopping stalls and V8/JavaScriptCore garbage collection pauses. 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: Unbatched per-tick JSON IPC serialization over notifyListeners causing bridge thread congestion and V8 GC thrashing 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 DriftUnbatched per-tick JSON IPC serialization over notifyListeners causing bridge thread congestion and V8 GC thrashingCritical
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 batch high-frequency sensor readings (>30Hz) into packed flat arrays or base64 binary chunks before crossing the Capacitor bridge.

Engineers MUST ALWAYS batch high-frequency sensor readings (>30Hz) into packed flat arrays or base64 binary chunks before crossing 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 plugin `notifyListeners()` on individual sensor ticks or per-packet native telemetry callbacks.

Engineers MUST NOT invoke plugin `notifyListeners()` on individual sensor ticks or per-packet native telemetry callbacks.

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 maintain a pre-allocated object and `Float32Array`/`Uint8Array` pool in TypeScript to ingest bridge payloads without allocating new heap objects per sample.

Code SHOULD maintain a pre-allocated object and `Float32Array`/`Uint8Array` pool in TypeScript to ingest bridge payloads without allocating new heap objects per sample.

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 throttle bridge dispatches to VSYNC cadence (16ms/33ms) using native ring buffers or fixed-interval flush timers.

Services MUST throttle bridge dispatches to VSYNC cadence (16ms/33ms) using native ring buffers or fixed-interval flush timers.

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 subscribe raw UI components directly to bridge event emitters

Components NEVER subscribe raw UI components directly to bridge event emitters; downstream state must be updated via pooled batch consumers outside the UI rendering path.

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 Bi-directional Bridge Memory Buffer Pooling & High-Frequency Streaming Guardrail critical for AI coding assistants?

High-frequency native sensor and telemetry streams must never execute per-sample JSON serialization over the Capacitor 7 bridge or trigger unbounded JavaScript heap allocations. This guardrail mandates native-to-web ring-buffer chunking, typed array pooling, and zero-allocation deserialization patterns to eliminate bridge thread-hopping stalls and V8/JavaScriptCore garbage collection pauses. 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 (Unbatched per-tick JSON IPC serialization over notifyListeners causing bridge thread congestion and V8 GC thrashing) 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