This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: room-kmp-sqlite-wal-concurrency-boundary

Room 2.7 KMP Multiplatform SQLite WAL Concurrency Boundary

Enforces strict Write-Ahead Logging (WAL) initialization, single-writer multi-reader coroutine dispatching, and POSIX-safe connection pool boundaries across iOS and Android in Room 2.7 Kotlin Multiplatform. Prevents SQLite multi-threading violations, fatal SQLITE_BUSY deadlocks, and cross-platform native thread lockups by isolating SQLite writes through a confined single-threaded coroutine context while allowing concurrent readers.

Prohibited Anti-Pattern: Unconfined Concurrent Coroutine Dispatching on Native SQLite SQLiteDriver Without WAL Isolation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Room 2.7 KMP Multiplatform SQLite WAL Concurrency Boundary - Enforces strict Write-Ahead Logging (WAL) initialization, single-writer multi-reader coroutine dispatching, and POSIX-safe connection pool boundaries across iOS and Android in Room 2.7 Kotlin Multiplatform. Prevents SQLite multi-threading violations, fatal SQLITE_BUSY deadlocks, and cross-platform native thread lockups by isolating SQLite writes through a confined single-threaded coroutine context while allowing concurrent readers.
globs: **/commonMain/**/database/**/*.kt, **/commonMain/**/*Database*.kt, **/iosMain/**/database/**/*.kt, **/androidMain/**/database/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/room-kmp-sqlite-wal-concurrency-boundary"
---

# Room 2.7 KMP Multiplatform SQLite WAL Concurrency Boundary

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unconfined Concurrent Coroutine Dispatching on Native SQLite SQLiteDriver Without WAL Isolation

## System Constraints
You are a Principal Mobile Architect enforcing Room 2.7 KMP SQLite WAL concurrency invariants. Mandate single-writer coroutine confinement, explicit WAL PRAGMA configuration via RoomDatabase.Callback, and isolated multi-reader POSIX thread safety across iOS and Android.

## Strict Guidelines
- Engineers MUST ALWAYS configure Room 2.7 KMP databases using explicit SQLiteDriver implementations (e.g., BundledSQLiteDriver) with PRAGMA journal_mode=WAL and PRAGMA busy_timeout configured on open callbacks.
- Engineers MUST ALWAYS confine write operations and write transactions to a dedicated, single-threaded CoroutineDispatcher (such as Dispatchers.IO.limitedParallelism(1)) to prevent concurrent writer contention and native POSIX thread lockups on Apple targets.
- Engineers MUST NOT allow unconfined Dispatchers.IO or Dispatchers.Default to execute Room @Transaction write blocks directly across multiplatform runtimes.
- Engineers MUST NOT execute blocking Room queries on main/UI dispatchers on either Android (Looper) or iOS (NSThread/GCD Main Queue).
- Shared KMP Room database builders MUST configure setQueryCoroutineContext with a dedicated dispatcher boundary that enforces single-writer multi-reader WAL semantics.
- iOS native target SQLite driver instances MUST configure POSIX file locking flags and busy timeouts (minimum 5000ms) to prevent immediate SQLITE_BUSY / SQLITE_LOCKED exceptions during concurrent background thread access.

## Bad vs Good Implementations
### Room 2.7 KMP Multiplatform Database Concurrency Boundary Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using unconfined Dispatchers.IO directly allows multiple coroutines to issue concurrent write transactions. Without WAL mode and busy_timeout PRAGMAs, POSIX file-locking on Apple platforms triggers SQLITE_BUSY or native SQLite deadlocks when writes overlap.
```kotlin
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO

fun getUnsafeDatabase(builder: RoomDatabase.Builder<AppDatabase>): AppDatabase {
    // ANTI-PATTERN: Default dispatcher allows unbounded concurrent writes.
    // Missing WAL pragma and busy_timeout causes SQLITE_BUSY crashes on iOS native threads.
    return builder
        .setDriver(BundledSQLiteDriver())
        .setQueryCoroutineContext(Dispatchers.IO)
        .build()
}
```

#### Production Standard (Correct)
> **Standard**: Confines Room operations to a controlled single-thread dispatcher via limitedParallelism(1), while setting SQLite to WAL mode with a 5000ms busy_timeout and NORMAL synchronous persistence. This satisfies POSIX thread-locking safety across Android and iOS runtimes without database lock contention.
```kotlin
import androidx.room.RoomDatabase
import androidx.sqlite.SQLiteConnection
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import androidx.sqlite.execSQL
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO

fun getResilientDatabase(builder: RoomDatabase.Builder<AppDatabase>): AppDatabase {
    // Confine writes and transactions to a single-threaded queue while keeping multi-threaded reader isolation
    val databaseDispatcher = Dispatchers.IO.limitedParallelism(1)
    
    return builder
        .setDriver(BundledSQLiteDriver())
        .setQueryCoroutineContext(databaseDispatcher)
        .addCallback(object : RoomDatabase.Callback() {
            override fun onOpen(connection: SQLiteConnection) {
                super.onOpen(connection)
                // Enforce WAL mode for non-blocking concurrent reads during writes
                connection.execSQL("PRAGMA journal_mode=WAL;")
                // Set POSIX-safe retry duration for multi-threaded file locks on iOS/Android
                connection.execSQL("PRAGMA busy_timeout=5000;")
                // Optimize WAL checkpointing overhead
                connection.execSQL("PRAGMA synchronous=NORMAL;")
            }
        })
        .build()
}
```

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: Room 2.7 KMP Multiplatform SQLite WAL Concurrency Boundary

Room 2.7 KMP Multiplatform SQLite WAL Concurrency Boundary defines an industrial-grade behavioral standard for mobile engineering. Enforces strict Write-Ahead Logging (WAL) initialization, single-writer multi-reader coroutine dispatching, and POSIX-safe connection pool boundaries across iOS and Android in Room 2.7 Kotlin Multiplatform. Prevents SQLite multi-threading violations, fatal SQLITE_BUSY deadlocks, and cross-platform native thread lockups by isolating SQLite writes through a confined single-threaded coroutine context while allowing concurrent readers. 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: Unconfined Concurrent Coroutine Dispatching on Native SQLite SQLiteDriver Without WAL Isolation 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 DriftUnconfined Concurrent Coroutine Dispatching on Native SQLite SQLiteDriver Without WAL IsolationCritical
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 Room 2.7 KMP databases using explicit SQLiteDriver implementations (e.g., BundledSQLiteDriver) with PRAGMA journal_mode=WAL and PRAGMA busy_timeout configured on open callbacks.

Engineers MUST ALWAYS configure Room 2.7 KMP databases using explicit SQLiteDriver implementations (e.g., BundledSQLiteDriver) with PRAGMA journal_mode=WAL and PRAGMA busy_timeout configured on open 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.
2

Engineers MUST ALWAYS confine write operations and write transactions to a dedicated, single-threaded CoroutineDispatcher (such as Dispatchers.IO.limitedParallelism(1)) to prevent concurrent writer contention and native POSIX thread lockups on Apple targets.

Engineers MUST ALWAYS confine write operations and write transactions to a dedicated, single-threaded CoroutineDispatcher (such as Dispatchers.IO.limitedParallelism(1)) to prevent concurrent writer contention and native POSIX thread lockups on Apple 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.
3

Engineers MUST NOT allow unconfined Dispatchers.IO or Dispatchers.Default to execute Room @Transaction write blocks directly across multiplatform runtimes.

Engineers MUST NOT allow unconfined Dispatchers.IO or Dispatchers.Default to execute Room @Transaction write blocks directly across multiplatform runtimes.

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 execute blocking Room queries on main/UI dispatchers on either Android (Looper) or iOS (NSThread/GCD Main Queue).

Engineers MUST NOT execute blocking Room queries on main/UI dispatchers on either Android (Looper) or iOS (NSThread/GCD Main Queue).

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

Shared KMP Room database builders MUST configure setQueryCoroutineContext with a dedicated dispatcher boundary that enforces single-writer multi-reader WAL semantics.

Shared KMP Room database builders MUST configure setQueryCoroutineContext with a dedicated dispatcher boundary that enforces single-writer multi-reader WAL semantics.

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

iOS native target SQLite driver instances MUST configure POSIX file locking flags and busy timeouts (minimum 5000ms) to prevent immediate SQLITE_BUSY / SQLITE_LOCKED exceptions during concurrent background thread access.

iOS native target SQLite driver instances MUST configure POSIX file locking flags and busy timeouts (minimum 5000ms) to prevent immediate SQLITE_BUSY / SQLITE_LOCKED exceptions during concurrent background thread access.

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 Room 2.7 KMP Multiplatform SQLite WAL Concurrency Boundary critical for AI coding assistants?

Enforces strict Write-Ahead Logging (WAL) initialization, single-writer multi-reader coroutine dispatching, and POSIX-safe connection pool boundaries across iOS and Android in Room 2.7 Kotlin Multiplatform. Prevents SQLite multi-threading violations, fatal SQLITE_BUSY deadlocks, and cross-platform native thread lockups by isolating SQLite writes through a confined single-threaded coroutine context while allowing concurrent readers. 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 (Unconfined Concurrent Coroutine Dispatching on Native SQLite SQLiteDriver Without WAL Isolation) 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

Room