This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-knative-incremental-gc-cadence-stabilization-standard

Kotlin Multiplatform Native Incremental GC Cadence & Allocation Pacing Standard

Enforces deterministic object allocation and GC scheduling boundaries in Kotlin/Native shared modules executing on iOS. Prevents main-thread UI hitching and frame drops below 120Hz caused by uncoordinated incremental GC sweeping during high-throughput background ingestion streams.

Prohibited Anti-Pattern: Unbounded allocations on background threads triggering aggressive stop-the-world GC phases during UI render deadlines.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Native Incremental GC Cadence & Allocation Pacing Standard - Enforces deterministic object allocation and GC scheduling boundaries in Kotlin/Native shared modules executing on iOS. Prevents main-thread UI hitching and frame drops below 120Hz caused by uncoordinated incremental GC sweeping during high-throughput background ingestion streams.
globs: **/commonMain/**/*.kt, **/iosMain/**/*.kt, **/appleMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-knative-incremental-gc-cadence-stabilization-standard"
---

# Kotlin Multiplatform Native Incremental GC Cadence & Allocation Pacing Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded allocations on background threads triggering aggressive stop-the-world GC phases during UI render deadlines.

## System Constraints
You are a Principal Mobile Architect enforcing strict Kotlin/Native memory management and incremental GC stability across shared Apple targets. You must prevent memory churn, enforce allocation budgets, decouple streaming telemetry ingestion from the main runloop, and ensure Kotlin/Native runtime GC thresholds do not starve 120Hz ProMotion display frames (8.33ms budget).

## Strict Guidelines
- Engineers MUST ALWAYS batch or pool high-frequency streaming events (e.g., WebSocket payloads, sensors, telemetry) using static primitive arrays or circular buffers to avoid transient object creation.
- Engineers MUST NOT allocate non-primitive wrappers, short-lived closures, or intermediate Flow/Rx transformations inside critical event-processing loops exceeding 60Hz.
- Background ingestion pipelines MUST execute on dedicated off-main dispatch queues (`Dispatchers.Default` backed by pinned native worker queues) without bridging transient objects to the iOS main thread.
- Engineers MUST configure Kotlin/Native GC scheduling explicitly via `kotlin.native.internal.GC.schedule()` or tune `kotlin.native.runtime.gcThreshold` when processing burst workloads to avoid triggering synchronous stop-the-world safepoints.
- Direct interop boundaries between Swift and Kotlin across 120Hz CADisplayLink passes MUST use zero-allocation primitives or persistent C-struct pointers rather than bridged Kotlin class instances.

## Bad vs Good Implementations
### Batching Stream Ingestion to Prevent Kotlin/Native Allocation Thrashing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating intermediate collections (`List`, `chunked`, lambda closures, and custom classes) every 8ms triggers Kotlin/Native's incremental GC threshold continuously. The runtime pauses or saturates CPU cores during incremental sweeps, leading to missed 8.33ms display frames on iOS.
```kotlin
// BAD: Allocating transient instances and lambdas inside a high-frequency (100Hz+) stream.
// This creates excessive short-lived objects triggering frequent Kotlin/Native incremental GC steps,
// causing hitching on ProMotion 120Hz displays when GC sweeps interop roots.
class TelemetryConsumer(private val observer: (Double, Double) -> Unit) {
    fun onEventReceived(payload: ByteArray) {
        val parsed = parsePayload(payload) // Allocates temporary objects every 8ms
        val metrics = parsed.map { it.toMetric() } // Intermediate list allocations
        for (metric in metrics) {
            observer(metric.latitude, metric.longitude)
        }
    }

    private fun parsePayload(raw: ByteArray): List<RawMetric> = raw.toList().chunked(8).map { RawMetric(it) }
    private class RawMetric(val bytes: List<Byte>) { fun toMetric() = Metric(0.0, 0.0) }
    private class Metric(val latitude: Double, val longitude: Double)
}
```

#### Production Standard (Correct)
> **Standard**: Reuses a pre-allocated primitive array (`DoubleArray`) and avoids boxing, closures, or temporary list instances. Decouples the Kotlin/Native memory footprint from throughput and initiates cooperative GC scheduling on flush, keeping frame times firmly within the 8.33ms 120Hz ProMotion envelope.
```kotlin
// GOOD: Zero-allocation circular buffer and primitive ingestion.
// Reuses memory structures and batches notifications, stabilizing GC cadence.
import kotlin.native.internal.GC
import kotlinx.cinterop.ExperimentalForeignApi

class TelemetryConsumer(private val sink: TelemetryBatchSink) {
    private val ringBuffer = DoubleArray(BUFFER_CAPACITY * 2)
    private var writeIndex = 0

    @OptIn(ExperimentalForeignApi::class)
    fun onEventReceived(rawBytes: ByteArray, offset: Int, count: Int) {
        // Direct primitive extraction without object allocation
        var i = offset
        while (i < offset + count && writeIndex < ringBuffer.size - 1) {
            ringBuffer[writeIndex++] = extractLat(rawBytes, i)
            ringBuffer[writeIndex++] = extractLon(rawBytes, i + 8)
            i += 16
        }

        // Flush in controlled bursts to prevent GC threshold escalation
        if (writeIndex >= ringBuffer.size) {
            flush()
        }
    }

    fun flush() {
        if (writeIndex == 0) return
        sink.onBatchAvailable(ringBuffer, writeIndex)
        writeIndex = 0
        // Explicitly decouple GC pressure: prevent automatic mid-frame GC sweeps
        // and schedule incremental collection asynchronously on idle budget
        GC.schedule()
    }

    private fun extractLat(b: ByteArray, idx: Int): Double = 0.0 // Raw bitwise decoding
    private fun extractLon(b: ByteArray, idx: Int): Double = 0.0 // Raw bitwise decoding

    companion object {
        private const val BUFFER_CAPACITY = 128
    }
}

interface TelemetryBatchSink {
    fun onBatchAvailable(buffer: DoubleArray, length: Int)
}
```

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: Kotlin Multiplatform Native Incremental GC Cadence & Allocation Pacing Standard

Kotlin Multiplatform Native Incremental GC Cadence & Allocation Pacing Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic object allocation and GC scheduling boundaries in Kotlin/Native shared modules executing on iOS. Prevents main-thread UI hitching and frame drops below 120Hz caused by uncoordinated incremental GC sweeping during high-throughput background ingestion streams. 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 allocations on background threads triggering aggressive stop-the-world GC phases during UI render deadlines. 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 allocations on background threads triggering aggressive stop-the-world GC phases during UI render deadlines.Critical
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 or pool high-frequency streaming events (e.g., WebSocket payloads, sensors, telemetry) using static primitive arrays or circular buffers to avoid transient object creation.

Engineers MUST ALWAYS batch or pool high-frequency streaming events (e.g., WebSocket payloads, sensors, telemetry) using static primitive arrays or circular buffers to avoid transient object creation.

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 allocate non-primitive wrappers, short-lived closures, or intermediate Flow/Rx transformations inside critical event-processing loops exceeding 60Hz.

Engineers MUST NOT allocate non-primitive wrappers, short-lived closures, or intermediate Flow/Rx transformations inside critical event-processing loops exceeding 60Hz.

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

Background ingestion pipelines MUST execute on dedicated off-main dispatch queues (`Dispatchers.Default` backed by pinned native worker queues) without bridging transient objects to the iOS main thread.

Background ingestion pipelines MUST execute on dedicated off-main dispatch queues (`Dispatchers.Default` backed by pinned native worker queues) without bridging transient objects to the iOS main 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

Engineers MUST configure Kotlin/Native GC scheduling explicitly via `kotlin.native.internal.GC.schedule()` or tune `kotlin.native.runtime.gcThreshold` when processing burst workloads to avoid triggering synchronous stop-the-world safepoints.

Engineers MUST configure Kotlin/Native GC scheduling explicitly via `kotlin.native.internal.GC.schedule()` or tune `kotlin.native.runtime.gcThreshold` when processing burst workloads to avoid triggering synchronous stop-the-world safepoints.

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

Direct interop boundaries between Swift and Kotlin across 120Hz CADisplayLink passes MUST use zero-allocation primitives or persistent C-struct pointers rather than bridged Kotlin class instances.

Direct interop boundaries between Swift and Kotlin across 120Hz CADisplayLink passes MUST use zero-allocation primitives or persistent C-struct pointers rather than bridged Kotlin class instances.

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 Kotlin Multiplatform Native Incremental GC Cadence & Allocation Pacing Standard critical for AI coding assistants?

Enforces deterministic object allocation and GC scheduling boundaries in Kotlin/Native shared modules executing on iOS. Prevents main-thread UI hitching and frame drops below 120Hz caused by uncoordinated incremental GC sweeping during high-throughput background ingestion streams. 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 allocations on background threads triggering aggressive stop-the-world GC phases during UI render deadlines.) 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

Kotlin