This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-ktor3-flow-ios-runloop-fence

KMP Ktor 3.0 Coroutine Flow iOS RunLoop Synchronization Fence

Enforces backpressure fences and RunLoop decoupling when bridging Ktor 3.0 reactive byte/event flows across Kotlin/Native to Apple Darwin platforms. Prevents CFRunLoop starvation, CADisplayLink hitching, and Grand Central Dispatch (GCD) thread pool exhaustion caused by direct main-thread Flow collection under high I/O ingress.

Prohibited Anti-Pattern: Direct Main-Thread Collection of Unbuffered Ktor 3.0 Streaming Flows on Apple Darwin

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Ktor 3.0 Coroutine Flow iOS RunLoop Synchronization Fence - Enforces backpressure fences and RunLoop decoupling when bridging Ktor 3.0 reactive byte/event flows across Kotlin/Native to Apple Darwin platforms. Prevents CFRunLoop starvation, CADisplayLink hitching, and Grand Central Dispatch (GCD) thread pool exhaustion caused by direct main-thread Flow collection under high I/O ingress.
globs: **/iosMain/**/*.kt, **/commonMain/**/network/**/*.kt, **/commonMain/**/repository/**/*.kt, **/*ViewModel*.swift, **/*FlowAdapter*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-ktor3-flow-ios-runloop-fence"
---

# KMP Ktor 3.0 Coroutine Flow iOS RunLoop Synchronization Fence

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Direct Main-Thread Collection of Unbuffered Ktor 3.0 Streaming Flows on Apple Darwin

## System Constraints
You are a Principal Mobile Architect enforcing strict Darwin thread boundaries and coroutine backpressure fences in Kotlin Multiplatform (KMP) using Ktor 3.0. You must ensure that high-frequency coroutine flows emitted by Ktor 3.0 do not saturate the iOS CFRunLoop or exhaust GCD worker threads during Swift/Kotlin bridging.

## Strict Guidelines
- Engineers MUST ALWAYS isolate Ktor 3.0 response streams (SSE, WebSockets, chunked HTTP) on Dispatchers.Default using bounded buffers with BufferOverflow.DROP_OLDEST or backpressure-aware Channel fences before bridging to iOS.
- Engineers MUST NOT collect raw Ktor 3.0 Flow streams directly on Dispatchers.Main or Dispatchers.Main.immediate within Darwin compilation units.
- Code bridging KMP Flows to Swift/SwiftUI MUST throttle or coalesce emissions to match CADisplayLink refresh intervals (e.g., 60Hz/120Hz) to prevent main RunLoop hitching.
- Services MUST implement explicit cooperative cancellation hooks bound to iOS UIViewController or SwiftUI view lifecycle events to invalidate active Darwin Ktor engines.
- Components NEVER bridge raw Flow collectors directly to Darwin GCD main queues without passing through an explicit CFRunLoopMode-aware synchronization fence.

## Bad vs Good Implementations
### KMP Flow Backpressure Fence for Darwin Consumption

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly collecting high-frequency SSE events on Darwin's Dispatchers.Main locks the CFRunLoop during touch tracking and animation cycles, causing noticeable UI hitching and thread starvation.
```kotlin
// ANTI-PATTERN: Streaming raw Ktor 3.0 flow directly to Dispatchers.Main
// Causes CADisplayLink frame drops and GCD thread pool exhaustion under heavy load
class TelemetryRepository(private val client: HttpClient) {
    fun streamTelemetry(): Flow<TelemetryEvent> = flow {
        client.serverSentEvents("https://api.internal/telemetry") { 
            incoming.collect { sseEvent ->
                emit(Json.decodeFromString<TelemetryEvent>(sseEvent.data ?: ""))
            }
        }
    }.flowOn(Dispatchers.Main) // Directly bound to Main thread RunLoop
}
```

#### Production Standard (Correct)
> **Standard**: Isolating collection to Dispatchers.Default and introducing a bounded buffer fence with conflation protects Darwin's CFRunLoop from being overloaded by packet bursts.
```kotlin
// PRODUCTION STANDARD: Isolated I/O, Bounded Buffer Fence, and RunLoop-Safe Emission
class TelemetryRepository(private val client: HttpClient) {
    fun streamTelemetry(): Flow<TelemetryEvent> {
        return flow {
            client.serverSentEvents("https://api.internal/telemetry") {
                incoming.collect { sseEvent ->
                    sseEvent.data?.let {
                        emit(Json.decodeFromString<TelemetryEvent>(it))
                    }
                }
            }
        }
        .flowOn(Dispatchers.Default)
        .buffer(capacity = 64, onBufferOverflow = BufferOverflow.DROP_OLDEST)
        .conflate()
    }
}
```

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: KMP Ktor 3.0 Coroutine Flow iOS RunLoop Synchronization Fence

KMP Ktor 3.0 Coroutine Flow iOS RunLoop Synchronization Fence defines an industrial-grade behavioral standard for mobile engineering. Enforces backpressure fences and RunLoop decoupling when bridging Ktor 3.0 reactive byte/event flows across Kotlin/Native to Apple Darwin platforms. Prevents CFRunLoop starvation, CADisplayLink hitching, and Grand Central Dispatch (GCD) thread pool exhaustion caused by direct main-thread Flow collection under high I/O ingress. 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: Direct Main-Thread Collection of Unbuffered Ktor 3.0 Streaming Flows on Apple Darwin 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 DriftDirect Main-Thread Collection of Unbuffered Ktor 3.0 Streaming Flows on Apple DarwinCritical
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 isolate Ktor 3.0 response streams (SSE, WebSockets, chunked HTTP) on Dispatchers.Default using bounded buffers with BufferOverflow.DROP_OLDEST or backpressure-aware Channel fences before bridging to iOS.

Engineers MUST ALWAYS isolate Ktor 3.0 response streams (SSE, WebSockets, chunked HTTP) on Dispatchers.Default using bounded buffers with BufferOverflow.DROP_OLDEST or backpressure-aware Channel fences before bridging to iOS.

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 collect raw Ktor 3.0 Flow streams directly on Dispatchers.Main or Dispatchers.Main.immediate within Darwin compilation units.

Engineers MUST NOT collect raw Ktor 3.0 Flow streams directly on Dispatchers.Main or Dispatchers.Main.immediate within Darwin compilation units.

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 bridging KMP Flows to Swift/SwiftUI MUST throttle or coalesce emissions to match CADisplayLink refresh intervals (e.g., 60Hz/120Hz) to prevent main RunLoop hitching.

Code bridging KMP Flows to Swift/SwiftUI MUST throttle or coalesce emissions to match CADisplayLink refresh intervals (e.g., 60Hz/120Hz) to prevent main RunLoop hitching.

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 explicit cooperative cancellation hooks bound to iOS UIViewController or SwiftUI view lifecycle events to invalidate active Darwin Ktor engines.

Services MUST implement explicit cooperative cancellation hooks bound to iOS UIViewController or SwiftUI view lifecycle events to invalidate active Darwin Ktor engines.

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 bridge raw Flow collectors directly to Darwin GCD main queues without passing through an explicit CFRunLoopMode-aware synchronization fence.

Components NEVER bridge raw Flow collectors directly to Darwin GCD main queues without passing through an explicit CFRunLoopMode-aware synchronization fence.

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 KMP Ktor 3.0 Coroutine Flow iOS RunLoop Synchronization Fence critical for AI coding assistants?

Enforces backpressure fences and RunLoop decoupling when bridging Ktor 3.0 reactive byte/event flows across Kotlin/Native to Apple Darwin platforms. Prevents CFRunLoop starvation, CADisplayLink hitching, and Grand Central Dispatch (GCD) thread pool exhaustion caused by direct main-thread Flow collection under high I/O ingress. 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 (Direct Main-Thread Collection of Unbuffered Ktor 3.0 Streaming Flows on Apple Darwin) 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

KMP