This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-ktor-sqldelight-driver-concurrency-standard

KMP Shared Network & Database: Ktor Concurrency, Driver Isolation, and SQLDelight Migrations

Enforces strict native memory and concurrency safety across Kotlin Multiplatform targets using Ktor HTTP Client and SQLDelight. Eliminates thread-freezing violations, race conditions, driver resource leaks, and schema version drift between iOS and Android runtime boundaries.

Prohibited Anti-Pattern: Global Unconfined Ktor Clients and Unmanaged Native SqlDriver Singletons Causing iOS Runtime Panics and Corrupted Schema Migrations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Shared Network & Database: Ktor Concurrency, Driver Isolation, and SQLDelight Migrations - Enforces strict native memory and concurrency safety across Kotlin Multiplatform targets using Ktor HTTP Client and SQLDelight. Eliminates thread-freezing violations, race conditions, driver resource leaks, and schema version drift between iOS and Android runtime boundaries.
globs: **/commonMain/**/*.kt, **/androidMain/**/*.kt, **/iosMain/**/*.kt, **/nativeMain/**/*.kt, **/*.sq
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-ktor-sqldelight-driver-concurrency-standard"
---

# KMP Shared Network & Database: Ktor Concurrency, Driver Isolation, and SQLDelight Migrations

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Global Unconfined Ktor Clients and Unmanaged Native SqlDriver Singletons Causing iOS Runtime Panics and Corrupted Schema Migrations

## System Constraints
You are a Principal Mobile Architect enforcing industrial-grade Kotlin Multiplatform (KMP) shared networking and persistence. Mandate deterministic lifecycle bounds for Ktor HttpClient instances, safe concurrency dispatchers on Native targets, and strict declarative versioning for SQLDelight database drivers and migrations across Android (JVM) and iOS (Native Darwin SQLite).

## Strict Guidelines
- Engineers MUST ALWAYS configure Ktor HttpClient engines explicitly per target using expect/actual or native platform engine factories (e.g., Darwin for iOS, OkHttp or Android for Android), enforcing bounded thread pools and explicit timeouts.
- Engineers MUST NEVER recreate HttpClient instances per request; client instances MUST be managed as long-lived, lifecycle-aware singletons injected via DI and explicitly closed on application teardown.
- Engineers MUST ALWAYS isolate SQLDelight SqlDriver creation behind platform-specific factories that enforce NativeSqliteDriver configuration with custom schema migration callbacks (Database.Schema) and strict WAL mode.
- Engineers MUST NOT run database queries or long-running network serialization on Dispatchers.Main; database interactions MUST be confined to Dispatchers.Default or a dedicated bounded dispatcher using asContextElement or Dispatchers.IO where supported.
- Code SHOULD maintain versioned '.sqm' migration scripts alongside '.sq' definition files and verify database upgrades via the SQLDelight verifyMigration Gradle task in continuous integration.
- Engineers MUST NEVER mutate shared in-memory response states across threads without atomic primitives (e.g., kotlinx.atomicfu or AtomicRef) on Kotlin Native targets.

## Bad vs Good Implementations
### Thread-Safe SQLDelight Driver Instantiation & Ktor Engine Lifecycle

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Recreating HttpClient on every invocation exhausts native sockets and disables engine-level connection pooling. Directly instantiating NativeSqliteDriver in common code without handling AppDatabase.Schema migrations crashes on version increments and leaks C-pointer handles.
```kotlin
// ANTI-PATTERN: Recreating HttpClient per call, hardcoded unconfined engine,
// and ignoring SQLDelight schema migrations on iOS native target.
class UserRepository {
    suspend fun fetchAndStoreUser(userId: String) {
        // Instantiating client per request leads to socket leakage and memory exhaustion
        val client = HttpClient()
        val userDto = client.get("https://api.example.com/users/$userId").body<UserDto>()
        
        // NativeSqliteDriver created directly in shared code without platform schema migration
        // iOS target will fail or overwrite corrupt schemas without AppDatabase.Schema.create
        val driver = NativeSqliteDriver(AppDatabase.Schema, "app.db")
        val database = AppDatabase(driver)
        database.userQueries.insertUser(userDto.id, userDto.name)
    }
}
```

#### Production Standard (Correct)
> **Standard**: HttpClient and AppDatabase are long-lived injected singletons. SQLDelight driver creation is deferred to target-specific factories with foreign keys enabled, and all network/DB tasks run safely off the main thread inside Dispatchers.Default with managed transactions.
```kotlin
// PRODUCTION STANDARD: Injected singletons, explicit platform engines, and managed migrations
interface DatabaseDriverFactory {
    fun createDriver(): SqlDriver
}

// iosMain/PlatformDatabaseDriverFactory.kt
// class NativeDatabaseDriverFactory : DatabaseDriverFactory {
//     override fun createDriver(): SqlDriver = NativeSqliteDriver(
//         schema = AppDatabase.Schema,
//         name = "app.db",
//         onConfiguration = { config -> config.copy(extendedConfig = DatabaseConfiguration.Extended(foreignKeyConstraints = true)) }
//     )
// }

class UserRepository(
    private val httpClient: HttpClient,
    private val database: AppDatabase,
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.Default
) {
    suspend fun fetchAndStoreUser(userId: String): Result<Unit> = withContext(ioDispatcher) {
        runCatching {
            val response = httpClient.get("https://api.example.com/users/$userId") {
                contentType(ContentType.Application.Json)
            }.body<UserDto>()

            database.userQueries.transaction {
                database.userQueries.insertUser(
                    id = response.id,
                    name = response.name
                )
            }
        }
    }
}
```

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 Shared Network & Database: Ktor Concurrency, Driver Isolation, and SQLDelight Migrations

KMP Shared Network & Database: Ktor Concurrency, Driver Isolation, and SQLDelight Migrations defines an industrial-grade behavioral standard for mobile engineering. Enforces strict native memory and concurrency safety across Kotlin Multiplatform targets using Ktor HTTP Client and SQLDelight. Eliminates thread-freezing violations, race conditions, driver resource leaks, and schema version drift between iOS and Android runtime 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: Global Unconfined Ktor Clients and Unmanaged Native SqlDriver Singletons Causing iOS Runtime Panics and Corrupted Schema Migrations 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 DriftGlobal Unconfined Ktor Clients and Unmanaged Native SqlDriver Singletons Causing iOS Runtime Panics and Corrupted Schema MigrationsCritical
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 configure Ktor HttpClient engines explicitly per target using expect/actual or native platform engine factories (e.g., Darwin for iOS, OkHttp or Android for Android), enforcing bounded thread pools and explicit timeouts.

Engineers MUST ALWAYS configure Ktor HttpClient engines explicitly per target using expect/actual or native platform engine factories (e.g., Darwin for iOS, OkHttp or Android for Android), enforcing bounded thread pools and explicit timeouts.

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 NEVER recreate HttpClient instances per request

Engineers MUST NEVER recreate HttpClient instances per request; client instances MUST be managed as long-lived, lifecycle-aware singletons injected via DI and explicitly closed on application teardown.

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

Engineers MUST ALWAYS isolate SQLDelight SqlDriver creation behind platform-specific factories that enforce NativeSqliteDriver configuration with custom schema migration callbacks (Database.Schema) and strict WAL mode.

Engineers MUST ALWAYS isolate SQLDelight SqlDriver creation behind platform-specific factories that enforce NativeSqliteDriver configuration with custom schema migration callbacks (Database.Schema) and strict WAL mode.

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 NOT run database queries or long-running network serialization on Dispatchers.Main

Engineers MUST NOT run database queries or long-running network serialization on Dispatchers.Main; database interactions MUST be confined to Dispatchers.Default or a dedicated bounded dispatcher using asContextElement or Dispatchers.IO where supported.

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

Code SHOULD maintain versioned '.sqm' migration scripts alongside '.sq' definition files and verify database upgrades via the SQLDelight verifyMigration Gradle task in continuous integration.

Code SHOULD maintain versioned '.sqm' migration scripts alongside '.sq' definition files and verify database upgrades via the SQLDelight verifyMigration Gradle task in continuous integration.

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.
6

Engineers MUST NEVER mutate shared in-memory response states across threads without atomic primitives (e.g., kotlinx.atomicfu or AtomicRef) on Kotlin Native targets.

Engineers MUST NEVER mutate shared in-memory response states across threads without atomic primitives (e.g., kotlinx.atomicfu or AtomicRef) on Kotlin Native targets.

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 Shared Network & Database: Ktor Concurrency, Driver Isolation, and SQLDelight Migrations critical for AI coding assistants?

Enforces strict native memory and concurrency safety across Kotlin Multiplatform targets using Ktor HTTP Client and SQLDelight. Eliminates thread-freezing violations, race conditions, driver resource leaks, and schema version drift between iOS and Android runtime 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 (Global Unconfined Ktor Clients and Unmanaged Native SqlDriver Singletons Causing iOS Runtime Panics and Corrupted Schema Migrations) 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